refactor: startup signal, dedup SSH ops, fix serverState, drop fake delays, backup rules

This commit is contained in:
samosvalishe committed 2026-03-30 13:25:42 +03:00
1 parent 14b1c4fd5e
commit 8a11c3a56e
5 files changed
+84 -84

No files matched your search

+11 -11
View File
@@ -371,13 +371,13 @@ if (showResetDialog) {
| # | Файл | Проблема | Действие | | # | Файл | Проблема | Действие |
|---|---|---|---| |---|---|---|---|
| P2-1 | `MainViewModel.kt:393` | `delay(2500)` + эвристика для определения старта | Добавить dedicated `StateFlow<StartupResult>` в `ProxyService` | | ✅ P2-1 | `MainViewModel.kt:393` | `delay(2500)` + эвристика для определения старта | Добавить dedicated `StateFlow<StartupResult>` в `ProxyService` |
| P2-2 | `MainViewModel.kt:162-335` | Дублирование `SimpleDateFormat` × 5, дублирование SSH-паттерна × 4 | Вынести в `timestamp()` и `runSshOperation()` | | ✅ P2-2 | `MainViewModel.kt:162-335` | Дублирование `SimpleDateFormat` × 5, дублирование SSH-паттерна × 4 | Вынести в `timestamp()` и `runSshOperation()` |
| ✅ P2-3 | `ProxyService.kt:86,41` | `AppPreferences(this@ProxyService)` без `applicationContext` | Заменить на `applicationContext` | | ✅ P2-3 | `ProxyService.kt:86,41` | `AppPreferences(this@ProxyService)` без `applicationContext` | Заменить на `applicationContext` |
| P2-4 | `MainViewModel.kt:203` | `_serverState` зависает в `Checking` при пустом IP | Добавить `_serverState.value = ServerState.Unknown` перед `return` | | ✅ P2-4 | `MainViewModel.kt:203` | `_serverState` зависает в `Checking` при пустом IP | Добавить `_serverState.value = ServerState.Unknown` перед `return` |
| ✅ P2-5 | `ProxyService.kt:139,207,239` | `destroy()` → SIGTERM, нативный процесс может зависнуть | Заменить на `destroyForcibly()` | | ✅ P2-5 | `ProxyService.kt:139,207,239` | `destroy()` → SIGTERM, нативный процесс может зависнуть | Заменить на `destroyForcibly()` |
| P2-6 | `MainViewModel.kt:157` | Фейковый прогресс подключения | Убрать `delay(400)`/`delay(300)`, начинать SSH сразу | | ✅ P2-6 | `MainViewModel.kt:157` | Фейковый прогресс подключения | Убрать `delay(400)`/`delay(300)`, начинать SSH сразу |
| P2-7 | `AppPreferences.kt` | DataStore не исключён из Android Backup | Добавить в `backup_rules.xml` и `data_extraction_rules.xml` | | ✅ P2-7 | `AppPreferences.kt` | DataStore не исключён из Android Backup | Добавить в `backup_rules.xml` и `data_extraction_rules.xml` |
### Приоритет 3 — Средние (производительность / качество) ### Приоритет 3 — Средние (производительность / качество)
@@ -421,12 +421,12 @@ if (showResetDialog) {
✅ P2-3 AppPreferences(applicationContext) в ProxyService и AppPreferences ✅ P2-3 AppPreferences(applicationContext) в ProxyService и AppPreferences
✅ P2-5 destroyForcibly() везде ✅ P2-5 destroyForcibly() везде
Спринт 3 (архитектура и UX): ← СЛЕДУЮЩИЙ Спринт 3 (архитектура и UX): ✅ ГОТОВО
P2-1 Явный сигнал запуска прокси ✅ P2-1 StartupResult StateFlow + withTimeoutOrNull(5s) вместо delay(2500)
P2-2 Дедупликация кода (timestamp, runSshOperation) ✅ P2-2 timestamp() + runSshCommand() — убрано 5× SimpleDateFormat и 6× boilerplate
P2-4 Фикс зависания serverState ✅ P2-4 serverState → Unknown при пустом IP
P2-6 Убрать фейковый прогресс ✅ P2-6 Убраны delay(400)/delay(300) — SSH начинается сразу
P2-7 Backup exclusion для DataStore ✅ P2-7 DataStore исключён из backup_rules.xml и data_extraction_rules.xml
Спринт 3 (архитектура и UX): Спринт 3 (архитектура и UX):
P2-1 Явный сигнал запуска прокси P2-1 Явный сигнал запуска прокси
@@ -30,6 +30,11 @@ import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
sealed class StartupResult {
data object Success : StartupResult()
data class Failed(val message: String) : StartupResult()
}
class ProxyService : Service() { class ProxyService : Service() {
companion object { companion object {
@@ -37,6 +42,7 @@ class ProxyService : Service() {
val isRunning = MutableStateFlow(false) val isRunning = MutableStateFlow(false)
val logs = MutableStateFlow<List<String>>(emptyList()) val logs = MutableStateFlow<List<String>>(emptyList())
val proxyFailed = MutableSharedFlow<Unit>(extraBufferCapacity = 1) val proxyFailed = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
val startupResult = MutableStateFlow<StartupResult?>(null)
fun addLog(msg: String) { fun addLog(msg: String) {
logs.update { (it + msg).takeLast(200) } logs.update { (it + msg).takeLast(200) }
@@ -134,6 +140,7 @@ class ProxyService : Service() {
var exitCode = -1 var exitCode = -1
val startedAt = System.currentTimeMillis() val startedAt = System.currentTimeMillis()
var startupEmitted = false
try { try {
addLog("Команда: ${cmdArgs.joinToString(" ")}") addLog("Команда: ${cmdArgs.joinToString(" ")}")
@@ -148,6 +155,18 @@ class ProxyService : Service() {
val l = line ?: continue val l = line ?: continue
addLog(l) addLog(l)
// P2-1: сигнализируем результат запуска по первой строке stdout
if (!startupEmitted) {
val lower = l.lowercase()
if (lower.contains("panic") || lower.contains("fatal") ||
lower.contains("rate limit")) {
startupResult.value = StartupResult.Failed(l)
} else {
startupResult.value = StartupResult.Success
}
startupEmitted = true
}
// Session Killer: compareAndSet гарантирует что postDelayed вызывается только раз // Session Killer: compareAndSet гарантирует что postDelayed вызывается только раз
// даже если две quota-ошибки придут одновременно из одного потока чтения // даже если две quota-ошибки придут одновременно из одного потока чтения
if (isQuotaError(l) && sessionKillScheduled.compareAndSet(false, true)) { if (isQuotaError(l) && sessionKillScheduled.compareAndSet(false, true)) {
@@ -166,6 +185,10 @@ class ProxyService : Service() {
exitCode = if (proc.waitFor(5, TimeUnit.MINUTES)) proc.exitValue() else -1 exitCode = if (proc.waitFor(5, TimeUnit.MINUTES)) proc.exitValue() else -1
addLog("=== ПРОЦЕСС ОСТАНОВЛЕН (Код: $exitCode) ===") addLog("=== ПРОЦЕСС ОСТАНОВЛЕН (Код: $exitCode) ===")
if (!startupEmitted) {
startupResult.value = StartupResult.Failed(
"Процесс завершился без вывода (код: $exitCode)")
}
} catch (e: Exception) { } catch (e: Exception) {
addLog("КРИТИЧЕСКАЯ ОШИБКА: ${e.message}") addLog("КРИТИЧЕСКАЯ ОШИБКА: ${e.message}")
@@ -8,6 +8,7 @@ import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.freeturn.app.ProxyService import com.freeturn.app.ProxyService
import com.freeturn.app.SSHManager import com.freeturn.app.SSHManager
import com.freeturn.app.StartupResult
import com.freeturn.app.data.AppPreferences import com.freeturn.app.data.AppPreferences
import com.freeturn.app.ui.HapticUtil import com.freeturn.app.ui.HapticUtil
import com.freeturn.app.data.ClientConfig import com.freeturn.app.data.ClientConfig
@@ -18,10 +19,12 @@ 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
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.filterNotNull
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.withContext import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.io.File import java.io.File
// ── SSH connection states ────────────────────────────────────────────────── // ── SSH connection states ──────────────────────────────────────────────────
@@ -93,6 +96,23 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
appendSshLog(" ---") appendSshLog(" ---")
} }
// P2-2: единый форматтер времени вместо 5 копий SimpleDateFormat
private fun timestamp(): String =
java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault())
.format(java.util.Date())
// P2-2: обобщённая SSH-операция — логирование + выполнение + вывод в SSH-лог
private suspend fun runSshCommand(cfg: SshConfig, label: String, cmd: String): String {
appendSshLog("", "=== $label [${timestamp()}] ===")
logCommand("${cfg.username}@${cfg.ip}:${cfg.port}", cmd)
val result = sshManager.executeSilentCommand(
cfg.ip, cfg.port, cfg.username, cfg.password, cmd,
knownFingerprint = cfg.fp, sshKey = cfg.key
)
result.lines().filter { it.isNotBlank() }.forEach { appendSshLog(it) }
return result
}
private val _proxyState = MutableStateFlow<ProxyState>(ProxyState.Idle) private val _proxyState = MutableStateFlow<ProxyState>(ProxyState.Idle)
val proxyState: StateFlow<ProxyState> = _proxyState.asStateFlow() val proxyState: StateFlow<ProxyState> = _proxyState.asStateFlow()
@@ -154,30 +174,16 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
prefs.saveSshConfig(config) prefs.saveSshConfig(config)
} }
sshManager.disconnect() sshManager.disconnect()
_sshState.value = SshConnectionState.Connecting("Подключение к серверу...") // P2-6: сразу начинаем реальное подключение, без фейковых delay(400)/delay(300)
_sshState.value = SshConnectionState.Connecting()
viewModelScope.launch { viewModelScope.launch {
delay(400) val result = runSshCommand(config, "Подключение", "echo OK")
_sshState.value = SshConnectionState.Connecting("Аутентификация...")
delay(300)
_sshState.value = SshConnectionState.Connecting("Проверка SSH...")
val ts = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date())
appendSshLog("", "=== Подключение [$ts] ===")
logCommand("${config.username}@${config.ip}:${config.port}", "echo OK")
val result = sshManager.executeSilentCommand(
config.ip, config.port, config.username, config.password, "echo OK",
knownFingerprint = config.fp, sshKey = config.key
)
appendSshLog(result.trim())
if (result.trim() == "OK") { if (result.trim() == "OK") {
// При первом подключении сохраняем отпечаток хоста
val fp = sshManager.lastSeenFingerprint ?: config.hostFingerprint val fp = sshManager.lastSeenFingerprint ?: config.hostFingerprint
if (config.hostFingerprint.isEmpty()) { if (config.hostFingerprint.isEmpty()) {
sshManager.lastSeenFingerprint?.let { prefs.saveSshFingerprint(it) } sshManager.lastSeenFingerprint?.let { prefs.saveSshFingerprint(it) }
} }
// Кешируем полный конфиг (включая пароль) в памяти, чтобы
// installServer/startServer/stopServer не зависели от EncryptedSharedPreferences
activeSshConfig = config.copy(hostFingerprint = fp) activeSshConfig = config.copy(hostFingerprint = fp)
HapticUtil.perform(getApplication(), HapticUtil.Pattern.SUCCESS) HapticUtil.perform(getApplication(), HapticUtil.Pattern.SUCCESS)
_sshState.value = SshConnectionState.Connected(config.ip) _sshState.value = SshConnectionState.Connected(config.ip)
@@ -197,8 +203,6 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
} }
fun reconnectSsh() { fun reconnectSsh() {
// sshConfig.value может быть пустым если HomeScreen не подписывается на flow —
// в таком случае читаем конфиг напрямую из DataStore
viewModelScope.launch { viewModelScope.launch {
val cfg = activeSshConfig val cfg = activeSshConfig
?: sshConfig.value.takeIf { it.ip.isNotEmpty() } ?: sshConfig.value.takeIf { it.ip.isNotEmpty() }
@@ -211,7 +215,11 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
fun checkServerState(config: SshConfig? = null) { fun checkServerState(config: SshConfig? = null) {
val cfg = config ?: activeSshConfig ?: sshConfig.value val cfg = config ?: activeSshConfig ?: sshConfig.value
if (cfg.ip.isEmpty()) return // P2-4: сброс в Unknown вместо зависания в Checking при пустом IP
if (cfg.ip.isEmpty()) {
_serverState.value = ServerState.Unknown
return
}
_serverState.value = ServerState.Checking _serverState.value = ServerState.Checking
val checkCmd = """ val checkCmd = """
@@ -220,12 +228,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
""".trimIndent() """.trimIndent()
viewModelScope.launch { viewModelScope.launch {
val ts = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date()) val result = runSshCommand(cfg, "Проверка состояния", checkCmd)
appendSshLog("", "=== Проверка состояния [$ts] ===")
logCommand("${cfg.username}@${cfg.ip}:${cfg.port}", checkCmd)
val result = sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, checkCmd,
knownFingerprint = cfg.fp, sshKey = cfg.key)
result.lines().filter { it.isNotBlank() }.forEach { appendSshLog(it) }
_serverState.value = if (result.startsWith("ERROR")) { _serverState.value = if (result.startsWith("ERROR")) {
ServerState.Error(result.removePrefix("ERROR: ")) ServerState.Error(result.removePrefix("ERROR: "))
} else { } else {
@@ -301,12 +304,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
""".trimIndent() """.trimIndent()
viewModelScope.launch { viewModelScope.launch {
val ts = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date()) val result = runSshCommand(cfg, "Установка", script)
appendSshLog("", "=== Установка [$ts] ===")
logCommand("${cfg.username}@${cfg.ip}:${cfg.port}", script)
val result = sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, script,
knownFingerprint = cfg.fp, sshKey = cfg.key)
result.lines().filter { it.isNotBlank() }.forEach { appendSshLog(it) }
if (!result.contains("DONE")) { if (!result.contains("DONE")) {
val errorMsg = result.lines() val errorMsg = result.lines()
.filter { it.isNotBlank() } .filter { it.isNotBlank() }
@@ -337,12 +335,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
""".trimIndent() """.trimIndent()
viewModelScope.launch { viewModelScope.launch {
val ts = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date()) runSshCommand(cfg, "Запуск", script)
appendSshLog("", "=== Запуск [$ts] ===")
logCommand("${cfg.username}@${cfg.ip}:${cfg.port}", script)
val result = sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, script,
knownFingerprint = cfg.fp, sshKey = cfg.key)
result.lines().filter { it.isNotBlank() }.forEach { appendSshLog(it) }
delay(2000) delay(2000)
checkServerState(cfg) checkServerState(cfg)
} }
@@ -361,12 +354,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
""".trimIndent() """.trimIndent()
viewModelScope.launch { viewModelScope.launch {
val ts = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date()) runSshCommand(cfg, "Остановка", script)
appendSshLog("", "=== Остановка [$ts] ===")
logCommand("${cfg.username}@${cfg.ip}:${cfg.port}", script)
val result = sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, script,
knownFingerprint = cfg.fp, sshKey = cfg.key)
result.lines().filter { it.isNotBlank() }.forEach { appendSshLog(it) }
delay(2000) delay(2000)
checkServerState(cfg) checkServerState(cfg)
} }
@@ -378,14 +366,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
_serverLogs.value = "…" _serverLogs.value = "…"
val logCmd = "tail -n 80 /opt/vk-turn/server.log 2>/dev/null || echo '(лог пуст)'" val logCmd = "tail -n 80 /opt/vk-turn/server.log 2>/dev/null || echo '(лог пуст)'"
viewModelScope.launch { viewModelScope.launch {
val ts = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date()) val out = runSshCommand(cfg, "server.log", logCmd)
appendSshLog("", "=== server.log [$ts] ===")
logCommand("${cfg.username}@${cfg.ip}:${cfg.port}", logCmd)
val out = sshManager.executeSilentCommand(
cfg.ip, cfg.port, cfg.username, cfg.password, logCmd,
knownFingerprint = cfg.fp, sshKey = cfg.key
)
out.lines().filter { it.isNotBlank() }.forEach { appendSshLog(it) }
_serverLogs.value = out.trim().ifEmpty { "(лог пуст)" } _serverLogs.value = out.trim().ifEmpty { "(лог пуст)" }
} }
} }
@@ -397,10 +378,8 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
fun startProxy(context: Context) { fun startProxy(context: Context) {
if (ProxyService.isRunning.value) return if (ProxyService.isRunning.value) return
// Сброс предыдущей ошибки перед повторной попыткой
if (_proxyState.value is ProxyState.Error) _proxyState.value = ProxyState.Idle if (_proxyState.value is ProxyState.Error) _proxyState.value = ProxyState.Idle
// Валидация конфига до запуска
val cfg = clientConfig.value val cfg = clientConfig.value
if (!cfg.isRawMode && (cfg.serverAddress.isBlank() || cfg.vkLink.isBlank())) { if (!cfg.isRawMode && (cfg.serverAddress.isBlank() || cfg.vkLink.isBlank())) {
setErrorWithAutoReset("Не заполнены настройки клиента") setErrorWithAutoReset("Не заполнены настройки клиента")
@@ -414,34 +393,27 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
_proxyState.value = ProxyState.Starting _proxyState.value = ProxyState.Starting
viewModelScope.launch { viewModelScope.launch {
// Сохраняем актуальный конфиг в DataStore — ProxyService читает его напрямую
prefs.saveClientConfig(cfg) prefs.saveClientConfig(cfg)
ProxyService.logs.value = emptyList() ProxyService.logs.value = emptyList()
ProxyService.startupResult.value = null
context.startForegroundService(Intent(context, ProxyService::class.java)) context.startForegroundService(Intent(context, ProxyService::class.java))
// Ждём запуска: проверяем логи на ошибку или успех вместо простого isRunning // P2-1: ожидаем явного сигнала от ProxyService вместо delay(2500) + эвристики
delay(2500) val result = withTimeoutOrNull(5_000L) {
ProxyService.startupResult.filterNotNull().first()
}
// Если proxyFailed уже обработал ошибку — не дублируем // Если proxyFailed уже обработал ошибку — не дублируем
if (_proxyState.value is ProxyState.Error) return@launch if (_proxyState.value is ProxyState.Error) return@launch
val logText = ProxyService.logs.value.joinToString("\n").lowercase()
when { when (result) {
!ProxyService.isRunning.value -> null -> setErrorWithAutoReset("Прокси не запустился")
setErrorWithAutoReset("Прокси не запустился") is StartupResult.Failed -> {
logText.contains("panic") || logText.contains("fatal") ||
logText.contains("rate limit") || logText.contains("критическая") -> {
context.stopService(Intent(context, ProxyService::class.java)) context.stopService(Intent(context, ProxyService::class.java))
val errorLine = ProxyService.logs.value setErrorWithAutoReset(result.message)
.lastOrNull { line ->
val l = line.lowercase()
l.contains("error") || l.contains("ошибка") ||
l.contains("panic") || l.contains("fatal") ||
l.contains("критическая")
} }
setErrorWithAutoReset(errorLine ?: "Ошибка запуска — проверьте настройки") is StartupResult.Success -> _proxyState.value = ProxyState.Running
}
else ->
_proxyState.value = ProxyState.Running
} }
} }
} }
+2
View File
@@ -3,4 +3,6 @@
<full-backup-content> <full-backup-content>
<exclude domain="sharedpref" path="secure_ssh_prefs.xml"/> <exclude domain="sharedpref" path="secure_ssh_prefs.xml"/>
<exclude domain="sharedpref" path="ProxyPrefs.xml"/> <exclude domain="sharedpref" path="ProxyPrefs.xml"/>
<!-- DataStore содержит SSH IP, порт, конфиг клиента — не бэкапим -->
<exclude domain="file" path="datastore/"/>
</full-backup-content> </full-backup-content>
@@ -5,9 +5,12 @@
<exclude domain="sharedpref" path="secure_ssh_prefs.xml"/> <exclude domain="sharedpref" path="secure_ssh_prefs.xml"/>
<!-- Конфиг прокси содержит VK/Yandex ссылку — не бэкапим --> <!-- Конфиг прокси содержит VK/Yandex ссылку — не бэкапим -->
<exclude domain="sharedpref" path="ProxyPrefs.xml"/> <exclude domain="sharedpref" path="ProxyPrefs.xml"/>
<!-- DataStore содержит SSH IP, порт, конфиг клиента -->
<exclude domain="file" path="datastore/"/>
</cloud-backup> </cloud-backup>
<device-transfer> <device-transfer>
<exclude domain="sharedpref" path="secure_ssh_prefs.xml"/> <exclude domain="sharedpref" path="secure_ssh_prefs.xml"/>
<exclude domain="sharedpref" path="ProxyPrefs.xml"/> <exclude domain="sharedpref" path="ProxyPrefs.xml"/>
<exclude domain="file" path="datastore/"/>
</device-transfer> </device-transfer>
</data-extraction-rules> </data-extraction-rules>