Files
TREK/client/src/sync/atlasSnapshot.ts
T
Maurice 68af65a2a6 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.
2026-11-28 22:35:11 +01:00

231 lines
9.3 KiB
TypeScript

/**
* 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 });
}
});
}