sync-outcome.ts

5.8 KB · raw

1// Why a sync run ended, in a form both the service worker and the popup can2// name. Before this existed, "no eligible host", "runner not wired" and3// "synced fine, nothing to do" were all a bare `return` — indistinguishable4// to the user and to us. A failed sync and a successful no-op must never5// look the same again.67export type SyncOutcome =8  | "completed_changes"9  | "completed_no_changes"10  | "no_paired_devices"11  | "no_eligible_host"12  | "runner_unavailable"13  | "sync_disabled"14  | "private_relay_unset"15  | "vault_locked"16  | "relay_unreachable"17  | "handshake_failed"18  | "vault_id_mismatch"19  | "sync_timeout"20  | "connection_lost"21  | "run_failed";2223/**24 * Outcomes where sync did not do what the user asked, so the UI shows red.25 *26 * Network-class failures (relay/handshake/timeout) are NOT in this set —27 * with a 10-minute background alarm the normal state for most minutes is28 * "the relay didn't answer this time". That is the network, not the app,29 * and the next alarm tick will retry. They live in `WARNINGS` so the30 * indicator goes yellow instead of red.31 */32const FAILURES: ReadonlySet<SyncOutcome> = new Set<SyncOutcome>([33  "no_eligible_host",34  "runner_unavailable",35  "private_relay_unset",36  "vault_locked",37  "vault_id_mismatch",38  "run_failed",39]);4041/**42 * Network-class outcomes — the dial did not reach the peer this attempt.43 * The alarm keeps trying, so this is warn (yellow), not error (red).44 */45const WARNINGS: ReadonlySet<SyncOutcome> = new Set<SyncOutcome>([46  "relay_unreachable",47  "handshake_failed",48  "sync_timeout",49  "connection_lost",50]);5152/**53 * A transport that hung up, as opposed to a protocol or vault problem.54 *55 * Lives here because two callers need the same judgement and must not drift:56 * the coordinator (a close while waiting for the peer's final SYNC_DONE echo57 * is a completed sync) and the trigger's error classifier (a close anywhere58 * else is network-class, so yellow rather than red).59 *60 * Deliberately does not match SyncFrameTooLargeError's "WebSocket close 1009"61 * — an oversized frame is a misbehaving peer and must keep failing.62 */63export function isConnectionClosedError(err: unknown): boolean {64  const message = err instanceof Error ? err.message : String(err);65  return /websocket closed|connection closed/i.test(message);66}6768export function isSyncFailure(outcome: SyncOutcome): boolean {69  return FAILURES.has(outcome);70}7172export function isSyncWarning(outcome: SyncOutcome): boolean {73  return WARNINGS.has(outcome);74}7576export interface SyncOutcomeSummary {77  status?: "idle" | "syncing" | "error";78  outcome?: SyncOutcome;79  entriesSent?: number;80  entriesReceived?: number;81  detail?: string;82  /** When the last attempt ended, success or not. */83  finishedAt?: number;84}8586/**87 * The one indicator light. `busy` pulses green, `ok` is solid green, `warn`88 * is yellow (a transient network miss — the next alarm tick retries),89 * `error` is red (the app is actually broken), `idle` is unlit. Nothing90 * that is actually broken may resolve to `ok` — a paired-but-unsyncable91 * device is red, not green. A dial that didn't reach the peer is yellow,92 * because the alarm will try again.93 */94export type SyncIndicator = "busy" | "ok" | "warn" | "error" | "idle";9596export function syncIndicator(s: SyncOutcomeSummary, pairedCount: number): SyncIndicator {97  if (s.status === "syncing") return "busy";98  if (s.outcome && isSyncFailure(s.outcome)) return "error";99  if (s.outcome && isSyncWarning(s.outcome)) return "warn";100  if (s.outcome === "completed_changes" || s.outcome === "completed_no_changes") {101    return "ok";102  }103  // Paired with a healthy history but no attempt since this SW woke: still a104  // successful pair, which is what the light is claiming.105  if (pairedCount > 0 && s.outcome === undefined) return "ok";106  return "idle";107}108109const INDICATOR_LABEL: Record<SyncIndicator, string> = {110  busy: "Syncing",111  ok: "Sync healthy",112  warn: "Last sync attempt missed — will retry",113  error: "Sync problem",114  idle: "Not syncing",115};116117/** Colour alone is never the signal — this is the same claim in words. */118export function syncIndicatorLabel(119  indicator: SyncIndicator,120  s: SyncOutcomeSummary,121): string {122  return `${INDICATOR_LABEL[indicator]} — ${describeSyncOutcome(s)}`;123}124125const COPY: Record<SyncOutcome, string> = {126  completed_changes: "Synced",127  completed_no_changes: "Up to date — nothing to send or receive",128  no_paired_devices: "No devices paired yet",129  no_eligible_host: "Paired, but no device here can accept a sync",130  runner_unavailable: "Sync isn't running in the background — reload Peach",131  sync_disabled: "Sync is switched off",132  private_relay_unset: "Private relay chosen but no address set",133  vault_locked: "Vault was locked — unlock and sync again",134  relay_unreachable: "Couldn't reach the relay",135  handshake_failed: "Reached the relay, but the device didn't answer",136  vault_id_mismatch: "That device holds a different vault",137  sync_timeout: "The device stopped responding mid-sync",138  connection_lost: "The connection dropped mid-sync — will retry",139  run_failed: "Sync failed",140};141142/**143 * One plain-English line for a sync outcome. `detail` — the raw internal code144 * or the device inventory behind `no_eligible_host` — is appended rather than145 * hidden: it is the whole diagnostic on a real device, where devtools is not146 * an option.147 */148export function describeSyncOutcome(s: SyncOutcomeSummary): string {149  if (!s.outcome) return "Not synced yet";150  const base = COPY[s.outcome] ?? "Sync failed";151  if (s.outcome === "completed_changes") {152    const moved = [153      (s.entriesSent ?? 0) > 0 ? `${s.entriesSent} sent` : null,154      (s.entriesReceived ?? 0) > 0 ? `${s.entriesReceived} received` : null,155    ].filter(Boolean);156    return moved.length > 0 ? `${base} — ${moved.join(", ")}` : base;157  }158  return s.detail ? `${base} (${s.detail})` : base;159}