SyncOutcomeReason.kt

10.9 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    RESET_REQUIRED,47    SYNC_GENERATION_UNKNOWN,48    SYNC_TIMEOUT,49    CONNECTION_LOST,50    RUN_FAILED,51    ;5253    /** The browser's snake_case spelling, for the screens that carry a code. */54    fun wire(): String = name.lowercase()5556    /** Outcomes where sync did not do what was asked, so the light goes red. */57    val isFailure: Boolean58        get() = when (this) {59            NO_ELIGIBLE_HOST,60            PRIVATE_RELAY_UNSET,61            FOREGROUND_START_BLOCKED,62            VAULT_ID_MISMATCH,63            PEER_PROTOCOL_OUTDATED,64            RESET_REQUIRED,65            SYNC_GENERATION_UNKNOWN,66            RUN_FAILED,67            -> true6869            COMPLETED_CHANGES,70            COMPLETED_NO_CHANGES,71            NO_PAIRED_DEVICES,72            SYNC_DISABLED,73            VAULT_LOCKED,74            RELAY_UNREACHABLE,75            HANDSHAKE_FAILED,76            SYNC_TIMEOUT,77            CONNECTION_LOST,78            -> false79        }8081    /**82     * Network-class outcomes — the dial did not reach the peer this attempt.83     * The background reconnect loop keeps trying, so the light goes amber84     * rather than red. Mirrors the browser's WARN tier.85     */86    val isWarning: Boolean87        get() = when (this) {88            RELAY_UNREACHABLE,89            HANDSHAKE_FAILED,90            SYNC_TIMEOUT,91            CONNECTION_LOST,92            VAULT_LOCKED,93            -> true9495            else -> false96        }97}9899/**100 * The last sync attempt, whatever happened. Persisted by [SyncOutcomeStore] so101 * a failure that happened before the process was killed is still explicable —102 * a reason that vanishes is useless for diagnosing real hardware.103 */104@Serializable105data class SyncOutcomeSummary(106    val reason: SyncOutcomeReason? = null,107    /** Raw internal code, or the peer inventory behind [SyncOutcomeReason.NO_ELIGIBLE_HOST]. */108    val detail: String? = null,109    val entriesSent: Int = 0,110    val entriesReceived: Int = 0,111    /** When the attempt ended, success or not. */112    val finishedAt: Long? = null,113    /** In flight right now. Transient by definition, so never persisted. */114    val syncing: Boolean = false,115)116117/**118 * The one indicator light. [BUSY] pulses green, [OK] is solid green, [WARN] is119 * amber (a transient network miss — the background loop retries), [ERROR] is120 * red (the app is actually broken), [IDLE] is unlit. Nothing that is actually121 * broken may resolve to [OK] — a paired-but-unsyncable device is red, not122 * green.123 */124enum class SyncIndicator { BUSY, OK, WARN, ERROR, IDLE }125126fun syncIndicator(summary: SyncOutcomeSummary, pairedCount: Int): SyncIndicator {127    if (summary.syncing) return SyncIndicator.BUSY128    val reason = summary.reason129    if (reason != null && reason.isWarning) return SyncIndicator.WARN130    if (reason != null && reason.isFailure) return SyncIndicator.ERROR131    if (reason == SyncOutcomeReason.COMPLETED_CHANGES ||132        reason == SyncOutcomeReason.COMPLETED_NO_CHANGES133    ) {134        return SyncIndicator.OK135    }136    // Paired with a healthy history but nothing attempted since launch: still a137    // successful pair, which is what the light is claiming.138    if (pairedCount > 0 && reason == null) return SyncIndicator.OK139    return SyncIndicator.IDLE140}141142private fun indicatorHeadline(indicator: SyncIndicator): String = when (indicator) {143    SyncIndicator.BUSY -> "Syncing"144    SyncIndicator.OK -> "Sync healthy"145    SyncIndicator.WARN -> "Last sync attempt missed — will retry"146    SyncIndicator.ERROR -> "Sync problem"147    SyncIndicator.IDLE -> "Not syncing"148}149150/** Colour alone is never the signal — this is the same claim in words. */151fun syncIndicatorLabel(indicator: SyncIndicator, summary: SyncOutcomeSummary): String =152    "${indicatorHeadline(indicator)} — ${describeSyncOutcome(summary)}"153154/**155 * One plain-English line for a sync outcome, word for word the browser's copy.156 * [SyncOutcomeSummary.detail] is appended rather than hidden: on a real handset157 * it is the whole diagnostic, and there is no devtools to fall back on.158 */159fun describeSyncOutcome(summary: SyncOutcomeSummary): String {160    val reason = summary.reason ?: return "Not synced yet"161    val base = when (reason) {162        SyncOutcomeReason.COMPLETED_CHANGES -> "Synced"163        SyncOutcomeReason.COMPLETED_NO_CHANGES -> "Up to date — nothing to send or receive"164        SyncOutcomeReason.NO_PAIRED_DEVICES -> "No devices paired yet"165        SyncOutcomeReason.NO_ELIGIBLE_HOST -> "Paired, but no device here can accept a sync"166        SyncOutcomeReason.SYNC_DISABLED -> "Sync is switched off"167        SyncOutcomeReason.PRIVATE_RELAY_UNSET -> "Private relay chosen but no address set"168        SyncOutcomeReason.VAULT_LOCKED -> "Vault was locked — unlock and sync again"169        SyncOutcomeReason.FOREGROUND_START_BLOCKED ->170            "Android blocked Peach from starting sync in the background — open Peach and sync again"171        SyncOutcomeReason.RELAY_UNREACHABLE -> "Couldn't reach the relay"172        SyncOutcomeReason.HANDSHAKE_FAILED -> "Reached the relay, but the device didn't answer"173        SyncOutcomeReason.VAULT_ID_MISMATCH -> "That device holds a different vault"174        SyncOutcomeReason.PEER_PROTOCOL_OUTDATED ->175            "Update Peach on both devices, then re-pair them"176        SyncOutcomeReason.RESET_REQUIRED ->177            "Sync is reset on this device — update Peach everywhere, then re-pair each device"178        SyncOutcomeReason.SYNC_GENERATION_UNKNOWN ->179            "This device's sync generation is unreadable — sync is stopped"180        SyncOutcomeReason.SYNC_TIMEOUT -> "The device stopped responding mid-sync"181        SyncOutcomeReason.CONNECTION_LOST -> "The connection dropped mid-sync — will retry"182        SyncOutcomeReason.RUN_FAILED -> "Sync failed"183    }184    if (reason == SyncOutcomeReason.COMPLETED_CHANGES) {185        val moved = listOfNotNull(186            "${summary.entriesSent} sent".takeIf { summary.entriesSent > 0 },187            "${summary.entriesReceived} received".takeIf { summary.entriesReceived > 0 },188        )189        return if (moved.isEmpty()) base else "$base — ${moved.joinToString(", ")}"190    }191    return summary.detail?.let { "$base ($it)" } ?: base192}193194/**195 * Session errors reach us as opaque strings by contract ([SyncOutcome.error]196 * and any throw out of the relay socket). Classifying them in one place is what197 * lets the copy above key off something stable.198 */199internal fun classifySyncError(error: String): SyncOutcomeReason = when {200    error.contains("VAULT_LOCKED") -> SyncOutcomeReason.VAULT_LOCKED201    error.contains("vault_id_mismatch") -> SyncOutcomeReason.VAULT_ID_MISMATCH202    error.contains("PEER_PROTOCOL_OUTDATED") -> SyncOutcomeReason.PEER_PROTOCOL_OUTDATED203    error.contains("timed out") || error.contains("sync_timeout") -> SyncOutcomeReason.SYNC_TIMEOUT204    // A KK failure, a mismatched PAIR_IDENTITY or a wrong room all mean the205    // relay was fine and the peer was not who we expected.206    Regex("handshake|PAIR_IDENTITY|identity does not match|capability does not match|clock-skew")207        .containsMatchIn(error) -> SyncOutcomeReason.HANDSHAKE_FAILED208    // A hang-up after a successful dial is a connection-lost, not a relay209    // problem — checked before the broad relay/websocket regex below so it210    // doesn't get swallowed into RELAY_UNREACHABLE. The browser does the same211    // narrow check.212    isConnectionClosedError(error) -> SyncOutcomeReason.CONNECTION_LOST213    Regex("relay_|websocket|Connection|connect|socket|Unable to resolve host", RegexOption.IGNORE_CASE)214        .containsMatchIn(error) -> SyncOutcomeReason.RELAY_UNREACHABLE215    else -> SyncOutcomeReason.RUN_FAILED216}217218/**219 * A transport that hung up, as opposed to a protocol or vault problem.220 * Mirrors `isConnectionClosedError` in the browser's sync-outcome.ts; the two221 * must stay in lockstep so a close on either side maps to the same outcome.222 */223internal fun isConnectionClosedError(error: String): Boolean =224    Regex("websocket closed|connection closed|Socket closed", RegexOption.IGNORE_CASE)225        .containsMatchIn(error)226227/**228 * Translate one finished session ([SyncCoordinator]'s per-round result) into the229 * user-facing vocabulary. Tombstones count as changes: a deletion that crossed230 * the wire is not "nothing to send or receive".231 */232internal fun SyncOutcome.toSummary(): SyncOutcomeSummary = when (status) {233    SyncOutcomeStatus.COMPLETED -> SyncOutcomeSummary(234        reason = if (entriesSent + entriesReceived + tombstonesSent + tombstonesReceived > 0) {235            SyncOutcomeReason.COMPLETED_CHANGES236        } else {237            SyncOutcomeReason.COMPLETED_NO_CHANGES238        },239        entriesSent = entriesSent,240        entriesReceived = entriesReceived,241    )242243    SyncOutcomeStatus.VAULT_MISMATCH ->244        SyncOutcomeSummary(reason = SyncOutcomeReason.VAULT_ID_MISMATCH, detail = error)245246    SyncOutcomeStatus.TIMEOUT ->247        SyncOutcomeSummary(reason = SyncOutcomeReason.SYNC_TIMEOUT, detail = error)248249    SyncOutcomeStatus.ERRORED -> SyncOutcomeSummary(250        reason = classifySyncError(error ?: "sync_failed"),251        detail = error,252    )253}