fix(service): команды запуска одной очередью, рестарт не перетирает стоп

This commit is contained in:
samosvalishe committed 2026-09-22 20:11:37 +03:00
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 { AppUpdater(androidContext()) }
single { BackupManager(get()) }
single { ProxyOrchestrator(get(), get(), get(), get()) }
single { ProxyOrchestrator(get(), get(), get()) }
// factory: своя SSH-сессия на каждый прогон мастера, живой SshRepository не трогаем.
factory { ServerSetupRepository(androidContext(), get()) }
// factory по той же причине: SSH-операции шаринга не делят сессию с активным сервером.
@@ -22,7 +22,6 @@ class ProxyOrchestrator(
private val prefs: AppPreferences,
private val launcher: ProxyServiceLauncher,
private val sshRepository: SshRepository,
private val store: ProxyStore
) {
// Процессный scope: рестарт пары не должен рваться вместе с экраном (VM гибнет с
// Activity) - между stop и start сервер остался бы погашенным.
@@ -123,10 +122,8 @@ class ProxyOrchestrator(
}
}
/** Команда START при живой сессии пересоздаёт её с новым конфигом. */
fun restartProxyIfRunning() {
if (!store.status.value.busy) return
launcher.start()
launcher.restartIfRunning()
}
private companion object {
@@ -1,10 +1,14 @@
package com.freeturn.app.domain.proxy
import kotlinx.coroutines.Job
/**
* Запуск/остановка платформенного прокси-сервиса. Инверсия зависимости: domain не
* знает про Android-Service, конкретный Intent держит реализация в слое service.
*/
interface ProxyServiceLauncher {
fun start()
fun stop()
fun start(): Job
fun stop(): Job
fun restartIfRunning(): Job
}
@@ -3,7 +3,6 @@ package com.freeturn.app.service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Looper
import com.freeturn.app.R
import com.freeturn.app.data.AppPreferences
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.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
@@ -25,33 +25,17 @@ class AndroidProxyServiceLauncher(
private val store: ProxyStore
) : ProxyServiceLauncher {
// Параллелизм 1: START и STOP обязаны уйти в систему в том же порядке, в каком их нажали.
@OptIn(ExperimentalCoroutinesApi::class)
private val dispatchScope =
CoroutineScope(Dispatchers.IO.limitedParallelism(1) + SupervisorJob())
/**
* С главного потока команда уходит в очередь: байндер-транзакция запуска сервиса
* занимает его ровно в момент нажатия, и в кадр не влезает анимация кнопки.
* Из бродкаста и тайла зовём на месте - `onReceive` вернётся раньше, чем очередь
* дойдёт до вызова, и заявку потеряли бы вместе с процессом.
*/
private fun dispatch(block: () -> Unit) {
if (Looper.myLooper() == Looper.getMainLooper()) dispatchScope.launch { block() } else block()
}
@Volatile private var desired: Boolean? = null
override fun start() {
override fun start(): Job {
prefs.setProxyDesired(true)
desired = true
store.starting()
dispatch {
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()))
}
}
return dispatchScope.launch { sendStart() }
}
/**
@@ -59,10 +43,11 @@ class AndroidProxyServiceLauncher(
* останавливать нечего - `stopService` уходит впустую, и сервис поднимается уже
* после отмены. Команда встаёт в ту же очередь и гасит его гарантированно.
*/
override fun stop() {
override fun stop(): Job {
prefs.setProxyDesired(false)
desired = false
store.idle()
dispatch {
return dispatchScope.launch {
try {
context.startService(command(ProxyActions.STOP))
} 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) =
Intent(context, ProxyService::class.java).setAction(action)
}
@@ -13,9 +13,13 @@ class ProxyReceiver : BroadcastReceiver(), KoinComponent {
private val launcher: ProxyServiceLauncher by inject()
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
val job = when (intent.action) {
ProxyActions.START -> launcher.start()
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 logs: StateFlow<List<LogEntry>> = log.lines
fun start() = launcher.start()
fun start() {
launcher.start()
}
fun stop() = launcher.stop()
fun stop() {
launcher.stop()
}
/**
* Возврат приложения на передний план. Живую сессию не трогаем - открытие окна