@phibac/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/queue.ts ADDED
@@ -0,0 +1,419 @@
1
+ // The offline write queue's flusher: queued writes are sent in order
2
+ // through POST /v1/batch while online, by one tab at a time, and each
3
+ // result is applied to the cache. Also Net, which tracks whether the
4
+ // server is reachable and the problems the app should tell the user about.
5
+ import { opKey, fold, type Cache, type StoredOp, type WireRecord } from "./cache.js";
6
+ import { PbError } from "./errors.js";
7
+ import type { Http } from "./http.js";
8
+ import type { QueuedOp } from "./index.js";
9
+
10
+ /** At most this many operations per batch (the server's BatchMax). */
11
+ const BATCH_OPS = 100;
12
+ /** About this many bytes of JSON per batch (the server allows 4 MiB). */
13
+ const BATCH_BYTES = 3.5 * 1024 * 1024;
14
+ const BACKOFF_START_MS = 1000;
15
+ const BACKOFF_MAX_MS = 60_000;
16
+
17
+ /**
18
+ * Errors that a retry can never fix: the op is dropped and reported
19
+ * through onConflict. Codes not listed here or in TRANSIENT are treated as
20
+ * permanent too, so an unknown error can never block the queue forever
21
+ * (the data is handed to onConflict, not lost).
22
+ */
23
+ const PERMANENT = new Set([
24
+ "record_deleted", "forbidden", "schema_violation", "version_unsupported", "not_found",
25
+ "invalid_request", "payload_too_large", "consent_required",
26
+ ]);
27
+
28
+ /** Errors that are retried with backoff, keeping the op and everything after it. */
29
+ const TRANSIENT = new Set([
30
+ "network", "internal", "invalid_response", "rate_limited", "storage_full", "trial_ended", "unauthorized", "app_suspended",
31
+ ]);
32
+
33
+ /** Transient errors the user can act on: surfaced as status().problem. */
34
+ const USER_FIXABLE = new Set(["storage_full", "trial_ended", "app_suspended"]);
35
+
36
+ /**
37
+ * Errors on the whole /v1/batch request that one of its operations can
38
+ * cause; the queue then sends operations one at a time to find it. Any
39
+ * other whole-request error (e.g. forbidden for the page's origin) says
40
+ * nothing about the operations: the queue is kept and retried.
41
+ */
42
+ function causedByAnOp(e: PbError): boolean {
43
+ // With several ops the culprit is searched for one op at a time; a request
44
+ // of exactly one op refused this way is that op's own failure.
45
+ return e.code === "payload_too_large" || e.code === "invalid_request";
46
+ }
47
+
48
+ /** Whole-request failures worth showing: everything but the plain outages. */
49
+ function worthShowing(e: PbError): boolean {
50
+ const status = e.extra.status;
51
+ return !["network", "internal", "rate_limited"].includes(e.code) && !(typeof status === "number" && status >= 500);
52
+ }
53
+
54
+ export function isTransient(e: PbError): boolean {
55
+ if (PERMANENT.has(e.code)) return false;
56
+ const status = e.extra.status;
57
+ return TRANSIENT.has(e.code) || (typeof status === "number" && status >= 500);
58
+ }
59
+
60
+ export function asPbError(e: unknown): PbError {
61
+ if (e instanceof PbError) return e;
62
+ return new PbError("internal", e instanceof Error ? e.message : String(e), "Retry later.");
63
+ }
64
+
65
+ // ---- reachability ----
66
+
67
+ /**
68
+ * Net makes every API call for the SDK's background work and remembers
69
+ * whether the last one reached the server. problem() is the first
70
+ * condition the app should show the user (storage_full, trial_ended,
71
+ * app_suspended, account_closed, consent_required for live updates), or
72
+ * undefined.
73
+ */
74
+ export class Net {
75
+ private reached = true;
76
+ private readonly problems = new Map<string, PbError>();
77
+ /** Aborted by abort(): cancels every request in flight (signOut). */
78
+ private readonly ac = new AbortController();
79
+
80
+ constructor(readonly http: Http) {}
81
+
82
+ /** Whether the device says it is online and the last call reached the server. */
83
+ get online(): boolean {
84
+ const nav = typeof navigator === "undefined" ? undefined : navigator;
85
+ return this.reached && nav?.onLine !== false;
86
+ }
87
+
88
+ /** Whether the device says it is online (requests are worth trying). */
89
+ get deviceOnline(): boolean {
90
+ return typeof navigator === "undefined" || navigator.onLine !== false;
91
+ }
92
+
93
+ set online(v: boolean) {
94
+ this.reached = v;
95
+ }
96
+
97
+ async request<T>(method: string, path: string, body?: unknown, headers?: Record<string, string>): Promise<T> {
98
+ try {
99
+ const out = await this.http.request<T>(method, path, body, headers, this.ac.signal);
100
+ this.reached = true;
101
+ return out;
102
+ } catch (e) {
103
+ const err = asPbError(e);
104
+ if (err.code === "network") this.reached = false;
105
+ else this.reached = true;
106
+ throw err;
107
+ }
108
+ }
109
+
110
+ /** abort cancels every request in flight and every later one. */
111
+ abort(): void {
112
+ this.ac.abort();
113
+ }
114
+
115
+ problem(): PbError | undefined {
116
+ return this.problems.values().next().value;
117
+ }
118
+
119
+ setProblem(source: string, e: PbError | undefined): void {
120
+ if (e) this.problems.set(source, e);
121
+ else this.problems.delete(source);
122
+ }
123
+ }
124
+
125
+ // ---- the flusher ----
126
+
127
+ export interface ConflictEvent {
128
+ op: QueuedOp;
129
+ error: PbError;
130
+ localData: unknown;
131
+ }
132
+
133
+ interface BatchResult {
134
+ opId?: unknown;
135
+ record?: WireRecord;
136
+ error?: Record<string, unknown>;
137
+ }
138
+
139
+ function wireOp(op: QueuedOp): Record<string, unknown> {
140
+ const out: Record<string, unknown> = { kind: op.kind, collection: op.collection, rkey: op.rkey, opId: op.opId };
141
+ const { schemaMajor, baseRev, data } = op.input;
142
+ if (schemaMajor !== undefined) out.schemaMajor = schemaMajor;
143
+ if (baseRev !== undefined) out.baseRev = baseRev;
144
+ if (data !== undefined) out.data = data;
145
+ return out;
146
+ }
147
+
148
+ const byteLength = (v: unknown) => new TextEncoder().encode(JSON.stringify(v)).length;
149
+
150
+ function resultError(e: Record<string, unknown>): PbError {
151
+ const { code, message, hint, ...extra } = e;
152
+ return new PbError(typeof code === "string" ? code : "internal", typeof message === "string" ? message : "", typeof hint === "string" ? hint : "", extra);
153
+ }
154
+
155
+ export interface FlusherDeps {
156
+ cache: Cache;
157
+ net: Net;
158
+ /** The Web Locks name: one flusher per server, app and user across tabs. */
159
+ lockName: string;
160
+ /** Reports a write the server refused for good. */
161
+ conflict: (e: ConflictEvent) => void;
162
+ /** Called whenever the number of queued writes may have changed. */
163
+ counted?: () => void;
164
+ }
165
+
166
+ /**
167
+ * Flusher sends the queue in order through /v1/batch: chunks of at most
168
+ * 100 operations and about 3.5 MiB, only while the device is online, and
169
+ * only in the tab holding the queue's Web Lock. A success stores the
170
+ * server's record; a permanent error drops the op through onConflict and
171
+ * reverts the record; a transient error keeps the op and everything after
172
+ * it and retries with backoff (1 s doubling to 60 s, at least Retry-After).
173
+ */
174
+ export class Flusher {
175
+ /** The number of queued writes, as last counted. */
176
+ pending = 0;
177
+ private timer: ReturnType<typeof setTimeout> | undefined;
178
+ private attempt = 0;
179
+ private running = false;
180
+ private again = false;
181
+ private stopped = false;
182
+ /** The flush in progress (awaited by idle()). */
183
+ private current: Promise<void> | null = null;
184
+ /** Send one op alone next: a whole batch was refused for good. */
185
+ private solo = false;
186
+ private localTail: Promise<unknown> = Promise.resolve();
187
+
188
+ constructor(private readonly d: FlusherDeps) {}
189
+
190
+ /** count re-reads the queue length. */
191
+ async count(): Promise<void> {
192
+ this.pending = await this.d.cache.queueLength();
193
+ this.d.counted?.();
194
+ }
195
+
196
+ /**
197
+ * kick asks for a flush. While a retry is scheduled the retry runs instead,
198
+ * unless now is true (the device just came online), which retries at once
199
+ * with the backoff reset.
200
+ */
201
+ kick(now = false): void {
202
+ if (this.stopped) return;
203
+ if (this.timer !== undefined) {
204
+ if (!now) return;
205
+ clearTimeout(this.timer);
206
+ this.timer = undefined;
207
+ this.attempt = 0;
208
+ }
209
+ if (!this.d.net.deviceOnline) return;
210
+ if (this.running) {
211
+ this.again = true;
212
+ return;
213
+ }
214
+ this.running = true;
215
+ this.current = this.withLock(() => this.flushLocked())
216
+ .catch(() => undefined)
217
+ .finally(() => {
218
+ this.running = false;
219
+ this.current = null;
220
+ if (this.again && this.timer === undefined) {
221
+ this.again = false;
222
+ this.kick();
223
+ }
224
+ });
225
+ }
226
+
227
+ stop(): void {
228
+ this.stopped = true;
229
+ if (this.timer !== undefined) clearTimeout(this.timer);
230
+ this.timer = undefined;
231
+ }
232
+
233
+ /**
234
+ * idle resolves once no flush is in progress (after stop(), none starts).
235
+ * It can wait on another tab holding the lock: callers bound the wait.
236
+ */
237
+ async idle(): Promise<void> {
238
+ while (this.current) await this.current;
239
+ }
240
+
241
+ private withLock(fn: () => Promise<void>): Promise<void> {
242
+ const locks = typeof navigator === "undefined" ? undefined : navigator.locks;
243
+ if (locks) return locks.request(this.d.lockName, () => (this.stopped ? undefined : fn()));
244
+ // Without Web Locks flushes are serialised in this tab only; two tabs
245
+ // may then send the same op, which the server applies once (opId).
246
+ const run = this.localTail.then(fn, fn);
247
+ this.localTail = run.catch(() => undefined);
248
+ return run;
249
+ }
250
+
251
+ private retryLater(e: PbError): void {
252
+ if (this.stopped) return;
253
+ const backoff = Math.min(BACKOFF_MAX_MS, BACKOFF_START_MS * 2 ** this.attempt);
254
+ this.attempt++;
255
+ const ra = e.code === "rate_limited" && typeof e.extra.retryAfter === "number" ? e.extra.retryAfter * 1000 : 0;
256
+ this.timer = setTimeout(() => {
257
+ this.timer = undefined;
258
+ this.kick();
259
+ }, Math.max(backoff, ra));
260
+ }
261
+
262
+ /**
263
+ * chunk takes the first ops of the queue that fit in one batch, cut before
264
+ * the second op on any record. The server runs every op of a batch even
265
+ * after one fails, so two ops on one record in one batch could be applied
266
+ * out of order when the first fails transiently and is retried.
267
+ */
268
+ private chunk(queued: StoredOp[]): StoredOp[] {
269
+ if (this.solo) return queued.slice(0, 1);
270
+ const out: StoredOp[] = [];
271
+ const records = new Set<string>();
272
+ let bytes = 0;
273
+ for (const s of queued) {
274
+ const n = byteLength(wireOp(s.op)) + 1;
275
+ if (out.length >= BATCH_OPS || (out.length > 0 && bytes + n > BATCH_BYTES) || records.has(opKey(s.op))) break;
276
+ out.push(s);
277
+ records.add(opKey(s.op));
278
+ bytes += n;
279
+ }
280
+ return out;
281
+ }
282
+
283
+ private async flushLocked(): Promise<void> {
284
+ this.again = false;
285
+ for (;;) {
286
+ if (this.stopped || !this.d.net.deviceOnline) return;
287
+ // Read inside the lock: another tab may have flushed meanwhile.
288
+ const queued = await this.d.cache.queued();
289
+ this.pending = queued.length;
290
+ this.d.counted?.();
291
+ if (queued.length === 0) {
292
+ this.attempt = 0;
293
+ this.d.net.setProblem("queue", undefined);
294
+ return;
295
+ }
296
+ const chunk = this.chunk(queued);
297
+ let body: { results?: unknown };
298
+ try {
299
+ body = (await this.d.net.request<{ results?: unknown }>("POST", "/v1/batch", { ops: chunk.map((s) => wireOp(s.op)) })) ?? {};
300
+ } catch (e) {
301
+ if (this.stopped) return;
302
+ const err = asPbError(e);
303
+ if (!causedByAnOp(err)) {
304
+ // Not about any op (an outage, or e.g. forbidden for this
305
+ // origin): keep the whole queue, retry, and tell the app.
306
+ if (worthShowing(err)) this.d.net.setProblem("queue", err);
307
+ else this.noteProblem(err);
308
+ this.retryLater(err);
309
+ return;
310
+ }
311
+ // An op made the whole request fail: find it by sending ops alone.
312
+ if (chunk.length > 1) {
313
+ this.solo = true;
314
+ continue;
315
+ }
316
+ await this.conflict(chunk[0]!, err);
317
+ this.solo = false;
318
+ continue;
319
+ }
320
+ if (this.stopped) return;
321
+ this.solo = false;
322
+ const results = Array.isArray(body.results) ? (body.results as BatchResult[]) : null;
323
+ if (!results || results.length !== chunk.length) {
324
+ const err = new PbError("invalid_response", `The batch response does not match the request.`, "Check that baseUrl points at the server; the queue keeps retrying.");
325
+ this.d.net.setProblem("queue", err);
326
+ this.retryLater(err);
327
+ return;
328
+ }
329
+ let stop: PbError | undefined;
330
+ for (const [i, s] of chunk.entries()) {
331
+ const r = results[i]!;
332
+ if (r.opId !== s.op.opId) {
333
+ stop = new PbError("invalid_response", "The batch results are out of order.", "Retry later.");
334
+ break;
335
+ }
336
+ if (r.error && typeof r.error === "object") {
337
+ const err = resultError(r.error);
338
+ if (isTransient(err)) {
339
+ stop = err;
340
+ break;
341
+ }
342
+ await this.conflict(s, err);
343
+ continue;
344
+ }
345
+ await this.success(s, r.record);
346
+ }
347
+ if (stop) {
348
+ this.noteProblem(stop);
349
+ await this.count();
350
+ this.retryLater(stop);
351
+ return;
352
+ }
353
+ this.attempt = 0;
354
+ this.d.net.setProblem("queue", undefined);
355
+ }
356
+ }
357
+
358
+ private noteProblem(e: PbError): void {
359
+ if (USER_FIXABLE.has(e.code)) this.d.net.setProblem("queue", e);
360
+ }
361
+
362
+ /** success stores the server's result of s and removes s from the queue. */
363
+ private async success(s: StoredOp, record: WireRecord | undefined): Promise<void> {
364
+ const { collection, rkey } = s.op;
365
+ if (this.stopped) return;
366
+ await this.d.cache.write(async (w) => {
367
+ await w.dequeue(s.seq!);
368
+ const e = (await w.entry(collection, rkey)) ?? w.newEntry(collection, rkey);
369
+ if (s.op.kind === "delete") {
370
+ e.deleted = true;
371
+ e.server = null;
372
+ } else if (record && !e.deleted && record.rev > e.rev) {
373
+ // A replayed op may return an older state than the cache already
374
+ // has (from a later change); the newer one is kept.
375
+ e.server = record;
376
+ e.rev = record.rev;
377
+ }
378
+ await w.save(e);
379
+ });
380
+ this.pending = Math.max(0, this.pending - 1);
381
+ this.d.counted?.();
382
+ }
383
+
384
+ /**
385
+ * conflict drops s (and, when s is a create, every later op on the same
386
+ * record, which cannot succeed without it), reverts the record to its
387
+ * server state and reports each dropped op with the data the app had.
388
+ */
389
+ private async conflict(s: StoredOp, error: PbError): Promise<void> {
390
+ const { collection, rkey } = s.op;
391
+ const events: ConflictEvent[] = [];
392
+ if (this.stopped) return;
393
+ await this.d.cache.write(async (w) => {
394
+ const e = (await w.entry(collection, rkey)) ?? w.newEntry(collection, rkey);
395
+ const ops = await w.opsFor(collection, rkey);
396
+ const at = ops.findIndex((o) => o.seq === s.seq);
397
+ // Already handled (another tab, without Web Locks): report it once.
398
+ if (at < 0) return;
399
+ const dropped = s.op.kind === "create" ? ops.filter((o) => o.seq! >= s.seq!) : [s];
400
+ for (const d of dropped) {
401
+ const i = ops.findIndex((o) => o.seq === d.seq);
402
+ const upTo = d.op.kind === "delete" ? i : i + 1;
403
+ const local = fold(e.server, e.deleted, ops.slice(0, Math.max(upTo, 0)));
404
+ events.push({ op: d.op, error, localData: local ? local.data : (e.server?.data ?? null) });
405
+ await w.dequeue(d.seq!);
406
+ }
407
+ if (error.code === "record_deleted") {
408
+ e.deleted = true;
409
+ e.server = null;
410
+ } else if (error.code === "not_found") {
411
+ e.server = null;
412
+ }
413
+ await w.save(e);
414
+ });
415
+ this.pending = Math.max(0, this.pending - events.length);
416
+ this.d.counted?.();
417
+ for (const ev of events) this.d.conflict(ev);
418
+ }
419
+ }