diff --git a/client/scripts/format-baseline.json b/client/scripts/format-baseline.json index 8a6efb1a8..09f4ac76a 100644 --- a/client/scripts/format-baseline.json +++ b/client/scripts/format-baseline.json @@ -139,7 +139,6 @@ "src/components/Admin/useSchoolHolidayCatalog.ts", "src/components/Atlas/AtlasCountryPlaces.test.tsx", "src/components/Atlas/AtlasCountryPlaces.tsx", - "src/components/Atlas/useGlassGlare.ts", "src/components/BackgroundTasks/BackgroundTasksWidget.extra.test.tsx", "src/components/BackgroundTasks/BackgroundTasksWidget.test.tsx", "src/components/BackgroundTasks/BackgroundTasksWidget.tsx", @@ -266,10 +265,6 @@ "src/components/Dashboard/CollectionsWidget.tsx", "src/components/Dawarich/DawarichAcceptDialog.test.tsx", "src/components/Dawarich/DawarichAcceptDialog.tsx", - "src/components/Dawarich/DawarichAtlasDialog.test.tsx", - "src/components/Dawarich/DawarichAtlasDialog.tsx", - "src/components/Dawarich/DawarichAtlasSidePanel.test.tsx", - "src/components/Dawarich/DawarichAtlasSidePanel.tsx", "src/components/Dawarich/DawarichBadge.test.tsx", "src/components/Dawarich/DawarichBadge.tsx", "src/components/Dawarich/DawarichSuggestionsPanel.test.tsx", @@ -1146,7 +1141,6 @@ "src/constants/tripTabs.ts", "src/db/cacheAssignment.ts", "src/db/offlineDb.test.ts", - "src/db/offlineDb.ts", "src/help/contexts/admin.ts", "src/help/contexts/atlas.ts", "src/help/contexts/collections.ts", @@ -1284,12 +1278,9 @@ "src/mobile/screens/admin/MAdminUsersSection.tsx", "src/mobile/screens/admin/MApiProviderBlocks.tsx", "src/mobile/screens/atlas/MAtlas.tsx", - "src/mobile/screens/atlas/MAtlasBucketSheet.tsx", "src/mobile/screens/atlas/MAtlasCountryPopup.test.tsx", "src/mobile/screens/atlas/MAtlasCountryPopup.tsx", - "src/mobile/screens/atlas/MAtlasSearch.tsx", "src/mobile/screens/atlas/MAtlasStatsCard.tsx", - "src/mobile/screens/atlas/atlasController.ts", "src/mobile/screens/collections/MCollAddSheet.tsx", "src/mobile/screens/collections/MCollCategoryPicker.tsx", "src/mobile/screens/collections/MCollEditSheet.tsx", @@ -1440,9 +1431,7 @@ "src/mobile/useIsPhone.ts", "src/pages/AdminPage.test.tsx", "src/pages/AdminPage.tsx", - "src/pages/AtlasPage.test.tsx", "src/pages/AtlasPage.tsx", - "src/pages/AtlasPage.wiring.test.tsx", "src/pages/CollectionsPage.test.tsx", "src/pages/CollectionsPage.tsx", "src/pages/CollectionsPage.wiring.test.tsx", @@ -1508,13 +1497,8 @@ "src/pages/admin/adminModel.ts", "src/pages/admin/useAdmin.ts", "src/pages/admin/useNotificationDefaults.ts", - "src/pages/atlas/AtlasCountrySearch.tsx", - "src/pages/atlas/AtlasLayerToggle.test.tsx", - "src/pages/atlas/AtlasLayerToggle.tsx", "src/pages/atlas/atlasModel.test.ts", "src/pages/atlas/atlasModel.ts", - "src/pages/atlas/useAtlas.test.tsx", - "src/pages/atlas/useAtlas.ts", "src/pages/collections/collectionsModel.test.ts", "src/pages/collections/collectionsModel.ts", "src/pages/collections/useCollections.test.tsx", @@ -1887,10 +1871,7 @@ "tests/unit/mobile/admin/MAdminSheets.test.tsx", "tests/unit/mobile/admin/MAdminStoragePanel.test.tsx", "tests/unit/mobile/admin/MAdminUsersSection.test.tsx", - "tests/unit/mobile/atlas/MAtlas.test.tsx", - "tests/unit/mobile/atlas/MAtlasBucketSheet.test.tsx", "tests/unit/mobile/atlas/MAtlasCountryPopup.test.tsx", - "tests/unit/mobile/atlas/MAtlasSearch.test.tsx", "tests/unit/mobile/atlas/MAtlasStatsCard.test.tsx", "tests/unit/mobile/collections/MCollAddSheet.test.tsx", "tests/unit/mobile/collections/MCollCategoryPicker.test.tsx", diff --git a/client/src/db/offlineDb.ts b/client/src/db/offlineDb.ts index 929c91505..82c2186c7 100644 --- a/client/src/db/offlineDb.ts +++ b/client/src/db/offlineDb.ts @@ -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; + body: unknown; + /** What the write is about, read when its answer is reconciled (e.g. 'atlasCountry'). */ + resource: string; + /** `:`: 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), 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; tripTags!: Table; tripAddons!: Table; + userMutationQueue!: Table; + atlasSnapshot!: Table; 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) => { - 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) => { + 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 { 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(table: TripScopedTable, tripId: number, rows: T[]): Promise { +export async function replaceTripRows( + table: TripScopedTable, + tripId: number, + rows: T[] +): Promise { const target = offlineDb[table] as unknown as Table; - 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(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 { const refs = (item: Pick) => - (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 { 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 { - 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 { 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 { 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 { 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 { /** Drop a job's stored source files once they've been handed to the review flow. */ export async function deleteImportFiles(jobId: string): Promise { - 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 { const entries = await offlineDb.blobCache.orderBy('cachedAt').toArray(); let count = entries.length; @@ -743,7 +868,7 @@ export async function clearTripData(tripId: number): Promise { // 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); diff --git a/client/src/repo/atlasBucketRepo.ts b/client/src/repo/atlasBucketRepo.ts new file mode 100644 index 000000000..c9aec8e8e --- /dev/null +++ b/client/src/repo/atlasBucketRepo.ts @@ -0,0 +1,38 @@ +import apiClient, { mapsApi } from '../api/client'; +import { dawarichApi } from '../api/dawarich'; + +/** Where a point lies on the Atlas: its country and, where there is admin-1 coverage, its region. */ +export interface AtlasLocation { + country_code: string | null; + region_code: string | null; + region_name: string | null; +} + +export interface BucketPlaceHit { + name?: string; + lat?: number; + lng?: number; + address?: string; +} + +/** + * The online lookups of the Atlas: the place search (bucket list form and the + * globe's search), where a place lies, and taking back a wish a Dawarich + * recording ticked off. Online-only on + * purpose, like the searches and the Dawarich reads elsewhere in this folder. + */ +export const atlasBucketRepo = { + async searchPlaces(query: string, lang: string): Promise { + const result = await mapsApi.search(query, lang); + return (result.places ?? []) as BucketPlaceHit[]; + }, + + /** The country and region a searched place lies in, for the globe's place search. */ + async locate(lat: number, lng: number): Promise { + return (await apiClient.get('/addons/atlas/locate', { params: { lat, lng } })).data as AtlasLocation; + }, + + async clearVisit(itemId: number): Promise { + await dawarichApi.clearBucketVisit(itemId); + }, +}; diff --git a/client/src/repo/atlasPluginLayersRepo.ts b/client/src/repo/atlasPluginLayersRepo.ts new file mode 100644 index 000000000..c405ac08e --- /dev/null +++ b/client/src/repo/atlasPluginLayersRepo.ts @@ -0,0 +1,19 @@ +import { pluginsApi, type PluginAtlasLayer } from '../api/client'; + +export type { PluginAtlasLayer }; + +/** + * The country tints plugins add to the Atlas (atlasLayerProvider hook). Online-only + * and fail-safe on purpose: a plugin overlay is decoration over the user's own map, + * so when it cannot be read the Atlas simply shows none. + */ +export const atlasPluginLayersRepo = { + async layers(): Promise { + try { + const r = await pluginsApi.atlasLayers(); + return r.layers ?? []; + } catch { + return []; + } + }, +}; diff --git a/client/src/repo/atlasRepo.offline.test.ts b/client/src/repo/atlasRepo.offline.test.ts new file mode 100644 index 000000000..01a808ed4 --- /dev/null +++ b/client/src/repo/atlasRepo.offline.test.ts @@ -0,0 +1,193 @@ +// The globe Atlas through the offline core: reads kept in Dexie and served +// offline, writes queued in the account queue and laid over every read. +import 'fake-indexeddb/auto'; +import { http, HttpResponse } from 'msw'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { server } from '../../tests/helpers/msw/server'; +import { clearAll, offlineDb } from '../db/offlineDb'; +import { setAuthed } from '../sync/authGate'; +import { mutationQueue } from '../sync/mutationQueue'; +import { ATLAS_NOT_CACHED, atlasRepo } from './atlasRepo'; + +function setOnline(value: boolean): void { + Object.defineProperty(navigator, 'onLine', { value, writable: true, configurable: true }); +} + +const STATS = { + countries: [ + { code: 'PT', tripCount: 1, placeCount: 4, status: 'visited' }, + { code: 'ES', tripCount: 0, placeCount: 0, status: 'planned' }, + ], + stats: { totalCountries: 1, totalCountriesPlanned: 1, totalTrips: 1, totalPlaces: 4, totalDays: 3 }, + continents: { Europe: 1 }, + continentsPlanned: { Europe: 1 }, +}; + +/** Answer every Atlas read the way the server does. */ +function serveAtlas(): void { + server.use( + http.get('/api/addons/atlas/stats', () => HttpResponse.json(STATS)), + http.get('/api/addons/atlas/regions', () => + HttpResponse.json({ regions: { PT: [{ code: 'PT-11', name: 'Lisboa', placeCount: 4, status: 'visited' }] } }) + ), + http.get('/api/addons/atlas/bucket-list', () => + HttpResponse.json({ + items: [ + { id: 7, name: 'Azores' }, + { id: 8, name: 'Madeira' }, + ], + }) + ), + http.get('/api/addons/atlas/flights', () => + HttpResponse.json({ routes: [], airports: [], totals: { flights: 0, km: 0, airports: 0, longestKm: 0 } }) + ) + ); +} + +/** Read everything once online, so the device keeps it. */ +async function readOnline(): Promise { + serveAtlas(); + await Promise.all([atlasRepo.stats(), atlasRepo.regions(), atlasRepo.bucketList(), atlasRepo.flights()]); +} + +type Stats = typeof STATS; + +beforeEach(async () => { + await clearAll(); + mutationQueue._resetFlushing(); + setAuthed(true); + setOnline(true); +}); + +afterEach(() => { + vi.restoreAllMocks(); + setAuthed(false); + setOnline(true); +}); + +describe('atlasRepo reads', () => { + it('FE-REPO-ATLAS-001: an online read keeps the answer and an offline one serves it', async () => { + await readOnline(); + setOnline(false); + + expect(await atlasRepo.stats()).toEqual(STATS); + expect(Object.keys(await atlasRepo.regions())).toEqual(['PT']); + expect(await atlasRepo.bucketList()).toHaveLength(2); + expect((await atlasRepo.flights()).totals.flights).toBe(0); + }); + + it('FE-REPO-ATLAS-002: a request that never reaches the server falls back to the kept answer', async () => { + await readOnline(); + server.use(http.get('/api/addons/atlas/stats', () => HttpResponse.error())); + + expect(await atlasRepo.stats()).toEqual(STATS); + }); + + it('FE-REPO-ATLAS-003: offline before the first read says so, and a server error is not swallowed', async () => { + setOnline(false); + await expect(atlasRepo.stats()).rejects.toThrow(ATLAS_NOT_CACHED); + + setOnline(true); + server.use(http.get('/api/addons/atlas/regions', () => HttpResponse.json({ error: 'boom' }, { status: 500 }))); + await expect(atlasRepo.regions()).rejects.toMatchObject({ response: { status: 500 } }); + }); +}); + +describe('atlasRepo writes offline', () => { + it('FE-REPO-ATLAS-010: a country marked offline waits in the account queue and every read shows it', async () => { + await readOnline(); + setOnline(false); + + await atlasRepo.markCountry('ES'); + await atlasRepo.markCountry('IS'); + + const [first, second] = await offlineDb.userMutationQueue.orderBy('createdAt').toArray(); + expect(first).toMatchObject({ method: 'POST', url: '/addons/atlas/country/ES/mark', entity: 'atlasCountry:ES' }); + expect(second.entity).toBe('atlasCountry:IS'); + const stats = (await atlasRepo.stats()) as Stats; + expect(stats.countries.map((c) => `${c.code}:${c.status}`)).toEqual(['PT:visited', 'ES:visited', 'IS:visited']); + expect(stats.stats).toMatchObject({ totalCountries: 3, totalCountriesPlanned: 0 }); + // What the device keeps is still what the server said. + expect((await offlineDb.atlasSnapshot.get('stats'))?.data).toEqual(STATS); + }); + + it('FE-REPO-ATLAS-011: a fresh server answer cannot hide a write that has not gone out', async () => { + await readOnline(); + setOnline(false); + await atlasRepo.unmarkRegion('PT-11'); + await atlasRepo.markRegion('ES-CT', 'Catalunya', 'ES'); + await atlasRepo.deleteBucketItem(7); + setAuthed(false); // keep the queue from sending while the reads run + setOnline(true); + + const regions = await atlasRepo.regions(); + expect(regions.PT[0]).toMatchObject({ code: 'PT-11', manuallyMarked: false }); + expect(regions.ES).toEqual([ + { code: 'ES-CT', name: 'Catalunya', placeCount: 0, status: 'visited', manuallyMarked: true }, + ]); + expect(((await atlasRepo.bucketList()) as Array<{ id: number }>).map((b) => b.id)).toEqual([8]); + }); +}); + +describe('atlasRepo writes online', () => { + it('FE-REPO-ATLAS-020: an online write goes straight out and stays in the kept reads', async () => { + await readOnline(); + const keys: Array = []; + server.use( + http.post('/api/addons/atlas/country/IS/mark', ({ request }) => { + keys.push(request.headers.get('X-Idempotency-Key')); + return HttpResponse.json({ success: true }); + }) + ); + + await atlasRepo.markCountry('IS'); + + expect(keys).toHaveLength(1); + expect(await offlineDb.userMutationQueue.count()).toBe(0); + setOnline(false); + const stats = (await atlasRepo.stats()) as Stats; + expect(stats.countries.some((c) => c.code === 'IS' && c.status === 'visited')).toBe(true); + }); + + it('FE-REPO-ATLAS-021: online behind an older queued write, a write waits in line', async () => { + await readOnline(); + setAuthed(false); // the flush stays off, so the line is visible + setOnline(false); + await atlasRepo.markCountry('ES'); + setOnline(true); + let direct = 0; + server.use( + http.delete('/api/addons/atlas/country/ES/mark', () => { + direct += 1; + return HttpResponse.json({ success: true }); + }) + ); + + await atlasRepo.unmarkCountry('ES'); + + expect(direct).toBe(0); + expect((await offlineDb.userMutationQueue.orderBy('createdAt').toArray()).map((row) => row.method)).toEqual([ + 'POST', + 'DELETE', + ]); + }); + + it('FE-REPO-ATLAS-022: a write whose request never reaches the server is queued under the key it was sent with', async () => { + await readOnline(); + setAuthed(false); + const keys: Array = []; + server.use( + http.delete('/api/addons/atlas/bucket-list/8', ({ request }) => { + keys.push(request.headers.get('X-Idempotency-Key')); + return HttpResponse.error(); + }) + ); + + await atlasRepo.deleteBucketItem(8); + + const [row] = await offlineDb.userMutationQueue.toArray(); + expect(row.id).toBe(keys[0]); + expect(((await atlasRepo.bucketList()) as Array<{ id: number }>).map((b) => b.id)).toEqual([7]); + }); +}); diff --git a/client/src/repo/atlasRepo.ts b/client/src/repo/atlasRepo.ts new file mode 100644 index 000000000..a0d58490d --- /dev/null +++ b/client/src/repo/atlasRepo.ts @@ -0,0 +1,244 @@ +import apiClient from '../api/client'; +import type { AtlasSnapshotPart } from '../db/offlineDb'; +import { + ATLAS_RESOURCE, + keepAtlasPart, + keptAtlasPart, + reconcileAtlasWrite, + withWaitingWrites, +} from '../sync/atlasSnapshot'; +import { generateUUID, mutationQueue } from '../sync/mutationQueue'; +import { userMutationQueue } from '../sync/userMutationQueue'; +import { isNetworkError, onlineThenCache } from './withOfflineFallback'; + +/** + * Reads and writes of the globe Atlas, offline-first. + * + * Reads go to the server first and keep its answer in Dexie (`atlasSnapshot`, + * one row per read); offline, or when the request never reached the server, + * the kept answer is served. Writes go straight to the server online and wait + * in the account's own queue (sync/userMutationQueue) offline, or online while + * an older Atlas write is still queued, so they keep their order. Every read + * lays the writes still waiting over its answer (sync/atlasSnapshot), so a + * mark made offline shows at once and a fresh server answer cannot hide it. + * + * Online only, said on purpose: the people of the instance (a live directory), + * a country's detail, adding a wish (the server refuses a duplicate), and the + * globe geometry, which the browser and the service worker cache as hashed files. + */ + +export interface AtlasRegionRow { + code: string; + name: string; + placeCount: number; + status?: 'visited' | 'planned' | 'idea'; + manuallyMarked?: boolean; +} + +export interface AtlasFlightAirport { + code: string | null; + name: string; + lat: number; + lng: number; +} + +export interface AtlasFlights { + routes: Array<{ + a: AtlasFlightAirport; + b: AtlasFlightAirport; + count: number; + km: number; + firstDate: string | null; + lastDate: string | null; + }>; + airports: Array; + totals: { flights: number; km: number; airports: number; longestKm: number }; +} + +export interface AtlasPerson { + id: number; + countries: number; + continents: number; + regions: number; + flightKm: number; + codes: string[]; + badges: Array< + Pick + >; +} + +interface AtlasDirectoryUser { + id: number; + username: string; + avatar_url?: string | null; +} + +/** Thrown by a read offline when this device never read it online. */ +export const ATLAS_NOT_CACHED = 'The Atlas has not been opened online on this device yet'; + +/** + * Network first, the kept answer when there is none, and the waiting writes + * laid over either. `fetch` answers what the read returns, unwrapped. + */ +async function readThrough(part: AtlasSnapshotPart, fetch: () => Promise): Promise { + return onlineThenCache( + async () => { + const data = await fetch(); + await keepAtlasPart(part, data); + return (await withWaitingWrites(part, data)) as T; + }, + async () => { + const kept = await keptAtlasPart(part); + if (!kept) throw new Error(ATLAS_NOT_CACHED); + return (await withWaitingWrites(part, kept.data)) as T; + } + ); +} + +interface WriteSpec { + method: 'POST' | 'DELETE'; + url: string; + body?: unknown; + resource: string; + /** `:`: the later writes to one entity wait behind a parked one. */ + entity: string; +} + +/** + * Send a write now, or queue it: offline, or while an older Atlas write is + * queued (see mustQueue). A request that never reached the server is queued + * too, under the same idempotency key, so a write whose answer was lost on the + * way is not made twice. A write that went through is laid into the kept + * reads, so it stays there offline. + */ +async function write(spec: WriteSpec): Promise { + const id = generateUUID(); + const body = spec.body ?? null; + if (!(await userMutationQueue.mustQueue(spec.entity, []))) { + try { + const res = await apiClient.request({ + method: spec.method, + url: spec.url, + data: spec.body, + headers: { 'X-Idempotency-Key': id }, + }); + await reconcileAtlasWrite({ ...spec, ids: {}, body, createdAt: Date.now(), answer: res.data }); + return; + } catch (err) { + if (!isNetworkError(err)) throw err; + } + } + await userMutationQueue.enqueue({ + id, + method: spec.method, + url: spec.url, + ids: {}, + body, + resource: spec.resource, + entity: spec.entity, + }); + mutationQueue.sendSoon(); +} + +export const atlasRepo = { + /** Everyone on this instance (the app's user directory) with their Atlas counts. */ + async people(): Promise> { + const dir = ((await apiClient.get('/auth/users')).data?.users ?? []) as AtlasDirectoryUser[]; + if (!dir.length) return []; + const ids = dir.map((u) => u.id).join(','); + const people = ((await apiClient.get('/addons/atlas/people', { params: { ids } })).data?.people ?? + []) as AtlasPerson[]; + const byId = new Map(dir.map((u) => [u.id, u])); + return people.map((p) => ({ + ...p, + username: byId.get(p.id)?.username ?? '?', + avatar_url: byId.get(p.id)?.avatar_url ?? null, + })); + }, + + async flights(): Promise { + return readThrough('flights', async () => (await apiClient.get('/addons/atlas/flights')).data as AtlasFlights); + }, + + /** A file below /api/addons/atlas/mesh/ (the manifest or a hashed topology). */ + async mesh(path: string): Promise { + const res = await apiClient.get(`/addons/atlas/mesh/${path}`, { timeout: 30000 }); + return res.data; + }, + + async stats(): Promise { + return readThrough('stats', async () => (await apiClient.get('/addons/atlas/stats')).data as unknown); + }, + + async regions(): Promise> { + return readThrough('regions', async () => { + const res = await apiClient.get('/addons/atlas/regions'); + return (res.data?.regions ?? {}) as Record; + }); + }, + + async bucketList(): Promise { + return readThrough('bucketList', async () => { + const res = await apiClient.get('/addons/atlas/bucket-list'); + return (res.data?.items ?? []) as unknown[]; + }); + }, + + async countryDetail(code: string): Promise { + return (await apiClient.get(`/addons/atlas/country/${code}`)).data; + }, + + async markCountry(code: string): Promise { + await write({ + method: 'POST', + url: `/addons/atlas/country/${code}/mark`, + resource: ATLAS_RESOURCE.country, + entity: `${ATLAS_RESOURCE.country}:${code}`, + }); + }, + + async unmarkCountry(code: string): Promise { + await write({ + method: 'DELETE', + url: `/addons/atlas/country/${code}/mark`, + resource: ATLAS_RESOURCE.country, + entity: `${ATLAS_RESOURCE.country}:${code}`, + }); + }, + + async markRegion(code: string, name: string, countryCode: string): Promise { + await write({ + method: 'POST', + url: `/addons/atlas/region/${code}/mark`, + body: { name, country_code: countryCode }, + resource: ATLAS_RESOURCE.region, + entity: `${ATLAS_RESOURCE.region}:${code}`, + }); + }, + + async unmarkRegion(code: string): Promise { + await write({ + method: 'DELETE', + url: `/addons/atlas/region/${code}/mark`, + resource: ATLAS_RESOURCE.region, + entity: `${ATLAS_RESOURCE.region}:${code}`, + }); + }, + + /** Online only: the server refuses a wish that is on the list already (409). */ + async addBucketItem(data: Record): Promise { + const item = (await apiClient.post('/addons/atlas/bucket-list', data)).data?.item as unknown; + const kept = await keptAtlasPart('bucketList'); + if (kept && Array.isArray(kept.data) && item) await keepAtlasPart('bucketList', [item, ...kept.data]); + return item; + }, + + async deleteBucketItem(id: number): Promise { + await write({ + method: 'DELETE', + url: `/addons/atlas/bucket-list/${id}`, + resource: ATLAS_RESOURCE.bucket, + entity: `${ATLAS_RESOURCE.bucket}:${id}`, + }); + }, +}; diff --git a/client/src/repo/dawarichRepo.ts b/client/src/repo/dawarichRepo.ts index 68b6b4c32..78501e0b4 100644 --- a/client/src/repo/dawarichRepo.ts +++ b/client/src/repo/dawarichRepo.ts @@ -70,4 +70,14 @@ export const dawarichRepo = { requireOnline() return dawarichAtlasSuggestionsSchema.parse(await dawarichApi.atlasSuggestions(from, to)) }, + + /** Ticks wishes off as reached on the day a recording put the user there; online only, the caller checks. */ + async confirmBucketVisits(itemIds: number[], visitedAt?: string): Promise<{ updated: number }> { + return await dawarichApi.confirmBucketVisits(itemIds, visitedAt) + }, + + /** Marks the countries Dawarich saw as visited in the Atlas; online only, the caller checks. */ + async acceptAtlasCountries(countryCodes: string[]): Promise<{ marked: number }> { + return await dawarichApi.acceptAtlasCountries(countryCodes) + }, } diff --git a/client/src/sync/atlasSnapshot.ts b/client/src/sync/atlasSnapshot.ts new file mode 100644 index 000000000..932944beb --- /dev/null +++ b/client/src/sync/atlasSnapshot.ts @@ -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; + +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; + continents?: Record; + continentsPlanned?: Record; +} + +function asStats(data: unknown): StatsShape | null { + return Array.isArray(fields(data).countries) ? (data as StatsShape) : null; +} + +function bump(counts: Record | undefined, key: string, by: number): Record { + return { ...counts, [key]: Math.max(0, (counts?.[key] ?? 0) + by) }; +} + +function total(s: StatsShape, key: string, by: number): Record { + 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; + +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 { + 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 { + 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 { + 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 { + 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 }); + } + }); +} diff --git a/client/src/sync/mutationQueue.ts b/client/src/sync/mutationQueue.ts index e721513ea..7d0642491 100644 --- a/client/src/sync/mutationQueue.ts +++ b/client/src/sync/mutationQueue.ts @@ -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, 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 { - 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 { - 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 { 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() }, } diff --git a/client/src/sync/queuePolicy.ts b/client/src/sync/queuePolicy.ts new file mode 100644 index 000000000..f8ebf6003 --- /dev/null +++ b/client/src/sync/queuePolicy.ts @@ -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__ : ''; diff --git a/client/src/sync/userMutationQueue.ts b/client/src/sync/userMutationQueue.ts new file mode 100644 index 000000000..786459fd8 --- /dev/null +++ b/client/src/sync/userMutationQueue.ts @@ -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 { + 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): Record | null { + const out: Record = {}; + 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): Promise { + 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, 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 { + 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): Promise { + 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 { + 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 { + 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 { + 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(); + for (const row of await table.where('status').equals('failed').toArray()) hold(held, row); + const idMap = new Map(); + 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 { + 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 { + 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 { + await offlineDb.userMutationQueue.where('status').equals('failed').delete(); + }, + + /** Reset the createdAt counter — tests only, through mutationQueue._resetFlushing. */ + _reset(): void { + lastCreatedAt = 0; + }, +}; diff --git a/client/tests/unit/db/offlineDb.upgrade.test.ts b/client/tests/unit/db/offlineDb.upgrade.test.ts index a13502472..2828275cc 100644 --- a/client/tests/unit/db/offlineDb.upgrade.test.ts +++ b/client/tests/unit/db/offlineDb.upgrade.test.ts @@ -59,6 +59,7 @@ const HISTORY: Record = { 14: { routeCache: 'key, savedAt' }, 15: { tripTags: 'tripId' }, 16: { tripAddons: 'tripId' }, + 17: { atlasSnapshot: 'part', userMutationQueue: 'id, status, createdAt, entity' }, }; const HISTORY_VERSIONS = Object.keys(HISTORY) @@ -147,6 +148,22 @@ function rowsAt(version: number): Record> { { id: 'budget', name: 'Costs', icon: 'Wallet', enabled: false, instanceEnabled: true, overridden: true }, ], }, + atlasSnapshot: { part: 'stats', data: { countries: [{ code: 'PT', status: 'visited' }], stats: {} } }, + userMutationQueue: { + id: 'account-1', + method: 'POST', + url: '/addons/atlas/country/PT/mark', + ids: {}, + body: null, + resource: 'atlasCountry', + entity: 'atlasCountry:PT', + createdAt: 2, + status: 'pending', + attempts: 0, + lastError: null, + schemaVersion: 1, + buildVersion: '5.3.0', + }, }; const tables = schemaAt(version); return Object.fromEntries(Object.entries(all).filter(([table]) => table in tables)); @@ -417,6 +434,28 @@ const UPGRADE_CASES: Record = { expect((await db.tripAddons.get(1))?.addons[0]).toMatchObject({ id: 'budget', enabled: true, overridden: false }); }, }, + 17: { + intent: 'adds the kept Atlas reads and the account queue, and leaves the trip queue as it was', + check: async (db) => { + // The trip queue an install already holds is not touched: same row, same indexes. + expect(await db.mutationQueue.where('tripId').equals(1).count()).toBe(1); + expect(await db.mutationQueue.get('queued-1')).not.toHaveProperty('scope'); + expect(await db.atlasSnapshot.count()).toBe(0); + expect(await db.userMutationQueue.count()).toBe(0); + // One kept answer per read: a second one replaces the first. + await db.atlasSnapshot.put({ part: 'regions', data: { DE: [] } }); + await db.atlasSnapshot.put({ part: 'regions', data: { FR: [] } }); + expect(await db.atlasSnapshot.count()).toBe(1); + expect((await db.atlasSnapshot.get('regions'))?.data).toEqual({ FR: [] }); + await db.table('userMutationQueue').bulkPut([ + { id: 'a', entity: 'atlasCountry:DE', status: 'pending', createdAt: 2, ids: {} }, + { id: 'b', entity: 'atlasCountry:FR', status: 'failed', createdAt: 1, ids: {} }, + ]); + expect(await db.userMutationQueue.where('entity').equals('atlasCountry:DE').count()).toBe(1); + expect(await db.userMutationQueue.where('status').equals('failed').count()).toBe(1); + expect(await db.userMutationQueue.orderBy('createdAt').primaryKeys()).toEqual(['b', 'a']); + }, + }, }; describe('offlineDb upgrades', () => { diff --git a/client/tests/unit/sync/userMutationQueue.test.ts b/client/tests/unit/sync/userMutationQueue.test.ts new file mode 100644 index 000000000..472919f81 --- /dev/null +++ b/client/tests/unit/sync/userMutationQueue.test.ts @@ -0,0 +1,292 @@ +/** + * The account queue: offline writes that belong to no trip (the globe Atlas). + * They replay inside mutationQueue.flush(), under its lock, by the trip queue's + * rules, and never need a trip id. The temporary-id cases use a made-up + * parent/child pair: the queue resolves the id of any create queued before it. + */ +import 'fake-indexeddb/auto'; +import { http, HttpResponse } from 'msw'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { clearAll, MUTATION_SCHEMA_VERSION, offlineDb, type UserQueuedMutation } from '../../../src/db/offlineDb'; +import { setAuthed } from '../../../src/sync/authGate'; +import { generateUUID, mutationQueue } from '../../../src/sync/mutationQueue'; +import { userMutationQueue, type UserMutationInput } from '../../../src/sync/userMutationQueue'; +import { server } from '../../helpers/msw/server'; + +function setOnline(value: boolean): void { + Object.defineProperty(navigator, 'onLine', { value, writable: true, configurable: true }); +} + +function input(overrides: Partial = {}): UserMutationInput { + return { + id: generateUUID(), + method: 'POST', + url: '/addons/atlas/country/DE/mark', + ids: {}, + body: null, + resource: 'atlasCountry', + entity: 'atlasCountry:DE', + ...overrides, + }; +} + +async function rows(): Promise { + return offlineDb.userMutationQueue.orderBy('createdAt').toArray(); +} + +beforeEach(async () => { + await clearAll(); + mutationQueue._resetFlushing(); + setAuthed(true); + setOnline(true); +}); + +afterEach(() => { + vi.restoreAllMocks(); + setAuthed(false); + setOnline(true); +}); + +describe('userMutationQueue', () => { + it('FE-SYNC-USERQ-001: stamps a queued write with its format and build, in the order made, without a trip id', async () => { + await userMutationQueue.enqueue(input()); + await userMutationQueue.enqueue(input({ url: '/addons/atlas/country/FR/mark', entity: 'atlasCountry:FR' })); + + const queued = await rows(); + expect(queued.map((row) => row.entity)).toEqual(['atlasCountry:DE', 'atlasCountry:FR']); + expect(queued[0]).toMatchObject({ status: 'pending', attempts: 0, schemaVersion: MUTATION_SCHEMA_VERSION }); + expect(queued[0].buildVersion).toBe(__TREK_UI_VERSION__); + expect(queued[0]).not.toHaveProperty('tripId'); + // The trip queue holds none of it. + expect(await offlineDb.mutationQueue.count()).toBe(0); + }); + + it('FE-SYNC-USERQ-002: flush replays it with its id as the idempotency key and drops it', async () => { + const keys: Array = []; + server.use( + http.post('/api/addons/atlas/country/DE/mark', ({ request }) => { + keys.push(request.headers.get('X-Idempotency-Key')); + return HttpResponse.json({ success: true }); + }) + ); + const id = await userMutationQueue.enqueue(input()); + + await mutationQueue.flush(); + + expect(keys).toEqual([id]); + expect(await offlineDb.userMutationQueue.count()).toBe(0); + }); + + it('FE-SYNC-USERQ-003: a create made offline hands its real id to the writes queued against it', async () => { + const sent: string[] = []; + server.use( + http.post('/api/addons/atlas/parents', () => { + sent.push('create'); + return HttpResponse.json({ id: 12 }, { status: 201 }); + }), + http.post('/api/addons/atlas/parents/:id/children', ({ params }) => { + sent.push(`child:${String(params.id)}`); + return HttpResponse.json({ id: 40 }); + }) + ); + await userMutationQueue.enqueue( + input({ + url: '/addons/atlas/parents', + resource: 'atlasParent', + entity: 'atlasParent:-5', + tempId: -5, + body: { name: 'A' }, + }) + ); + await userMutationQueue.enqueue( + input({ + url: '/addons/atlas/parents/{parent}/children', + ids: { parent: -5 }, + resource: 'atlasChild', + entity: 'atlasChild:-6', + tempId: -6, + body: { name: 'B' }, + }) + ); + + await mutationQueue.flush(); + + expect(sent).toEqual(['create', 'child:12']); + expect(await offlineDb.userMutationQueue.count()).toBe(0); + }); + + it('FE-SYNC-USERQ-004: a write left behind learns the real id durably for the next pass', async () => { + server.use( + http.post('/api/addons/atlas/parents', () => HttpResponse.json({ id: 12 })), + http.put('/api/addons/atlas/parents/:id', () => HttpResponse.json({ error: 'busy' }, { status: 503 })) + ); + await userMutationQueue.enqueue( + input({ + url: '/addons/atlas/parents', + resource: 'atlasParent', + entity: 'atlasParent:-5', + tempId: -5, + body: { name: 'A' }, + }) + ); + await userMutationQueue.enqueue( + input({ + method: 'PUT', + url: '/addons/atlas/parents/{parent}', + ids: { parent: -5 }, + resource: 'atlasParent', + entity: 'atlasParent:-5', + body: { color: '#fff' }, + }) + ); + + await mutationQueue.flush(); + + const [left] = await rows(); + expect(left).toMatchObject({ ids: { parent: 12 }, entity: 'atlasParent:12', status: 'pending', attempts: 1 }); + expect(left.retryAfter).toBeGreaterThan(Date.now()); + }); + + it('FE-SYNC-USERQ-005: a refused create parks itself and the write that needed its id', async () => { + server.use(http.post('/api/addons/atlas/parents', () => HttpResponse.json({ error: 'bad' }, { status: 400 }))); + await userMutationQueue.enqueue( + input({ url: '/addons/atlas/parents', resource: 'atlasParent', entity: 'atlasParent:-5', tempId: -5, body: {} }) + ); + await userMutationQueue.enqueue( + input({ + method: 'DELETE', + url: '/addons/atlas/parents/{parent}', + ids: { parent: -5 }, + resource: 'atlasParent', + entity: 'atlasParent:-7', + }) + ); + + await mutationQueue.flush(); + + const queued = await rows(); + expect(queued.map((row) => row.status)).toEqual(['failed', 'failed']); + expect(queued[1].lastError).toContain('unresolved temp id'); + expect(await mutationQueue.failedCount()).toBe(2); + }); + + it('FE-SYNC-USERQ-006: a parked write holds back the later writes to its entity, not the others', async () => { + const sent: string[] = []; + server.use( + http.post('/api/addons/atlas/country/:code/mark', ({ params }) => { + sent.push(String(params.code)); + return HttpResponse.json({ success: true }); + }), + http.delete('/api/addons/atlas/country/:code/mark', ({ params }) => { + sent.push(`-${String(params.code)}`); + return HttpResponse.json({ success: true }); + }) + ); + await userMutationQueue.enqueue(input()); + await offlineDb.userMutationQueue.toCollection().modify({ status: 'failed' }); + await userMutationQueue.enqueue(input({ method: 'DELETE' })); + await userMutationQueue.enqueue(input({ url: '/addons/atlas/country/FR/mark', entity: 'atlasCountry:FR' })); + + await mutationQueue.flush(); + + expect(sent).toEqual(['FR']); + expect((await rows()).map((row) => `${row.entity}:${row.status}`)).toEqual([ + 'atlasCountry:DE:failed', + 'atlasCountry:DE:pending', + ]); + + await mutationQueue.retryFailed(); + + expect(sent).toEqual(['FR', 'DE', '-DE']); + expect(await offlineDb.userMutationQueue.count()).toBe(0); + }); + + it('FE-SYNC-USERQ-007: a write from a newer format is left alone and holds its entity', async () => { + const sent: string[] = []; + server.use( + http.all('/api/addons/atlas/*', ({ request }) => { + sent.push(request.method); + return HttpResponse.json({ success: true }); + }) + ); + await userMutationQueue.enqueue(input()); + await offlineDb.userMutationQueue.toCollection().modify({ schemaVersion: MUTATION_SCHEMA_VERSION + 1 }); + await userMutationQueue.enqueue(input({ method: 'DELETE' })); + + await mutationQueue.flush(); + + expect(sent).toEqual([]); + expect((await rows()).map((row) => row.status)).toEqual(['pending', 'pending']); + }); + + it('FE-SYNC-USERQ-008: a delete the server no longer has is done, a lost connection keeps the write', async () => { + server.use( + http.delete('/api/addons/atlas/bucket-list/7', () => HttpResponse.json({ error: 'gone' }, { status: 404 })), + http.delete('/api/addons/atlas/bucket-list/8', () => HttpResponse.error()) + ); + await userMutationQueue.enqueue( + input({ method: 'DELETE', url: '/addons/atlas/bucket-list/7', resource: 'atlasBucket', entity: 'atlasBucket:7' }) + ); + await userMutationQueue.enqueue( + input({ method: 'DELETE', url: '/addons/atlas/bucket-list/8', resource: 'atlasBucket', entity: 'atlasBucket:8' }) + ); + + await mutationQueue.flush(); + + const [left] = await rows(); + expect(left).toMatchObject({ entity: 'atlasBucket:8', status: 'pending', attempts: 1 }); + expect(await mutationQueue.pendingCount()).toBe(1); + }); + + it('FE-SYNC-USERQ-009: discarding the parked changes drops the account ones too', async () => { + await userMutationQueue.enqueue(input()); + await offlineDb.userMutationQueue.toCollection().modify({ status: 'failed' }); + + await mutationQueue.discardFailed(); + + expect(await offlineDb.userMutationQueue.count()).toBe(0); + }); + + it('FE-SYNC-USERQ-010: an online write joins the queue only behind an older one, or naming a create still waiting', async () => { + expect(await userMutationQueue.mustQueue('atlasCountry:DE', [])).toBe(false); + expect(await userMutationQueue.mustQueue(null, [-3])).toBe(true); + + await userMutationQueue.enqueue(input()); + expect(await userMutationQueue.mustQueue('atlasCountry:FR', [])).toBe(true); + + // A parked write holds only its own entity. + await offlineDb.userMutationQueue.toCollection().modify({ status: 'failed' }); + expect(await userMutationQueue.mustQueue('atlasCountry:FR', [])).toBe(false); + expect(await userMutationQueue.mustQueue('atlasCountry:DE', [])).toBe(true); + + setOnline(false); + expect(await userMutationQueue.mustQueue('atlasCountry:FR', [])).toBe(true); + }); + + it('FE-SYNC-USERQ-011: a stuck syncing row from a killed tab is sent again', async () => { + const sent: number[] = []; + server.use( + http.post('/api/addons/atlas/country/DE/mark', () => { + sent.push(1); + return HttpResponse.json({ success: true }); + }) + ); + await userMutationQueue.enqueue(input()); + await offlineDb.userMutationQueue.toCollection().modify({ status: 'syncing', syncingSince: Date.now() - 120_000 }); + + await mutationQueue.flush(); + + expect(sent).toEqual([1]); + expect(await offlineDb.userMutationQueue.count()).toBe(0); + }); + + it('FE-SYNC-USERQ-012: nothing goes out signed out', async () => { + setAuthed(false); + await userMutationQueue.enqueue(input()); + + await mutationQueue.flush(); + + expect((await rows())[0].status).toBe('pending'); + }); +});