fix(atlas): reconcile offline country and region changes together

Keep country and region reads in step with queued writes and with the mark source held by the server. Reconcile a delete already applied elsewhere before removing it from the account queue.
This commit is contained in:
Maurice
2026-12-06 17:20:49 +01:00
parent da0ecc3f88
commit e3922b76d8
13 changed files with 328 additions and 110 deletions
+32 -1
View File
@@ -138,7 +138,7 @@ describe('atlasRepo writes offline', () => {
setOnline(true);
const regions = await atlasRepo.regions();
expect(regions.PT[0]).toMatchObject({ code: 'PT-11', manuallyMarked: false });
expect(regions.PT).toBeUndefined();
expect(regions.ES).toEqual([
{ code: 'ES-CT', name: 'Catalunya', placeCount: 0, status: 'visited', manuallyMarked: true },
]);
@@ -194,6 +194,37 @@ describe('atlasRepo writes online', () => {
await expect(atlasRepo.addBucketItem({ name: 'Faro' })).resolves.toEqual({ id: 9, name: 'Faro' });
});
it('FE-REPO-ATLAS-025: a wish removed elsewhere stays gone after the queued delete gets a 404', async () => {
await readOnline();
setOnline(false);
await atlasRepo.deleteBucketItem(7);
server.use(http.delete('/api/addons/atlas/bucket-list/7', () => new HttpResponse(null, { status: 404 })));
setOnline(true);
await mutationQueue.flush();
setOnline(false);
expect(await offlineDb.userMutationQueue.count()).toBe(0);
expect(await atlasRepo.bucketList()).toEqual([{ id: 8, name: 'Madeira' }]);
});
it('FE-REPO-ATLAS-026: replaying a region removal refreshes a legacy country read with unknown provenance', async () => {
await readOnline();
setOnline(false);
await atlasRepo.unmarkRegion('PT-11');
server.use(
http.delete('/api/addons/atlas/region/PT-11/mark', () => HttpResponse.json({ success: true })),
http.get('/api/addons/atlas/stats', () => HttpResponse.json({ countries: [STATS.countries[1]] }))
);
setOnline(true);
await mutationQueue.flush();
setOnline(false);
expect(await atlasRepo.stats()).toEqual({ countries: [STATS.countries[1]] });
expect(await atlasRepo.regions()).toEqual({});
});
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
+6 -3
View File
@@ -127,7 +127,7 @@ async function write(spec: WriteSpec): Promise<void> {
headers: { 'X-Idempotency-Key': id },
});
if (account === offlineDb.name) {
await reconcileAtlasWrite({ ...spec, ids: {}, body, createdAt: Date.now() }).catch(() => undefined);
await reconcileAtlasWrite({ ...spec, body }).catch(() => undefined);
}
return;
} catch (err) {
@@ -174,12 +174,15 @@ export const atlasRepo = {
},
async stats(): Promise<unknown> {
return readThrough('stats', async () => (await apiClient.get('/addons/atlas/stats')).data as unknown);
return readThrough(
'stats',
async () => (await apiClient.get('/addons/atlas/stats', { params: { offline: 1 } })).data as unknown
);
},
async regions(): Promise<Record<string, AtlasRegionRow[]>> {
return readThrough('regions', async () => {
const res = await apiClient.get('/addons/atlas/regions');
const res = await apiClient.get('/addons/atlas/regions', { params: { offline: 1 } });
return (res.data?.regions ?? {}) as Record<string, AtlasRegionRow[]>;
});
},
+54 -12
View File
@@ -45,7 +45,13 @@ const region = (code: string, method: 'POST' | 'DELETE', body: unknown = null) =
});
interface Stats {
countries: Array<{ code: string; status?: string; placeCount?: number; tripCount?: number }>;
countries: Array<{
code: string;
status?: string;
placeCount?: number;
tripCount?: number;
offline?: { directMark: boolean; placeStatus: string | null };
}>;
stats?: Record<string, number | undefined>;
continents?: Record<string, number>;
continentsPlanned?: Record<string, number>;
@@ -107,12 +113,16 @@ describe('countries over the stats read', () => {
it('FE-ATLAS2-DATA-005: marking a country already visited changes nothing, also one without a status', async () => {
await queued(country('PT'));
const data = baseStats();
data.countries[0].offline = { directMark: true, placeStatus: 'visited' };
expect(await withWaitingWrites('stats', data)).toBe(data);
await clearAll();
const noStatus: Stats = { countries: [{ code: 'FR' }], stats: { totalCountries: 1 } };
await queued(country('FR'));
expect(await withWaitingWrites('stats', noStatus)).toEqual(noStatus);
expect(await withWaitingWrites('stats', noStatus)).toEqual({
countries: [{ code: 'FR', offline: { directMark: true, placeStatus: null } }],
stats: { totalCountries: 1 },
});
});
it('FE-ATLAS2-DATA-006: a read without a countries list is not touched', async () => {
@@ -240,6 +250,7 @@ describe('regions', () => {
placeCount: 4,
status: 'visited',
manuallyMarked: true,
placeStatus: 'visited',
});
expect(out.PT).toHaveLength(2);
});
@@ -261,10 +272,10 @@ describe('regions', () => {
expect(await withWaitingWrites('regions', null)).toBeNull();
});
it('FE-ATLAS2-DATA-021: unmarking a region with places keeps it, only the manual flag goes', async () => {
it('FE-ATLAS2-DATA-021: unmarking hides a region even when it has places', async () => {
await queued(region('PT-11', 'DELETE'));
const out = (await withWaitingWrites('regions', regions())) as ReturnType<typeof regions>;
expect(out.PT[0]).toMatchObject({ code: 'PT-11', manuallyMarked: false, placeCount: 4 });
expect(out.PT.map((r) => r.code)).toEqual(['PT-13']);
});
it('FE-ATLAS2-DATA-022: unmarking a region without places drops it', async () => {
@@ -280,11 +291,41 @@ describe('regions', () => {
expect(await withWaitingWrites('regions', null)).toBeNull();
});
it('FE-ATLAS2-DATA-024: a country write or a PUT on a region leaves the regions read alone', async () => {
it('FE-ATLAS2-DATA-024: unmarking a country clears its manual regions but keeps its places', async () => {
await queued(country('PT', 'DELETE'));
await queued({ ...region('PT-11', 'POST', { country_code: 'PT' }), method: 'PUT' });
const data = regions();
expect(await withWaitingWrites('regions', data)).toBe(data);
expect(await withWaitingWrites('regions', data)).toEqual({ PT: [data.PT[0]] });
});
it('FE-ATLAS2-DATA-033: a region added offline also marks its country visited', async () => {
await queued(region('JP-13', 'POST', { country_code: 'JP', name: 'Tokyo' }));
const stats = (await withWaitingWrites('stats', baseStats())) as Stats;
expect(stats.countries.find((c) => c.code === 'JP')).toMatchObject({
status: 'visited',
offline: { directMark: false, placeStatus: null },
});
expect(stats.stats?.totalCountries).toBe(2);
});
it('FE-ATLAS2-DATA-034: a country loses its last region in queue order unless it has its own mark', async () => {
await keepAtlasPart('regions', regions());
await queued(region('PT-11', 'DELETE'));
await queued(region('PT-13', 'DELETE'));
const data = baseStats();
data.countries[0].offline = { directMark: false, placeStatus: 'planned' };
expect(await withWaitingWrites('stats', data)).toMatchObject({
countries: [
{ code: 'PT', status: 'planned' },
{ code: 'ES', status: 'planned' },
],
stats: { totalCountries: 0, totalCountriesPlanned: 2 },
});
data.countries[0].offline.directMark = true;
expect(await withWaitingWrites('stats', data)).toBe(data);
});
});
@@ -320,15 +361,12 @@ describe('a write that went through', () => {
await keepAtlasPart('flights', { routes: [] });
await keepAtlasPart('bucketList', [{ id: 7 }, { id: 9 }]);
await reconcileAtlasWrite({ ...country('JP'), ids: {}, body: null, createdAt: 1 });
await reconcileAtlasWrite({ ...country('JP'), body: null });
await reconcileAtlasWrite({
resource: ATLAS_RESOURCE.bucket,
entity: `${ATLAS_RESOURCE.bucket}:9`,
method: 'DELETE',
ids: {},
body: null,
createdAt: 2,
answer: { success: true },
});
const stats = (await keptAtlasPart('stats'))?.data as Stats;
@@ -339,10 +377,14 @@ describe('a write that went through', () => {
it('FE-ATLAS2-DATA-029: laying the same write in twice changes nothing more', async () => {
await keepAtlasPart('regions', {});
const w = { ...region('ES-CT', 'POST', { name: 'Catalunya', country_code: 'ES' }), ids: {}, createdAt: 1 };
const w = region('ES-CT', 'POST', { name: 'Catalunya', country_code: 'ES' });
await keepAtlasPart('stats', baseStats());
await reconcileAtlasWrite(w);
const once = (await keptAtlasPart('regions'))?.data;
const stats = (await keptAtlasPart('stats'))?.data;
await reconcileAtlasWrite(w);
expect((await keptAtlasPart('stats'))?.data).toEqual(stats);
expect(stats).toMatchObject({ countries: [{ code: 'PT' }, { code: 'ES', status: 'visited' }] });
expect((await keptAtlasPart('regions'))?.data).toEqual(once);
expect(once).toEqual({
ES: [{ code: 'ES-CT', name: 'Catalunya', placeCount: 0, status: 'visited', manuallyMarked: true }],
@@ -350,7 +392,7 @@ describe('a write that went through', () => {
});
it('FE-ATLAS2-DATA-030: with nothing kept there is nothing to change', async () => {
await reconcileAtlasWrite({ ...country('JP'), ids: {}, body: null, createdAt: 1 });
await reconcileAtlasWrite({ ...country('JP'), body: null });
expect(await offlineDb.atlasSnapshot.count()).toBe(0);
});
});
+138 -47
View File
@@ -14,7 +14,8 @@
* 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 { continentForCountry, type VisitStatus } from '@trek/shared';
import { apiClient } from '../api/client';
import { offlineDb, type AtlasSnapshotPart, type UserQueuedMutation } from '../db/offlineDb';
/** The resources of the Atlas writes in the account queue. */
@@ -24,13 +25,7 @@ export const ATLAS_RESOURCE = {
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 AtlasWrite = Pick<UserQueuedMutation, 'resource' | 'method' | 'entity' | 'body'>;
type Fields = Record<string, unknown>;
@@ -51,7 +46,8 @@ function keyOf(w: AtlasWrite): string {
interface StatsCountry {
code: string;
status?: string;
status?: VisitStatus;
offline?: { directMark: boolean; placeStatus?: VisitStatus | null };
placeCount?: number;
tripCount?: number;
}
@@ -75,49 +71,75 @@ function total(s: StatsShape, key: string, by: number): Record<string, number |
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 {
function placeStatusOf(country: StatsCountry | undefined): VisitStatus | null | undefined {
if (country?.offline) return country.offline.placeStatus;
if (!country || !(country.placeCount || country.tripCount)) return null;
return country.status === 'visited' ? undefined : country.status;
}
/** Add a visit without losing a direct mark, or the status left by the country's places. */
function markCountry(data: unknown, code: string, directMark: boolean): 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 offline = { directMark: directMark || !!known?.offline?.directMark, placeStatus: placeStatusOf(known) };
if (status === 'visited') {
// An older read cannot tell what marked the country. A regional mark cannot settle that.
if (!directMark || known?.offline?.directMark) return data;
return { ...s, countries: s.countries.map((c) => (c.code === code ? { ...c, offline } : c)) };
}
const continent = continentForCountry(code);
const visited: StatsCountry & Fields = {
code,
tripCount: 0,
placeCount: 0,
const visited = {
...(known ?? { code, tripCount: 0, placeCount: 0 }),
firstVisit: null,
lastVisit: null,
status: 'visited',
status: 'visited' as const,
offline,
};
const next: StatsShape = {
...s,
countries: known
? s.countries.map((c) => (c.code === code ? { ...c, status: 'visited' } : c))
: [...s.countries, visited],
countries: known ? s.countries.map((c) => (c.code === code ? visited : c)) : [...s.countries, visited],
stats: total(s, 'totalCountries', 1),
continents: bump(s.continents, continent, 1),
};
if (status === 'idea') return { ...next, stats: total(next, 'totalCountriesIdea', -1) };
if (status !== 'planned') return next;
return {
...next,
stats: { ...next.stats, totalCountriesPlanned: Math.max(0, (s.stats?.totalCountriesPlanned ?? 0) - 1) },
stats: total(next, 'totalCountriesPlanned', -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. */
/** A direct unmark leaves the country painted by its own places, if any. */
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 {
const placeStatus = placeStatusOf(known);
if (placeStatus === undefined) return data;
const continent = continentForCountry(code);
const next: StatsShape = {
...s,
countries: s.countries.filter((c) => c.code !== code),
countries: placeStatus
? s.countries.map((c) =>
c.code === code ? { ...c, status: placeStatus, offline: { directMark: false, placeStatus } } : c
)
: s.countries.filter((c) => c.code !== code),
stats: total(s, 'totalCountries', -1),
continents: bump(s.continents, continentForCountry(code), -1),
continents: bump(s.continents, continent, -1),
};
if (placeStatus === 'visited') {
return { ...s, countries: next.countries };
}
if (placeStatus === 'idea') return { ...next, stats: total(next, 'totalCountriesIdea', 1) };
if (placeStatus !== 'planned') return next;
return {
...next,
stats: total(next, 'totalCountriesPlanned', 1),
continentsPlanned: bump(s.continentsPlanned, continent, 1),
};
}
@@ -127,7 +149,9 @@ interface RegionRow {
code: string;
name: string;
placeCount: number;
status?: string;
status?: VisitStatus;
/** The status the region's places give it without the mark. */
placeStatus?: VisitStatus;
/** Marked by hand, the server's own name for it. */
manuallyMarked?: boolean;
}
@@ -143,32 +167,77 @@ function markRegion(data: unknown, code: string, name: string, countryCode: stri
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 };
if (known?.status === 'visited' && (known.manuallyMarked || known.placeStatus)) return data;
const placeStatus = known?.placeCount ? (known.placeStatus ?? known.status) : undefined;
const marked: RegionRow = {
...(known ?? { code, name, placeCount: 0 }),
status: 'visited',
manuallyMarked: true,
...(placeStatus ? { placeStatus } : {}),
};
return { ...regions, [countryCode]: known ? rows.map((r) => (r.code === code ? marked : r)) : [...rows, marked] };
}
function countryOfRegion(regions: Regions, code: string): string | undefined {
return Object.keys(regions).find((cc) => (regions[cc] ?? []).some((r) => r.code === code));
}
/** The server hides an explicitly removed region, even if it has places. */
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 };
if (!regions) return data;
const country = countryOfRegion(regions, code);
if (!country) return data;
const rows = regions[country].filter((r) => r.code !== code);
if (rows.length) return { ...regions, [country]: rows };
const remaining = { ...regions };
delete remaining[country];
return remaining;
}
function clearCountryRegions(data: unknown, country: string): unknown {
const regions = asRegions(data);
const current = regions?.[country];
if (!regions || !current) return data;
const withPlaces = current
.filter((r) => r.placeCount > 0)
.map((r) => {
const { placeStatus, ...row } = r;
delete row.manuallyMarked;
return placeStatus ? { ...row, status: placeStatus } : row;
});
if (withPlaces.length) return { ...regions, [country]: withPlaces };
const remaining = { ...regions };
delete remaining[country];
return remaining;
}
// ── 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 lastRegionCountry(data: unknown, w: AtlasWrite): string | undefined {
if (w.resource !== ATLAS_RESOURCE.region || w.method !== 'DELETE') return;
const regions = asRegions(data);
const country = regions && countryOfRegion(regions, keyOf(w));
if (regions && country && regions[country].length === 1) return country;
}
function applyToStats(data: unknown, w: AtlasWrite, regions: unknown): unknown {
if (w.resource === ATLAS_RESOURCE.country) {
if (w.method === 'POST') return markCountry(data, keyOf(w), true);
if (w.method === 'DELETE') return unmarkCountry(data, keyOf(w));
}
if (w.resource === ATLAS_RESOURCE.region && w.method === 'POST') {
const code = text(fields(w.body).country_code);
if (code) return markCountry(data, code, false);
}
const country = lastRegionCountry(regions, w);
if (!country) return data;
const row = asStats(data)?.countries.find((c) => c.code === country);
return row?.offline?.directMark === false ? unmarkCountry(data, country) : data;
}
function applyToRegions(data: unknown, w: AtlasWrite): unknown {
if (w.resource === ATLAS_RESOURCE.country && w.method === 'DELETE') return clearCountryRegions(data, keyOf(w));
if (w.resource !== ATLAS_RESOURCE.region) return data;
const body = fields(w.body);
const country = text(body.country_code);
@@ -178,10 +247,10 @@ function applyToRegions(data: unknown, w: AtlasWrite): unknown {
}
/** What one Atlas read reads as once the write is laid over it. */
function applyAtlasWrite(part: AtlasSnapshotPart, data: unknown, w: AtlasWrite): unknown {
function applyAtlasWrite(part: AtlasSnapshotPart, data: unknown, w: AtlasWrite, regions?: unknown): unknown {
switch (part) {
case 'stats':
return applyToStats(data, w);
return applyToStats(data, w, regions);
case 'regions':
return applyToRegions(data, w);
case 'bucketList': {
@@ -205,7 +274,15 @@ async function waitingWrites(): Promise<UserQueuedMutation[]> {
/** 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);
if (part !== 'stats' || !writes.some((w) => w.resource === ATLAS_RESOURCE.region && w.method === 'DELETE')) {
return writes.reduce((out, w) => applyAtlasWrite(part, out, w), data);
}
let regions = (await keptAtlasPart('regions'))?.data ?? {};
for (const w of writes) {
data = applyToStats(data, w, regions);
regions = applyToRegions(regions, w);
}
return data;
}
/** Keep a read's answer as the server gave it. */
@@ -218,13 +295,27 @@ export async function keptAtlasPart(part: AtlasSnapshotPart): Promise<{ data: un
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. */
/** Apply a write the server accepted to the kept reads. */
export async function reconcileAtlasWrite(w: AtlasWrite): Promise<void> {
await offlineDb.transaction('rw', offlineDb.atlasSnapshot, async () => {
const account = offlineDb.name;
const needsStats = await offlineDb.transaction('rw', offlineDb.atlasSnapshot, async () => {
const rows = await offlineDb.atlasSnapshot.toArray();
const regions = rows.find((row) => row.part === 'regions')?.data;
for (const row of rows) {
const next = applyAtlasWrite(row.part, row.data, w);
const next = applyAtlasWrite(row.part, row.data, w, regions);
if (next !== row.data) await offlineDb.atlasSnapshot.put({ part: row.part, data: next });
}
const country = lastRegionCountry(regions, w);
const stats = rows.find((row) => row.part === 'stats')?.data;
const known = country && asStats(stats)?.countries.find((c) => c.code === country);
return !!known && !known.offline;
});
// An old snapshot cannot distinguish a direct mark from a country's last region.
if (!needsStats || account !== offlineDb.name) return;
try {
const { data } = await apiClient.get('/addons/atlas/stats', { params: { offline: 1 } });
if (account === offlineDb.name) await keepAtlasPart('stats', data);
} catch {
// The mutation already synced. The next online read can refresh this snapshot.
}
}
+8 -2
View File
@@ -97,6 +97,9 @@ async function settle(row: UserQueuedMutation, err: unknown): Promise<Outcome> {
const status = (err as { response?: { status?: number } } | null)?.response?.status;
// A delete of something the server no longer has did what it set out to do.
if (status === 404 && row.method === 'DELETE') {
const account = offlineDb.name;
if (row.resource.startsWith('atlas')) await reconcileAtlasWrite(row);
if (account !== offlineDb.name) return 'stop';
await offlineDb.userMutationQueue.delete(row.id);
return 'done';
}
@@ -119,6 +122,7 @@ async function settle(row: UserQueuedMutation, err: unknown): Promise<Outcome> {
async function replay(row: UserQueuedMutation, idMap: Map<number, number>): Promise<Outcome> {
const ids = resolveIds(row, idMap);
if (!ids) return park(row, 'unresolved temp id (dependent create did not sync)');
const account = offlineDb.name;
await offlineDb.userMutationQueue.update(row.id, { status: 'syncing', syncingSince: Date.now() });
try {
const response = await apiClient.request({
@@ -127,13 +131,15 @@ async function replay(row: UserQueuedMutation, idMap: Map<number, number>): Prom
data: row.body,
headers: { 'X-Idempotency-Key': row.id },
});
if (account !== offlineDb.name) return 'stop';
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 });
if (row.resource.startsWith('atlas')) await reconcileAtlasWrite(row);
if (account !== offlineDb.name) return 'stop';
await offlineDb.userMutationQueue.delete(row.id);
return 'done';
} catch (err: unknown) {
return settle(row, err);
return account === offlineDb.name ? settle(row, err) : 'stop';
}
}