fix(settings): не терять правки и рестарт пары при уходе с экрана
Отложенное сохранение полей дописывается на dispose и идёт транзакцией DataStore. Рестарт сервер+клиент живёт в процессном scope оркестратора.
This commit is contained in:
1 parent
88dc0d1038
commit
a6caf4e8f4
4 files changed
+93
-77
No files matched your search
@@ -2,15 +2,79 @@ package com.freeturn.app.domain.proxy
|
|||||||
|
|
||||||
import com.freeturn.app.data.AppPreferences
|
import com.freeturn.app.data.AppPreferences
|
||||||
import com.freeturn.app.data.config.HostPort
|
import com.freeturn.app.data.config.HostPort
|
||||||
|
import com.freeturn.app.data.server.Server
|
||||||
import com.freeturn.app.domain.ServerState
|
import com.freeturn.app.domain.ServerState
|
||||||
import com.freeturn.app.domain.ssh.SshRepository
|
import com.freeturn.app.domain.ssh.SshRepository
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.NonCancellable
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
class ProxyOrchestrator(
|
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
|
||||||
) {
|
) {
|
||||||
|
// Процессный scope: рестарт пары не должен рваться вместе с экраном (VM гибнет с
|
||||||
|
// Activity) - между stop и start сервер остался бы погашенным.
|
||||||
|
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
|
||||||
|
// Два рестарта пары подряд не должны переплетать stop/start.
|
||||||
|
private val pairMutex = Mutex()
|
||||||
|
private var syncJob: Job? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Отложенный рестарт пары сервер+клиент после правки опций: правки летят пачками,
|
||||||
|
* SSH-команда - одна. Новая правка переносит рестарт, но начатый не обрывает.
|
||||||
|
*/
|
||||||
|
fun scheduleSync() {
|
||||||
|
synchronized(this) {
|
||||||
|
syncJob?.cancel()
|
||||||
|
syncJob = scope.launch {
|
||||||
|
delay(SYNC_DEBOUNCE_MS)
|
||||||
|
withContext(NonCancellable) {
|
||||||
|
pairMutex.withLock {
|
||||||
|
if (!prefs.clientConfigFlow.first().syncServerSwitches) return@withLock
|
||||||
|
restartServerIfRunning()
|
||||||
|
restartProxyIfRunning()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Рестарт пары сразу ("Применить"). [syncServer] false - сервер не трогаем. */
|
||||||
|
fun restartPair(syncServer: Boolean) {
|
||||||
|
scope.launch {
|
||||||
|
pairMutex.withLock {
|
||||||
|
if (syncServer) restartServerIfRunning()
|
||||||
|
else sshRepository.logNote("рестарт сервера пропущен: синхронизация выключена")
|
||||||
|
restartProxyIfRunning()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Переключение активного сервера: рантайм подтягивается к новому, не рвясь с экраном. */
|
||||||
|
fun onActiveServerChanged(target: Server) {
|
||||||
|
scope.launch {
|
||||||
|
pairMutex.withLock {
|
||||||
|
if (prefs.restartServerOnSwitchFlow.first()) restartServerIfRunning()
|
||||||
|
sshRepository.activeSshConfig?.let { prev ->
|
||||||
|
if (prev.ip != target.ssh.ip || prev.port != target.ssh.port) {
|
||||||
|
sshRepository.disconnect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
restartProxyIfRunning()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun restartServerIfRunning() {
|
suspend fun restartServerIfRunning() {
|
||||||
val active = sshRepository.activeSshConfig
|
val active = sshRepository.activeSshConfig
|
||||||
if (active == null) {
|
if (active == null) {
|
||||||
@@ -57,4 +121,7 @@ class ProxyOrchestrator(
|
|||||||
launcher.start()
|
launcher.start()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val SYNC_DEBOUNCE_MS = 600L
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -25,11 +25,13 @@ import androidx.compose.material3.Scaffold
|
|||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TopAppBarDefaults
|
import androidx.compose.material3.TopAppBarDefaults
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.DisposableEffect
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableFloatStateOf
|
import androidx.compose.runtime.mutableFloatStateOf
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
@@ -70,13 +72,9 @@ fun ClientSetupScreen(
|
|||||||
val effSshIp = server?.ssh?.ip ?: sshConfig.ip
|
val effSshIp = server?.ssh?.ip ?: sshConfig.ip
|
||||||
val effProxyListen = server?.proxyListen ?: activeProxyListen
|
val effProxyListen = server?.proxyListen ?: activeProxyListen
|
||||||
|
|
||||||
// Единая точка записи client-конфига: сервер by-id либо активный.
|
|
||||||
fun clientEdit(transform: (ClientConfig) -> ClientConfig) {
|
fun clientEdit(transform: (ClientConfig) -> ClientConfig) {
|
||||||
if (serverId != null) {
|
val targetId = serverId ?: snapshot.activeId ?: return
|
||||||
settingsViewModel.updateServerClient(serverId, transform)
|
settingsViewModel.updateServerClient(targetId, transform)
|
||||||
} else {
|
|
||||||
settingsViewModel.saveClientConfig(transform(settingsViewModel.clientConfig.value), snapshot.activeId)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
@@ -114,12 +112,7 @@ fun ClientSetupScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Авто-сохранение с дебаунсом 600 мс.
|
fun persistFields() {
|
||||||
LaunchedEffect(
|
|
||||||
fieldsKey, serverAddress, vkLink, threads, streamsPerCred, localPort, magicTurn, customDns
|
|
||||||
) {
|
|
||||||
if (!fieldsDirty) return@LaunchedEffect
|
|
||||||
delay(600)
|
|
||||||
clientEdit { current ->
|
clientEdit { current ->
|
||||||
current.copy(
|
current.copy(
|
||||||
serverAddress = serverAddress.trim(),
|
serverAddress = serverAddress.trim(),
|
||||||
@@ -133,6 +126,21 @@ fun ClientSetupScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var pendingSave by remember(fieldsKey) { mutableStateOf(false) }
|
||||||
|
LaunchedEffect(
|
||||||
|
fieldsKey, serverAddress, vkLink, threads, streamsPerCred, localPort, magicTurn, customDns
|
||||||
|
) {
|
||||||
|
if (!fieldsDirty) return@LaunchedEffect
|
||||||
|
pendingSave = true
|
||||||
|
delay(600)
|
||||||
|
persistFields()
|
||||||
|
pendingSave = false
|
||||||
|
}
|
||||||
|
val flush by rememberUpdatedState { persistFields() }
|
||||||
|
DisposableEffect(Unit) {
|
||||||
|
onDispose { if (pendingSave) flush() }
|
||||||
|
}
|
||||||
|
|
||||||
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
|
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
|
|||||||
+2
-5
@@ -88,11 +88,8 @@ fun ConnectionModeScreen(
|
|||||||
val isActive = serverId == null || serverId == snapshot.activeId
|
val isActive = serverId == null || serverId == snapshot.activeId
|
||||||
|
|
||||||
fun clientEdit(transform: (ClientConfig) -> ClientConfig) {
|
fun clientEdit(transform: (ClientConfig) -> ClientConfig) {
|
||||||
if (serverId != null) {
|
val targetId = serverId ?: snapshot.activeId ?: return
|
||||||
settingsViewModel.updateServerClient(serverId, transform)
|
settingsViewModel.updateServerClient(targetId, transform)
|
||||||
} else {
|
|
||||||
settingsViewModel.saveClientConfig(transform(settingsViewModel.clientConfig.value), snapshot.activeId)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
|||||||
@@ -25,9 +25,6 @@ import com.freeturn.app.domain.UpdateState
|
|||||||
import com.freeturn.app.domain.proxy.ProxyStore
|
import com.freeturn.app.domain.proxy.ProxyStore
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.NonCancellable
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
@@ -39,8 +36,6 @@ import kotlinx.coroutines.flow.asStateFlow
|
|||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.sync.Mutex
|
|
||||||
import kotlinx.coroutines.sync.withLock
|
|
||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
|
|
||||||
sealed interface ServerCleanupState {
|
sealed interface ServerCleanupState {
|
||||||
@@ -117,11 +112,6 @@ class SettingsViewModel(
|
|||||||
// Ожидаем DataStore, чтобы дефолт StateFlow не пропустил диалог первой сессии.
|
// Ожидаем DataStore, чтобы дефолт StateFlow не пропустил диалог первой сессии.
|
||||||
suspend fun batteryPromptShownOnce(): Boolean = prefs.batteryPromptShownFlow.first()
|
suspend fun batteryPromptShownOnce(): Boolean = prefs.batteryPromptShownFlow.first()
|
||||||
|
|
||||||
// Persist мгновенный; сетевые рестарты коалесцируются.
|
|
||||||
private val syncSideEffectMutex = Mutex()
|
|
||||||
private var syncSideEffectJob: Job? = null
|
|
||||||
private val syncSideEffectDebounceMs = 600L
|
|
||||||
|
|
||||||
init {
|
init {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
_initialTgSubscribeShown.value = prefs.tgSubscribeShownFlow.first()
|
_initialTgSubscribeShown.value = prefs.tgSubscribeShownFlow.first()
|
||||||
@@ -179,18 +169,6 @@ class SettingsViewModel(
|
|||||||
viewModelScope.launch { prefs.setAutoConnect(enabled) }
|
viewModelScope.launch { prefs.setAutoConnect(enabled) }
|
||||||
}
|
}
|
||||||
|
|
||||||
// expectedActiveId не даёт отложенной записи затереть новый активный сервер.
|
|
||||||
fun saveClientConfig(config: ClientConfig, expectedActiveId: String? = null) {
|
|
||||||
viewModelScope.launch {
|
|
||||||
val targetId = expectedActiveId
|
|
||||||
?: prefs.serversSnapshot.first().activeId ?: return@launch
|
|
||||||
if (!prefs.updateServer(targetId) { it.copy(client = config) }) return@launch
|
|
||||||
if (targetId == prefs.serversSnapshot.first().activeId) {
|
|
||||||
ProxyStore.setLogsEnabled(config.logsEnabled)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setSplitTunnelMode(value: String) {
|
fun setSplitTunnelMode(value: String) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
prefs.updateActiveServer {
|
prefs.updateActiveServer {
|
||||||
@@ -229,18 +207,7 @@ class SettingsViewModel(
|
|||||||
val target = prefs.serversSnapshot.first().list.firstOrNull { it.id == id }
|
val target = prefs.serversSnapshot.first().list.firstOrNull { it.id == id }
|
||||||
?: return@launch
|
?: return@launch
|
||||||
prefs.setActiveServerId(target.id)
|
prefs.setActiveServerId(target.id)
|
||||||
|
orchestrator.onActiveServerChanged(target)
|
||||||
if (prefs.restartServerOnSwitchFlow.first()) {
|
|
||||||
orchestrator.restartServerIfRunning()
|
|
||||||
}
|
|
||||||
|
|
||||||
sshRepository.activeSshConfig?.let { prev ->
|
|
||||||
if (prev.ip != target.ssh.ip || prev.port != target.ssh.port) {
|
|
||||||
sshRepository.disconnect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
orchestrator.restartProxyIfRunning()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -289,23 +256,7 @@ class SettingsViewModel(
|
|||||||
it.copy(client = it.client.copy(syncServerSwitches = enabled))
|
it.copy(client = it.client.copy(syncServerSwitches = enabled))
|
||||||
}
|
}
|
||||||
if (!changed) return@launch
|
if (!changed) return@launch
|
||||||
scheduleServerSync()
|
orchestrator.scheduleSync()
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Отложенный рестарт пары сервер+клиент: правки летят пачками, SSH-команда - одна. */
|
|
||||||
private fun scheduleServerSync() {
|
|
||||||
// NonCancellable не даёт новому переключению оборвать SSH-команду на полпути.
|
|
||||||
syncSideEffectJob?.cancel()
|
|
||||||
syncSideEffectJob = viewModelScope.launch {
|
|
||||||
delay(syncSideEffectDebounceMs)
|
|
||||||
syncSideEffectMutex.withLock {
|
|
||||||
if (!prefs.clientConfigFlow.first().syncServerSwitches) return@withLock
|
|
||||||
withContext(NonCancellable) {
|
|
||||||
orchestrator.restartServerIfRunning()
|
|
||||||
orchestrator.restartProxyIfRunning()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -328,7 +279,7 @@ class SettingsViewModel(
|
|||||||
}
|
}
|
||||||
if (!changed) return@launch
|
if (!changed) return@launch
|
||||||
if (id != null && id != prefs.serversSnapshot.first().activeId) return@launch
|
if (id != null && id != prefs.serversSnapshot.first().activeId) return@launch
|
||||||
scheduleServerSync()
|
orchestrator.scheduleSync()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -361,14 +312,7 @@ class SettingsViewModel(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (changed) {
|
if (changed) orchestrator.restartPair(syncServer = sync)
|
||||||
if (sync) {
|
|
||||||
orchestrator.restartServerIfRunning()
|
|
||||||
} else {
|
|
||||||
sshRepository.logNote("рестарт сервера пропущен: синхронизация выключена")
|
|
||||||
}
|
|
||||||
orchestrator.restartProxyIfRunning()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user