@pgxsinkit/client 0.1.32 → 0.1.36
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/README.md +11 -0
- package/dist/convergence.d.ts +76 -0
- package/dist/convergence.d.ts.map +1 -0
- package/dist/debug.d.ts +34 -0
- package/dist/debug.d.ts.map +1 -0
- package/dist/index.d.ts +421 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7214 -2234
- package/dist/index.js.map +74 -44
- package/dist/lazy-guard.d.ts +58 -0
- package/dist/lazy-guard.d.ts.map +1 -0
- package/dist/local-store.d.ts +56 -0
- package/dist/local-store.d.ts.map +1 -0
- package/dist/local-tables.d.ts +707 -0
- package/dist/local-tables.d.ts.map +1 -0
- package/dist/mutation-state.d.ts +62 -0
- package/dist/mutation-state.d.ts.map +1 -0
- package/dist/mutation.d.ts +117 -4
- package/dist/mutation.d.ts.map +1 -1
- package/dist/schema.d.ts +49 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +180 -0
- package/dist/shape-sync.d.ts.map +1 -0
- package/dist/sync/apply.d.ts +51 -0
- package/dist/sync/apply.d.ts.map +1 -0
- package/dist/sync/copy.d.ts +43 -0
- package/dist/sync/copy.d.ts.map +1 -0
- package/dist/sync/drizzle-executor.d.ts +5 -0
- package/dist/sync/drizzle-executor.d.ts.map +1 -0
- package/dist/sync/index.d.ts +32 -0
- package/dist/sync/index.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +131 -0
- package/dist/sync/metadata-tables.d.ts.map +1 -0
- package/dist/sync/nudge.d.ts +49 -0
- package/dist/sync/nudge.d.ts.map +1 -0
- package/dist/sync/shape-inbox.d.ts +215 -0
- package/dist/sync/shape-inbox.d.ts.map +1 -0
- package/dist/sync/subscription-state.d.ts +39 -0
- package/dist/sync/subscription-state.d.ts.map +1 -0
- package/dist/sync/tags.d.ts +130 -0
- package/dist/sync/tags.d.ts.map +1 -0
- package/dist/sync/types.d.ts +118 -0
- package/dist/sync/types.d.ts.map +1 -0
- package/dist/sync-auth.d.ts +53 -0
- package/dist/sync-auth.d.ts.map +1 -0
- package/dist/worker/attach-sync-client.d.ts +75 -0
- package/dist/worker/attach-sync-client.d.ts.map +1 -0
- package/dist/worker/define-sync-worker.d.ts +75 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -0
- package/dist/worker/live-diff.d.ts +44 -0
- package/dist/worker/live-diff.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +260 -0
- package/dist/worker/protocol.d.ts.map +1 -0
- package/dist/worker/token-cache.d.ts +26 -0
- package/dist/worker/token-cache.d.ts.map +1 -0
- package/oxlint-plugin.js +143 -0
- package/package.json +15 -7
- package/skills/core/SKILL.md +197 -0
- package/skills/operating/SKILL.md +243 -0
- package/src/convergence.ts +197 -0
- package/src/debug.ts +151 -0
- package/src/index.ts +1104 -44
- package/src/lazy-guard.ts +121 -0
- package/src/local-store.ts +193 -0
- package/src/local-tables.ts +546 -0
- package/src/mutation-state.ts +90 -0
- package/src/mutation.ts +1868 -562
- package/src/schema.ts +352 -27
- package/src/shape-sync.ts +477 -0
- package/src/sync/apply.ts +530 -0
- package/src/sync/copy.ts +206 -0
- package/src/sync/drizzle-executor.ts +48 -0
- package/src/sync/index.ts +1076 -0
- package/src/sync/metadata-tables.ts +67 -0
- package/src/sync/nudge.ts +110 -0
- package/src/sync/shape-inbox.ts +566 -0
- package/src/sync/subscription-state.ts +135 -0
- package/src/sync/tags.ts +365 -0
- package/src/sync/types.ts +132 -0
- package/src/sync-auth.ts +117 -0
- package/src/worker/attach-sync-client.ts +558 -0
- package/src/worker/define-sync-worker.ts +596 -0
- package/src/worker/live-diff.ts +140 -0
- package/src/worker/protocol.ts +325 -0
- package/src/worker/token-cache.ts +84 -0
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// The live-query DIFF machinery (ADR-0032 S2 §4). Two pure pieces sit either side of the bridge:
|
|
2
|
+
// - {@link computeLiveDiff} (worker-side): turn a fresh ordered result-set into a {added, changed, removed}
|
|
3
|
+
// diff against the previously-sent one, keyed by the query's PK — so only deltas cross the wire.
|
|
4
|
+
// - {@link LiveRowsMaterializer} (tab-side): fold each diff back into an ordered array while preserving
|
|
5
|
+
// row-object identity for unchanged rows (React memo bails on `===`).
|
|
6
|
+
// Both are transport-free and worker-free, so they unit-test directly.
|
|
7
|
+
|
|
8
|
+
import type { LiveDiffPayload } from "./protocol";
|
|
9
|
+
|
|
10
|
+
// A NUL separator — never a legitimate character inside a PK text value, so composite keys can't collide.
|
|
11
|
+
const KEY_SEP = String.fromCharCode(0);
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The stable key for a result row (§4). With `pkColumns`, join their values (composite-safe) — this is the
|
|
15
|
+
* diff-keying identity, so a row whose PK is unchanged is the SAME logical row even if other columns moved.
|
|
16
|
+
* Without `pkColumns` (a keyless query) fall back to the whole-row JSON value: still diff-shaped (never a
|
|
17
|
+
* full resend), but an update surfaces as remove+add rather than a `changed` — the documented keyless
|
|
18
|
+
* fallback. Duplicate identical keyless rows collapse under this scheme (accepted for the fallback).
|
|
19
|
+
*/
|
|
20
|
+
export function rowKey(row: Record<string, unknown>, pkColumns: readonly string[] | undefined): string {
|
|
21
|
+
if (pkColumns && pkColumns.length > 0) {
|
|
22
|
+
return pkColumns.map((col) => String(row[col])).join(KEY_SEP);
|
|
23
|
+
}
|
|
24
|
+
return JSON.stringify(row);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A shallow value-equality over a row's own enumerable keys — decides `changed` vs unchanged in a diff. */
|
|
28
|
+
function rowsEqual(a: Record<string, unknown>, b: Record<string, unknown>): boolean {
|
|
29
|
+
const aKeys = Object.keys(a);
|
|
30
|
+
const bKeys = Object.keys(b);
|
|
31
|
+
if (aKeys.length !== bKeys.length) return false;
|
|
32
|
+
for (const key of aKeys) {
|
|
33
|
+
if (!Object.is(a[key], b[key])) return false;
|
|
34
|
+
}
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The worker's per-subscription memory: the last delivered rows keyed by {@link rowKey}, in delivered order. */
|
|
39
|
+
export interface LiveDiffState {
|
|
40
|
+
pkColumns?: readonly string[];
|
|
41
|
+
/** key → the exact row body last sent, so the next diff can detect `changed` and skip unchanged rows. */
|
|
42
|
+
previous: Map<string, Record<string, unknown>>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Seed the diff state from the initial snapshot (which the worker sends verbatim, not as a diff). */
|
|
46
|
+
export function seedLiveDiffState(
|
|
47
|
+
rows: readonly Record<string, unknown>[],
|
|
48
|
+
pkColumns: readonly string[] | undefined,
|
|
49
|
+
): LiveDiffState {
|
|
50
|
+
const previous = new Map<string, Record<string, unknown>>();
|
|
51
|
+
for (const row of rows) previous.set(rowKey(row, pkColumns), row);
|
|
52
|
+
return { ...(pkColumns ? { pkColumns } : {}), previous };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Diff a fresh ordered result set against the state's previous set, MUTATING the state to the new set and
|
|
57
|
+
* returning the wire diff (§4). `order` is every key in the new ORDER BY order (keys only — cheap); `added`/
|
|
58
|
+
* `changed` carry the delta row BODIES; `removed` carries dropped keys. Never emits the full result set: a
|
|
59
|
+
* single-row change yields one `changed` and the (key-only) `order`.
|
|
60
|
+
*/
|
|
61
|
+
export function computeLiveDiff(
|
|
62
|
+
state: LiveDiffState,
|
|
63
|
+
nextRows: readonly Record<string, unknown>[],
|
|
64
|
+
): Omit<LiveDiffPayload, "queryId"> {
|
|
65
|
+
const order: string[] = [];
|
|
66
|
+
const added: { key: string; row: Record<string, unknown> }[] = [];
|
|
67
|
+
const changed: { key: string; row: Record<string, unknown> }[] = [];
|
|
68
|
+
const nextKeys = new Set<string>();
|
|
69
|
+
const nextMap = new Map<string, Record<string, unknown>>();
|
|
70
|
+
|
|
71
|
+
for (const row of nextRows) {
|
|
72
|
+
const key = rowKey(row, state.pkColumns);
|
|
73
|
+
// A duplicate key within one result set (composite PK not actually unique, or a keyless collision):
|
|
74
|
+
// keep the first, so `order`/diff stay a faithful set. Rare; the read projections are PK-unique.
|
|
75
|
+
if (nextKeys.has(key)) continue;
|
|
76
|
+
nextKeys.add(key);
|
|
77
|
+
nextMap.set(key, row);
|
|
78
|
+
order.push(key);
|
|
79
|
+
|
|
80
|
+
const prior = state.previous.get(key);
|
|
81
|
+
if (prior === undefined) {
|
|
82
|
+
added.push({ key, row });
|
|
83
|
+
} else if (!rowsEqual(prior, row)) {
|
|
84
|
+
changed.push({ key, row });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const removed: string[] = [];
|
|
89
|
+
for (const key of state.previous.keys()) {
|
|
90
|
+
if (!nextKeys.has(key)) removed.push(key);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
state.previous = nextMap;
|
|
94
|
+
return { order, added, changed, removed };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The tab-side fold of live diffs into an ordered row array with STABLE object identity (§4). The initial
|
|
99
|
+
* snapshot seeds the cache; each diff rebuilds the array from `diff.order`, reusing the cached object for
|
|
100
|
+
* any key not in `added`/`changed` (so an unchanged row keeps `===` and a memoized React row skips its
|
|
101
|
+
* re-render), and installing a fresh object for added/changed keys. Order is exactly `diff.order` — the
|
|
102
|
+
* query's ORDER BY as delivered by the worker.
|
|
103
|
+
*/
|
|
104
|
+
export class LiveRowsMaterializer<TRow extends Record<string, unknown> = Record<string, unknown>> {
|
|
105
|
+
private byKey = new Map<string, TRow>();
|
|
106
|
+
private rows: TRow[] = [];
|
|
107
|
+
private readonly pkColumns: readonly string[] | undefined;
|
|
108
|
+
|
|
109
|
+
constructor(pkColumns: readonly string[] | undefined) {
|
|
110
|
+
this.pkColumns = pkColumns;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Seed from the initial snapshot; returns the initial ordered rows (each a distinct cached object). */
|
|
114
|
+
seed(initialRows: readonly TRow[]): TRow[] {
|
|
115
|
+
this.byKey = new Map();
|
|
116
|
+
this.rows = [];
|
|
117
|
+
for (const row of initialRows) {
|
|
118
|
+
const key = rowKey(row, this.pkColumns);
|
|
119
|
+
this.byKey.set(key, row);
|
|
120
|
+
this.rows.push(row);
|
|
121
|
+
}
|
|
122
|
+
return this.rows;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Apply a diff; returns the new ordered array (a fresh array, but unchanged rows keep their object identity). */
|
|
126
|
+
apply(diff: Omit<LiveDiffPayload, "queryId">): TRow[] {
|
|
127
|
+
for (const key of diff.removed) this.byKey.delete(key);
|
|
128
|
+
for (const { key, row } of diff.added) this.byKey.set(key, row as TRow);
|
|
129
|
+
for (const { key, row } of diff.changed) this.byKey.set(key, row as TRow);
|
|
130
|
+
// Rebuild strictly from the delivered order, reusing whatever object each key now maps to. Added/changed
|
|
131
|
+
// keys already point at fresh objects (set above); every other key keeps its prior object (=== holds).
|
|
132
|
+
this.rows = diff.order.map((key) => this.byKey.get(key)!).filter((row): row is TRow => row !== undefined);
|
|
133
|
+
return this.rows;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The current ordered rows (identity-stable across `apply` calls for unchanged rows). */
|
|
137
|
+
current(): TRow[] {
|
|
138
|
+
return this.rows;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
// The bridge protocol (ADR-0032 S2). Everything that crosses between a tab and the shared sync engine
|
|
2
|
+
// travels as a typed {@link BridgeEnvelope} over a minimal {@link BridgePort} (a MessagePort-shaped
|
|
3
|
+
// transport). The router only ever inspects the envelope's `type`/`id`; its `payload` is OPAQUE to the
|
|
4
|
+
// router and always passes through a {@link BridgeCodec}, so a later columnar/transferable codec can be
|
|
5
|
+
// swapped in WITHOUT any protocol change (see BridgeCodec's doc).
|
|
6
|
+
//
|
|
7
|
+
// Deliberately transport-agnostic: `defineSyncWorker` and `attachSyncClient` both talk to a `BridgePort`,
|
|
8
|
+
// never a real `Worker`/`SharedWorker` directly — which is exactly why the whole bridge is unit-testable
|
|
9
|
+
// over bun's `MessageChannel` with no worker at all.
|
|
10
|
+
|
|
11
|
+
import type { SyncRuntimeStatus } from "@pgxsinkit/contracts";
|
|
12
|
+
|
|
13
|
+
export const BRIDGE_CHANNEL = "pgxsinkit-bridge" as const;
|
|
14
|
+
export const BRIDGE_PROTOCOL_VERSION = 1 as const;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* A structured-clone transferable (an `ArrayBuffer`, a `MessagePort`, …). The library carries no DOM lib
|
|
18
|
+
* dependency (like the convergence triggers), so this is the toolkit's own name for the type a future
|
|
19
|
+
* columnar codec would hand to `postMessage`'s transfer list. v1's identity codec never produces one.
|
|
20
|
+
*/
|
|
21
|
+
export type BridgeTransferable = unknown;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The minimal MessagePort-shaped transport the bridge needs — the intersection of a real `MessagePort`,
|
|
25
|
+
* a `SharedWorker` port, and a dedicated `Worker`/`self`. Injected everywhere so the protocol layer is
|
|
26
|
+
* exercised with a plain `MessageChannel` (no Worker) in tests. `start()` is optional (MessagePort needs
|
|
27
|
+
* it, `Worker`/`self` do not); `close()` is optional (a dedicated `self` cannot be closed by the tab).
|
|
28
|
+
*/
|
|
29
|
+
export interface BridgePort {
|
|
30
|
+
postMessage: (message: unknown, transfer?: BridgeTransferable[]) => void;
|
|
31
|
+
addEventListener: (type: "message", listener: (event: { data: unknown }) => void) => void;
|
|
32
|
+
removeEventListener: (type: "message", listener: (event: { data: unknown }) => void) => void;
|
|
33
|
+
start?: () => void;
|
|
34
|
+
close?: () => void;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The wire envelope. `payload` is the codec-encoded body — opaque to the router, which only routes on
|
|
39
|
+
* `type` and correlates on `id`. Keeping the body opaque is what lets a future codec return a columnar
|
|
40
|
+
* buffer (a transferable) in `payload` without any change to routing.
|
|
41
|
+
*/
|
|
42
|
+
export interface BridgeEnvelope {
|
|
43
|
+
ch: typeof BRIDGE_CHANNEL;
|
|
44
|
+
v: typeof BRIDGE_PROTOCOL_VERSION;
|
|
45
|
+
type: BridgeMessageType;
|
|
46
|
+
/** Correlation id for request/response pairs (rpc, subscribe, token pull). Absent for fire-and-forget fanout. */
|
|
47
|
+
id?: string;
|
|
48
|
+
/** Codec-encoded body — opaque to the router; decode with the same {@link BridgeCodec}. */
|
|
49
|
+
payload: unknown;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export type BridgeMessageType =
|
|
53
|
+
// tab → worker
|
|
54
|
+
| "provision"
|
|
55
|
+
| "attach"
|
|
56
|
+
| "detach"
|
|
57
|
+
| "token-push"
|
|
58
|
+
| "token-response"
|
|
59
|
+
| "rpc"
|
|
60
|
+
| "subscribe"
|
|
61
|
+
| "unsubscribe"
|
|
62
|
+
| "wake"
|
|
63
|
+
| "set-online"
|
|
64
|
+
// worker → tab
|
|
65
|
+
| "provision-ack"
|
|
66
|
+
| "attach-ack"
|
|
67
|
+
| "token-request"
|
|
68
|
+
| "rpc-result"
|
|
69
|
+
| "live-initial"
|
|
70
|
+
| "live-diff"
|
|
71
|
+
| "event";
|
|
72
|
+
|
|
73
|
+
// ─── Payload shapes ───────────────────────────────────────────────────────────
|
|
74
|
+
|
|
75
|
+
/** A single auth token snapshot the tab owns and pushes to the worker (ADR-0032 decision 3). */
|
|
76
|
+
export interface AuthTokenSnapshot {
|
|
77
|
+
accessToken: string;
|
|
78
|
+
/** Absolute expiry in epoch milliseconds (`Date.now()`-comparable), so the worker can apply an expiry margin. */
|
|
79
|
+
expiresAt: number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* tab → worker: pre-spawn the store WITHOUT booting the engine (ADR-0032 decision 5). Sent at the
|
|
84
|
+
* login screen against the freshly-named spare worker: the worker only runs PGlite `create`/initdb
|
|
85
|
+
* (off every thread that matters) and holds the raw store idle — no schema, no shape streams, no token
|
|
86
|
+
* — until the real {@link AttachPayload} arrives (with config + token) and adopts the provisioned store.
|
|
87
|
+
* Role-agnostic on purpose: the spare is minted before the user (and role) is known, so provisioning
|
|
88
|
+
* carries no registry — the schema is applied at attach with the role-resolved registry.
|
|
89
|
+
*/
|
|
90
|
+
export interface ProvisionPayload {
|
|
91
|
+
/** The bound store id (informational; naming is done tab-side via the SharedWorker name). */
|
|
92
|
+
storeId?: string;
|
|
93
|
+
/** The PGlite data dir to `create` ahead of attach (`idb://…` in a browser, `memory://…` in tests). */
|
|
94
|
+
dataDir?: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** worker → tab: the provision completed (or failed). Lets the login screen confirm the spare is warm. */
|
|
98
|
+
export interface ProvisionAckPayload {
|
|
99
|
+
ok: boolean;
|
|
100
|
+
storeId?: string;
|
|
101
|
+
/** Present when `!ok` — the initdb/create failed; the worker falls back to a fresh create at attach. */
|
|
102
|
+
error?: { message: string };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** tab → worker: the attach handshake. The first attach boots the engine; later attaches join it. */
|
|
106
|
+
export interface AttachPayload {
|
|
107
|
+
/** The bound store id (SharedWorker naming resolves it tab-side before attach — ADR-0032 decision 5). */
|
|
108
|
+
storeId?: string;
|
|
109
|
+
/** Explicit PGlite data dir if the worker should create its own store; `memory://…` in tests. */
|
|
110
|
+
dataDir?: string;
|
|
111
|
+
/** The tab's current auth token at attach time, or null when unauthenticated. */
|
|
112
|
+
token: AuthTokenSnapshot | null;
|
|
113
|
+
/**
|
|
114
|
+
* Serializable per-attach config overrides (kept minimal; the urls are baked into the worker). `role`
|
|
115
|
+
* selects which baked registry the worker boots (ADR-0032 S3): the spare is minted role-agnostic, so
|
|
116
|
+
* the role is only known at claim/attach — a single worker file bakes BOTH registries and picks here.
|
|
117
|
+
* `freshStore` is the fresh-store prefetch-overlap hint (ADR-0032 S4): the tab's claim path knows a
|
|
118
|
+
* claimed spare is schemaless (fresh) while a mapped/returning store never is, and forwards that here so
|
|
119
|
+
* the worker's `createSyncClient` can overlap the shape catch-up with the local boot phases.
|
|
120
|
+
*/
|
|
121
|
+
config?: { syncEnabled?: boolean; role?: string; freshStore?: boolean };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* tab → worker: gate the worker's outbound convergence (the board's Offline toggle, ADR-0032 S3). In
|
|
126
|
+
* in-process mode the toggle gates the local `autoSync` trigger; the worker owns convergence instead, so
|
|
127
|
+
* the tab forwards the flag and the worker suppresses/resumes its flush passes. Going back online fires
|
|
128
|
+
* one immediate pass so queued writes flush without waiting for the next interval tick.
|
|
129
|
+
*/
|
|
130
|
+
export interface SetOnlinePayload {
|
|
131
|
+
online: boolean;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** worker → tab: attach acknowledged. `alreadyBooted` is false for the attach that booted the engine. */
|
|
135
|
+
export interface AttachAckPayload {
|
|
136
|
+
alreadyBooted: boolean;
|
|
137
|
+
/**
|
|
138
|
+
* True when the engine's initial sync had ALREADY fired by the time this attach was acked (a late
|
|
139
|
+
* attach, ADR-0032 FIX 3). `ready` is monotonic in-process — once it resolves it stays resolved even if
|
|
140
|
+
* the phase later degrades — so a tab attaching after that moment must resolve `ready` immediately from
|
|
141
|
+
* the ack, rather than wait for a phase-"ready" status that may never come again.
|
|
142
|
+
*/
|
|
143
|
+
engineReady?: boolean;
|
|
144
|
+
/**
|
|
145
|
+
* Present when the engine boot REJECTED for this attach: the tab rejects `attachSyncClient` with this
|
|
146
|
+
* message instead of hanging forever on the ack (ADR-0032 FIX 1). A later attach retries the boot.
|
|
147
|
+
*/
|
|
148
|
+
error?: { message: string; detail?: unknown };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** worker → tab: a broadcast pull-request — any attached tab may answer, first response wins (ADR-0032 decision 3). */
|
|
152
|
+
export interface TokenRequestPayload {
|
|
153
|
+
requestId: string;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** tab → worker: the answer to a {@link TokenRequestPayload}. `token: null` = the tab has none. */
|
|
157
|
+
export interface TokenResponsePayload {
|
|
158
|
+
requestId: string;
|
|
159
|
+
token: AuthTokenSnapshot | null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The RPC ops the attach facade proxies to the worker's booted client — the write API (mirrors
|
|
164
|
+
* `client.mutate`/flush), mutation-state reads, and the one-shot raw inspection reads (`rawQuery`/`rawExec`).
|
|
165
|
+
*/
|
|
166
|
+
export type RpcOp =
|
|
167
|
+
| "create"
|
|
168
|
+
| "update"
|
|
169
|
+
| "delete"
|
|
170
|
+
| "batch"
|
|
171
|
+
| "transaction"
|
|
172
|
+
| "flush"
|
|
173
|
+
| "reconcile"
|
|
174
|
+
| "retryFailed"
|
|
175
|
+
| "recoverSending"
|
|
176
|
+
| "discardConflict"
|
|
177
|
+
| "discardQuarantined"
|
|
178
|
+
| "readMutationDetails"
|
|
179
|
+
| "diagnostics"
|
|
180
|
+
| "rawQuery"
|
|
181
|
+
| "rawExec";
|
|
182
|
+
|
|
183
|
+
/** tab → worker: a write/read-of-mutation-state RPC. `id` correlates the matching {@link RpcResultPayload}. */
|
|
184
|
+
export interface RpcPayload {
|
|
185
|
+
op: RpcOp;
|
|
186
|
+
args: unknown[];
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** worker → tab: an RPC outcome, mirroring today's in-process resolve/reject semantics. */
|
|
190
|
+
export interface RpcResultPayload {
|
|
191
|
+
ok: boolean;
|
|
192
|
+
/** The resolved value (present when `ok`). */
|
|
193
|
+
value?: unknown;
|
|
194
|
+
/** The rejection message + optional structured detail (present when `!ok`). */
|
|
195
|
+
error?: { message: string; detail?: unknown };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** tab → worker: register a live query. `id` correlates the initial snapshot; `queryId` keys subsequent diffs. */
|
|
199
|
+
export interface SubscribePayload {
|
|
200
|
+
queryId: string;
|
|
201
|
+
sql: string;
|
|
202
|
+
params: unknown[];
|
|
203
|
+
/**
|
|
204
|
+
* The result's primary-key columns, driving diff keying (§4). One column → the incremental path
|
|
205
|
+
* (`live.incrementalQuery`); many → worker-side diff by composite PK; empty/absent → value-identity
|
|
206
|
+
* fallback for a keyless query.
|
|
207
|
+
*/
|
|
208
|
+
pkColumns?: string[];
|
|
209
|
+
/** Lazy relations to activate before the query runs (ADR-0021), forwarded to the worker's `prepareQuery`. */
|
|
210
|
+
use?: string[];
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** worker → tab: the initial ordered snapshot for a subscription. `id` correlates the `subscribe` request. */
|
|
214
|
+
export interface LiveInitialPayload {
|
|
215
|
+
queryId: string;
|
|
216
|
+
rows: Record<string, unknown>[];
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* worker → tab: a DIFF update for a subscription (§4). Never a full result-set resend after the initial
|
|
221
|
+
* snapshot. `order` is the full ordered list of row keys (cheap — keys only, no row bodies); `added`/
|
|
222
|
+
* `changed` carry only the delta row bodies; `removed` carries only the dropped keys. The tab materializer
|
|
223
|
+
* rebuilds the ordered array from `order`, reusing cached row objects for keys not in `added`/`changed` so
|
|
224
|
+
* an unchanged row keeps its object identity (React memo bails on `===`).
|
|
225
|
+
*/
|
|
226
|
+
export interface LiveDiffPayload {
|
|
227
|
+
queryId: string;
|
|
228
|
+
/** Every result key in ORDER BY order (the query's delivered order). */
|
|
229
|
+
order: string[];
|
|
230
|
+
added: { key: string; row: Record<string, unknown> }[];
|
|
231
|
+
changed: { key: string; row: Record<string, unknown> }[];
|
|
232
|
+
removed: string[];
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** worker → tab: the single broadcast event stream (ADR-0032 decision 7), re-exposed as today's callbacks. */
|
|
236
|
+
export type BridgeEvent =
|
|
237
|
+
| { kind: "status"; status: SyncRuntimeStatus }
|
|
238
|
+
| { kind: "groupReady"; groupKey: string }
|
|
239
|
+
| { kind: "conflict"; details: unknown }
|
|
240
|
+
| { kind: "quarantine"; details: unknown }
|
|
241
|
+
| { kind: "reject"; details: unknown }
|
|
242
|
+
| { kind: "schema-change"; event: unknown }
|
|
243
|
+
| { kind: "sync-error"; message: string }
|
|
244
|
+
| { kind: "timing"; label: string; ms: number; data?: Record<string, unknown> }
|
|
245
|
+
// The debug rail (ADR-0032 decision 7): stamped with the WORKER's monotonic clock and origin-tagged so a
|
|
246
|
+
// tab can re-print it as `[pgxsinkit·w <stamp>ms] <line>` — a SharedWorker's own console is invisible.
|
|
247
|
+
| { kind: "debug"; stamp: number; line: string; data?: Record<string, unknown> };
|
|
248
|
+
|
|
249
|
+
/** tab → worker: an app-driven wake (online/visibilitychange), treated as a convergence pass request. */
|
|
250
|
+
export interface WakePayload {
|
|
251
|
+
reason: "online" | "visibility" | "manual";
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// ─── Codec seam ─────────────────────────────────────────────────────────────
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* The codec every bridge payload crosses through (owner-mandated seam, ADR-0032 S2 §1). v1 ships exactly
|
|
258
|
+
* ONE codec — {@link identityCodec}, which relies on the transport's own structured clone. The seam exists
|
|
259
|
+
* so a columnar/transferable codec (e.g. one that packs live-diff rows into a shared `ArrayBuffer` and
|
|
260
|
+
* returns it as a transferable) can be swapped in later WITHOUT any protocol change: the router already
|
|
261
|
+
* treats `BridgeEnvelope.payload` as opaque, and `encode` may return `{ payload, transfer }` so the sender
|
|
262
|
+
* hands transferables to `postMessage`. Keep encode/decode inverse and side-effect free.
|
|
263
|
+
*/
|
|
264
|
+
export interface BridgeCodec {
|
|
265
|
+
/** Encode a raw payload into the envelope body. May declare transferables for a future zero-copy codec. */
|
|
266
|
+
encode: (payload: unknown) => { payload: unknown; transfer?: BridgeTransferable[] };
|
|
267
|
+
/** Decode an envelope body back into the raw payload. Inverse of {@link encode}. */
|
|
268
|
+
decode: (payload: unknown) => unknown;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* The v1 identity codec: the body IS the payload, and the transport's structured clone does the real
|
|
273
|
+
* copying. No transferables. The only codec shipped in S2 — swapping in a columnar codec later touches
|
|
274
|
+
* only this object, never the message types or the router.
|
|
275
|
+
*/
|
|
276
|
+
export const identityCodec: BridgeCodec = {
|
|
277
|
+
encode: (payload) => ({ payload }),
|
|
278
|
+
decode: (payload) => payload,
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
// ─── Envelope helpers ─────────────────────────────────────────────────────────
|
|
282
|
+
|
|
283
|
+
/** Build a wire envelope, running the payload through the codec. Returns the envelope + any transferables. */
|
|
284
|
+
export function encodeEnvelope(
|
|
285
|
+
codec: BridgeCodec,
|
|
286
|
+
type: BridgeMessageType,
|
|
287
|
+
payload: unknown,
|
|
288
|
+
id?: string,
|
|
289
|
+
): { envelope: BridgeEnvelope; transfer?: BridgeTransferable[] } {
|
|
290
|
+
const encoded = codec.encode(payload);
|
|
291
|
+
const envelope: BridgeEnvelope = {
|
|
292
|
+
ch: BRIDGE_CHANNEL,
|
|
293
|
+
v: BRIDGE_PROTOCOL_VERSION,
|
|
294
|
+
type,
|
|
295
|
+
payload: encoded.payload,
|
|
296
|
+
...(id !== undefined ? { id } : {}),
|
|
297
|
+
};
|
|
298
|
+
return { envelope, ...(encoded.transfer ? { transfer: encoded.transfer } : {}) };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Type-guard a received message as a bridge envelope of the current protocol version (ignore foreign traffic). */
|
|
302
|
+
export function isBridgeEnvelope(data: unknown): data is BridgeEnvelope {
|
|
303
|
+
return (
|
|
304
|
+
typeof data === "object" &&
|
|
305
|
+
data !== null &&
|
|
306
|
+
(data as { ch?: unknown }).ch === BRIDGE_CHANNEL &&
|
|
307
|
+
(data as { v?: unknown }).v === BRIDGE_PROTOCOL_VERSION
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Send a typed message over a port: encode → post (with any transferables). The one write choke point. */
|
|
312
|
+
export function postBridgeMessage(
|
|
313
|
+
port: BridgePort,
|
|
314
|
+
codec: BridgeCodec,
|
|
315
|
+
type: BridgeMessageType,
|
|
316
|
+
payload: unknown,
|
|
317
|
+
id?: string,
|
|
318
|
+
): void {
|
|
319
|
+
const { envelope, transfer } = encodeEnvelope(codec, type, payload, id);
|
|
320
|
+
if (transfer && transfer.length > 0) {
|
|
321
|
+
port.postMessage(envelope, transfer);
|
|
322
|
+
} else {
|
|
323
|
+
port.postMessage(envelope);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// The worker's single auth token cache + pull mechanism (ADR-0032 decision 3). The worker holds exactly
|
|
2
|
+
// ONE token and NEVER refreshes it — the tab layer is the sole auth owner (exactly one refresher exists, so
|
|
3
|
+
// GoTrue refresh-token reuse detection can never trip). A read/write that finds the cache within the expiry
|
|
4
|
+
// margin triggers ONE pull broadcast; concurrent needs dedupe onto that single in-flight pull; the first
|
|
5
|
+
// tab answer wins. Factored out of `defineSyncWorker` so this mechanism is unit-tested in isolation.
|
|
6
|
+
|
|
7
|
+
import type { AuthTokenSnapshot } from "./protocol";
|
|
8
|
+
|
|
9
|
+
export interface WorkerTokenCache {
|
|
10
|
+
/**
|
|
11
|
+
* Resolve the access token for a shape/flush request. Returns the cached token when it is comfortably
|
|
12
|
+
* ahead of expiry; otherwise broadcasts ONE pull (deduped across concurrent callers) and resolves when a
|
|
13
|
+
* tab answers. Falls back to the (stale) cached token if a pull yields nothing.
|
|
14
|
+
*/
|
|
15
|
+
getToken: () => Promise<string | undefined>;
|
|
16
|
+
/** The tab pushed a fresh token (auth state change or the initial attach) — cache it and satisfy any pull. */
|
|
17
|
+
push: (token: AuthTokenSnapshot | null) => void;
|
|
18
|
+
/**
|
|
19
|
+
* Seed the cache from a LATER attach's token, but only if it is strictly fresher than what is cached
|
|
20
|
+
* (ADR-0032 FIX 5). Attach seeding must never CLOBBER a fresher cached token with an older/null one —
|
|
21
|
+
* only the explicit `push` path (the tab as auth owner saying "this is current") may overwrite
|
|
22
|
+
* unconditionally, including null on logout.
|
|
23
|
+
*/
|
|
24
|
+
pushIfFresher: (token: AuthTokenSnapshot | null) => void;
|
|
25
|
+
/** A tab answered a pull-request. First matching answer wins; later duplicates are ignored. */
|
|
26
|
+
respond: (requestId: string, token: AuthTokenSnapshot | null) => void;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function createWorkerTokenCache(options: {
|
|
30
|
+
marginMs: number;
|
|
31
|
+
broadcastRequest: (requestId: string) => void;
|
|
32
|
+
now?: () => number;
|
|
33
|
+
}): WorkerTokenCache {
|
|
34
|
+
const now = options.now ?? (() => Date.now());
|
|
35
|
+
let cached: AuthTokenSnapshot | null = null;
|
|
36
|
+
let inFlight: Promise<AuthTokenSnapshot | null> | null = null;
|
|
37
|
+
let resolveInFlight: ((token: AuthTokenSnapshot | null) => void) | null = null;
|
|
38
|
+
let currentRequestId: string | null = null;
|
|
39
|
+
let requestCounter = 0;
|
|
40
|
+
|
|
41
|
+
const settle = (token: AuthTokenSnapshot | null) => {
|
|
42
|
+
if (token) cached = token;
|
|
43
|
+
const resolve = resolveInFlight;
|
|
44
|
+
inFlight = null;
|
|
45
|
+
resolveInFlight = null;
|
|
46
|
+
currentRequestId = null;
|
|
47
|
+
resolve?.(token);
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
getToken: async () => {
|
|
52
|
+
if (cached && cached.expiresAt - now() > options.marginMs) {
|
|
53
|
+
return cached.accessToken;
|
|
54
|
+
}
|
|
55
|
+
if (!inFlight) {
|
|
56
|
+
currentRequestId = `pull-${++requestCounter}`;
|
|
57
|
+
inFlight = new Promise<AuthTokenSnapshot | null>((resolve) => {
|
|
58
|
+
resolveInFlight = resolve;
|
|
59
|
+
});
|
|
60
|
+
// Exactly one broadcast per pull; concurrent getToken calls below await the same `inFlight`.
|
|
61
|
+
options.broadcastRequest(currentRequestId);
|
|
62
|
+
}
|
|
63
|
+
const answered = await inFlight;
|
|
64
|
+
return answered?.accessToken ?? cached?.accessToken;
|
|
65
|
+
},
|
|
66
|
+
push: (token) => {
|
|
67
|
+
cached = token;
|
|
68
|
+
// A push satisfies an outstanding pull too (the tab volunteered before answering the request).
|
|
69
|
+
if (inFlight) settle(token);
|
|
70
|
+
},
|
|
71
|
+
pushIfFresher: (token) => {
|
|
72
|
+
if (!token) return;
|
|
73
|
+
if (cached && cached.expiresAt >= token.expiresAt) return;
|
|
74
|
+
// Strictly fresher than the cache (or the cache is empty) → adopt it via `push`, which also settles
|
|
75
|
+
// any in-flight pull.
|
|
76
|
+
cached = token;
|
|
77
|
+
if (inFlight) settle(token);
|
|
78
|
+
},
|
|
79
|
+
respond: (requestId, token) => {
|
|
80
|
+
// First response for the CURRENT pull wins; a stale/duplicate requestId (or no pull) is ignored.
|
|
81
|
+
if (inFlight && requestId === currentRequestId) settle(token);
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|