mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
@@ -241,6 +241,47 @@ describe('mutationQueue.flush — offline guard', () => {
|
||||
|
||||
// ── pending / pendingCount ────────────────────────────────────────────────────
|
||||
|
||||
describe('mutationQueue.flush — interrupted flush recovery', () => {
|
||||
it('replays a row an earlier flush abandoned on syncing', async () => {
|
||||
let seen = 0;
|
||||
server.use(
|
||||
http.post('/api/trips/1/places', () => {
|
||||
seen += 1;
|
||||
return HttpResponse.json({ place: buildPlace({ id: 42 }) });
|
||||
}),
|
||||
);
|
||||
|
||||
// What a killed tab leaves behind: marked syncing, stamped long enough ago
|
||||
// that no live request could still be in flight.
|
||||
const id = generateUUID();
|
||||
await offlineDb.mutationQueue.add({
|
||||
id, tripId: 1, method: 'POST', url: '/trips/1/places',
|
||||
body: { name: 'Eiffel Tower' }, resource: 'places',
|
||||
createdAt: Date.now() - 600_000, status: 'syncing', attempts: 0, lastError: null,
|
||||
syncingSince: Date.now() - 600_000,
|
||||
});
|
||||
|
||||
await mutationQueue.flush();
|
||||
|
||||
expect(seen).toBe(1);
|
||||
expect(await offlineDb.mutationQueue.get(id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('leaves a freshly marked syncing row alone (a concurrent flush owns it)', async () => {
|
||||
const id = generateUUID();
|
||||
await offlineDb.mutationQueue.add({
|
||||
id, tripId: 1, method: 'POST', url: '/trips/1/places',
|
||||
body: { name: 'Eiffel Tower' }, resource: 'places',
|
||||
createdAt: Date.now(), status: 'syncing', attempts: 0, lastError: null,
|
||||
syncingSince: Date.now(),
|
||||
});
|
||||
|
||||
await mutationQueue.flush();
|
||||
|
||||
expect((await offlineDb.mutationQueue.get(id))!.status).toBe('syncing');
|
||||
});
|
||||
});
|
||||
|
||||
describe('mutationQueue.pending', () => {
|
||||
it('returns pending mutations for a trip', async () => {
|
||||
const id1 = generateUUID();
|
||||
|
||||
@@ -9,9 +9,12 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
const flush = vi.fn(() => Promise.resolve());
|
||||
const syncAll = vi.fn(() => Promise.resolve());
|
||||
const hydrate = vi.fn(() => Promise.resolve());
|
||||
const loadSettings = vi.fn(() => Promise.resolve());
|
||||
|
||||
let refetchCb: ((tripId: string) => void) | null = null;
|
||||
let preReconnect: (() => Promise<void>) | null = null;
|
||||
let settingsLoaded = false;
|
||||
let authenticated = true;
|
||||
|
||||
vi.mock('../../../src/sync/mutationQueue', () => ({
|
||||
mutationQueue: { flush: () => flush() },
|
||||
@@ -27,6 +30,12 @@ vi.mock('../../../src/api/websocket', () => ({
|
||||
vi.mock('../../../src/store/tripStore', () => ({
|
||||
useTripStore: { getState: () => ({ hydrateActiveTrip: hydrate }) },
|
||||
}));
|
||||
vi.mock('../../../src/store/settingsStore', () => ({
|
||||
useSettingsStore: { getState: () => ({ isLoaded: settingsLoaded, loadSettings }) },
|
||||
}));
|
||||
vi.mock('../../../src/store/authStore', () => ({
|
||||
useAuthStore: { getState: () => ({ isAuthenticated: authenticated }) },
|
||||
}));
|
||||
|
||||
import { registerSyncTriggers, unregisterSyncTriggers } from '../../../src/sync/syncTriggers';
|
||||
|
||||
@@ -35,8 +44,9 @@ const flushMicrotasks = async () => {
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
flush.mockClear(); syncAll.mockClear(); hydrate.mockClear();
|
||||
flush.mockClear(); syncAll.mockClear(); hydrate.mockClear(); loadSettings.mockClear();
|
||||
refetchCb = null; preReconnect = null;
|
||||
settingsLoaded = false; authenticated = true;
|
||||
Object.defineProperty(navigator, 'onLine', { value: true, writable: true, configurable: true });
|
||||
});
|
||||
|
||||
@@ -72,5 +82,35 @@ describe('syncTriggers', () => {
|
||||
expect(flush).toHaveBeenCalled();
|
||||
expect(syncAll).toHaveBeenCalled();
|
||||
expect(hydrate).toHaveBeenCalledWith('7');
|
||||
// The order is the point: re-seeding Dexie before the queue drains would
|
||||
// overwrite edits that have not been sent yet.
|
||||
expect(flush.mock.invocationCallOrder[0]).toBeLessThan(syncAll.mock.invocationCallOrder[0]);
|
||||
expect(flush.mock.invocationCallOrder[0]).toBeLessThan(hydrate.mock.invocationCallOrder[0]);
|
||||
});
|
||||
|
||||
it('online event retries the settings load when it has not yet succeeded (#1618)', async () => {
|
||||
registerSyncTriggers();
|
||||
window.dispatchEvent(new Event('online'));
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(loadSettings).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not retry the settings load once it has loaded', async () => {
|
||||
settingsLoaded = true;
|
||||
registerSyncTriggers();
|
||||
window.dispatchEvent(new Event('online'));
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(loadSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not retry the settings load while unauthenticated', async () => {
|
||||
authenticated = false;
|
||||
registerSyncTriggers();
|
||||
window.dispatchEvent(new Event('online'));
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(loadSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
* Covers: bbox computation, tile math, URL building, size guard,
|
||||
* offline/no-SW guard, syncMeta update.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import 'fake-indexeddb/auto';
|
||||
import {
|
||||
@@ -14,14 +16,18 @@ import {
|
||||
countTiles,
|
||||
prefetchTiles,
|
||||
prefetchTilesForTrip,
|
||||
clearTileCache,
|
||||
MAX_TILES,
|
||||
TILE_CONCURRENCY,
|
||||
type TileBbox,
|
||||
} from '../../../src/sync/tilePrefetcher';
|
||||
import { offlineDb, clearAll, upsertSyncMeta } from '../../../src/db/offlineDb';
|
||||
import { setAuthed } from '../../../src/sync/authGate';
|
||||
import { buildPlace } from '../../helpers/factories';
|
||||
|
||||
beforeEach(async () => {
|
||||
await clearAll();
|
||||
setAuthed(true);
|
||||
Object.defineProperty(navigator, 'onLine', { value: true, writable: true, configurable: true });
|
||||
// Stub fetch + serviceWorker so prefetch path is exercised
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }));
|
||||
@@ -33,6 +39,7 @@ beforeEach(async () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setAuthed(false);
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
@@ -118,7 +125,45 @@ describe('buildTileUrl', () => {
|
||||
it('replaces {s} with a subdomain character', () => {
|
||||
const tmpl = 'https://{s}.tiles.example.com/{z}/{x}/{y}.png';
|
||||
const url = buildTileUrl(tmpl, 10, 0, 0);
|
||||
expect(url).toMatch(/^https:\/\/[abcd]\.tiles\.example\.com\/10\/0\/0\.png$/);
|
||||
expect(url).toMatch(/^https:\/\/[abc]\.tiles\.example\.com\/10\/0\/0\.png$/);
|
||||
});
|
||||
|
||||
it('picks the subdomain deterministically so a tile keeps one URL', () => {
|
||||
const tmpl = 'https://{s}.tiles.example.com/{z}/{x}/{y}.png';
|
||||
// A rotating counter would hand out a different host on each call, which
|
||||
// both breaks the cache lookup and stores the tile once per host.
|
||||
const first = buildTileUrl(tmpl, 10, 479, 329);
|
||||
buildTileUrl(tmpl, 10, 480, 330);
|
||||
expect(buildTileUrl(tmpl, 10, 479, 329)).toBe(first);
|
||||
});
|
||||
|
||||
it('spreads neighbouring tiles across subdomains', () => {
|
||||
const tmpl = 'https://{s}.tiles.example.com/{z}/{x}/{y}.png';
|
||||
const hosts = new Set(
|
||||
[0, 1, 2].map(dy => buildTileUrl(tmpl, 10, 479, 329 + dy).slice(8, 9)),
|
||||
);
|
||||
expect(hosts.size).toBe(3);
|
||||
});
|
||||
|
||||
it('uses the same subdomain rotation as Leaflet', () => {
|
||||
// Leaflet's TileLayer defaults to subdomains 'abc' and indexes it with
|
||||
// Math.abs(x + y) % length. A different list length here would cache each
|
||||
// tile under a host the map never asks for.
|
||||
const tmpl = 'https://{s}.tiles.example.com/{z}/{x}/{y}.png';
|
||||
const leaflet = 'abc';
|
||||
for (const [x, y] of [[479, 329], [480, 330], [12, 7], [0, 0], [5, 4]]) {
|
||||
const expected = leaflet[Math.abs(x + y) % leaflet.length];
|
||||
expect(buildTileUrl(tmpl, 10, x, y)).toBe(
|
||||
`https://${expected}.tiles.example.com/10/${x}/${y}.png`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('collapses the retired OSM subdomain sharding onto the single host', () => {
|
||||
// d.tile.openstreetmap.org stopped resolving after OSM dropped sharding, so
|
||||
// a template saved before that must not reach the network as-is (#1733).
|
||||
const url = buildTileUrl('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 13, 4091, 2722);
|
||||
expect(url).toBe('https://tile.openstreetmap.org/13/4091/2722.png');
|
||||
});
|
||||
|
||||
it('removes {r} (retina placeholder)', () => {
|
||||
@@ -185,6 +230,102 @@ describe('prefetchTiles — normal operation', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ── throttling ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('prefetchTiles — throttling', () => {
|
||||
/** fetch stub that resolves on the next macrotask and tracks concurrency. */
|
||||
function trackingFetch() {
|
||||
const state = { inFlight: 0, peak: 0, calls: 0 };
|
||||
vi.stubGlobal('fetch', vi.fn(() => {
|
||||
state.calls++;
|
||||
state.inFlight++;
|
||||
state.peak = Math.max(state.peak, state.inFlight);
|
||||
return new Promise(resolve => setTimeout(() => {
|
||||
state.inFlight--;
|
||||
resolve({ ok: true });
|
||||
}, 0));
|
||||
}));
|
||||
return state;
|
||||
}
|
||||
|
||||
it('never exceeds TILE_CONCURRENCY requests in flight', async () => {
|
||||
const state = trackingFetch();
|
||||
const bbox: TileBbox = { minLat: 48.0, maxLat: 49.0, minLng: 2.0, maxLng: 3.0 };
|
||||
|
||||
await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 12);
|
||||
|
||||
expect(state.calls).toBeGreaterThan(TILE_CONCURRENCY);
|
||||
expect(state.peak).toBeLessThanOrEqual(TILE_CONCURRENCY);
|
||||
});
|
||||
|
||||
it('resolves only once every tile has been dealt with', async () => {
|
||||
const state = trackingFetch();
|
||||
const bbox: TileBbox = { minLat: 48.8, maxLat: 48.9, minLng: 2.3, maxLng: 2.4 };
|
||||
|
||||
const fetched = await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 11);
|
||||
|
||||
expect(fetched).toBe(state.calls);
|
||||
expect(state.inFlight).toBe(0);
|
||||
});
|
||||
|
||||
it('stops fetching when the user logs out mid-run', async () => {
|
||||
let calls = 0;
|
||||
vi.stubGlobal('fetch', vi.fn(() => {
|
||||
if (++calls === TILE_CONCURRENCY) setAuthed(false);
|
||||
return Promise.resolve({ ok: true });
|
||||
}));
|
||||
const bbox: TileBbox = { minLat: 48.0, maxLat: 49.0, minLng: 2.0, maxLng: 3.0 };
|
||||
|
||||
await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 12);
|
||||
|
||||
// The workers finish their current tile, then bail — nowhere near the ~336
|
||||
// tiles this bbox enumerates.
|
||||
expect(calls).toBeLessThan(2 * TILE_CONCURRENCY);
|
||||
});
|
||||
|
||||
it('goes quiet when the connection drops mid-run', async () => {
|
||||
let calls = 0;
|
||||
vi.stubGlobal('fetch', vi.fn(() => {
|
||||
if (++calls === TILE_CONCURRENCY) {
|
||||
Object.defineProperty(navigator, 'onLine', { value: false, configurable: true });
|
||||
}
|
||||
return Promise.resolve({ ok: true });
|
||||
}));
|
||||
const bbox: TileBbox = { minLat: 48.0, maxLat: 49.0, minLng: 2.0, maxLng: 3.0 };
|
||||
|
||||
await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 12);
|
||||
|
||||
expect(calls).toBeLessThan(2 * TILE_CONCURRENCY);
|
||||
});
|
||||
});
|
||||
|
||||
// ── cache reuse ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe('prefetchTiles — cache reuse', () => {
|
||||
it('skips tiles already in Cache Storage instead of hitting the network', async () => {
|
||||
vi.stubGlobal('caches', {
|
||||
open: vi.fn().mockResolvedValue({ match: vi.fn().mockResolvedValue({}) }),
|
||||
});
|
||||
const bbox: TileBbox = { minLat: 48.8, maxLat: 48.9, minLng: 2.3, maxLng: 2.4 };
|
||||
|
||||
const fetched = await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 11);
|
||||
|
||||
expect(fetched).toBe(0);
|
||||
expect(vi.mocked(fetch)).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('still fetches when Cache Storage has no entry for the tile', async () => {
|
||||
vi.stubGlobal('caches', {
|
||||
open: vi.fn().mockResolvedValue({ match: vi.fn().mockResolvedValue(undefined) }),
|
||||
});
|
||||
const bbox: TileBbox = { minLat: 48.8, maxLat: 48.9, minLng: 2.3, maxLng: 2.4 };
|
||||
|
||||
const fetched = await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 11);
|
||||
|
||||
expect(fetched).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ── prefetchTilesForTrip ──────────────────────────────────────────────────────
|
||||
|
||||
describe('prefetchTilesForTrip', () => {
|
||||
@@ -239,6 +380,62 @@ describe('prefetchTilesForTrip', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ── repeat runs ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe('prefetchTilesForTrip — repeat runs', () => {
|
||||
const places = [buildPlace({ trip_id: 1, lat: 48.8566, lng: 2.3522 })];
|
||||
const tmpl = 'https://{s}.example.com/{z}/{x}/{y}.png';
|
||||
|
||||
beforeEach(async () => {
|
||||
await upsertSyncMeta({ tripId: 1, lastSyncedAt: Date.now(), status: 'idle', tilesBbox: null, filesCachedCount: 0 });
|
||||
});
|
||||
|
||||
it('does nothing on a second run with an unchanged bbox', async () => {
|
||||
await prefetchTilesForTrip(1, places, tmpl);
|
||||
const first = vi.mocked(fetch).mock.calls.length;
|
||||
expect(first).toBeGreaterThan(0);
|
||||
|
||||
vi.mocked(fetch).mockClear();
|
||||
await prefetchTilesForTrip(1, places, tmpl);
|
||||
|
||||
expect(vi.mocked(fetch)).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prefetches again once a place moves the bbox', async () => {
|
||||
await prefetchTilesForTrip(1, places, tmpl);
|
||||
vi.mocked(fetch).mockClear();
|
||||
|
||||
const moved = [...places, buildPlace({ trip_id: 1, lat: 45.4642, lng: 9.19 })];
|
||||
await prefetchTilesForTrip(1, moved, tmpl);
|
||||
|
||||
expect(vi.mocked(fetch)).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('runs anyway when forced (prepare for offline)', async () => {
|
||||
await prefetchTilesForTrip(1, places, tmpl);
|
||||
vi.mocked(fetch).mockClear();
|
||||
|
||||
await prefetchTilesForTrip(1, places, tmpl, true);
|
||||
|
||||
expect(vi.mocked(fetch)).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clearTileCache resets the bboxes so the next sync refills the cache', async () => {
|
||||
await prefetchTilesForTrip(1, places, tmpl);
|
||||
vi.mocked(fetch).mockClear();
|
||||
|
||||
vi.stubGlobal('caches', { delete: vi.fn().mockResolvedValue(true) });
|
||||
await clearTileCache();
|
||||
expect((await offlineDb.syncMeta.get(1))!.tilesBbox).toBeNull();
|
||||
|
||||
vi.unstubAllGlobals();
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }));
|
||||
await prefetchTilesForTrip(1, places, tmpl);
|
||||
|
||||
expect(vi.mocked(fetch)).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ── cap coherence ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe('MAX_TILES budget', () => {
|
||||
@@ -246,3 +443,79 @@ describe('MAX_TILES budget', () => {
|
||||
expect(MAX_TILES).toBe(12288);
|
||||
});
|
||||
});
|
||||
|
||||
// ── service worker rule coherence ───────────────────────────────────────────────
|
||||
|
||||
describe('the map-tiles rule for OpenStreetMap (#1733)', () => {
|
||||
// Vitest runs with the client package as its root, so cwd is stable here.
|
||||
const config = readFileSync(resolve(process.cwd(), 'vite.config.js'), 'utf8');
|
||||
|
||||
// Pull the OSM runtimeCaching pattern back out of the config and exercise it,
|
||||
// so this stays a statement about matching behaviour rather than about the
|
||||
// exact characters someone typed.
|
||||
const osmRule = /urlPattern:\s*(\/\^https[^\n]*openstreetmap[^\n]*\/i),/.exec(config);
|
||||
if (!osmRule) throw new Error('no OpenStreetMap runtimeCaching rule found in vite.config.js');
|
||||
const literal = osmRule[1];
|
||||
const pattern = new RegExp(literal.slice(1, literal.lastIndexOf('/')), 'i');
|
||||
|
||||
it('caches the single-host URLs the prefetcher now builds', () => {
|
||||
// Without this the prefetch writes nothing to map-tiles, cache.match() never
|
||||
// hits, and the offline tile store stays empty.
|
||||
const url = buildTileUrl('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 13, 4091, 2722);
|
||||
expect(url).toBe('https://tile.openstreetmap.org/13/4091/2722.png');
|
||||
expect(pattern.test(url)).toBe(true);
|
||||
});
|
||||
|
||||
it('still matches the sharded URLs already sitting in existing caches', () => {
|
||||
for (const shard of ['a', 'b', 'c']) {
|
||||
expect(pattern.test(`https://${shard}.tile.openstreetmap.org/13/4091/2722.png`)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not swallow a look-alike host', () => {
|
||||
expect(pattern.test('https://tile.openstreetmap.org.example.com/13/4091/2722.png')).toBe(false);
|
||||
expect(pattern.test('https://tile.openstreetmap.de/13/4091/2722.png')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the GL style document is not served stale (#1924)', () => {
|
||||
const config = readFileSync(resolve(process.cwd(), 'vite.config.js'), 'utf8');
|
||||
|
||||
// Read the rules in file order and exercise them the way Workbox does: the
|
||||
// first route whose pattern matches wins, so order is behaviour here, not style.
|
||||
const rules = [...config.matchAll(/urlPattern:\s*(\/[^\n]*?\/i),\s*\n\s*handler:\s*'([A-Za-z]+)'/g)].map(m => ({
|
||||
pattern: new RegExp(m[1].slice(1, m[1].lastIndexOf('/')), 'i'),
|
||||
handler: m[2],
|
||||
}));
|
||||
const firstMatch = (url: string) => rules.find(r => r.pattern.test(url));
|
||||
|
||||
const MAPBOX_STYLE = 'https://api.mapbox.com/styles/v1/acme/ckabc123?sdk=js-3.25.0&access_token=pk.test';
|
||||
const OPENFREEMAP_STYLE = 'https://tiles.openfreemap.org/styles/liberty';
|
||||
const MAPBOX_TILE = 'https://a.tiles.mapbox.com/v4/mapbox.mapbox-streets-v8/13/4091/2722.vector.pbf';
|
||||
const MAPBOX_GLYPHS = 'https://api.mapbox.com/fonts/v1/mapbox/DIN%20Pro%20Regular/0-255.pbf';
|
||||
|
||||
it('finds the runtime caching rules at all (guards the parser above)', () => {
|
||||
expect(rules.length).toBeGreaterThan(4);
|
||||
});
|
||||
|
||||
it('takes the Mapbox style from the network first', () => {
|
||||
// Under the tile rule's StaleWhileRevalidate the map was built from the
|
||||
// previous revision on every load, so a style republished with different
|
||||
// label languages kept rendering the old ones.
|
||||
expect(firstMatch(MAPBOX_STYLE)?.handler).toBe('NetworkFirst');
|
||||
});
|
||||
|
||||
it('takes the OpenFreeMap style from the network first too', () => {
|
||||
expect(firstMatch(OPENFREEMAP_STYLE)?.handler).toBe('NetworkFirst');
|
||||
});
|
||||
|
||||
it('leaves tiles, glyphs and sprites on the offline-friendly rule', () => {
|
||||
// Those are safe to serve stale and are what makes the basemap work offline.
|
||||
expect(firstMatch(MAPBOX_TILE)?.handler).toBe('StaleWhileRevalidate');
|
||||
expect(firstMatch(MAPBOX_GLYPHS)?.handler).toBe('StaleWhileRevalidate');
|
||||
});
|
||||
|
||||
it('keeps the style out of the tile cache, so tile eviction cannot reach it', () => {
|
||||
expect(config).toMatch(/cacheName:\s*'gl-map-styles'/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -22,11 +22,12 @@ import {
|
||||
buildTripFile,
|
||||
} from '../../helpers/factories';
|
||||
|
||||
// Helper to get today ± N days as YYYY-MM-DD
|
||||
// Helper to get today ± N days as YYYY-MM-DD. Local calendar date, like the
|
||||
// manager itself, so the ±1-day boundary cases hold outside UTC too.
|
||||
function dateOffset(days: number): string {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() + days);
|
||||
return d.toISOString().slice(0, 10);
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function makeBundle(tripId: number) {
|
||||
@@ -283,3 +284,94 @@ describe('tripSyncManager — file blob caching', () => {
|
||||
expect(cached.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ── local calendar dates ───────────────────────────────────────────────────────
|
||||
|
||||
describe('tripSyncManager.syncAll — local calendar dates', () => {
|
||||
// Only Date is faked; Dexie and MSW keep their real timers.
|
||||
const withClock = (tz: string, iso: string, run: () => Promise<void>) => async () => {
|
||||
const prevTz = process.env.TZ;
|
||||
process.env.TZ = tz;
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.setSystemTime(new Date(iso));
|
||||
try {
|
||||
await run();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
if (prevTz === undefined) delete process.env.TZ;
|
||||
else process.env.TZ = prevTz;
|
||||
}
|
||||
};
|
||||
|
||||
it('caches a trip on its last evening west of UTC', withClock(
|
||||
'America/Los_Angeles',
|
||||
// 21:00 on the 22nd in Los Angeles is already the 23rd in UTC.
|
||||
'2026-08-23T04:00:00Z',
|
||||
async () => {
|
||||
const tripId = 110;
|
||||
const trip = buildTrip({ id: tripId, end_date: '2026-08-22' });
|
||||
const bundle = { ...makeBundle(tripId), trip };
|
||||
|
||||
server.use(
|
||||
http.get('/api/trips', () => HttpResponse.json({ trips: [trip] })),
|
||||
http.get(`/api/trips/${tripId}/bundle`, () => HttpResponse.json(bundle)),
|
||||
);
|
||||
|
||||
await tripSyncManager.syncAll();
|
||||
expect(await offlineDb.trips.get(tripId)).toBeDefined();
|
||||
},
|
||||
));
|
||||
|
||||
it('drops a trip that ended yesterday east of UTC', withClock(
|
||||
'Asia/Tokyo',
|
||||
// 08:00 on the 23rd in Tokyo is still the 22nd in UTC.
|
||||
'2026-08-22T23:00:00Z',
|
||||
async () => {
|
||||
const tripId = 111;
|
||||
const trip = buildTrip({ id: tripId, end_date: '2026-08-22' });
|
||||
|
||||
let bundleCalled = false;
|
||||
server.use(
|
||||
http.get('/api/trips', () => HttpResponse.json({ trips: [trip] })),
|
||||
http.get(`/api/trips/${tripId}/bundle`, () => {
|
||||
bundleCalled = true;
|
||||
return HttpResponse.json({});
|
||||
}),
|
||||
);
|
||||
|
||||
await tripSyncManager.syncAll();
|
||||
expect(bundleCalled).toBe(false);
|
||||
expect(await offlineDb.trips.get(tripId)).toBeUndefined();
|
||||
},
|
||||
));
|
||||
});
|
||||
|
||||
// ── logout mid-sync ────────────────────────────────────────────────────────────
|
||||
|
||||
describe('tripSyncManager.syncAll — logout while syncing', () => {
|
||||
it('stops writing trips once the gate closes mid-loop', async () => {
|
||||
const firstId = 500;
|
||||
const secondId = 501;
|
||||
const first = buildTrip({ id: firstId, end_date: dateOffset(5) });
|
||||
const second = buildTrip({ id: secondId, end_date: dateOffset(5) });
|
||||
|
||||
let secondBundleCalled = false;
|
||||
server.use(
|
||||
http.get('/api/trips', () => HttpResponse.json({ trips: [first, second] })),
|
||||
http.get(`/api/trips/${firstId}/bundle`, () => {
|
||||
// The user logs out while the first bundle is on the wire.
|
||||
setAuthed(false);
|
||||
return HttpResponse.json({ ...makeBundle(firstId), trip: first });
|
||||
}),
|
||||
http.get(`/api/trips/${secondId}/bundle`, () => {
|
||||
secondBundleCalled = true;
|
||||
return HttpResponse.json({ ...makeBundle(secondId), trip: second });
|
||||
}),
|
||||
);
|
||||
|
||||
await tripSyncManager.syncAll();
|
||||
|
||||
expect(secondBundleCalled).toBe(false);
|
||||
expect(await offlineDb.trips.get(secondId)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user