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
+230
View File
@@ -0,0 +1,230 @@
/**
* The globe Atlas as this device last read it, and the account's queued Atlas
* writes laid over it.
*
* `atlasSnapshot` holds each Atlas read as the server last answered it. A write
* made offline, or online behind an older one still queued, is not written
* there: it waits in userMutationQueue as the only copy of it, and every read,
* online or offline, lays the writes still on their way over the answer. So a
* fresh server answer cannot hide a mark that has not gone out yet, and a write
* the server refused for good stops showing once it is parked. Once a write
* went through, its answer is laid into the stored rows (reconcileAtlasWrite),
* so the device keeps it when it goes offline again before the next read.
*
* Every step here is idempotent: a read that raced a replay may already hold
* the write, and laying it over once more must change nothing.
*/
import { continentForCountry } from '@trek/shared';
import { offlineDb, type AtlasSnapshotPart, type UserQueuedMutation } from '../db/offlineDb';
/** The resources of the Atlas writes in the account queue. */
export const ATLAS_RESOURCE = {
country: 'atlasCountry',
region: 'atlasRegion',
bucket: 'atlasBucket',
} as const;
/** A write as it is laid over a read: a queued row, or a write that just went through with the server's answer. */
type AtlasWrite = Pick<
UserQueuedMutation,
'resource' | 'method' | 'entity' | 'ids' | 'body' | 'tempId' | 'createdAt'
> & {
answer?: unknown;
};
type Fields = Record<string, unknown>;
function fields(value: unknown): Fields {
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Fields) : {};
}
function text(value: unknown): string | null {
return typeof value === 'string' ? value : null;
}
/** The code or id the write's entity names, `atlasCountry:DE` → `DE`. */
function keyOf(w: AtlasWrite): string {
return w.entity.slice(w.resource.length + 1);
}
// ── Countries (the stats read) ────────────────────────────────────────────────
interface StatsCountry {
code: string;
status?: string;
placeCount?: number;
tripCount?: number;
}
interface StatsShape {
countries: StatsCountry[];
stats?: Record<string, number | undefined>;
continents?: Record<string, number>;
continentsPlanned?: Record<string, number>;
}
function asStats(data: unknown): StatsShape | null {
return Array.isArray(fields(data).countries) ? (data as StatsShape) : null;
}
function bump(counts: Record<string, number> | undefined, key: string, by: number): Record<string, number> {
return { ...counts, [key]: Math.max(0, (counts?.[key] ?? 0) + by) };
}
function total(s: StatsShape, key: string, by: number): Record<string, number | undefined> {
return { ...s.stats, [key]: Math.max(0, (s.stats?.[key] ?? 0) + by) };
}
/** A manual "I have been here": a country planned before moves over to the visited tally. */
function markCountry(data: unknown, code: string): unknown {
const s = asStats(data);
if (!s) return data;
const known = s.countries.find((c) => c.code === code);
const status = known?.status ?? (known ? 'visited' : null);
if (status === 'visited') return data;
const continent = continentForCountry(code);
const visited: StatsCountry & Fields = {
code,
tripCount: 0,
placeCount: 0,
firstVisit: null,
lastVisit: null,
status: 'visited',
};
const next: StatsShape = {
...s,
countries: known
? s.countries.map((c) => (c.code === code ? { ...c, status: 'visited' } : c))
: [...s.countries, visited],
stats: total(s, 'totalCountries', 1),
continents: bump(s.continents, continent, 1),
};
if (status !== 'planned') return next;
return {
...next,
stats: { ...next.stats, totalCountriesPlanned: Math.max(0, (s.stats?.totalCountriesPlanned ?? 0) - 1) },
continentsPlanned: bump(s.continentsPlanned, continent, -1),
};
}
/** The manual mark taken back: a country with no trip and no place in it leaves the map. */
function unmarkCountry(data: unknown, code: string): unknown {
const s = asStats(data);
const known = s?.countries.find((c) => c.code === code);
if (!s || !known || (known.status ?? 'visited') !== 'visited') return data;
if ((known.placeCount ?? 0) > 0 || (known.tripCount ?? 0) > 0) return data;
return {
...s,
countries: s.countries.filter((c) => c.code !== code),
stats: total(s, 'totalCountries', -1),
continents: bump(s.continents, continentForCountry(code), -1),
};
}
// ── Regions ───────────────────────────────────────────────────────────────────
interface RegionRow {
code: string;
name: string;
placeCount: number;
status?: string;
/** Marked by hand, the server's own name for it. */
manuallyMarked?: boolean;
}
type Regions = Record<string, RegionRow[]>;
function asRegions(data: unknown): Regions | null {
return data && typeof data === 'object' && !Array.isArray(data) ? (data as Regions) : null;
}
function markRegion(data: unknown, code: string, name: string, countryCode: string): unknown {
const regions = asRegions(data);
if (!regions) return data;
const rows = regions[countryCode] ?? [];
const known = rows.find((r) => r.code === code);
if (known?.status === 'visited' && known.manuallyMarked) return data;
const marked: RegionRow = { ...(known ?? { code, name, placeCount: 0 }), status: 'visited', manuallyMarked: true };
return { ...regions, [countryCode]: known ? rows.map((r) => (r.code === code ? marked : r)) : [...rows, marked] };
}
function unmarkRegion(data: unknown, code: string): unknown {
const regions = asRegions(data);
const country = regions && Object.keys(regions).find((cc) => (regions[cc] ?? []).some((r) => r.code === code));
if (!regions || !country) return data;
// A region with places in it stays visited by them; only the manual mark goes.
const rows = regions[country]
.map((r) => (r.code === code ? { ...r, manuallyMarked: false } : r))
.filter((r) => r.code !== code || r.placeCount > 0);
return { ...regions, [country]: rows };
}
// ── One write over one read ───────────────────────────────────────────────────
function applyToStats(data: unknown, w: AtlasWrite): unknown {
if (w.resource !== ATLAS_RESOURCE.country) return data;
if (w.method === 'POST') return markCountry(data, keyOf(w));
if (w.method === 'DELETE') return unmarkCountry(data, keyOf(w));
return data;
}
function applyToRegions(data: unknown, w: AtlasWrite): unknown {
if (w.resource !== ATLAS_RESOURCE.region) return data;
const body = fields(w.body);
const country = text(body.country_code);
if (w.method === 'POST' && country) return markRegion(data, keyOf(w), text(body.name) ?? keyOf(w), country);
if (w.method === 'DELETE') return unmarkRegion(data, keyOf(w));
return data;
}
/** What one Atlas read reads as once the write is laid over it. */
function applyAtlasWrite(part: AtlasSnapshotPart, data: unknown, w: AtlasWrite): unknown {
switch (part) {
case 'stats':
return applyToStats(data, w);
case 'regions':
return applyToRegions(data, w);
case 'bucketList': {
if (w.resource !== ATLAS_RESOURCE.bucket || w.method !== 'DELETE' || !Array.isArray(data)) return data;
const id = Number(keyOf(w));
return data.filter((item) => fields(item).id !== id);
}
default:
return data;
}
}
// ── Reading and keeping ───────────────────────────────────────────────────────
/** The Atlas writes still on their way, oldest first. A parked one is not laid over: the server did not take it. */
async function waitingWrites(): Promise<UserQueuedMutation[]> {
const rows = await offlineDb.userMutationQueue.where('status').anyOf(['pending', 'syncing']).sortBy('createdAt');
return rows.filter((row) => row.resource.startsWith('atlas'));
}
/** A read with every Atlas write still on its way laid over it, in the order they were made. */
export async function withWaitingWrites(part: AtlasSnapshotPart, data: unknown): Promise<unknown> {
const writes = await waitingWrites();
return writes.reduce((out, w) => applyAtlasWrite(part, out, w), data);
}
/** Keep a read's answer as the server gave it. */
export async function keepAtlasPart(part: AtlasSnapshotPart, data: unknown): Promise<void> {
await offlineDb.atlasSnapshot.put({ part, data });
}
/** The kept answer of a read, or undefined when this device never read it. */
export async function keptAtlasPart(part: AtlasSnapshotPart): Promise<{ data: unknown } | undefined> {
return offlineDb.atlasSnapshot.get(part);
}
/** A write that went through: its answer is laid into every kept read, so it stays once the device is offline again. */
export async function reconcileAtlasWrite(w: AtlasWrite): Promise<void> {
await offlineDb.transaction('rw', offlineDb.atlasSnapshot, async () => {
const rows = await offlineDb.atlasSnapshot.toArray();
for (const row of rows) {
const next = applyAtlasWrite(row.part, row.data, w);
if (next !== row.data) await offlineDb.atlasSnapshot.put({ part: row.part, data: next });
}
});
}
+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()
},
}
+32
View File
@@ -0,0 +1,32 @@
/**
* The replay rules both write queues follow: the trip queue (mutationQueue)
* and the account's own writes (userMutationQueue). One place, so a retry or
* backoff change cannot reach one queue and miss the other.
*/
// 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.
export const STUCK_SYNCING_MS = 60_000;
/**
* 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.
*/
export const MAX_SERVER_ERROR_ATTEMPTS = 8;
export const SERVER_ERROR_BACKOFF_MS = 30_000;
/** HTTP statuses that should be retried later rather than treated as terminal. */
export 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 UI build stamped onto each queued write, for diagnosis. Empty where the
// bundler defined none.
export const BUILD_VERSION: string = typeof __TREK_UI_VERSION__ === 'string' ? __TREK_UI_VERSION__ : '';
+238
View File
@@ -0,0 +1,238 @@
/**
* The account's own offline writes: the ones that belong to no trip (the
* globe Atlas). They wait in `userMutationQueue`, a table of their own, so a
* row never has to make up a trip id, and the trip queue's replay, its
* per-trip ordering and an older bundle that knows only that queue never see
* them.
*
* The rules are the trip queue's (see mutationQueue and queuePolicy): FIFO,
* the row's id as X-Idempotency-Key, a create made offline under a temporary
* negative id that the later writes naming it learn the real one of, a write
* parked as failed holding back the later writes to the same entity, a 5xx
* retried with growing gaps, a row from a newer format left alone. The replay
* runs inside mutationQueue.flush(), under its cross-tab lock, so the account
* queue never needs triggers or a lock of its own. None of these writes carry
* a version token, so a 409 is a refusal like any other 4xx.
*/
import { apiClient } from '../api/client';
import { MUTATION_SCHEMA_VERSION, offlineDb, type MutationStatus, type UserQueuedMutation } from '../db/offlineDb';
import { reconcileAtlasWrite } from './atlasSnapshot';
import { isAuthed } from './authGate';
import { isEffectivelyOffline } from './networkMode';
import {
BUILD_VERSION,
isRetryableStatus,
MAX_SERVER_ERROR_ATTEMPTS,
SERVER_ERROR_BACKOFF_MS,
STUCK_SYNCING_MS,
} from './queuePolicy';
/** What a repo hands in; the queue stamps the rest. */
export type UserMutationInput = Pick<
UserQueuedMutation,
'id' | 'method' | 'url' | 'ids' | 'body' | 'resource' | 'entity' | 'tempId'
>;
type Outcome = 'done' | 'parked' | 'stop';
// Monotonic, so same-millisecond enqueues keep their FIFO order.
let lastCreatedAt = 0;
/** Fill `{name}` placeholders of a path from `ids`. */
export function fillPath(url: string, ids: Record<string, number>): string {
return Object.entries(ids).reduce((path, [name, id]) => path.replace(`{${name}}`, String(id)), url);
}
/**
* The ids a row names with every temporary one this pass learned replaced, or
* null while one still names a create that did not sync.
*/
function resolveIds(row: UserQueuedMutation, idMap: Map<number, number>): Record<string, number> | null {
const out: Record<string, number> = {};
for (const [name, id] of Object.entries(row.ids)) {
const real = id < 0 ? idMap.get(id) : id;
if (real === undefined) return null;
out[name] = real;
}
return out;
}
/** The real id the server answered a create with. */
function createdId(data: unknown): number | undefined {
const id = data && typeof data === 'object' ? (data as { id?: unknown }).id : undefined;
return typeof id === 'number' ? id : undefined;
}
/**
* A create went through: every later row naming its temporary id names the
* real one now, in memory for this pass and durably for the next.
*/
async function learnId(tempId: number, realId: number, idMap: Map<number, number>): Promise<void> {
idMap.set(tempId, realId);
await offlineDb.userMutationQueue
.filter((row) => Object.values(row.ids).includes(tempId) || row.entity.endsWith(`:${tempId}`))
.modify((row) => {
for (const name of Object.keys(row.ids)) if (row.ids[name] === tempId) row.ids[name] = realId;
if (row.entity === `${row.resource}:${tempId}`) row.entity = `${row.resource}:${realId}`;
});
}
function hold(held: Map<string, number>, row: UserQueuedMutation): void {
const since = held.get(row.entity);
if (since === undefined || row.createdAt < since) held.set(row.entity, row.createdAt);
}
async function park(row: UserQueuedMutation, error: string): Promise<'parked'> {
await offlineDb.userMutationQueue.update(row.id, {
status: 'failed',
attempts: row.attempts + 1,
lastError: error,
retryAfter: undefined,
});
return 'parked';
}
/** Settle a replay that threw: done, parked for the user, or the pass stops here. */
async function settle(row: UserQueuedMutation, err: unknown): Promise<Outcome> {
const status = (err as { response?: { status?: number } } | null)?.response?.status;
// A delete of something the server no longer has did what it set out to do.
if (status === 404 && row.method === 'DELETE') {
await offlineDb.userMutationQueue.delete(row.id);
return 'done';
}
const attempts = row.attempts + 1;
const lastError = String(err);
// No answer, or one worth waiting out: back to pending, the next trigger retries.
if (status === undefined || isRetryableStatus(status)) {
await offlineDb.userMutationQueue.update(row.id, { status: 'pending', attempts, lastError });
return 'stop';
}
// The server failed: retried with growing gaps until it has failed too often.
if (status >= 500 && attempts < MAX_SERVER_ERROR_ATTEMPTS) {
const retryAfter = Date.now() + SERVER_ERROR_BACKOFF_MS * 2 ** (attempts - 1);
await offlineDb.userMutationQueue.update(row.id, { status: 'pending', attempts, lastError, retryAfter });
return 'stop';
}
return park(row, lastError);
}
async function replay(row: UserQueuedMutation, idMap: Map<number, number>): Promise<Outcome> {
const ids = resolveIds(row, idMap);
if (!ids) return park(row, 'unresolved temp id (dependent create did not sync)');
await offlineDb.userMutationQueue.update(row.id, { status: 'syncing', syncingSince: Date.now() });
try {
const response = await apiClient.request({
method: row.method,
url: fillPath(row.url, ids),
data: row.body,
headers: { 'X-Idempotency-Key': row.id },
});
const realId = row.tempId === undefined ? undefined : createdId(response.data);
if (row.tempId !== undefined && realId !== undefined) await learnId(row.tempId, realId, idMap);
if (row.resource.startsWith('atlas')) await reconcileAtlasWrite({ ...row, ids, answer: response.data });
await offlineDb.userMutationQueue.delete(row.id);
return 'done';
} catch (err: unknown) {
return settle(row, err);
}
}
export const userMutationQueue = {
async enqueue(input: UserMutationInput): Promise<string> {
const now = Date.now();
lastCreatedAt = now > lastCreatedAt ? now : lastCreatedAt + 1;
await offlineDb.userMutationQueue.put({
...input,
createdAt: lastCreatedAt,
status: 'pending',
attempts: 0,
lastError: null,
schemaVersion: MUTATION_SCHEMA_VERSION,
buildVersion: BUILD_VERSION,
});
return input.id;
},
/**
* Does a write have to join the queue? Offline, always; online too when it
* names a create still waiting here (a negative id), when an older write to
* the same entity is still queued or parked, or while the queue is still
* sending: none of these writes carry a version token, so sent straight to
* the server it would land before the older ones and be overwritten by
* their replay. `entity` is null for a create, which has no older writes.
*/
async mustQueue(entity: string | null, ids: readonly number[]): Promise<boolean> {
if (isEffectivelyOffline() || ids.some((id) => id < 0)) return true;
const waiting = await offlineDb.userMutationQueue
.where('status')
.anyOf(['pending', 'syncing', 'failed'])
.filter((row) => row.status !== 'failed' || row.entity === entity)
.first();
return waiting !== undefined;
},
/**
* One pass over the pending rows. Only mutationQueue's flush calls it, under
* its lock. A server error or a lost connection stops the pass: the
* account's writes are one line, and the later ones keep their order behind it.
*/
async flushPass(): Promise<void> {
const table = offlineDb.userMutationQueue;
const stuckBefore = Date.now() - STUCK_SYNCING_MS;
await table
.where('status')
.equals('syncing')
.filter((row) => (row.syncingSince ?? 0) < stuckBefore)
.modify((row) => {
row.status = 'pending';
row.syncingSince = undefined;
});
const pending = await table.where('status').equals('pending').sortBy('createdAt');
const held = new Map<string, number>();
for (const row of await table.where('status').equals('failed').toArray()) hold(held, row);
const idMap = new Map<number, number>();
for (const row of pending) {
// Re-checked every row: after a logout the database is another one.
if (!isAuthed() || isEffectivelyOffline()) return;
const since = held.get(row.entity);
if (since !== undefined && since < row.createdAt) continue;
// Queued by a newer build: left as it is for that build, holding its entity.
if (row.schemaVersion > MUTATION_SCHEMA_VERSION) {
hold(held, row);
continue;
}
if (row.retryAfter !== undefined && row.retryAfter > Date.now()) return;
const outcome = await replay(row, idMap);
if (outcome === 'stop') return;
if (outcome === 'parked') hold(held, row);
}
},
/** Rows in any of these states, for the badge. */
async count(statuses: MutationStatus[]): Promise<number> {
return offlineDb.userMutationQueue.where('status').anyOf(statuses).count();
},
/** Put every parked row back in line from a fresh start (mutationQueue.retryFailed flushes). */
async retryFailed(): Promise<void> {
await offlineDb.userMutationQueue
.where('status')
.equals('failed')
.modify((row) => {
row.status = 'pending';
row.attempts = 0;
row.retryAfter = undefined;
row.lastError = null;
});
},
/** Drop every parked row; the next Atlas read shows what the server has. */
async discardFailed(): Promise<void> {
await offlineDb.userMutationQueue.where('status').equals('failed').delete();
},
/** Reset the createdAt counter — tests only, through mutationQueue._resetFlushing. */
_reset(): void {
lastCreatedAt = 0;
},
};