feat(atlas): read and write the Atlas offline

The Atlas reads go network first and fall back to a snapshot kept in a new
Dexie table (v17, append-only). Marks, unmarks and wishlist deletes made
offline wait in their own account-level queue, replayed in order with an
idempotency key, and every read lays them over the kept answer.
This commit is contained in:
Maurice
2026-11-28 22:34:41 +01:00
parent 04d134755a
commit 68af65a2a6
13 changed files with 1539 additions and 121 deletions
+11 -34
View File
@@ -12,6 +12,8 @@ import { isAuthed } from './authGate'
import { isEffectivelyOffline } from './networkMode'
import { getOfflinePrefs } from './offlinePrefs'
import { randomId } from '../utils/randomId'
import { BUILD_VERSION, isRetryableStatus, MAX_SERVER_ERROR_ATTEMPTS, SERVER_ERROR_BACKOFF_MS, STUCK_SYNCING_MS } from './queuePolicy'
import { userMutationQueue } from './userMutationQueue'
import type { QueuedMutation } from '../db/offlineDb'
import type { Table } from 'dexie'
import { roadtripPreferencesResponseSchema, assignmentSchema, tourCreateResponseSchema, tourDraftResponseSchema, tourVisitListResponseSchema, type TourCreateResponse } from '@trek/shared'
@@ -79,13 +81,6 @@ function acquireFlushLock(): Promise<() => void> {
.catch(() => resolve(noop))
})
}
// A row sits on 'syncing' only while its request is in flight, and the shared
// axios instance times out at 8s. Anything still 'syncing' a minute later
// belongs to a flush that never reached its catch — the tab was killed, the PWA
// was evicted, the device slept mid-request. flush() only ever selects
// 'pending', so without recovery that row is stranded: counted in the badge,
// never replayed, and blocking every dependent behind it.
const STUCK_SYNCING_MS = 60_000
// Monotonically increasing timestamp so same-millisecond enqueues
// still get a deterministic FIFO order when sorted by createdAt.
let _lastTs = 0
@@ -106,21 +101,6 @@ export function nextTempId(): number {
return -_lastTempId
}
/**
* A write the server answers with a 5xx this many times is parked as failed.
* The gaps double from 30 s, so the last try comes about two hours after the
* first: long enough for a restart or an outage, short of blocking forever.
*/
const MAX_SERVER_ERROR_ATTEMPTS = 8
const SERVER_ERROR_BACKOFF_MS = 30_000
/** HTTP statuses that should be retried later rather than treated as terminal. */
function isRetryableStatus(status: number | undefined): boolean {
// 401: token expired mid-flush (offline window) — retry after re-auth.
// 408/425/429: timeout / too-early / rate-limited — transient.
return status === 401 || status === 408 || status === 425 || status === 429
}
/**
* The entity a queued write targets, as `resource:id`. A create is keyed by its
* temporary id, which is also what the writes queued against it carry until it
@@ -153,10 +133,6 @@ function holdEntity(held: Map<string, number>, m: QueuedMutation): void {
if (since === undefined || m.createdAt < since) held.set(key, m.createdAt)
}
// The UI build stamped onto each queued write, for diagnosis. Empty where the
// bundler defined none.
const BUILD_VERSION: string = typeof __TREK_UI_VERSION__ === 'string' ? __TREK_UI_VERSION__ : ''
/**
* Was this write queued by a build whose row format this one does not know? A
* tab still on the previous bundle, or an install rolled back, would otherwise
@@ -837,6 +813,8 @@ export const mutationQueue = {
}
}
}
// The account's own writes (the Atlas), which belong to no trip, under the same lock.
if (isAuthed()) await userMutationQueue.flushPass()
} finally {
release()
}
@@ -863,19 +841,15 @@ export const mutationQueue = {
/** Count pending mutations (for banner badge). */
async pendingCount(): Promise<number> {
return offlineDb.mutationQueue
.where('status')
.anyOf(['pending', 'syncing'])
.count()
const trip = await offlineDb.mutationQueue.where('status').anyOf(['pending', 'syncing']).count()
return trip + (await userMutationQueue.count(['pending', 'syncing']))
},
/** Count permanently-failed mutations (surfaced separately so the user knows
* changes were dropped — they are NOT folded into pendingCount). */
async failedCount(): Promise<number> {
return offlineDb.mutationQueue
.where('status')
.equals('failed')
.count()
const trip = await offlineDb.mutationQueue.where('status').equals('failed').count()
return trip + (await userMutationQueue.count(['failed']))
},
/**
@@ -894,6 +868,7 @@ export const mutationQueue = {
.where('status')
.equals('failed')
.modify(m => { m.status = 'pending'; m.attempts = 0; m.retryAfter = undefined; m.lastError = null })
await userMutationQueue.retryFailed()
await this.flush()
},
@@ -904,6 +879,7 @@ export const mutationQueue = {
*/
async discardFailed(): Promise<void> {
await offlineDb.mutationQueue.where('status').equals('failed').delete()
await userMutationQueue.discardFailed()
await this.flush()
},
@@ -954,5 +930,6 @@ export const mutationQueue = {
_flushAgain = false
_lastTs = 0
_lastTempId = 0
userMutationQueue._reset()
},
}