Validate CoreActivity ownership before mutations and cache completed JNI requests

This commit is contained in:
evgeny committed 2026-10-27 20:02:55 +01:00
1 parent 658e69b7d0
commit fcb4eb6fe5
3 files changed
+46 -16

No files matched your search

@@ -2,32 +2,59 @@ package com.utun.chat.data
import android.os.Looper
/** Один расчёт активности ядра: завершение одного владельца не усыпляет остальных. */
/** Main thread: объединяет запросы активности экрана, звонка, приглашения рации и передачи файлов через OR.
* Пока ядро не готово, сохраняет намерение владельцев. Новый SERVICE_STARTED повторно отправляет актуальный запрос.
* Кэш хранит последний нормально завершившийся JNI-вызов, а не подтверждённый режим: ядро применяет команду
* асинхронно и учитывает собственные удержания активности, например трансляции. */
object CoreActivity {
private var visible = false
private var call = false
private var radioCall = false
private var transfer = false
private var applied: Boolean? = null
fun visible(value: Boolean) { visible = value; sync() }
fun call(value: Boolean) { call = value; sync() }
fun radioCall(value: Boolean) { radioCall = value; sync() }
fun transfer(value: Boolean) { transfer = value; sync() }
fun reset() { applied = null }
private var requested: Boolean? = null
fun visible(value: Boolean) { checkMain(); visible = value; sync() }
fun call(value: Boolean) { checkMain(); call = value; sync() }
fun radioCall(value: Boolean) { checkMain(); radioCall = value; sync() }
fun transfer(value: Boolean) { checkMain(); transfer = value; sync() }
/** Сбрасывает только кэш команды: владельцы сохраняются, следующий sync отправит актуальное намерение. */
fun reset() {
checkMain()
requested = null
LogManager.addLog("DEBUG", "Activity", "activity request cache reset")
}
private fun checkMain() {
check(Looper.myLooper() === Looper.getMainLooper()) {
val message = "CoreActivity requires main thread: caller=${Thread.currentThread().name}"
LogManager.addLog("ERROR", "Activity", message)
message
}
}
/** Новый экземпляр ядра ещё не получал состояние владельцев активности. */
fun onCoreStarted() {
check(Looper.myLooper() == Looper.getMainLooper())
applied = null
checkMain()
requested = null
LogManager.addLog("INFO", "Activity", "core started; resynchronizing activity")
sync()
}
fun sync() {
check(Looper.myLooper() == Looper.getMainLooper())
if (!NativeLib.isReady()) { applied = null; return }
checkMain()
if (!NativeLib.isReady()) {
requested = null
LogManager.addLog("DEBUG", "Activity", "activity request deferred: core is not ready")
return
}
val active = visible || call || radioCall || transfer
if (applied == active) return
applied = active
LogManager.addLog("INFO", "Activity", "core active=$active visible=$visible call=$call radioCall=$radioCall transfer=$transfer")
NativeLib.setActive(active)
if (requested == active) return
try {
NativeLib.setActive(active)
} catch (e: Exception) {
LogManager.addLog("ERROR", "Activity", "activity request failed active=$active: ${e.javaClass.simpleName}: ${e.message}")
throw e
}
requested = active
LogManager.addLog("INFO", "Activity", "core activity requested=$active visible=$visible call=$call radioCall=$radioCall transfer=$transfer")
}
}
@@ -95,6 +95,7 @@ object NativeLib {
fun isResponsive(): Boolean = nativeIsResponsive()
/* ── App foreground/background (Android lifecycle) ── */
/** Асинхронный запрос ACTIVE/STANDBY; возврат JNI не подтверждает применение. Фактический режим учитывает stream hold ядра. */
fun setActive(active: Boolean) { nativeSetActive(active) }
/* ── External network activity (ConnectivityManager) ── */
@@ -251,7 +251,9 @@ char* utun_bridge_get_local_sockets_json(void);
void utun_bridge_on_network_change(void);
/* Поставить client_activity в uasync: active!=0 — foreground, 0 — standby. */
/* Поставить запрос client_activity в uasync: active!=0 — ACTIVE, 0 — STANDBY.
* Возврат не подтверждает применение; utun_set_client_activity учитывает удержание трансляций,
* ошибки перехода логирует trampoline в потоке ядра. */
void utun_bridge_set_active(int active);