Restore connections on app foregrounding
Add a process-lifecycle foreground reconnector and pure recovery policy, wiring repository recovery through the validated saved endpoint. Include lifecycle-process and focused unit coverage while preserving explicit Disconnect and stale socket callback guards. Checked packaged templates and packaged authoring skill references: neither documents Android connection lifecycle behavior, so neither needs updating. Shared android README changes are recorded in docs/notes/foreground-reconnect.md for the docs-fold writer.
This commit is contained in:
@@ -1,12 +1,15 @@
|
||||
package net.awan.pipelines
|
||||
|
||||
import android.app.Application
|
||||
import androidx.lifecycle.ProcessLifecycleOwner
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import net.awan.pipelines.data.ForegroundReconnector
|
||||
import net.awan.pipelines.data.PipelinesRepository
|
||||
import net.awan.pipelines.data.SettingsRepository
|
||||
import net.awan.pipelines.data.transport.PipelinesClient
|
||||
import net.awan.pipelines.data.transport.ServerUrl
|
||||
import net.awan.pipelines.notify.RunNotifier
|
||||
|
||||
/**
|
||||
@@ -30,8 +33,39 @@ class PipelinesApplication : Application() {
|
||||
*/
|
||||
val runNotifier: RunNotifier by lazy { RunNotifier(this) }
|
||||
|
||||
/**
|
||||
* The one owner of return-to-foreground recovery: when the process comes back
|
||||
* to the front it restores a connection the background took away, with no
|
||||
* interaction. It is created once with the Application and observes the
|
||||
* process lifecycle, so every Activity and ViewModel recreation leaves it
|
||||
* untouched. The liveness check is the existing `ping`; the reconnect is the
|
||||
* same shared-client connect the app's own Connect/Reconnect uses, so the
|
||||
* policy lives only in `foregroundAction` and the client's backoff stays the
|
||||
* only reconnect mechanism.
|
||||
*/
|
||||
private val foregroundReconnector: ForegroundReconnector by lazy {
|
||||
ForegroundReconnector(
|
||||
state = { repository.connectionState.value },
|
||||
confirmAlive = {
|
||||
// The existing ping is the positive check: on a dead socket it
|
||||
// throws (or never answers) instead of returning, so reaching the
|
||||
// next line is the proof of life.
|
||||
repository.ping()
|
||||
true
|
||||
},
|
||||
reconnect = {
|
||||
// A saved URL that no longer validates is left for Settings to
|
||||
// report; there is nothing to reconnect to.
|
||||
val validated = ServerUrl.validate(settings.serverUrl.value)
|
||||
if (validated.valid) repository.recover(validated)
|
||||
},
|
||||
scope = applicationScope,
|
||||
)
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
runNotifier.ensureChannel()
|
||||
ProcessLifecycleOwner.get().lifecycle.addObserver(foregroundReconnector)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package net.awan.pipelines.data
|
||||
|
||||
import androidx.lifecycle.DefaultLifecycleObserver
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import net.awan.pipelines.data.transport.ConnectionState
|
||||
import net.awan.pipelines.data.transport.ForegroundAction
|
||||
import net.awan.pipelines.data.transport.foregroundAction
|
||||
|
||||
/**
|
||||
* The one lifecycle-aware owner of the app's return-to-foreground recovery.
|
||||
*
|
||||
* While another app is in front Android freezes — and often kills — this process,
|
||||
* so the socket it holds dies or goes quiet and the client's own bounded backoff
|
||||
* either never starts or starts too late for the operator, who comes back and
|
||||
* taps Connect. The client's backoff (see `PipelinesClient.scheduleReconnect`) is
|
||||
* still the only reconnect mechanism; this owner only decides *when* to drive it,
|
||||
* and does so the moment the app becomes visible again.
|
||||
*
|
||||
* It observes the whole process lifecycle (a `ProcessLifecycleOwner`), never the
|
||||
* Activity or the ViewModel, both of which Android recreates: the owner is
|
||||
* created once with the Application and survives every recreation. The decision
|
||||
* itself is the one pure [foregroundAction] policy; this class supplies only the
|
||||
* current state, a positive liveness check and the reconnect effect, so the
|
||||
* policy is unit-testable with no device, socket or framework.
|
||||
*/
|
||||
class ForegroundReconnector(
|
||||
private val state: () -> ConnectionState,
|
||||
private val confirmAlive: suspend () -> Boolean,
|
||||
private val reconnect: () -> Unit,
|
||||
private val scope: CoroutineScope,
|
||||
private val confirmTimeoutMillis: Long = CONFIRM_TIMEOUT_MILLIS,
|
||||
) : DefaultLifecycleObserver {
|
||||
|
||||
/**
|
||||
* The app became visible again. A state the policy calls reconnecting is
|
||||
* reconnected at once — the pending backoff delay is cancelled by the
|
||||
* reconnect effect, so the operator never waits it out. A socket the state
|
||||
* still calls Connected is first confirmed to answer, so a silent
|
||||
* "Connected" is never trusted; the state is re-read afterwards, because the
|
||||
* socket's own failure callback may have run while the check was in flight.
|
||||
*/
|
||||
override fun onStart(owner: LifecycleOwner) {
|
||||
val before = state()
|
||||
if (before !is ConnectionState.Connected) {
|
||||
if (foregroundAction(before, confirmedAlive = false) == ForegroundAction.Reconnect) reconnect()
|
||||
return
|
||||
}
|
||||
scope.launch {
|
||||
val alive = confirm()
|
||||
if (foregroundAction(state(), alive) == ForegroundAction.Reconnect) reconnect()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirms a supposedly-connected socket still answers, bounded so a dead one
|
||||
* cannot hold recovery: the check runs off the main thread on the app scope
|
||||
* and a probe that fails, throws or outlives its budget counts as not alive.
|
||||
*/
|
||||
private suspend fun confirm(): Boolean =
|
||||
withTimeoutOrNull(confirmTimeoutMillis) {
|
||||
try {
|
||||
confirmAlive()
|
||||
} catch (t: Throwable) {
|
||||
if (t is CancellationException) throw t
|
||||
false
|
||||
}
|
||||
} ?: false
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Bounds the liveness check. A healthy round trip on the trusted LAN/VPN
|
||||
* is far shorter, so a socket that cannot answer is noticed promptly
|
||||
* instead of holding the "Connected" the operator is looking at.
|
||||
*/
|
||||
const val CONFIRM_TIMEOUT_MILLIS = 3_000L
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,9 @@ class PipelinesRepository(
|
||||
/** Opens the single shared connection to a validated server URL. */
|
||||
fun connect(validated: ServerUrl.Validated) = client.connect(validated)
|
||||
|
||||
/** Recovers a lost connection without reversing an explicit Disconnect. */
|
||||
fun recover(validated: ServerUrl.Validated) = client.recover(validated)
|
||||
|
||||
/** Explicit disconnect; the client then stays Idle. */
|
||||
fun disconnect() = client.disconnect()
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package net.awan.pipelines.data.transport
|
||||
|
||||
/** What the app does with the connection the moment it becomes visible again. */
|
||||
enum class ForegroundAction {
|
||||
/** Leave the connection exactly as it is. */
|
||||
LeaveAlone,
|
||||
|
||||
/** Re-establish the connection now, cancelling any pending reconnect delay. */
|
||||
Reconnect,
|
||||
}
|
||||
|
||||
/**
|
||||
* The app's return-to-foreground recovery policy, in one pure place.
|
||||
*
|
||||
* Android freezes and often kills a backgrounded app's process, so the socket
|
||||
* the app holds dies or goes quiet while another app is in front and nothing in
|
||||
* the process notices in time. Coming back must restore that connection without
|
||||
* the operator tapping Connect — but an explicit Disconnect is the operator's
|
||||
* own decision and stays authoritative. A deliberate Disconnect is the only way
|
||||
* the client reaches [ConnectionState.Idle], so Idle is left alone; every other
|
||||
* state reconnects.
|
||||
*
|
||||
* A still [ConnectionState.Connected] socket is not trusted on return: a frozen
|
||||
* process can leave it claiming Connected while it answers nothing, which is
|
||||
* exactly the stale state this replaces. The caller therefore checks it with a
|
||||
* positive probe (the existing ping) and passes the verdict as [confirmedAlive];
|
||||
* only a connection just confirmed to answer is left alone.
|
||||
*
|
||||
* @param state the connection state at the moment the app became visible again.
|
||||
* @param confirmedAlive whether a [ConnectionState.Connected] socket has just
|
||||
* been confirmed to answer. It is consulted only for Connected; every other
|
||||
* state carries its own answer.
|
||||
*/
|
||||
fun foregroundAction(state: ConnectionState, confirmedAlive: Boolean): ForegroundAction = when (state) {
|
||||
ConnectionState.Idle -> ForegroundAction.LeaveAlone
|
||||
is ConnectionState.Connected ->
|
||||
if (confirmedAlive) ForegroundAction.LeaveAlone else ForegroundAction.Reconnect
|
||||
is ConnectionState.Connecting -> ForegroundAction.Reconnect
|
||||
is ConnectionState.Disconnected -> ForegroundAction.Reconnect
|
||||
}
|
||||
Reference in New Issue
Block a user