feat(atlas): read and write the Atlas offline

The Atlas reads go network first and fall back to a snapshot kept in a new
Dexie table (v17, append-only). Marks, unmarks and wishlist deletes made
offline wait in their own account-level queue, replayed in order with an
idempotency key, and every read lays them over the kept answer.
This commit is contained in:
Maurice
2026-11-28 22:34:41 +01:00
parent 04d134755a
commit 68af65a2a6
13 changed files with 1539 additions and 121 deletions
@@ -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> = {}): 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<UserQueuedMutation[]> {
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<string | null> = [];
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');
});
});