SyncOutcomeReason.kt

10.5 KB · raw

1package com.peachpasswords.sync23import kotlinx.serialization.Serializable45/**6 * Why a sync attempt ended, in the same vocabulary the browser uses7 * (`src/shared/sync-outcome.ts`). June runs both clients side by side, so the8 * names, the state machine and the user-facing wording are deliberately kept9 * identical; only the Kotlin spelling differs.10 *11 * Before this existed Android had [SyncOutcomeSummary]'s ancestor `SyncStatus`,12 * whose `LastSynced` was set the instant the sync *service* was asked to start13 * — a claim of success it had not earned. Every real failure below it was14 * swallowed by the reconnect loop's `runCatching`, so "synced fine", "the peer15 * refused us" and "the vault was locked" were one indistinguishable state.16 *17 * One browser outcome is deliberately absent, because on Android it names a18 * state that cannot occur: `runner_unavailable` — the browser injects its19 * per-device sync runner and can find it missing. Android's runner is20 * [PeachSyncService], which is always present; the only way it fails to run is21 * a locked vault, which is [VAULT_LOCKED].22 *23 * [FOREGROUND_START_BLOCKED] is the other way round — Android-only, with no24 * browser counterpart, because only Android can refuse to start the runner at25 * all (background foreground-service restrictions, API 31+).26 *27 * `no_eligible_host` is kept but means something narrower than the browser's:28 * the browser rejects peers it cannot dial, whereas this phone usually *waits*29 * and can talk to any peer type. What it cannot talk to is a peer with no30 * rendezvous secret, which the reconnect loop skips in silence. See31 * [weDialPeer] for why the roles differ.32 */33enum class SyncOutcomeReason {34    COMPLETED_CHANGES,35    COMPLETED_NO_CHANGES,36    NO_PAIRED_DEVICES,37    NO_ELIGIBLE_HOST,38    SYNC_DISABLED,39    PRIVATE_RELAY_UNSET,40    VAULT_LOCKED,41    FOREGROUND_START_BLOCKED,42    RELAY_UNREACHABLE,43    HANDSHAKE_FAILED,44    VAULT_ID_MISMATCH,45    PEER_PROTOCOL_OUTDATED,46    SYNC_TIMEOUT,47    CONNECTION_LOST,48    RUN_FAILED,49    ;5051    /** The browser's snake_case spelling, for the screens that carry a code. */52    fun wire(): String = name.lowercase()5354    /** Outcomes where sync did not do what was asked, so the light goes red. */55    val isFailure: Boolean56        get() = when (this) {57            NO_ELIGIBLE_HOST,58            PRIVATE_RELAY_UNSET,59            FOREGROUND_START_BLOCKED,60            VAULT_ID_MISMATCH,61            PEER_PROTOCOL_OUTDATED,62            RUN_FAILED,63            -> true6465            COMPLETED_CHANGES,66            COMPLETED_NO_CHANGES,67            NO_PAIRED_DEVICES,68            SYNC_DISABLED,69            VAULT_LOCKED,70            RELAY_UNREACHABLE,71            HANDSHAKE_FAILED,72            SYNC_TIMEOUT,73            CONNECTION_LOST,74            -> false75        }7677    /**78     * Network-class outcomes — the dial did not reach the peer this attempt.79     * The background reconnect loop keeps trying, so the light goes amber80     * rather than red. Mirrors the browser's WARN tier.81     */82    val isWarning: Boolean83        get() = when (this) {84            RELAY_UNREACHABLE,85            HANDSHAKE_FAILED,86            SYNC_TIMEOUT,87            CONNECTION_LOST,88            VAULT_LOCKED,89            -> true9091            else -> false92        }93}9495/**96 * The last sync attempt, whatever happened. Persisted by [SyncOutcomeStore] so97 * a failure that happened before the process was killed is still explicable —98 * a reason that vanishes is useless for diagnosing real hardware.99 */100@Serializable101data class SyncOutcomeSummary(102    val reason: SyncOutcomeReason? = null,103    /** Raw internal code, or the peer inventory behind [SyncOutcomeReason.NO_ELIGIBLE_HOST]. */104    val detail: String? = null,105    val entriesSent: Int = 0,106    val entriesReceived: Int = 0,107    /** When the attempt ended, success or not. */108    val finishedAt: Long? = null,109    /** In flight right now. Transient by definition, so never persisted. */110    val syncing: Boolean = false,111)112113/**114 * The one indicator light. [BUSY] pulses green, [OK] is solid green, [WARN] is115 * amber (a transient network miss — the background loop retries), [ERROR] is116 * red (the app is actually broken), [IDLE] is unlit. Nothing that is actually117 * broken may resolve to [OK] — a paired-but-unsyncable device is red, not118 * green.119 */120enum class SyncIndicator { BUSY, OK, WARN, ERROR, IDLE }121122fun syncIndicator(summary: SyncOutcomeSummary, pairedCount: Int): SyncIndicator {123    if (summary.syncing) return SyncIndicator.BUSY124    val reason = summary.reason125    if (reason != null && reason.isWarning) return SyncIndicator.WARN126    if (reason != null && reason.isFailure) return SyncIndicator.ERROR127    if (reason == SyncOutcomeReason.COMPLETED_CHANGES ||128        reason == SyncOutcomeReason.COMPLETED_NO_CHANGES129    ) {130        return SyncIndicator.OK131    }132    // Paired with a healthy history but nothing attempted since launch: still a133    // successful pair, which is what the light is claiming.134    if (pairedCount > 0 && reason == null) return SyncIndicator.OK135    return SyncIndicator.IDLE136}137138private fun indicatorHeadline(indicator: SyncIndicator): String = when (indicator) {139    SyncIndicator.BUSY -> "Syncing"140    SyncIndicator.OK -> "Sync healthy"141    SyncIndicator.WARN -> "Last sync attempt missed — will retry"142    SyncIndicator.ERROR -> "Sync problem"143    SyncIndicator.IDLE -> "Not syncing"144}145146/** Colour alone is never the signal — this is the same claim in words. */147fun syncIndicatorLabel(indicator: SyncIndicator, summary: SyncOutcomeSummary): String =148    "${indicatorHeadline(indicator)} — ${describeSyncOutcome(summary)}"149150/**151 * One plain-English line for a sync outcome, word for word the browser's copy.152 * [SyncOutcomeSummary.detail] is appended rather than hidden: on a real handset153 * it is the whole diagnostic, and there is no devtools to fall back on.154 */155fun describeSyncOutcome(summary: SyncOutcomeSummary): String {156    val reason = summary.reason ?: return "Not synced yet"157    val base = when (reason) {158        SyncOutcomeReason.COMPLETED_CHANGES -> "Synced"159        SyncOutcomeReason.COMPLETED_NO_CHANGES -> "Up to date — nothing to send or receive"160        SyncOutcomeReason.NO_PAIRED_DEVICES -> "No devices paired yet"161        SyncOutcomeReason.NO_ELIGIBLE_HOST -> "Paired, but no device here can accept a sync"162        SyncOutcomeReason.SYNC_DISABLED -> "Sync is switched off"163        SyncOutcomeReason.PRIVATE_RELAY_UNSET -> "Private relay chosen but no address set"164        SyncOutcomeReason.VAULT_LOCKED -> "Vault was locked — unlock and sync again"165        SyncOutcomeReason.FOREGROUND_START_BLOCKED ->166            "Android blocked Peach from starting sync in the background — open Peach and sync again"167        SyncOutcomeReason.RELAY_UNREACHABLE -> "Couldn't reach the relay"168        SyncOutcomeReason.HANDSHAKE_FAILED -> "Reached the relay, but the device didn't answer"169        SyncOutcomeReason.VAULT_ID_MISMATCH -> "That device holds a different vault"170        SyncOutcomeReason.PEER_PROTOCOL_OUTDATED -> "Your other device needs to update before it can sync"171        SyncOutcomeReason.SYNC_TIMEOUT -> "The device stopped responding mid-sync"172        SyncOutcomeReason.CONNECTION_LOST -> "The connection dropped mid-sync — will retry"173        SyncOutcomeReason.RUN_FAILED -> "Sync failed"174    }175    if (reason == SyncOutcomeReason.COMPLETED_CHANGES) {176        val moved = listOfNotNull(177            "${summary.entriesSent} sent".takeIf { summary.entriesSent > 0 },178            "${summary.entriesReceived} received".takeIf { summary.entriesReceived > 0 },179        )180        return if (moved.isEmpty()) base else "$base — ${moved.joinToString(", ")}"181    }182    return summary.detail?.let { "$base ($it)" } ?: base183}184185/**186 * Session errors reach us as opaque strings by contract ([SyncOutcome.error]187 * and any throw out of the relay socket). Classifying them in one place is what188 * lets the copy above key off something stable.189 */190internal fun classifySyncError(error: String): SyncOutcomeReason = when {191    error.contains("VAULT_LOCKED") -> SyncOutcomeReason.VAULT_LOCKED192    error.contains("vault_id_mismatch") -> SyncOutcomeReason.VAULT_ID_MISMATCH193    error.contains("PEER_PROTOCOL_OUTDATED") -> SyncOutcomeReason.PEER_PROTOCOL_OUTDATED194    error.contains("timed out") || error.contains("sync_timeout") -> SyncOutcomeReason.SYNC_TIMEOUT195    // A KK failure, a mismatched PAIR_IDENTITY or a wrong room all mean the196    // relay was fine and the peer was not who we expected.197    Regex("handshake|PAIR_IDENTITY|identity does not match|capability does not match|clock-skew")198        .containsMatchIn(error) -> SyncOutcomeReason.HANDSHAKE_FAILED199    // A hang-up after a successful dial is a connection-lost, not a relay200    // problem — checked before the broad relay/websocket regex below so it201    // doesn't get swallowed into RELAY_UNREACHABLE. The browser does the same202    // narrow check.203    isConnectionClosedError(error) -> SyncOutcomeReason.CONNECTION_LOST204    Regex("relay_|websocket|Connection|connect|socket|Unable to resolve host", RegexOption.IGNORE_CASE)205        .containsMatchIn(error) -> SyncOutcomeReason.RELAY_UNREACHABLE206    else -> SyncOutcomeReason.RUN_FAILED207}208209/**210 * A transport that hung up, as opposed to a protocol or vault problem.211 * Mirrors `isConnectionClosedError` in the browser's sync-outcome.ts; the two212 * must stay in lockstep so a close on either side maps to the same outcome.213 */214internal fun isConnectionClosedError(error: String): Boolean =215    Regex("websocket closed|connection closed|Socket closed", RegexOption.IGNORE_CASE)216        .containsMatchIn(error)217218/**219 * Translate one finished session ([SyncCoordinator]'s per-round result) into the220 * user-facing vocabulary. Tombstones count as changes: a deletion that crossed221 * the wire is not "nothing to send or receive".222 */223internal fun SyncOutcome.toSummary(): SyncOutcomeSummary = when (status) {224    SyncOutcomeStatus.COMPLETED -> SyncOutcomeSummary(225        reason = if (entriesSent + entriesReceived + tombstonesSent + tombstonesReceived > 0) {226            SyncOutcomeReason.COMPLETED_CHANGES227        } else {228            SyncOutcomeReason.COMPLETED_NO_CHANGES229        },230        entriesSent = entriesSent,231        entriesReceived = entriesReceived,232    )233234    SyncOutcomeStatus.VAULT_MISMATCH ->235        SyncOutcomeSummary(reason = SyncOutcomeReason.VAULT_ID_MISMATCH, detail = error)236237    SyncOutcomeStatus.TIMEOUT ->238        SyncOutcomeSummary(reason = SyncOutcomeReason.SYNC_TIMEOUT, detail = error)239240    SyncOutcomeStatus.ERRORED -> SyncOutcomeSummary(241        reason = classifySyncError(error ?: "sync_failed"),242        detail = error,243    )244}