mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 01:44:13 +00:00
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:
@@ -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<BucketPlaceHit[]> {
|
||||
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<AtlasLocation> {
|
||||
return (await apiClient.get('/addons/atlas/locate', { params: { lat, lng } })).data as AtlasLocation;
|
||||
},
|
||||
|
||||
async clearVisit(itemId: number): Promise<void> {
|
||||
await dawarichApi.clearBucketVisit(itemId);
|
||||
},
|
||||
};
|
||||
@@ -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<PluginAtlasLayer[]> {
|
||||
try {
|
||||
const r = await pluginsApi.atlasLayers();
|
||||
return r.layers ?? [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -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<void> {
|
||||
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<string | null> = [];
|
||||
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<string | null> = [];
|
||||
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]);
|
||||
});
|
||||
});
|
||||
@@ -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<AtlasFlightAirport & { count: number }>;
|
||||
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<import('@trek/shared').Badge, 'id' | 'motif' | 'tier' | 'titleKey' | 'params' | 'year' | 'target'>
|
||||
>;
|
||||
}
|
||||
|
||||
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<T>(part: AtlasSnapshotPart, fetch: () => Promise<T>): Promise<T> {
|
||||
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;
|
||||
/** `<resource>:<code or id>`: 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<void> {
|
||||
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<Array<AtlasPerson & { username: string; avatar_url: string | null }>> {
|
||||
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<AtlasFlights> {
|
||||
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<unknown> {
|
||||
const res = await apiClient.get(`/addons/atlas/mesh/${path}`, { timeout: 30000 });
|
||||
return res.data;
|
||||
},
|
||||
|
||||
async stats(): Promise<unknown> {
|
||||
return readThrough('stats', async () => (await apiClient.get('/addons/atlas/stats')).data as unknown);
|
||||
},
|
||||
|
||||
async regions(): Promise<Record<string, AtlasRegionRow[]>> {
|
||||
return readThrough('regions', async () => {
|
||||
const res = await apiClient.get('/addons/atlas/regions');
|
||||
return (res.data?.regions ?? {}) as Record<string, AtlasRegionRow[]>;
|
||||
});
|
||||
},
|
||||
|
||||
async bucketList(): Promise<unknown[]> {
|
||||
return readThrough('bucketList', async () => {
|
||||
const res = await apiClient.get('/addons/atlas/bucket-list');
|
||||
return (res.data?.items ?? []) as unknown[];
|
||||
});
|
||||
},
|
||||
|
||||
async countryDetail(code: string): Promise<unknown> {
|
||||
return (await apiClient.get(`/addons/atlas/country/${code}`)).data;
|
||||
},
|
||||
|
||||
async markCountry(code: string): Promise<void> {
|
||||
await write({
|
||||
method: 'POST',
|
||||
url: `/addons/atlas/country/${code}/mark`,
|
||||
resource: ATLAS_RESOURCE.country,
|
||||
entity: `${ATLAS_RESOURCE.country}:${code}`,
|
||||
});
|
||||
},
|
||||
|
||||
async unmarkCountry(code: string): Promise<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<string, unknown>): Promise<unknown> {
|
||||
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<void> {
|
||||
await write({
|
||||
method: 'DELETE',
|
||||
url: `/addons/atlas/bucket-list/${id}`,
|
||||
resource: ATLAS_RESOURCE.bucket,
|
||||
entity: `${ATLAS_RESOURCE.bucket}:${id}`,
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -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)
|
||||
},
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user