fix(service): команды запуска одной очередью, рестарт не перетирает стоп
This commit is contained in:
1 parent
4a7952b7ef
commit
428c84e9ad
6 files changed
+43
-33
No files matched your search
@@ -43,7 +43,7 @@ val appModule = module {
|
|||||||
single { SshRepository(androidContext(), get()) }
|
single { SshRepository(androidContext(), get()) }
|
||||||
single { AppUpdater(androidContext()) }
|
single { AppUpdater(androidContext()) }
|
||||||
single { BackupManager(get()) }
|
single { BackupManager(get()) }
|
||||||
single { ProxyOrchestrator(get(), get(), get(), get()) }
|
single { ProxyOrchestrator(get(), get(), get()) }
|
||||||
// factory: своя SSH-сессия на каждый прогон мастера, живой SshRepository не трогаем.
|
// factory: своя SSH-сессия на каждый прогон мастера, живой SshRepository не трогаем.
|
||||||
factory { ServerSetupRepository(androidContext(), get()) }
|
factory { ServerSetupRepository(androidContext(), get()) }
|
||||||
// factory по той же причине: SSH-операции шаринга не делят сессию с активным сервером.
|
// factory по той же причине: SSH-операции шаринга не делят сессию с активным сервером.
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ class ProxyOrchestrator(
|
|||||||
private val prefs: AppPreferences,
|
private val prefs: AppPreferences,
|
||||||
private val launcher: ProxyServiceLauncher,
|
private val launcher: ProxyServiceLauncher,
|
||||||
private val sshRepository: SshRepository,
|
private val sshRepository: SshRepository,
|
||||||
private val store: ProxyStore
|
|
||||||
) {
|
) {
|
||||||
// Процессный scope: рестарт пары не должен рваться вместе с экраном (VM гибнет с
|
// Процессный scope: рестарт пары не должен рваться вместе с экраном (VM гибнет с
|
||||||
// Activity) - между stop и start сервер остался бы погашенным.
|
// Activity) - между stop и start сервер остался бы погашенным.
|
||||||
@@ -123,10 +122,8 @@ class ProxyOrchestrator(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Команда START при живой сессии пересоздаёт её с новым конфигом. */
|
|
||||||
fun restartProxyIfRunning() {
|
fun restartProxyIfRunning() {
|
||||||
if (!store.status.value.busy) return
|
launcher.restartIfRunning()
|
||||||
launcher.start()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
package com.freeturn.app.domain.proxy
|
package com.freeturn.app.domain.proxy
|
||||||
|
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Запуск/остановка платформенного прокси-сервиса. Инверсия зависимости: domain не
|
* Запуск/остановка платформенного прокси-сервиса. Инверсия зависимости: domain не
|
||||||
* знает про Android-Service, конкретный Intent держит реализация в слое service.
|
* знает про Android-Service, конкретный Intent держит реализация в слое service.
|
||||||
*/
|
*/
|
||||||
interface ProxyServiceLauncher {
|
interface ProxyServiceLauncher {
|
||||||
fun start()
|
fun start(): Job
|
||||||
fun stop()
|
fun stop(): Job
|
||||||
|
|
||||||
|
fun restartIfRunning(): Job
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,6 @@ package com.freeturn.app.service
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Looper
|
|
||||||
import com.freeturn.app.R
|
import com.freeturn.app.R
|
||||||
import com.freeturn.app.data.AppPreferences
|
import com.freeturn.app.data.AppPreferences
|
||||||
import com.freeturn.app.domain.proxy.ProxyServiceLauncher
|
import com.freeturn.app.domain.proxy.ProxyServiceLauncher
|
||||||
@@ -11,6 +10,7 @@ import com.freeturn.app.domain.proxy.ProxyStore
|
|||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
@@ -25,33 +25,17 @@ class AndroidProxyServiceLauncher(
|
|||||||
private val store: ProxyStore
|
private val store: ProxyStore
|
||||||
) : ProxyServiceLauncher {
|
) : ProxyServiceLauncher {
|
||||||
|
|
||||||
// Параллелизм 1: START и STOP обязаны уйти в систему в том же порядке, в каком их нажали.
|
|
||||||
@OptIn(ExperimentalCoroutinesApi::class)
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
private val dispatchScope =
|
private val dispatchScope =
|
||||||
CoroutineScope(Dispatchers.IO.limitedParallelism(1) + SupervisorJob())
|
CoroutineScope(Dispatchers.IO.limitedParallelism(1) + SupervisorJob())
|
||||||
|
|
||||||
/**
|
@Volatile private var desired: Boolean? = null
|
||||||
* С главного потока команда уходит в очередь: байндер-транзакция запуска сервиса
|
|
||||||
* занимает его ровно в момент нажатия, и в кадр не влезает анимация кнопки.
|
|
||||||
* Из бродкаста и тайла зовём на месте - `onReceive` вернётся раньше, чем очередь
|
|
||||||
* дойдёт до вызова, и заявку потеряли бы вместе с процессом.
|
|
||||||
*/
|
|
||||||
private fun dispatch(block: () -> Unit) {
|
|
||||||
if (Looper.myLooper() == Looper.getMainLooper()) dispatchScope.launch { block() } else block()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun start() {
|
override fun start(): Job {
|
||||||
prefs.setProxyDesired(true)
|
prefs.setProxyDesired(true)
|
||||||
|
desired = true
|
||||||
store.starting()
|
store.starting()
|
||||||
dispatch {
|
return dispatchScope.launch { sendStart() }
|
||||||
try {
|
|
||||||
val intent = command(ProxyActions.START)
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent)
|
|
||||||
else context.startService(intent)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
store.fail(context.getString(R.string.proxy_error_service, e.detail()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -59,10 +43,11 @@ class AndroidProxyServiceLauncher(
|
|||||||
* останавливать нечего - `stopService` уходит впустую, и сервис поднимается уже
|
* останавливать нечего - `stopService` уходит впустую, и сервис поднимается уже
|
||||||
* после отмены. Команда встаёт в ту же очередь и гасит его гарантированно.
|
* после отмены. Команда встаёт в ту же очередь и гасит его гарантированно.
|
||||||
*/
|
*/
|
||||||
override fun stop() {
|
override fun stop(): Job {
|
||||||
prefs.setProxyDesired(false)
|
prefs.setProxyDesired(false)
|
||||||
|
desired = false
|
||||||
store.idle()
|
store.idle()
|
||||||
dispatch {
|
return dispatchScope.launch {
|
||||||
try {
|
try {
|
||||||
context.startService(command(ProxyActions.STOP))
|
context.startService(command(ProxyActions.STOP))
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
@@ -72,6 +57,22 @@ class AndroidProxyServiceLauncher(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun restartIfRunning(): Job = dispatchScope.launch {
|
||||||
|
if (desired == false || !store.status.value.busy) return@launch
|
||||||
|
store.starting()
|
||||||
|
sendStart()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendStart() {
|
||||||
|
try {
|
||||||
|
val intent = command(ProxyActions.START)
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent)
|
||||||
|
else context.startService(intent)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
store.fail(context.getString(R.string.proxy_error_service, e.detail()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun command(action: String) =
|
private fun command(action: String) =
|
||||||
Intent(context, ProxyService::class.java).setAction(action)
|
Intent(context, ProxyService::class.java).setAction(action)
|
||||||
}
|
}
|
||||||
@@ -13,9 +13,13 @@ class ProxyReceiver : BroadcastReceiver(), KoinComponent {
|
|||||||
private val launcher: ProxyServiceLauncher by inject()
|
private val launcher: ProxyServiceLauncher by inject()
|
||||||
|
|
||||||
override fun onReceive(context: Context, intent: Intent) {
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
when (intent.action) {
|
val job = when (intent.action) {
|
||||||
ProxyActions.START -> launcher.start()
|
ProxyActions.START -> launcher.start()
|
||||||
ProxyActions.STOP -> launcher.stop()
|
ProxyActions.STOP -> launcher.stop()
|
||||||
|
else -> return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val pending = goAsync()
|
||||||
|
job.invokeOnCompletion { pending.finish() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -26,9 +26,13 @@ class ProxyViewModel(
|
|||||||
val status: StateFlow<ProxyStatus> = store.status
|
val status: StateFlow<ProxyStatus> = store.status
|
||||||
val logs: StateFlow<List<LogEntry>> = log.lines
|
val logs: StateFlow<List<LogEntry>> = log.lines
|
||||||
|
|
||||||
fun start() = launcher.start()
|
fun start() {
|
||||||
|
launcher.start()
|
||||||
|
}
|
||||||
|
|
||||||
fun stop() = launcher.stop()
|
fun stop() {
|
||||||
|
launcher.stop()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Возврат приложения на передний план. Живую сессию не трогаем - открытие окна
|
* Возврат приложения на передний план. Живую сессию не трогаем - открытие окна
|
||||||
|
|||||||
Reference in new issue
Block a user