fix(service): события ядра и сети адресованы своей сессии
This commit is contained in:
1 parent
2305ae0127
commit
28506b0263
3 files changed
+35
-29
No files matched your search
@@ -170,29 +170,25 @@ class ProxyEngine(
|
||||
/**
|
||||
* Устройство проснулось: стримы бросают backoff и пересоздают TURN-аллокации,
|
||||
* не дожидаясь гэп-детектора ядра (тик 30 c) и тем более провалов ChannelBind.
|
||||
*
|
||||
* Мимо [lock]: ядро само проверяет, есть ли живая сессия, а ждать за локом
|
||||
* долгий `start`/`stop` смысла нет - к их концу пинок уже неактуален.
|
||||
*/
|
||||
fun wake() {
|
||||
if (running == 0L) return
|
||||
scope.launch {
|
||||
runCatching { Mobile.wake() }
|
||||
.onFailure { log.add("Пробуждение ядра не удалось: ${it.message}", LogLevel.Warning) }
|
||||
}
|
||||
}
|
||||
fun wake(session: Long) = onSession(session, "Пробуждение ядра") { Mobile.wake() }
|
||||
|
||||
/**
|
||||
* Смена сети: аллокации пересоздаются, туннель и tun-дескриптор остаются.
|
||||
* Пустой [dnsServers] оставляет текущие резолверы.
|
||||
*/
|
||||
fun reconnect(dnsServers: String) {
|
||||
if (running == 0L) return
|
||||
fun reconnect(session: Long, dnsServers: String) = onSession(session, "Переподключение") {
|
||||
Mobile.setDNSServers(dnsServers)
|
||||
Mobile.reconnect()
|
||||
}
|
||||
|
||||
private fun onSession(session: Long, what: String, call: () -> Unit) {
|
||||
if (running != session) return
|
||||
scope.launch {
|
||||
runCatching {
|
||||
Mobile.setDNSServers(dnsServers)
|
||||
Mobile.reconnect()
|
||||
}.onFailure { log.add("Переподключение не удалось: ${it.message}", LogLevel.Warning) }
|
||||
lock.withLock {
|
||||
if (running != session) return@withLock
|
||||
runCatching(call).onFailure { log.add("$what не удалось: ${it.message}", LogLevel.Warning) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,8 +217,9 @@ class ProxyEngine(
|
||||
private inner class CoreEventSink : EventSink {
|
||||
|
||||
override fun onState(state: String, streams: Long, total: Long, errMsg: String) {
|
||||
if (running == 0L) return
|
||||
store.setPhase(state.toPhase(), streams.toInt(), total.toInt(), errMsg)
|
||||
val session = running
|
||||
if (session == 0L) return
|
||||
store.setPhase(session, state.toPhase(), streams.toInt(), total.toInt(), errMsg)
|
||||
}
|
||||
|
||||
override fun onLog(level: String, msg: String, unixMillis: Long) {
|
||||
|
||||
@@ -34,12 +34,13 @@ class ProxyStore {
|
||||
|
||||
// Ошибка именно ОТ ЯДРА, а не любая красная фаза: fail() зовут и снаружи сессии
|
||||
// (отказ от VPN-согласия в трамплине, отлуп startForegroundService), а хост по такой
|
||||
// ошибке сворачивал бы живую чужую сессию.
|
||||
private val _coreErrors = MutableSharedFlow<String>(
|
||||
// ошибке сворачивал бы живую чужую сессию. Id сессии - ошибка из буфера могла
|
||||
// дождаться сборщика уже после рестарта.
|
||||
private val _coreErrors = MutableSharedFlow<CoreError>(
|
||||
extraBufferCapacity = 8,
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST
|
||||
)
|
||||
val coreErrors: SharedFlow<String> = _coreErrors.asSharedFlow()
|
||||
val coreErrors: SharedFlow<CoreError> = _coreErrors.asSharedFlow()
|
||||
|
||||
private val captchaSeq = AtomicLong(0)
|
||||
// Поколение показанной ошибки: таймер гасит только свою. Ошибки приходят из горутин
|
||||
@@ -70,11 +71,11 @@ class ProxyStore {
|
||||
scheduleErrorReset(generation)
|
||||
}
|
||||
|
||||
/** Фаза от ядра. Момент подключения ставится один раз - рестарт его не сбивает. */
|
||||
fun setPhase(phase: ProxyPhase, active: Int, total: Int, error: String = "") {
|
||||
/** Фаза от ядра сессии [session]. Момент подключения ставится один раз - рестарт его не сбивает. */
|
||||
fun setPhase(session: Long, phase: ProxyPhase, active: Int, total: Int, error: String = "") {
|
||||
if (phase == ProxyPhase.Error) {
|
||||
scheduleErrorReset(errorSeq.incrementAndGet())
|
||||
_coreErrors.tryEmit(error)
|
||||
_coreErrors.tryEmit(CoreError(session, error))
|
||||
}
|
||||
_status.update {
|
||||
val connected = if (phase == ProxyPhase.Connected) {
|
||||
@@ -109,3 +110,5 @@ class ProxyStore {
|
||||
const val ERROR_RESET_MS = 4_000L
|
||||
}
|
||||
}
|
||||
|
||||
data class CoreError(val session: Long, val message: String)
|
||||
@@ -89,7 +89,7 @@ class ProxyService : VpnService() {
|
||||
// Длительность сна - опора при разборе отвалов: по ней видно, пережила ли
|
||||
// аллокация паузу и не мы ли сами её выбросили.
|
||||
log.add("Пробуждение после сна ${gap / 1000} c - будим ядро")
|
||||
engine.wake()
|
||||
if (!stopping) engine.wake(session)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,9 +319,15 @@ class ProxyService : VpnService() {
|
||||
if (stopping || !engine.isRunning) return
|
||||
val slept = (SystemClock.elapsedRealtime() - SystemClock.uptimeMillis() - sleptMillis) / 1000
|
||||
log.add("Смена сети - переподключение (сон с прошлой проверки $slept c)")
|
||||
withCoreDns { session, dns -> engine.reconnect(session, dns) }
|
||||
}
|
||||
|
||||
private fun withCoreDns(apply: (session: Long, dns: String) -> Unit) {
|
||||
val session = this.session
|
||||
scope.launch {
|
||||
val cfg = prefs.clientConfigFlow.first()
|
||||
engine.reconnect(cfg.coreDnsServers { network.physicalDnsServers() }.joinToString(","))
|
||||
if (!isCurrent(session)) return@launch
|
||||
apply(session, cfg.coreDnsServers { network.physicalDnsServers() }.joinToString(","))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,9 +341,9 @@ class ProxyService : VpnService() {
|
||||
}
|
||||
|
||||
private suspend fun observeCoreErrors() {
|
||||
store.coreErrors.collect { message ->
|
||||
if (stopping || session == 0L) return@collect
|
||||
shutdown("ошибка ядра: $message")
|
||||
store.coreErrors.collect { error ->
|
||||
if (!isCurrent(error.session)) return@collect
|
||||
shutdown("ошибка ядра: ${error.message}")
|
||||
stopSelf(lastStartId)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user