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
+193 -68
View File
@@ -1,6 +1,31 @@
import type { Ferrata, RoadtripPreferences, TripAddon, TourActivity, TourDraft, TourListItem, TourObstacleCheck, TourPackingLink, TourProvenance, TourVisit, TourWaypoint } from '@trek/shared';
import type {
Ferrata,
RoadtripPreferences,
TourActivity,
TourDraft,
TourListItem,
TourObstacleCheck,
TourPackingLink,
TourProvenance,
TourVisit,
TourWaypoint,
TripAddon,
} from '@trek/shared';
import Dexie, { type Table } from 'dexie';
import type { Trip, Day, Place, PackingItem, TodoItem, BudgetItem, Reservation, TripFile, Accommodation, TripMember, Tag, Category } from '../types';
import type {
Accommodation,
BudgetItem,
Category,
Day,
PackingItem,
Place,
Reservation,
Tag,
TodoItem,
Trip,
TripFile,
TripMember,
} from '../types';
/** TripMember enriched with tripId so we can index by trip. */
export interface CachedTripMember extends TripMember {
@@ -182,6 +207,59 @@ export interface QueuedMutation {
buildVersion?: string;
}
/**
* A write that belongs to the signed-in account rather than to a trip (the
* Atlas: marks and the bucket list). It waits in a queue of its own,
* userMutationQueue, so it never needs a trip id it does not have, and a build
* that only knows the trip queue never sees it. sync/userMutationQueue replays
* it under the same lock and rules as the trip queue.
*/
export interface UserQueuedMutation {
/** UUID, also sent as X-Idempotency-Key on replay. */
id: string;
method: 'POST' | 'PUT' | 'PATCH' | 'DELETE';
/**
* The path, with a `{name}` placeholder for every entry of `ids`, filled in
* when the write is sent, so an id learned from an earlier create is used.
*/
url: string;
/** The ids the url names, by placeholder. A negative one is a create still waiting in this queue. */
ids: Record<string, number>;
body: unknown;
/** What the write is about, read when its answer is reconciled (e.g. 'atlasCountry'). */
resource: string;
/** `<resource>:<id or code>`: the later writes to one entity wait behind a parked one. */
entity: string;
/** A create made offline: the temporary (negative) id it stands under until it syncs. */
tempId?: number;
createdAt: number;
status: MutationStatus;
attempts: number;
lastError: string | null;
/** When the row was marked 'syncing', so a killed tab's row is recognised (see QueuedMutation). */
syncingSince?: number;
/** Not before this time (ms), after a 5xx. */
retryAfter?: number;
/** MUTATION_SCHEMA_VERSION of the build that queued it; every row of this queue carries one. */
schemaVersion: number;
/** The UI build that queued the row. For diagnosis only, never compared. */
buildVersion: string;
}
/** The Atlas reads kept for offline use, one row per read. */
export type AtlasSnapshotPart = 'stats' | 'regions' | 'bucketList' | 'flights';
/**
* The last answer of one Atlas read as the server gave it. The database is the
* signed-in user's own (trek-offline-u<id>), so the row needs no user key. A
* write made offline is not written here: it waits in userMutationQueue, and
* every read lays it over this answer (see sync/atlasSnapshot).
*/
interface AtlasSnapshotRow {
part: AtlasSnapshotPart;
data: unknown;
}
export interface SyncMeta {
tripId: number;
lastSyncedAt: number | null;
@@ -314,41 +392,48 @@ export class TrekOfflineDb extends Dexie {
routeCache!: Table<CachedRoute, string>;
tripTags!: Table<CachedTripTags, number>;
tripAddons!: Table<CachedTripAddons, number>;
userMutationQueue!: Table<UserQueuedMutation, string>;
atlasSnapshot!: Table<AtlasSnapshotRow, AtlasSnapshotPart>;
constructor(name: string = ANON_DB_NAME) {
super(name);
this.version(1).stores({
trips: 'id',
days: 'id, trip_id',
places: 'id, trip_id',
trips: 'id',
days: 'id, trip_id',
places: 'id, trip_id',
packingItems: 'id, trip_id',
todoItems: 'id, trip_id',
budgetItems: 'id, trip_id',
todoItems: 'id, trip_id',
budgetItems: 'id, trip_id',
reservations: 'id, trip_id',
tripFiles: 'id, trip_id',
mutationQueue:'id, tripId, status, createdAt',
syncMeta: 'tripId',
blobCache: 'url, cachedAt',
tripFiles: 'id, trip_id',
mutationQueue: 'id, tripId, status, createdAt',
syncMeta: 'tripId',
blobCache: 'url, cachedAt',
});
this.version(2).stores({
accommodations: 'id, trip_id',
tripMembers: '[tripId+id], tripId',
tags: 'id',
categories: 'id',
tripMembers: '[tripId+id], tripId',
tags: 'id',
categories: 'id',
});
// v3: scope the blob cache by trip so it can be evicted with the trip and
// bounded by an LRU budget (see enforceBlobBudget).
this.version(3).stores({
blobCache: 'url, cachedAt, tripId',
}).upgrade(async (tx) => {
await tx.table('blobCache').toCollection().modify((row: Partial<BlobCacheEntry>) => {
if (row.tripId == null) row.tripId = -1;
if (row.bytes == null) row.bytes = row.blob?.size ?? 0;
this.version(3)
.stores({
blobCache: 'url, cachedAt, tripId',
})
.upgrade(async (tx) => {
await tx
.table('blobCache')
.toCollection()
.modify((row: Partial<BlobCacheEntry>) => {
if (row.tripId == null) row.tripId = -1;
if (row.bytes == null) row.bytes = row.blob?.size ?? 0;
});
});
});
// v4: durable store for booking-import source files (survives a reload mid-parse).
this.version(4).stores({
@@ -374,13 +459,18 @@ export class TrekOfflineDb extends Dexie {
// table is dropped and rebuilt, and every stored fingerprint is cleared so
// the next sync refills what the drop took.
this.version(7).stores({ areaPlaces: null });
this.version(8).stores({
areaPlaces: '[gers+tripId], gers, tripId, searchName',
}).upgrade(async (tx) => {
await tx.table('syncMeta').toCollection().modify((row: { areaPlacesKey?: string }) => {
delete row.areaPlacesKey;
this.version(8)
.stores({
areaPlaces: '[gers+tripId], gers, tripId, searchName',
})
.upgrade(async (tx) => {
await tx
.table('syncMeta')
.toCollection()
.modify((row: { areaPlacesKey?: string }) => {
delete row.areaPlacesKey;
});
});
});
// v9: the Tours facet, keyed like the place it belongs to, so a Tour still
// reads as one offline and can be edited there.
@@ -414,6 +504,16 @@ export class TrekOfflineDb extends Dexie {
// v16: the trip addons of each trip, on or off for that trip, one list per
// trip, so the tabs a trip switched off stay hidden offline too.
this.version(16).stores({ tripAddons: 'tripId' });
// v17: the globe Atlas offline. `atlasSnapshot` keeps the last answer of
// each Atlas read; `userMutationQueue` holds the account's own writes, which
// belong to no trip (`entity` so a write can ask whether an older one to the
// same thing still waits). Both are new tables: the rows an install already
// holds, its trip queue among them, stay exactly as they are.
this.version(17).stores({
atlasSnapshot: 'part',
userMutationQueue: 'id, status, createdAt, entity',
});
}
}
@@ -464,7 +564,11 @@ export async function deleteCurrentUserDb(): Promise<void> {
await switchTo(ANON_DB_NAME);
return;
}
try { await _db.delete(); } catch { /* ignore — fall through to anon */ }
try {
await _db.delete();
} catch {
/* ignore — fall through to anon */
}
_db = new TrekOfflineDb(ANON_DB_NAME);
await _db.open();
}
@@ -507,7 +611,8 @@ export async function upsertAccommodations(items: Accommodation[]): Promise<void
await offlineDb.accommodations.bulkPut(items);
}
type TripScopedTable = 'days' | 'places' | 'packingItems' | 'todoItems' | 'budgetItems' | 'reservations' | 'tripFiles' | 'accommodations';
type TripScopedTable =
'days' | 'places' | 'packingItems' | 'todoItems' | 'budgetItems' | 'reservations' | 'tripFiles' | 'accommodations';
/**
* Make one trip's rows in `table` match the server's list: put every row it
@@ -516,14 +621,18 @@ type TripScopedTable = 'days' | 'places' | 'packingItems' | 'todoItems' | 'budge
* Rows with a negative (temporary) id were created offline and have not
* synced yet; they stay.
*/
export async function replaceTripRows<T extends { id: number }>(table: TripScopedTable, tripId: number, rows: T[]): Promise<void> {
export async function replaceTripRows<T extends { id: number }>(
table: TripScopedTable,
tripId: number,
rows: T[]
): Promise<void> {
const target = offlineDb[table] as unknown as Table<T, number>;
const keep = new Set(rows.map(r => r.id));
const keep = new Set(rows.map((r) => r.id));
await offlineDb.transaction('rw', target, async () => {
await target
.where('trip_id')
.equals(tripId)
.filter(row => row.id > 0 && !keep.has(row.id))
.filter((row) => row.id > 0 && !keep.has(row.id))
.delete();
await target.bulkPut(rows);
});
@@ -532,8 +641,8 @@ export async function replaceTripRows<T extends { id: number }>(table: TripScope
/** The recorded tracks a cached detail holds, while the list still names the same ones (ACT-01). */
function keptActivities(previous: CachedTour | undefined, tour: TourListItem): Pick<CachedTour, 'activities'> {
const refs = (item: Pick<TourListItem, 'activity_tracks'>) =>
(item.activity_tracks ?? []).map(ref => `${ref.id}:${ref.track_place_id}:${ref.assignment_id}`).join(',')
return previous?.activities && refs(previous) === refs(tour) ? { activities: previous.activities } : {}
(item.activity_tracks ?? []).map((ref) => `${ref.id}:${ref.track_place_id}:${ref.assignment_id}`).join(',');
return previous?.activities && refs(previous) === refs(tour) ? { activities: previous.activities } : {};
}
/**
@@ -544,40 +653,49 @@ function keptActivities(previous: CachedTour | undefined, tour: TourListItem): P
*/
export async function replaceTripTours(tripId: number, tours: TourListItem[]): Promise<void> {
await offlineDb.transaction('rw', offlineDb.tours, async () => {
const cached = new Map((await offlineDb.tours.where('trip_id').equals(tripId).toArray()).map(t => [t.place_id, t]));
const keep = new Set(tours.map(t => t.place_id));
const cached = new Map(
(await offlineDb.tours.where('trip_id').equals(tripId).toArray()).map((t) => [t.place_id, t])
);
const keep = new Set(tours.map((t) => t.place_id));
await offlineDb.tours
.where('trip_id')
.equals(tripId)
.filter(t => t.place_id > 0 && !keep.has(t.place_id))
.filter((t) => t.place_id > 0 && !keep.has(t.place_id))
.delete();
await offlineDb.tours.bulkPut(tours.map(tour => {
const previous = cached.get(tour.place_id);
const sameRoute = previous !== undefined
&& previous.distance === tour.distance
&& previous.elevation_gain === tour.elevation_gain
&& previous.elevation_loss === tour.elevation_loss
&& previous.has_waypoints === tour.has_waypoints;
return {
...tour,
trip_id: tripId,
...(sameRoute && previous.waypoints ? { waypoints: previous.waypoints } : {}),
...(previous?.provenance ? { provenance: previous.provenance } : {}),
...(previous?.obstacle_check ? { obstacle_check: previous.obstacle_check } : {}),
...keptActivities(previous, tour),
// The list carries no packing link (P2D-XD-01); the one last read stays.
...(previous?.packing_link !== undefined ? { packing_link: previous.packing_link } : {}),
};
}));
await offlineDb.tours.bulkPut(
tours.map((tour) => {
const previous = cached.get(tour.place_id);
const sameRoute =
previous !== undefined &&
previous.distance === tour.distance &&
previous.elevation_gain === tour.elevation_gain &&
previous.elevation_loss === tour.elevation_loss &&
previous.has_waypoints === tour.has_waypoints;
return {
...tour,
trip_id: tripId,
...(sameRoute && previous.waypoints ? { waypoints: previous.waypoints } : {}),
...(previous?.provenance ? { provenance: previous.provenance } : {}),
...(previous?.obstacle_check ? { obstacle_check: previous.obstacle_check } : {}),
...keptActivities(previous, tour),
// The list carries no packing link (P2D-XD-01); the one last read stays.
...(previous?.packing_link !== undefined ? { packing_link: previous.packing_link } : {}),
};
})
);
});
}
export async function upsertTripMembers(tripId: number, members: TripMember[]): Promise<void> {
const rows: CachedTripMember[] = members.map(m => ({ ...m, tripId }));
const keep = new Set(rows.map(r => r.id));
const rows: CachedTripMember[] = members.map((m) => ({ ...m, tripId }));
const keep = new Set(rows.map((r) => r.id));
await offlineDb.transaction('rw', offlineDb.tripMembers, async () => {
// A member who left the trip leaves the cached list too.
await offlineDb.tripMembers.where('tripId').equals(tripId).filter(m => !keep.has(m.id)).delete();
await offlineDb.tripMembers
.where('tripId')
.equals(tripId)
.filter((m) => !keep.has(m.id))
.delete();
await offlineDb.tripMembers.bulkPut(rows);
});
}
@@ -604,9 +722,7 @@ export async function getCachedBlob(url: string): Promise<Blob | null> {
try {
const entry = await offlineDb.blobCache.get(url);
if (!entry) return null;
return entry.blob.type
? entry.blob
: new Blob([entry.blob], { type: entry.mime || 'application/octet-stream' });
return entry.blob.type ? entry.blob : new Blob([entry.blob], { type: entry.mime || 'application/octet-stream' });
} catch {
return null;
}
@@ -624,17 +740,22 @@ const IMPORT_FILE_TTL_MS = 60 * 60_000;
export async function saveImportFiles(jobId: string, files: File[]): Promise<void> {
try {
const now = Date.now();
await offlineDb.importFiles.bulkPut(files.map(f => ({ jobId, fileName: f.name, blob: f, createdAt: now })));
await offlineDb.importFiles.bulkPut(files.map((f) => ({ jobId, fileName: f.name, blob: f, createdAt: now })));
// Prune leftovers from imports that were never reviewed.
await offlineDb.importFiles.where('createdAt').below(now - IMPORT_FILE_TTL_MS).delete();
} catch { /* the in-memory copy still serves the no-reload path */ }
await offlineDb.importFiles
.where('createdAt')
.below(now - IMPORT_FILE_TTL_MS)
.delete();
} catch {
/* the in-memory copy still serves the no-reload path */
}
}
/** A job's stored source files, rebuilt as File objects (name + type preserved for upload). */
export async function getImportFiles(jobId: string): Promise<File[]> {
try {
const rows = await offlineDb.importFiles.where('jobId').equals(jobId).toArray();
return rows.map(r => new File([r.blob], r.fileName, { type: r.blob.type || 'application/octet-stream' }));
return rows.map((r) => new File([r.blob], r.fileName, { type: r.blob.type || 'application/octet-stream' }));
} catch {
return [];
}
@@ -642,7 +763,11 @@ export async function getImportFiles(jobId: string): Promise<File[]> {
/** Drop a job's stored source files once they've been handed to the review flow. */
export async function deleteImportFiles(jobId: string): Promise<void> {
try { await offlineDb.importFiles.where('jobId').equals(jobId).delete(); } catch { /* ignore */ }
try {
await offlineDb.importFiles.where('jobId').equals(jobId).delete();
} catch {
/* ignore */
}
}
// ── Blob-cache budget ───────────────────────────────────────────────────────
@@ -662,7 +787,7 @@ export const BLOB_CACHE_MAX_BYTES = 100 * 1024 * 1024; // 100 MB
*/
export async function enforceBlobBudget(
maxCount = BLOB_CACHE_MAX_ENTRIES,
maxBytes = BLOB_CACHE_MAX_BYTES,
maxBytes = BLOB_CACHE_MAX_BYTES
): Promise<void> {
const entries = await offlineDb.blobCache.orderBy('cachedAt').toArray();
let count = entries.length;
@@ -743,7 +868,7 @@ export async function clearTripData(tripId: number): Promise<void> {
// accumulated for the life of the install.
await offlineDb.areaPlaces.where('tripId').equals(tripId).delete();
await offlineDb.ferrataTiles.where('tripId').equals(tripId).delete();
},
}
);
// Remove the trip row itself outside the transaction since it's a separate table
await offlineDb.trips.delete(tripId);