fix(server): диагностика скипов рестарта и гонка перезапуска прокси

Оркестратор пишет причину пропуска рестарта сервера в SSH-журнал
вместо молчаливого return. Ожидание остановки сервиса 2с -> 10с
(таймаут оставлял прокси остановленным). Единый HostPort-валидатор
listen/connect: гейт Применить, startServer, оркестратор.
This commit is contained in:
samosvalishe committed 2026-07-08 01:45:33 +03:00
1 parent a29c060262
commit 8e56023449
6 files changed
+46 -18

No files matched your search

@@ -42,6 +42,14 @@ object ObfProfile {
ByteArray(32).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
}
/** host:port для -listen/-connect ядра (IPv6-скобки ядро не принимает). Единая проверка для UI и оркестратора. */
object HostPort {
private val REGEX = Regex("""^[\w.\-]+:\d{1,5}$""")
fun isValid(value: String): Boolean =
value.matches(REGEX) && value.substringAfterLast(":").toInt() in 1..65535
}
/** Client ID (флаг -client-id ядра): авторизация по allowlist clients.json на сервере. */
object ClientId {
private val ID_REGEX = Regex("^[0-9a-f]{32}$")
@@ -1,6 +1,7 @@
package com.freeturn.app.domain.proxy
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.config.HostPort
import com.freeturn.app.domain.ServerState
import com.freeturn.app.domain.ssh.SshRepository
import kotlinx.coroutines.flow.first
@@ -12,17 +13,32 @@ class ProxyOrchestrator(
private val sshRepository: SshRepository
) {
suspend fun restartServerIfRunning() {
val active = sshRepository.activeSshConfig
if (active == null) {
sshRepository.logNote("рестарт сервера пропущен: нет активной SSH-сессии")
return
}
// Сессия должна вести на хост активного профиля: после смены профиля она ещё
// может указывать на прошлый сервер - иначе рестартнём чужой хост.
val active = sshRepository.activeSshConfig ?: return
val cfg = prefs.sshConfigFlow.first()
if (active.ip != cfg.ip || active.port != cfg.port) return
val running = (sshRepository.serverState.value as? ServerState.Known)?.running == true
if (!running) return
if (active.ip != cfg.ip || active.port != cfg.port) {
sshRepository.logNote("рестарт сервера пропущен: SSH-сессия указывает на другой хост")
return
}
val state = sshRepository.serverState.value
val known = state as? ServerState.Known
if (known?.running != true) {
val reason = if (known != null) "сервер остановлен"
else "состояние сервера ${state::class.simpleName}"
sshRepository.logNote("рестарт сервера пропущен: $reason")
return
}
val l = prefs.proxyListenFlow.first()
val c = prefs.proxyConnectFlow.first()
if (!l.matches(Regex("""^[\w.\-]+:\d{1,5}$""")) ||
!c.matches(Regex("""^[\w.\-]+:\d{1,5}$"""))) return
if (!HostPort.isValid(l) || !HostPort.isValid(c)) {
sshRepository.logNote("рестарт сервера пропущен: некорректный listen/connect ($l -> $c)")
return
}
val opts = prefs.serverOptsFlow.first()
val tcpMode = prefs.clientConfigFlow.first().tcpForward
sshRepository.stopServer()
@@ -38,7 +54,7 @@ class ProxyOrchestrator(
suspend fun restartProxyIfRunning() {
if (!ProxyServiceState.isRunning.value) return
proxyManager.stopProxy()
withTimeoutOrNull(2_000) {
withTimeoutOrNull(10_000) {
ProxyServiceState.isRunning.first { !it }
}
proxyManager.startProxy(prefs.clientConfigFlow.first())
@@ -257,6 +257,10 @@ class SshRepository(
_serverState.value = state
}
fun logNote(line: String) {
appendSshLog("", "--- $line [${timestamp()}]")
}
fun clearSshLog() {
_sshLog.value = emptyList()
}
@@ -54,6 +54,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.freeturn.app.R
import com.freeturn.app.data.config.HostPort
import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.domain.ServerState
import com.freeturn.app.domain.SshConnectionState
@@ -124,10 +125,11 @@ fun ServerManagementScreen(
// Ключ валиден: обфускация выкл, 64 hex, или пусто.
val keyOkForApply = obfDraft == ObfProfile.NONE || keyDraft.isBlank() ||
ObfProfile.isValidKey(keyDraft)
val addressesOk = HostPort.isValid(listenFull) && HostPort.isValid(proxyConnect)
// FAB "Применить": только при изменениях и валидном состоянии.
val canApply = serverSettingsAvailable(isConnected, syncOn) &&
configDirty && keyOkForApply && !isWorking
configDirty && keyOkForApply && addressesOk && !isWorking
fun applyConfig() {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
// Активный - apply в живой рантайм (один рестарт). Неактивный - пишем только снимок сервера.
@@ -4,6 +4,7 @@ import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.config.HostPort
import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.data.server.ServerOpts
import com.freeturn.app.data.config.SshConfig
@@ -115,7 +116,7 @@ class ServerViewModel(
viewModelScope.launch {
val l = prefs.proxyListenFlow.first()
val c = prefs.proxyConnectFlow.first()
if (!l.matches(Regex("""^[\w.\-]+:\d{1,5}$""")) || !c.matches(Regex("""^[\w.\-]+:\d{1,5}$"""))) {
if (!HostPort.isValid(l) || !HostPort.isValid(c)) {
sshRepository.updateServerState(ServerState.Error("Неверный формат адреса (ожидается host:port)"))
return@launch
}
@@ -39,7 +39,6 @@ import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeoutOrNull
import java.io.IOException
/** Состояние очистки сервера от FreeTurn (snapshot для диалога). */
@@ -245,13 +244,7 @@ class SettingsViewModel(
}
}
if (ProxyServiceState.isRunning.value) {
proxyManager.stopProxy()
withTimeoutOrNull(2_000) {
ProxyServiceState.isRunning.first { !it }
}
proxyManager.startProxy(target.client)
}
orchestrator.restartProxyIfRunning()
}
}
@@ -372,7 +365,11 @@ class SettingsViewModel(
)
}
if (changed) {
if (sync) orchestrator.restartServerIfRunning()
if (sync) {
orchestrator.restartServerIfRunning()
} else {
sshRepository.logNote("рестарт сервера пропущен: синхронизация выключена")
}
orchestrator.restartProxyIfRunning()
}
}