feat(domain): единый SSH-лог и apply для неактивных профилей

- журнал сервера сливается в единый sshLog (заголовки-разделители,
  флаг journalLoading, clearSshLog); отдельный serverLogs удалён
- Failed/Offline хаба стали data object: причина ошибки — внутренняя
  SSH-деталь, полный текст остаётся в sshLog
- applyProfileServerConfig: apply-модель для неактивного профиля пишет
  только снимок, живой рантайм не трогается
- updateProfileClient правит конфиг по id без активации профиля
- рестарт по тогглу синка дебаунсится и коалесцируется; окно
  расхождения при смерти процесса задокументировано (probe покажет
  live-режим, следующий apply чинит)
This commit is contained in:
samosvalishe committed 2026-06-10 14:15:36 +03:00
1 parent 376ee26a7c
commit a7623c8513
4 files changed
+117 -42

No files matched your search

@@ -2,6 +2,7 @@ package com.freeturn.app.domain
import android.content.Context import android.content.Context
import com.freeturn.app.SSHManager import com.freeturn.app.SSHManager
import com.freeturn.app.data.ObfProfile
import com.freeturn.app.data.SshConfig import com.freeturn.app.data.SshConfig
import com.freeturn.app.domain.server.CmdResult import com.freeturn.app.domain.server.CmdResult
import com.freeturn.app.domain.server.ServerCommand import com.freeturn.app.domain.server.ServerCommand
@@ -32,12 +33,14 @@ class SshRepository(
private val _serverState = MutableStateFlow<ServerState>(ServerState.Unknown) private val _serverState = MutableStateFlow<ServerState>(ServerState.Unknown)
val serverState: StateFlow<ServerState> = _serverState.asStateFlow() val serverState: StateFlow<ServerState> = _serverState.asStateFlow()
private val _serverLogs = MutableStateFlow<String?>(null)
val serverLogs: StateFlow<String?> = _serverLogs.asStateFlow()
private val _sshLog = MutableStateFlow<List<String>>(emptyList()) private val _sshLog = MutableStateFlow<List<String>>(emptyList())
val sshLog: StateFlow<List<String>> = _sshLog.asStateFlow() val sshLog: StateFlow<List<String>> = _sshLog.asStateFlow()
// Идёт ли запрос server.log. Сам вывод уходит в sshLog (через runCmd → logCmdResult),
// отдельного состояния журнала нет — он часть единого SSH-лога.
private val _journalLoading = MutableStateFlow(false)
val journalLoading: StateFlow<Boolean> = _journalLoading.asStateFlow()
private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss") private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss")
private fun timestamp(): String = LocalTime.now().format(timeFormatter) private fun timestamp(): String = LocalTime.now().format(timeFormatter)
@@ -105,13 +108,18 @@ class SshRepository(
_serverState.value = ServerState.Unknown _serverState.value = ServerState.Unknown
} }
suspend fun checkServerState(config: SshConfig? = null) { /**
* @param silent пропустить промежуточный [ServerState.Checking]. Нужно при перепроверке
* после действия (стоп/старт/установка): иначе хаб моргает Working→«Подключение»→Online.
* При silent текущий Working держится до прихода [ServerState.Known].
*/
suspend fun checkServerState(config: SshConfig? = null, silent: Boolean = false) {
val cfg = config ?: activeSshConfig ?: return val cfg = config ?: activeSshConfig ?: return
if (cfg.ip.isEmpty()) { if (cfg.ip.isEmpty()) {
_serverState.value = ServerState.Unknown _serverState.value = ServerState.Unknown
return return
} }
_serverState.value = ServerState.Checking if (!silent) _serverState.value = ServerState.Checking
when (val r = runCmd(cfg, "Проверка состояния", ServerCommand.Probe)) { when (val r = runCmd(cfg, "Проверка состояния", ServerCommand.Probe)) {
is CmdResult.Err -> _serverState.value = ServerState.Error(r.message) is CmdResult.Err -> _serverState.value = ServerState.Error(r.message)
@@ -163,7 +171,7 @@ class SshRepository(
// VM решает, как стартовать (с актуальными prefs). // VM решает, как стартовать (с актуальными prefs).
} }
delay(300) delay(300)
checkServerState(cfg) checkServerState(cfg, silent = true)
InstallOutcome.Success(stage = stage, version = version, needsRestart = needsRestart) InstallOutcome.Success(stage = stage, version = version, needsRestart = needsRestart)
} }
} }
@@ -197,7 +205,7 @@ class SshRepository(
return false return false
} }
delay(1500) delay(1500)
checkServerState(cfg) checkServerState(cfg, silent = true)
return true return true
} }
@@ -212,21 +220,18 @@ class SshRepository(
return return
} }
delay(1000) delay(1000)
checkServerState(cfg) checkServerState(cfg, silent = true)
}
fun clearServerLogs() {
_serverLogs.value = null
} }
/** Тянет server.log по SSH. Вывод (и ошибки) пишутся в общий sshLog через runCmd. */
suspend fun fetchServerLogs(lines: Int = 200) { suspend fun fetchServerLogs(lines: Int = 200) {
val cfg = activeSshConfig ?: return val cfg = activeSshConfig ?: return
if (cfg.ip.isEmpty()) return if (cfg.ip.isEmpty()) return
_serverLogs.value = "…" _journalLoading.value = true
when (val r = runCmd(cfg, "server.log", ServerCommand.FetchLogs(lines))) { try {
is CmdResult.Err -> _serverLogs.value = "ERROR: ${r.message}" runCmd(cfg, "server.log", ServerCommand.FetchLogs(lines))
is CmdResult.Ok -> } finally {
_serverLogs.value = r.logs.joinToString("\n").ifEmpty { "(лог пуст)" } _journalLoading.value = false
} }
} }
@@ -236,9 +241,7 @@ class SshRepository(
if (cfg.ip.isEmpty()) return null if (cfg.ip.isEmpty()) return null
return when (val r = runCmd(cfg, "Генерация obf-key", ServerCommand.GenObfKey)) { return when (val r = runCmd(cfg, "Генерация obf-key", ServerCommand.GenObfKey)) {
is CmdResult.Err -> null is CmdResult.Err -> null
is CmdResult.Ok -> r.kv["OBFKEY"]?.takeIf { is CmdResult.Ok -> r.kv["OBFKEY"]?.takeIf { ObfProfile.isValidKey(it) }
it.matches(Regex("^[0-9a-fA-F]{64}$"))
}
} }
} }
@@ -246,9 +249,12 @@ class SshRepository(
_serverState.value = state _serverState.value = state
} }
fun clearSshLog() {
_sshLog.value = emptyList()
}
fun resetAll() { fun resetAll() {
disconnect() disconnect()
_serverLogs.value = null
_sshLog.value = emptyList() _sshLog.value = emptyList()
} }
} }
@@ -26,8 +26,10 @@ sealed class ServerState {
} }
sealed interface ServerHubStatus { sealed interface ServerHubStatus {
/** Профиль не активен: живой SSH/ядро принадлежат активному. Предлагаем активировать. */ /**
data class Offline(val serverAddress: String?, val sshIp: String?) : ServerHubStatus * Профиль не активен: живой SSH/ядро принадлежат активному. Предлагаем активировать.
*/
data object Offline : ServerHubStatus
/** Активен, но SSH не настроен — нечего подключать. */ /** Активен, но SSH не настроен — нечего подключать. */
data object NotPaired : ServerHubStatus data object NotPaired : ServerHubStatus
/** Идёт подключение/проверка (единая busy-фаза, skeleton). */ /** Идёт подключение/проверка (единая busy-фаза, skeleton). */
@@ -41,13 +43,23 @@ sealed interface ServerHubStatus {
val tcpMode: Boolean?, val tcpMode: Boolean?,
val obfProfile: String?, val obfProfile: String?,
val version: String?, val version: String?,
val installStage: String?,
val sshIp: String val sshIp: String
) : ServerHubStatus ) : ServerHubStatus
/** Ошибка SSH или серверной команды. */ /** Ошибка SSH или серверной команды. Причина — внутренняя java/SSH-ошибка, юзеру
data class Failed(val message: String?) : ServerHubStatus * бесполезна и в hero не показывается; полный текст остаётся в sshLog (NerdScreen). */
data object Failed : ServerHubStatus
/** Sync с сервером выключен — live-статус ядра нерелевантен, нейтральная заглушка. */
data object SyncOff : ServerHubStatus
} }
/**
* Доступность «Настроек сервера»: при sync ON правки пушатся на сервер → нужен живой SSH;
* при sync OFF настройки клиент-локальны → доступны и оффлайн. Единственное место с этим
* правилом — его используют и вход в экран (ServerDetailScreen), и сам экран
* (ServerManagementScreen), иначе условия разъезжаются.
*/
fun serverSettingsAvailable(connected: Boolean, syncOn: Boolean): Boolean = connected || !syncOn
// Local proxy client states // Local proxy client states
sealed class ProxyState { sealed class ProxyState {
object Idle : ProxyState() object Idle : ProxyState()
@@ -31,7 +31,7 @@ class ServerViewModel(
val sshState: StateFlow<SshConnectionState> = sshRepository.sshState val sshState: StateFlow<SshConnectionState> = sshRepository.sshState
val serverState: StateFlow<ServerState> = sshRepository.serverState val serverState: StateFlow<ServerState> = sshRepository.serverState
val sshLog: StateFlow<List<String>> = sshRepository.sshLog val sshLog: StateFlow<List<String>> = sshRepository.sshLog
val serverLogs: StateFlow<String?> = sshRepository.serverLogs val journalLoading: StateFlow<Boolean> = sshRepository.journalLoading
val serverOpts: StateFlow<AppPreferences.ServerOpts> = prefs.serverOptsFlow val serverOpts: StateFlow<AppPreferences.ServerOpts> = prefs.serverOptsFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AppPreferences.ServerOpts()) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AppPreferences.ServerOpts())
@@ -39,21 +39,19 @@ class ServerViewModel(
val sshConfig: StateFlow<SshConfig> = prefs.sshConfigFlow val sshConfig: StateFlow<SshConfig> = prefs.sshConfigFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SshConfig()) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SshConfig())
private val _serverInstallStage = MutableStateFlow<String?>(null)
private val _isRegeneratingObfKey = MutableStateFlow(false) private val _isRegeneratingObfKey = MutableStateFlow(false)
val isRegeneratingObfKey: StateFlow<Boolean> = _isRegeneratingObfKey.asStateFlow() val isRegeneratingObfKey: StateFlow<Boolean> = _isRegeneratingObfKey.asStateFlow()
/** /**
* Сводный статус АКТИВНОГО сервера для хаба — одна модель из 3 потоков. Profile-контекст * Сводный статус АКТИВНОГО сервера для хаба — одна модель из 2 потоков. Profile-контекст
* (активность профиля, наличие SSH) добавляет экран. Промежуточные фазы коллапсятся в * (активность профиля, наличие SSH) добавляет экран. Промежуточные фазы коллапсятся в
* [ServerHubStatus.Connecting]: от cold start до готовности — один переход в [ServerHubStatus.Online]. * [ServerHubStatus.Connecting]: от cold start до готовности — один переход в [ServerHubStatus.Online].
*/ */
val hubStatus: StateFlow<ServerHubStatus> = val hubStatus: StateFlow<ServerHubStatus> =
combine(sshState, serverState, _serverInstallStage) { ssh, server, stage -> combine(sshState, serverState) { ssh, server ->
when { when {
ssh is SshConnectionState.Error -> ServerHubStatus.Failed(ssh.message) ssh is SshConnectionState.Error -> ServerHubStatus.Failed
server is ServerState.Error -> ServerHubStatus.Failed(server.message) server is ServerState.Error -> ServerHubStatus.Failed
server is ServerState.Working -> ServerHubStatus.Working(server.action) server is ServerState.Working -> ServerHubStatus.Working(server.action)
ssh is SshConnectionState.Connected && server is ServerState.Known -> ssh is SshConnectionState.Connected && server is ServerState.Known ->
ServerHubStatus.Online( ServerHubStatus.Online(
@@ -62,7 +60,6 @@ class ServerViewModel(
tcpMode = server.tcpMode, tcpMode = server.tcpMode,
obfProfile = server.obfProfile, obfProfile = server.obfProfile,
version = server.version, version = server.version,
installStage = stage,
sshIp = ssh.ip sshIp = ssh.ip
) )
// Disconnected / Connecting / Connected+Checking → единый busy-визуал. // Disconnected / Connecting / Connected+Checking → единый busy-визуал.
@@ -97,10 +94,8 @@ class ServerViewModel(
fun installServer() { fun installServer() {
viewModelScope.launch { viewModelScope.launch {
_serverInstallStage.value = null
val outcome = sshRepository.installServer() val outcome = sshRepository.installServer()
if (outcome is com.freeturn.app.domain.InstallOutcome.Success) { if (outcome is com.freeturn.app.domain.InstallOutcome.Success) {
_serverInstallStage.value = outcome.stage
if (outcome.stage == "downloaded") { if (outcome.stage == "downloaded") {
val current = prefs.serverOptsFlow.first() val current = prefs.serverOptsFlow.first()
if (current.obfKey.isBlank()) { if (current.obfKey.isBlank()) {
@@ -145,9 +140,7 @@ class ServerViewModel(
viewModelScope.launch { sshRepository.fetchServerLogs(lines) } viewModelScope.launch { sshRepository.fetchServerLogs(lines) }
} }
fun clearServerLogs() { fun clearSshLog() = sshRepository.clearSshLog()
sshRepository.clearServerLogs()
}
fun regenerateObfKey() { fun regenerateObfKey() {
viewModelScope.launch { viewModelScope.launch {
@@ -15,6 +15,10 @@ import com.freeturn.app.domain.AppUpdater
import com.freeturn.app.domain.LocalProxyManager import com.freeturn.app.domain.LocalProxyManager
import com.freeturn.app.domain.ProxyOrchestrator import com.freeturn.app.domain.ProxyOrchestrator
import com.freeturn.app.domain.SshRepository import com.freeturn.app.domain.SshRepository
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
@@ -52,6 +56,9 @@ class SettingsViewModel(
val dynamicTheme: StateFlow<Boolean> = prefs.dynamicThemeFlow val dynamicTheme: StateFlow<Boolean> = prefs.dynamicThemeFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), true) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), true)
val nerdMode: StateFlow<Boolean> = prefs.nerdModeFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
val profilesSnapshot: StateFlow<ProfilesSnapshot> = prefs.profilesSnapshot val profilesSnapshot: StateFlow<ProfilesSnapshot> = prefs.profilesSnapshot
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ProfilesSnapshot()) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ProfilesSnapshot())
@@ -71,6 +78,12 @@ class SettingsViewModel(
private val profileMutex = Mutex() private val profileMutex = Mutex()
// Дебаунс быстрых тыков тоггла синка: persist мгновенный, а дорогой сетевой
// side-effect (SSH stop+start + рестарт прокси) откладывается и коалесцируется.
private val syncSideEffectMutex = Mutex()
private var syncSideEffectJob: Job? = null
private val syncSideEffectDebounceMs = 600L
init { init {
viewModelScope.launch { viewModelScope.launch {
val done = prefs.onboardingDoneFlow.first() val done = prefs.onboardingDoneFlow.first()
@@ -92,6 +105,10 @@ class SettingsViewModel(
viewModelScope.launch { prefs.setDynamicTheme(enabled) } viewModelScope.launch { prefs.setDynamicTheme(enabled) }
} }
fun setNerdMode(enabled: Boolean) {
viewModelScope.launch { prefs.setNerdMode(enabled) }
}
fun setTgSubscribeShown() { fun setTgSubscribeShown() {
viewModelScope.launch { prefs.setTgSubscribeShown() } viewModelScope.launch { prefs.setTgSubscribeShown() }
} }
@@ -333,9 +350,25 @@ class SettingsViewModel(
persistClient(current.copy(syncServerSwitches = enabled)) persistClient(current.copy(syncServerSwitches = enabled))
true true
} }
if (changed && enabled) { if (!changed) return@launch
orchestrator.restartServerIfRunning() // Дебаунс: отменяем отложенный side-effect, перепланируем. delay — окно
orchestrator.restartProxyIfRunning() // отмены (гасит спам ON/OFF/ON → один рестарт). Сам рестарт под mutex
// (две последовательности не интерливятся) и NonCancellable (новый тык не
// рвёт SSH-команду на полпути). Читаем ФИНАЛЬНОЕ состояние после дебаунса —
// рестартим только если синк в итоге включён (…→OFF → ноль рестартов).
// Смерть процесса в окне дебаунса оставит сервер на старом конфиге при
// новом тоггле — принято: probe хаба покажет live-режим, любой следующий
// apply/старт приводит сервер в соответствие.
syncSideEffectJob?.cancel()
syncSideEffectJob = viewModelScope.launch {
delay(syncSideEffectDebounceMs)
syncSideEffectMutex.withLock {
if (!prefs.clientConfigFlow.first().syncServerSwitches) return@withLock
withContext(NonCancellable) {
orchestrator.restartServerIfRunning()
orchestrator.restartProxyIfRunning()
}
}
} }
} }
} }
@@ -382,6 +415,37 @@ class SettingsViewModel(
} }
} }
/**
* Apply-модель «Настроек сервера» для НЕактивного профиля (sync OFF): серверные
* параметры тут клиент-локальны, поэтому пишем ТОЛЬКО снимок профиля по id — ни
* legacy-ключи, ни рантайм (SSH/прокси активного сервера) не трогаем. Без живого SSH
* obf-ключ на сервере не генерим: пустой остаётся пустым (клиент стартует как есть).
*/
fun applyProfileServerConfig(
id: String,
listen: String,
connect: String,
tcpForward: Boolean,
obfProfile: String,
obfKey: String
) {
viewModelScope.launch {
profileMutex.withLock {
val snap = prefs.profilesSnapshot.first()
val target = snap.list.firstOrNull { it.id == id } ?: return@withLock
val effKey = obfKey.trim().ifBlank { target.server.obfKey }
val next = target.copy(
proxyListen = listen,
proxyConnect = connect,
client = target.client.copy(tcpForward = tcpForward),
server = target.server.copy(obfProfile = obfProfile, obfKey = effKey)
)
if (next == target) return@withLock
prefs.saveProfiles(snap.list.map { if (it.id == id) next else it })
}
}
}
// --- Updates --- // --- Updates ---
fun checkForUpdate() { fun checkForUpdate() {
viewModelScope.launch { appUpdater.checkForUpdate(silent = false) } viewModelScope.launch { appUpdater.checkForUpdate(silent = false) }