mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 23:50:08 +00:00
68af65a2a6
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.
239 lines
9.6 KiB
TypeScript
239 lines
9.6 KiB
TypeScript
/**
|
|
* 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, number>): 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<number, number>): Record<string, number> | null {
|
|
const out: Record<string, number> = {};
|
|
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<number, number>): Promise<void> {
|
|
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<string, number>, 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<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') {
|
|
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<number, number>): Promise<Outcome> {
|
|
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<string> {
|
|
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<boolean> {
|
|
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<void> {
|
|
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<string, number>();
|
|
for (const row of await table.where('status').equals('failed').toArray()) hold(held, row);
|
|
const idMap = new Map<number, number>();
|
|
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<number> {
|
|
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<void> {
|
|
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<void> {
|
|
await offlineDb.userMutationQueue.where('status').equals('failed').delete();
|
|
},
|
|
|
|
/** Reset the createdAt counter — tests only, through mutationQueue._resetFlushing. */
|
|
_reset(): void {
|
|
lastCreatedAt = 0;
|
|
},
|
|
};
|