@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
package/src/sync-auth.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import type { ExternalHeadersRecord, ShapeStreamOptions } from "@electric-sql/client";
|
|
2
|
+
|
|
3
|
+
/** The per-shape error handler shape Electric expects (`ShapeStreamOptions.onError`). */
|
|
4
|
+
type ShapeStreamErrorHandler = NonNullable<ShapeStreamOptions["onError"]>;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Read-path identity (ADR-0013). The two ingress points must share **one** token lifecycle: the
|
|
8
|
+
* write path already calls `getAuthToken` fresh on every flush, so the read path must too — never
|
|
9
|
+
* freezing a JWT at boot, which wedges a long-lived offline-first session the instant the token
|
|
10
|
+
* expires.
|
|
11
|
+
*
|
|
12
|
+
* `buildAuthShapeHeaders` returns the read-path `Authorization` header as an **async function**.
|
|
13
|
+
* Electric resolves header-value functions on every request *and every retry*
|
|
14
|
+
* (`ExternalHeadersRecord` allows `string | (() => string | Promise<string>)`), so each shape fetch
|
|
15
|
+
* presents a fresh token. This is the client mirror of ADR-0003's server-side one-identity decision.
|
|
16
|
+
*
|
|
17
|
+
* The provider contract (documented in `docs/architecture.md`): `getAuthToken` is now called per
|
|
18
|
+
* request by both paths and **must be refresh-deduping** — return the cached valid token and refresh
|
|
19
|
+
* single-flight, so an N-shape consistency group does not trigger N refreshes.
|
|
20
|
+
*/
|
|
21
|
+
/**
|
|
22
|
+
* Build the read-path shape headers: the optional async `Authorization` (per ADR-0013) **plus** any
|
|
23
|
+
* caller-supplied static `requestHeaders`. The static headers are spread first so the toolkit-owned
|
|
24
|
+
* `Authorization` always wins; they exist for deployment-gateway credentials the toolkit is otherwise
|
|
25
|
+
* agnostic about — e.g. a Supabase `apikey` header the platform function gateway expects. Emitted
|
|
26
|
+
* whenever *either* a token provider or static headers are present, so a credential-only consumer
|
|
27
|
+
* (no per-request token) still sends its headers.
|
|
28
|
+
*/
|
|
29
|
+
export function buildShapeHeaders(input: {
|
|
30
|
+
getAuthToken?: () => Promise<string | undefined>;
|
|
31
|
+
requestHeaders?: Record<string, string>;
|
|
32
|
+
}): ExternalHeadersRecord {
|
|
33
|
+
const headers: ExternalHeadersRecord = { ...(input.requestHeaders ?? {}) };
|
|
34
|
+
const getAuthToken = input.getAuthToken;
|
|
35
|
+
if (getAuthToken) {
|
|
36
|
+
// Resolved per request: a fresh token each time, never one captured at boot. An absent token
|
|
37
|
+
// yields an empty value (unauthenticated) rather than the literal string `Bearer undefined`.
|
|
38
|
+
headers["Authorization"] = async () => {
|
|
39
|
+
const token = await getAuthToken();
|
|
40
|
+
return token ? `Bearer ${token}` : "";
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
return headers;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Token-only convenience over {@link buildShapeHeaders}; retained for callers that pass a provider. */
|
|
47
|
+
export function buildAuthShapeHeaders(
|
|
48
|
+
getAuthToken: () => Promise<string | undefined>,
|
|
49
|
+
requestHeaders?: Record<string, string>,
|
|
50
|
+
): ExternalHeadersRecord {
|
|
51
|
+
return buildShapeHeaders({ getAuthToken, ...(requestHeaders ? { requestHeaders } : {}) });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** HTTP statuses that mean "the credential is the problem" — re-auth, never give up (ADR-0013). */
|
|
55
|
+
const AUTH_ERROR_STATUSES = new Set([401, 403]);
|
|
56
|
+
|
|
57
|
+
/** Read the duck-typed numeric `status` off an Electric `FetchError`, or `undefined` for a plain error. */
|
|
58
|
+
function readErrorStatus(error: unknown): number | undefined {
|
|
59
|
+
if (typeof error !== "object" || error === null || !("status" in error)) {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
const status = (error as { status: unknown }).status;
|
|
63
|
+
return typeof status === "number" ? status : undefined;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* True when the error is an auth failure (Electric's `FetchError` with a 401/403 `status`). We read
|
|
68
|
+
* the documented `status` field rather than `instanceof FetchError`: the experimental and client
|
|
69
|
+
* packages can resolve to *different* `@electric-sql/client` copies, so an `instanceof` against one
|
|
70
|
+
* copy can miss a `FetchError` thrown from the other. A duck-typed numeric `status` is robust and
|
|
71
|
+
* carries no false positives — a plain network/`Error` has no numeric `status`.
|
|
72
|
+
*/
|
|
73
|
+
function isAuthError(error: unknown): boolean {
|
|
74
|
+
const status = readErrorStatus(error);
|
|
75
|
+
return status !== undefined && AUTH_ERROR_STATUSES.has(status);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Whether a non-auth read-stream error is worth retrying (#4): a transient transport fault — a 5xx,
|
|
80
|
+
* a 429 rate-limit, or a network error with no HTTP status. A genuine non-auth 4xx (400/404/409/…)
|
|
81
|
+
* is structural: retrying re-fails, so we stop. (401/403 are handled separately as auth.)
|
|
82
|
+
*/
|
|
83
|
+
function isRetryableStreamError(error: unknown): boolean {
|
|
84
|
+
const status = readErrorStatus(error);
|
|
85
|
+
if (status === undefined) {
|
|
86
|
+
return true; // network/transport error — retry with Electric's backoff
|
|
87
|
+
}
|
|
88
|
+
return status >= 500 || status === 429;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The per-shape `ShapeStreamOptions.onError` handler for the read path. It is the only place that can
|
|
93
|
+
* request a retry (the `MultiShapeStream.subscribe` `onError` is notification-only), so it owns BOTH
|
|
94
|
+
* read-path identity (ADR-0013) and read-stream error surfacing (#4):
|
|
95
|
+
*
|
|
96
|
+
* - **auth (401/403)** → `onAuthError` + return `{}` (retry): Electric re-issues the request,
|
|
97
|
+
* re-resolving the async Authorization header ({@link buildAuthShapeHeaders}) for a *fresh* token.
|
|
98
|
+
* Never return `void` here — that stops the stream permanently, wrong for offline-first: a dead
|
|
99
|
+
* session must keep retrying (jittered backoff bounds the cost) so sync resumes the instant re-auth
|
|
100
|
+
* makes the token valid again. The optional `onAuthError` surfaces a distinct "re-login" status.
|
|
101
|
+
* - **any other error** → `onReadStreamError` (so the runtime can move to a `degraded` status instead
|
|
102
|
+
* of silently believing the read path is live), then retry transient faults ({@link
|
|
103
|
+
* isRetryableStreamError}: 5xx/429/network → `{}`) or stop a structural 4xx (return `undefined`). A
|
|
104
|
+
* later successful fetch (`onSyncActivity`) clears the degraded status back to live.
|
|
105
|
+
*/
|
|
106
|
+
export function createShapeErrorHandler(
|
|
107
|
+
options: { onAuthError?: () => void; onReadStreamError?: (error: Error) => void } = {},
|
|
108
|
+
): ShapeStreamErrorHandler {
|
|
109
|
+
return (error: Error) => {
|
|
110
|
+
if (isAuthError(error)) {
|
|
111
|
+
options.onAuthError?.();
|
|
112
|
+
return {}; // retry → re-resolves the async Authorization header for a fresh token
|
|
113
|
+
}
|
|
114
|
+
options.onReadStreamError?.(error);
|
|
115
|
+
return isRetryableStreamError(error) ? {} : undefined;
|
|
116
|
+
};
|
|
117
|
+
}
|
|
@@ -0,0 +1,558 @@
|
|
|
1
|
+
// The tab facade (ADR-0032 S2, decisions 3/4/6/7). `attachSyncClient` returns the SAME client shape as
|
|
2
|
+
// `createSyncClient` wherever semantics allow — the write API (RPC-backed), per-group readiness, the
|
|
3
|
+
// live-rows seam, `ready`/`status`/`stop` — transparently proxied to the one shared worker engine. The tab
|
|
4
|
+
// stays the single auth owner: it pushes its token at attach and on `notifyAuthChanged`, and answers the
|
|
5
|
+
// worker's expiry pull-requests via `getToken`.
|
|
6
|
+
//
|
|
7
|
+
// One-shot Drizzle reads (`query`/`queryRaw`/…), local `pglite`/`ensureSynced`/`destroy` are NOT proxied in
|
|
8
|
+
// S2 (the mandated attach surface is the write API + live rows + readiness) — they throw a clear
|
|
9
|
+
// not-supported error. Query BUILDING still works on the tab: `drizzle`/`views` are the same build-only
|
|
10
|
+
// handles `createSyncClient` exposes, compiled to SQL here and executed in the worker.
|
|
11
|
+
|
|
12
|
+
import type { Results } from "@electric-sql/pglite";
|
|
13
|
+
|
|
14
|
+
import type {
|
|
15
|
+
MutationDiagnostics,
|
|
16
|
+
SyncRuntimeStatus,
|
|
17
|
+
SyncTableName,
|
|
18
|
+
SyncTableRegistry,
|
|
19
|
+
WriteMode,
|
|
20
|
+
} from "@pgxsinkit/contracts";
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
buildRegistryReadHandles,
|
|
24
|
+
type LiveRowsSubscription,
|
|
25
|
+
type MutationBatchItem,
|
|
26
|
+
type MutationDetail,
|
|
27
|
+
type SubscribeLiveRowsInput,
|
|
28
|
+
type SyncClient,
|
|
29
|
+
type SyncTransaction,
|
|
30
|
+
type SyncTransactionResult,
|
|
31
|
+
} from "../index";
|
|
32
|
+
import type { LocalStoreVersionEvent } from "../local-store";
|
|
33
|
+
import { LiveRowsMaterializer } from "./live-diff";
|
|
34
|
+
import {
|
|
35
|
+
type AttachAckPayload,
|
|
36
|
+
type AttachPayload,
|
|
37
|
+
type AuthTokenSnapshot,
|
|
38
|
+
type BridgeCodec,
|
|
39
|
+
type BridgeEvent,
|
|
40
|
+
type BridgePort,
|
|
41
|
+
type BridgeTransferable,
|
|
42
|
+
identityCodec,
|
|
43
|
+
isBridgeEnvelope,
|
|
44
|
+
type LiveDiffPayload,
|
|
45
|
+
type LiveInitialPayload,
|
|
46
|
+
postBridgeMessage,
|
|
47
|
+
type ProvisionAckPayload,
|
|
48
|
+
type RpcOp,
|
|
49
|
+
type RpcResultPayload,
|
|
50
|
+
type TokenRequestPayload,
|
|
51
|
+
} from "./protocol";
|
|
52
|
+
|
|
53
|
+
/** A `Worker`/`SharedWorker`-shaped handle: a dedicated `Worker` IS the port; a `SharedWorker` carries `.port`. */
|
|
54
|
+
interface WorkerLike {
|
|
55
|
+
port?: BridgePort;
|
|
56
|
+
postMessage?: (message: unknown, transfer?: BridgeTransferable[]) => void;
|
|
57
|
+
addEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
|
|
58
|
+
removeEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
62
|
+
registry: TRegistry;
|
|
63
|
+
/** A native `Worker` or `SharedWorker` (or anything port-shaped). Provide this OR {@link port}. */
|
|
64
|
+
worker?: WorkerLike;
|
|
65
|
+
/** A raw transport port (a `MessageChannel` port in tests, a `SharedWorker.port` in a browser). */
|
|
66
|
+
port?: BridgePort;
|
|
67
|
+
/**
|
|
68
|
+
* The tab's token provider (ADR-0032 decision 3). Richer than `createSyncClient`'s string form: the
|
|
69
|
+
* worker needs the EXPIRY to apply its pull margin, so this yields `{accessToken, expiresAt}` (or null
|
|
70
|
+
* when unauthenticated). Pushed at attach and answered on every worker pull-request.
|
|
71
|
+
*/
|
|
72
|
+
getToken?: () => Promise<AuthTokenSnapshot | null>;
|
|
73
|
+
/** The bound store id (resolved tab-side before attach — SharedWorker naming, ADR-0032 decision 5). */
|
|
74
|
+
storeId?: string;
|
|
75
|
+
dataDir?: string;
|
|
76
|
+
syncEnabled?: boolean;
|
|
77
|
+
/**
|
|
78
|
+
* Which baked registry the worker boots (ADR-0032 S3) — forwarded in the attach `config.role`. A worker
|
|
79
|
+
* file that bakes multiple role variants (the board's admin/member) picks by this; single-registry
|
|
80
|
+
* workers ignore it.
|
|
81
|
+
*/
|
|
82
|
+
role?: string;
|
|
83
|
+
/**
|
|
84
|
+
* Fresh-store prefetch-overlap hint (ADR-0032 S4), forwarded in the attach `config.freshStore`. Set true
|
|
85
|
+
* ONLY when the tab knows the store is a claimed schemaless spare (never for a mapped/returning store);
|
|
86
|
+
* the worker's `createSyncClient` then overlaps the shape catch-up with its local boot phases.
|
|
87
|
+
*/
|
|
88
|
+
freshStore?: boolean;
|
|
89
|
+
codec?: BridgeCodec;
|
|
90
|
+
onStatusChange?: (status: SyncRuntimeStatus) => void;
|
|
91
|
+
onConflict?: (details: MutationDetail[]) => void;
|
|
92
|
+
onQuarantine?: (details: MutationDetail[]) => void;
|
|
93
|
+
onReject?: (details: MutationDetail[]) => void;
|
|
94
|
+
onSchemaChange?: (event: LocalStoreVersionEvent) => void;
|
|
95
|
+
onSyncError?: (error: Error) => void;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The worker-attached client: `SyncClient`'s shape, worker-proxied, plus `notifyAuthChanged` (re-push the
|
|
100
|
+
* token after an app auth-state change, ADR-0032 decision 3). The unsupported one-shot-read members throw.
|
|
101
|
+
*/
|
|
102
|
+
export type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient<TRegistry> & {
|
|
103
|
+
notifyAuthChanged: () => void;
|
|
104
|
+
/**
|
|
105
|
+
* Forward the app's Offline toggle to the worker (ADR-0032 S3). The worker owns convergence, so the
|
|
106
|
+
* tab cannot gate a local trigger; this sends `set-online`, which suppresses/resumes the worker's flush
|
|
107
|
+
* passes (resuming fires one immediate pass). The in-process client gates its own `autoSync` instead.
|
|
108
|
+
*/
|
|
109
|
+
setOnline: (online: boolean) => void;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
export async function attachSyncClient<const TRegistry extends SyncTableRegistry>(
|
|
113
|
+
options: AttachSyncClientOptions<TRegistry>,
|
|
114
|
+
): Promise<AttachedSyncClient<TRegistry>> {
|
|
115
|
+
const codec = options.codec ?? identityCodec;
|
|
116
|
+
const port = resolvePort(options);
|
|
117
|
+
|
|
118
|
+
// ─── Correlation + subscription bookkeeping ──────────────────────────────────────────────────────
|
|
119
|
+
let nextId = 0;
|
|
120
|
+
const newId = (prefix: string) => `${prefix}-${++nextId}`;
|
|
121
|
+
const rpcPending = new Map<string, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();
|
|
122
|
+
const initialPending = new Map<
|
|
123
|
+
string,
|
|
124
|
+
{ resolve: (payload: LiveInitialPayload) => void; reject: (error: Error) => void }
|
|
125
|
+
>();
|
|
126
|
+
const diffHandlers = new Map<string, (diff: Omit<LiveDiffPayload, "queryId">) => void>();
|
|
127
|
+
|
|
128
|
+
// ─── Status + readiness ──────────────────────────────────────────────────────────────────────────
|
|
129
|
+
const status: SyncRuntimeStatus = { phase: "booting", isRunning: false };
|
|
130
|
+
let resolveReady!: () => void;
|
|
131
|
+
const ready = new Promise<void>((resolve) => {
|
|
132
|
+
resolveReady = resolve;
|
|
133
|
+
});
|
|
134
|
+
let readyResolved = false;
|
|
135
|
+
const readyGroups = new Set<string>();
|
|
136
|
+
const groupWaiters = new Map<string, Array<() => void>>();
|
|
137
|
+
|
|
138
|
+
// ─── Auth: push at attach + on notifyAuthChanged, answer pull-requests ────────────────────────────
|
|
139
|
+
const pushToken = async () => {
|
|
140
|
+
const token = options.getToken ? await options.getToken() : null;
|
|
141
|
+
postBridgeMessage(port, codec, "token-push", token);
|
|
142
|
+
};
|
|
143
|
+
const answerPull = async (requestId: string) => {
|
|
144
|
+
const token = options.getToken ? await options.getToken() : null;
|
|
145
|
+
postBridgeMessage(port, codec, "token-response", { requestId, token });
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
// ─── Inbound message routing ─────────────────────────────────────────────────────────────────────
|
|
149
|
+
const markReady = () => {
|
|
150
|
+
if (readyResolved) return;
|
|
151
|
+
readyResolved = true;
|
|
152
|
+
resolveReady();
|
|
153
|
+
};
|
|
154
|
+
// Record a group as ready and settle any waiters — shared by the discrete `groupReady` edge and the
|
|
155
|
+
// status snapshot's `status.groups` merge (ADR-0032 FIX 4), so a tab attaching after the edge fired
|
|
156
|
+
// still resolves `client.groupReady(table)` off the snapshot it gets at attach.
|
|
157
|
+
const markGroupReady = (groupKey: string) => {
|
|
158
|
+
readyGroups.add(groupKey);
|
|
159
|
+
const waiters = groupWaiters.get(groupKey);
|
|
160
|
+
if (waiters) {
|
|
161
|
+
groupWaiters.delete(groupKey);
|
|
162
|
+
for (const resolve of waiters) resolve();
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
const onEvent = (event: BridgeEvent) => {
|
|
166
|
+
switch (event.kind) {
|
|
167
|
+
case "status": {
|
|
168
|
+
Object.assign(status, event.status);
|
|
169
|
+
options.onStatusChange?.(event.status);
|
|
170
|
+
// Match the in-process contract EXACTLY (ADR-0032 FIX 3): `ready` resolves ONLY from phase
|
|
171
|
+
// "ready" (all eager groups caught up, or the syncEnabled:false path). `auth-needed`/`degraded`
|
|
172
|
+
// do NOT resolve it — an engine stuck retrying auth keeps `ready` pending, as in-process.
|
|
173
|
+
if (event.status.phase === "ready") markReady();
|
|
174
|
+
// Late-attach group merge (ADR-0032 FIX 4): fold every already-ready group from the snapshot.
|
|
175
|
+
for (const [groupKey, ready] of Object.entries(event.status.groups ?? {})) {
|
|
176
|
+
if (ready) markGroupReady(groupKey);
|
|
177
|
+
}
|
|
178
|
+
break;
|
|
179
|
+
}
|
|
180
|
+
case "groupReady": {
|
|
181
|
+
markGroupReady(event.groupKey);
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
case "conflict":
|
|
185
|
+
options.onConflict?.(event.details as MutationDetail[]);
|
|
186
|
+
break;
|
|
187
|
+
case "quarantine":
|
|
188
|
+
options.onQuarantine?.(event.details as MutationDetail[]);
|
|
189
|
+
break;
|
|
190
|
+
case "reject":
|
|
191
|
+
options.onReject?.(event.details as MutationDetail[]);
|
|
192
|
+
break;
|
|
193
|
+
case "schema-change":
|
|
194
|
+
options.onSchemaChange?.(event.event as LocalStoreVersionEvent);
|
|
195
|
+
break;
|
|
196
|
+
case "sync-error":
|
|
197
|
+
options.onSyncError?.(new Error(event.message));
|
|
198
|
+
break;
|
|
199
|
+
case "debug": {
|
|
200
|
+
// Re-print the worker's rail line gated on THIS tab's own flag, origin-tagged with the worker's
|
|
201
|
+
// monotonic stamp (ADR-0032 decision 7) — a SharedWorker's own console is otherwise invisible.
|
|
202
|
+
if ((globalThis as { __pgxsinkitDebug?: boolean }).__pgxsinkitDebug === true) {
|
|
203
|
+
const line = `[pgxsinkit·w ${event.stamp.toFixed(0)}ms] ${event.line}`;
|
|
204
|
+
if (event.data) console.debug(line, event.data);
|
|
205
|
+
else console.debug(line);
|
|
206
|
+
}
|
|
207
|
+
break;
|
|
208
|
+
}
|
|
209
|
+
case "timing":
|
|
210
|
+
break;
|
|
211
|
+
default:
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
const listener = (message: { data: unknown }) => {
|
|
217
|
+
if (!isBridgeEnvelope(message.data)) return;
|
|
218
|
+
const envelope = message.data;
|
|
219
|
+
const payload = codec.decode(envelope.payload);
|
|
220
|
+
switch (envelope.type) {
|
|
221
|
+
case "attach-ack": {
|
|
222
|
+
const ack = payload as AttachAckPayload;
|
|
223
|
+
// A boot failure crosses in the ack's `error` (ADR-0032 FIX 1): reject the handshake so
|
|
224
|
+
// `attachSyncClient` rejects instead of hanging forever. On success, the engine exists and the
|
|
225
|
+
// status event that follows drives `ready`; `engineReady` covers a LATE attach whose engine already
|
|
226
|
+
// fired its monotonic `ready` before this ack (FIX 3), so resolve `ready` straight away.
|
|
227
|
+
if (ack.error) {
|
|
228
|
+
attachAckReject?.(rebuildError(ack.error));
|
|
229
|
+
} else {
|
|
230
|
+
if (ack.engineReady) markReady();
|
|
231
|
+
attachAckResolve?.(ack);
|
|
232
|
+
}
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
case "token-request":
|
|
236
|
+
void answerPull((payload as TokenRequestPayload).requestId);
|
|
237
|
+
break;
|
|
238
|
+
case "rpc-result": {
|
|
239
|
+
const id = envelope.id;
|
|
240
|
+
if (id == null) break;
|
|
241
|
+
const result = payload as RpcResultPayload;
|
|
242
|
+
const pending = rpcPending.get(id);
|
|
243
|
+
if (pending) {
|
|
244
|
+
rpcPending.delete(id);
|
|
245
|
+
if (result.ok) pending.resolve(result.value);
|
|
246
|
+
else pending.reject(rebuildError(result.error));
|
|
247
|
+
break;
|
|
248
|
+
}
|
|
249
|
+
// A failed `subscribe` is reported as an `rpc-result` correlated by the subscribe's envelope id
|
|
250
|
+
// (the worker has no client to hand an initial snapshot), so route the miss to the initial waiter
|
|
251
|
+
// (ADR-0032 FIX 2). A successful subscribe never lands here — it resolves via `live-initial`.
|
|
252
|
+
const initial = initialPending.get(id);
|
|
253
|
+
if (initial && !result.ok) {
|
|
254
|
+
initialPending.delete(id);
|
|
255
|
+
initial.reject(rebuildError(result.error));
|
|
256
|
+
}
|
|
257
|
+
break;
|
|
258
|
+
}
|
|
259
|
+
case "live-initial": {
|
|
260
|
+
const id = envelope.id;
|
|
261
|
+
const initial = payload as LiveInitialPayload;
|
|
262
|
+
if (id != null) {
|
|
263
|
+
const pending = initialPending.get(id);
|
|
264
|
+
if (pending) {
|
|
265
|
+
initialPending.delete(id);
|
|
266
|
+
pending.resolve(initial);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
break;
|
|
270
|
+
}
|
|
271
|
+
case "live-diff": {
|
|
272
|
+
const diff = payload as LiveDiffPayload;
|
|
273
|
+
diffHandlers.get(diff.queryId)?.(diff);
|
|
274
|
+
break;
|
|
275
|
+
}
|
|
276
|
+
case "event":
|
|
277
|
+
onEvent(payload as BridgeEvent);
|
|
278
|
+
break;
|
|
279
|
+
default:
|
|
280
|
+
break;
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
port.addEventListener("message", listener);
|
|
284
|
+
port.start?.();
|
|
285
|
+
|
|
286
|
+
// ─── RPC helper ──────────────────────────────────────────────────────────────────────────────────
|
|
287
|
+
const rpc = <T>(op: RpcOp, args: unknown[]): Promise<T> => {
|
|
288
|
+
const id = newId("rpc");
|
|
289
|
+
return new Promise<T>((resolve, reject) => {
|
|
290
|
+
rpcPending.set(id, { resolve: resolve as (value: unknown) => void, reject });
|
|
291
|
+
postBridgeMessage(port, codec, "rpc", { op, args }, id);
|
|
292
|
+
});
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
// ─── Attach handshake ────────────────────────────────────────────────────────────────────────────
|
|
296
|
+
let attachAckResolve: ((ack: AttachAckPayload) => void) | null = null;
|
|
297
|
+
let attachAckReject: ((error: Error) => void) | null = null;
|
|
298
|
+
const attachAck = new Promise<AttachAckPayload>((resolve, reject) => {
|
|
299
|
+
attachAckResolve = resolve;
|
|
300
|
+
attachAckReject = reject;
|
|
301
|
+
});
|
|
302
|
+
const initialToken = options.getToken ? await options.getToken() : null;
|
|
303
|
+
const attachPayload: AttachPayload = {
|
|
304
|
+
token: initialToken,
|
|
305
|
+
...(options.storeId ? { storeId: options.storeId } : {}),
|
|
306
|
+
...(options.dataDir ? { dataDir: options.dataDir } : {}),
|
|
307
|
+
...(options.syncEnabled != null || options.role != null || options.freshStore != null
|
|
308
|
+
? {
|
|
309
|
+
config: {
|
|
310
|
+
...(options.syncEnabled != null ? { syncEnabled: options.syncEnabled } : {}),
|
|
311
|
+
...(options.role != null ? { role: options.role } : {}),
|
|
312
|
+
...(options.freshStore != null ? { freshStore: options.freshStore } : {}),
|
|
313
|
+
},
|
|
314
|
+
}
|
|
315
|
+
: {}),
|
|
316
|
+
};
|
|
317
|
+
postBridgeMessage(port, codec, "attach", attachPayload);
|
|
318
|
+
try {
|
|
319
|
+
await attachAck;
|
|
320
|
+
} catch (error) {
|
|
321
|
+
// The worker's engine boot failed (ADR-0032 FIX 1): tear down this tab's listener so no port handler
|
|
322
|
+
// leaks, then let the boot error propagate out of `attachSyncClient`.
|
|
323
|
+
port.removeEventListener("message", listener);
|
|
324
|
+
throw error;
|
|
325
|
+
}
|
|
326
|
+
status.isRunning = true;
|
|
327
|
+
|
|
328
|
+
// ─── Live-rows seam (ADR-0032 S2 §4) ─────────────────────────────────────────────────────────────
|
|
329
|
+
const subscribeLiveRows = async <TRow extends Record<string, unknown>>(
|
|
330
|
+
input: SubscribeLiveRowsInput,
|
|
331
|
+
onRows: (rows: TRow[]) => void,
|
|
332
|
+
): Promise<LiveRowsSubscription<TRow>> => {
|
|
333
|
+
const queryId = newId("live");
|
|
334
|
+
const id = newId("sub");
|
|
335
|
+
const materializer = new LiveRowsMaterializer<TRow>(input.pkColumns);
|
|
336
|
+
diffHandlers.set(queryId, (diff) => {
|
|
337
|
+
onRows(materializer.apply(diff));
|
|
338
|
+
});
|
|
339
|
+
let initial: LiveInitialPayload;
|
|
340
|
+
try {
|
|
341
|
+
initial = await new Promise<LiveInitialPayload>((resolve, reject) => {
|
|
342
|
+
initialPending.set(id, { resolve, reject });
|
|
343
|
+
postBridgeMessage(
|
|
344
|
+
port,
|
|
345
|
+
codec,
|
|
346
|
+
"subscribe",
|
|
347
|
+
{
|
|
348
|
+
queryId,
|
|
349
|
+
sql: input.sql,
|
|
350
|
+
params: [...input.params],
|
|
351
|
+
...(input.pkColumns ? { pkColumns: [...input.pkColumns] } : {}),
|
|
352
|
+
...(input.use ? { use: [...input.use] } : {}),
|
|
353
|
+
},
|
|
354
|
+
id,
|
|
355
|
+
);
|
|
356
|
+
});
|
|
357
|
+
} catch (error) {
|
|
358
|
+
// The worker rejected the subscribe (invalid SQL, etc.); the initial-payload waiter rejected via the
|
|
359
|
+
// `rpc-result` route (ADR-0032 FIX 2). Drop the pre-registered diff handler so no orphan survives.
|
|
360
|
+
diffHandlers.delete(queryId);
|
|
361
|
+
throw error;
|
|
362
|
+
}
|
|
363
|
+
const initialRows = materializer.seed(initial.rows as TRow[]);
|
|
364
|
+
return {
|
|
365
|
+
initialRows,
|
|
366
|
+
unsubscribe: () => {
|
|
367
|
+
diffHandlers.delete(queryId);
|
|
368
|
+
postBridgeMessage(port, codec, "unsubscribe", { queryId });
|
|
369
|
+
},
|
|
370
|
+
};
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
// ─── Assembled client ────────────────────────────────────────────────────────────────────────────
|
|
374
|
+
const { drizzle, views } = buildRegistryReadHandles(options.registry);
|
|
375
|
+
const notSupported = (name: string) => (): never => {
|
|
376
|
+
throw new Error(
|
|
377
|
+
`[pgxsinkit] ${name} is not available on a worker-attached client (ADR-0032 S2). Use the live-rows hooks / subscribeLiveRows for reads, the write API for mutations.`,
|
|
378
|
+
);
|
|
379
|
+
};
|
|
380
|
+
|
|
381
|
+
const groupKeyForTable = (table: SyncTableName<TRegistry>): string | undefined => {
|
|
382
|
+
const entry = options.registry[table];
|
|
383
|
+
return entry?.consistencyGroup ?? entry?.shape?.shapeKey;
|
|
384
|
+
};
|
|
385
|
+
|
|
386
|
+
const client: AttachedSyncClient<TRegistry> = {
|
|
387
|
+
drizzle,
|
|
388
|
+
views,
|
|
389
|
+
// The tab has no local PGlite; reads go through the live-rows bridge. Touching `.pglite` is a misuse.
|
|
390
|
+
pglite: new Proxy(
|
|
391
|
+
{},
|
|
392
|
+
{
|
|
393
|
+
get: notSupported("client.pglite"),
|
|
394
|
+
},
|
|
395
|
+
) as never,
|
|
396
|
+
tables: Object.fromEntries(
|
|
397
|
+
Object.keys(options.registry).map((tableKey) => [
|
|
398
|
+
tableKey,
|
|
399
|
+
{
|
|
400
|
+
key: tableKey,
|
|
401
|
+
mode: options.registry[tableKey as SyncTableName<TRegistry>]!.mode,
|
|
402
|
+
create: (input: unknown) => rpc<void>("create", [tableKey, input]),
|
|
403
|
+
update: (entityKey: Record<string, string>, patch: unknown) =>
|
|
404
|
+
rpc<void>("update", [tableKey, entityKey, patch]),
|
|
405
|
+
delete: (entityKey: Record<string, string>) => rpc<void>("delete", [tableKey, entityKey]),
|
|
406
|
+
},
|
|
407
|
+
]),
|
|
408
|
+
) as SyncClient<TRegistry>["tables"],
|
|
409
|
+
ready,
|
|
410
|
+
status,
|
|
411
|
+
start: async () => {
|
|
412
|
+
await ready;
|
|
413
|
+
},
|
|
414
|
+
stop: async () => {
|
|
415
|
+
// Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2).
|
|
416
|
+
status.isRunning = false;
|
|
417
|
+
for (const queryId of diffHandlers.keys()) postBridgeMessage(port, codec, "unsubscribe", { queryId });
|
|
418
|
+
diffHandlers.clear();
|
|
419
|
+
postBridgeMessage(port, codec, "detach", null);
|
|
420
|
+
port.removeEventListener("message", listener);
|
|
421
|
+
port.close?.();
|
|
422
|
+
},
|
|
423
|
+
destroy: notSupported("client.destroy"),
|
|
424
|
+
dropReadCache: notSupported("client.dropReadCache"),
|
|
425
|
+
flush: (table) => rpc<void>("flush", [table]),
|
|
426
|
+
reconcile: (table) => rpc<void>("reconcile", [table]),
|
|
427
|
+
retryFailed: (table) => rpc<void>("retryFailed", [table]),
|
|
428
|
+
recoverSending: (table) => rpc<void>("recoverSending", [table]),
|
|
429
|
+
readMutationDetails: (table) => rpc<MutationDetail[]>("readMutationDetails", [table]),
|
|
430
|
+
// Inspection reads run in the worker (ADR-0032 S2) — the same surface as the in-process client. `pglite`
|
|
431
|
+
// itself stays blocked (below); these route the raw statement over the RPC round-trip instead.
|
|
432
|
+
rawQuery: (sql, params, options) => rpc<Results>("rawQuery", [sql, params, options]),
|
|
433
|
+
rawExec: (sql, options) => rpc<Results[]>("rawExec", [sql, options]),
|
|
434
|
+
mutate: {
|
|
435
|
+
create: (table, input) => rpc<void>("create", [table, input]),
|
|
436
|
+
update: (table, entityKey, patch) => rpc<void>("update", [table, entityKey, patch]),
|
|
437
|
+
delete: (table, entityKey) => rpc<void>("delete", [table, entityKey]),
|
|
438
|
+
batch: (items) => rpc<void>("batch", [items]),
|
|
439
|
+
},
|
|
440
|
+
discardConflict: (table, entityKey) => rpc<void>("discardConflict", [table, entityKey]),
|
|
441
|
+
discardQuarantined: (table, entityKey) => rpc<void>("discardQuarantined", [table, entityKey]),
|
|
442
|
+
diagnostics: (table) => rpc<{ mutation: MutationDiagnostics }>("diagnostics", [table]),
|
|
443
|
+
query: notSupported("client.query"),
|
|
444
|
+
queryRow: notSupported("client.queryRow"),
|
|
445
|
+
queryRaw: notSupported("client.queryRaw"),
|
|
446
|
+
queryRawRow: notSupported("client.queryRawRow"),
|
|
447
|
+
ensureSynced: notSupported("client.ensureSynced"),
|
|
448
|
+
isSynced: notSupported("client.isSynced"),
|
|
449
|
+
desync: notSupported("client.desync"),
|
|
450
|
+
// The worker activates lazy relations inside its `subscribe` handler (via the `use` hint), so the tab's
|
|
451
|
+
// `prepareQuery` is a no-op — the live-rows subscription is already guarded worker-side (ADR-0021).
|
|
452
|
+
prepareQuery: async () => undefined,
|
|
453
|
+
transaction: async ({ mode }: { mode: WriteMode }, run) => {
|
|
454
|
+
// Collect the unit's mutations tab-side (the run callback cannot cross the wire), then RPC the
|
|
455
|
+
// serialized items + mode; the worker replays them into a real `client.transaction` (matching acks).
|
|
456
|
+
const collected: MutationBatchItem<TRegistry>[] = [];
|
|
457
|
+
const txTables = Object.fromEntries(
|
|
458
|
+
Object.keys(options.registry).map((tableKey) => [
|
|
459
|
+
tableKey,
|
|
460
|
+
{
|
|
461
|
+
create: (input: unknown) => {
|
|
462
|
+
collected.push({ table: tableKey, kind: "create", input } as MutationBatchItem<TRegistry>);
|
|
463
|
+
},
|
|
464
|
+
update: (entityKey: Record<string, string>, patch: unknown) => {
|
|
465
|
+
collected.push({ table: tableKey, kind: "update", entityKey, patch } as MutationBatchItem<TRegistry>);
|
|
466
|
+
},
|
|
467
|
+
updateBlind: (entityKey: Record<string, string>, patch: unknown) => {
|
|
468
|
+
// ADR-0022 addendum: the `blind` flag rides the serialized item across the wire; the worker
|
|
469
|
+
// replays it through `client.transaction`'s `updateBlind`, identical to the in-process client.
|
|
470
|
+
collected.push({
|
|
471
|
+
table: tableKey,
|
|
472
|
+
kind: "update",
|
|
473
|
+
entityKey,
|
|
474
|
+
patch,
|
|
475
|
+
blind: true,
|
|
476
|
+
} as MutationBatchItem<TRegistry>);
|
|
477
|
+
},
|
|
478
|
+
delete: (entityKey: Record<string, string>) => {
|
|
479
|
+
collected.push({ table: tableKey, kind: "delete", entityKey } as MutationBatchItem<TRegistry>);
|
|
480
|
+
},
|
|
481
|
+
},
|
|
482
|
+
]),
|
|
483
|
+
) as SyncTransaction<TRegistry>["tables"];
|
|
484
|
+
await run({ tables: txTables });
|
|
485
|
+
if (collected.length === 0) return { acks: [] };
|
|
486
|
+
return rpc<SyncTransactionResult>("transaction", [{ mode, items: collected }]);
|
|
487
|
+
},
|
|
488
|
+
groupReady: async (table) => {
|
|
489
|
+
const groupKey = groupKeyForTable(table);
|
|
490
|
+
if (groupKey == null || readyGroups.has(groupKey)) return;
|
|
491
|
+
await new Promise<void>((resolve) => {
|
|
492
|
+
const waiters = groupWaiters.get(groupKey) ?? [];
|
|
493
|
+
waiters.push(resolve);
|
|
494
|
+
groupWaiters.set(groupKey, waiters);
|
|
495
|
+
});
|
|
496
|
+
},
|
|
497
|
+
subscribeLiveRows,
|
|
498
|
+
notifyAuthChanged: () => {
|
|
499
|
+
void pushToken();
|
|
500
|
+
},
|
|
501
|
+
setOnline: (online: boolean) => {
|
|
502
|
+
postBridgeMessage(port, codec, "set-online", { online });
|
|
503
|
+
},
|
|
504
|
+
};
|
|
505
|
+
|
|
506
|
+
return client;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen
|
|
511
|
+
* against a freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the
|
|
512
|
+
* raw store idle until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the
|
|
513
|
+
* provision (its initdb settled); rejects only if the worker reports the create failed — the caller treats
|
|
514
|
+
* either outcome as best-effort, since attach falls back to a fresh create regardless.
|
|
515
|
+
*/
|
|
516
|
+
export function provisionSyncWorker<TRegistry extends SyncTableRegistry>(
|
|
517
|
+
options: Pick<AttachSyncClientOptions<TRegistry>, "worker" | "port" | "storeId" | "dataDir" | "codec">,
|
|
518
|
+
): Promise<void> {
|
|
519
|
+
const codec = options.codec ?? identityCodec;
|
|
520
|
+
const port = resolvePort(options);
|
|
521
|
+
return new Promise<void>((resolve, reject) => {
|
|
522
|
+
const listener = (message: { data: unknown }) => {
|
|
523
|
+
if (!isBridgeEnvelope(message.data)) return;
|
|
524
|
+
if (message.data.type !== "provision-ack") return;
|
|
525
|
+
port.removeEventListener("message", listener);
|
|
526
|
+
const ack = codec.decode(message.data.payload) as ProvisionAckPayload;
|
|
527
|
+
if (ack.ok) resolve();
|
|
528
|
+
else reject(new Error(ack.error?.message ?? "worker provision failed"));
|
|
529
|
+
};
|
|
530
|
+
port.addEventListener("message", listener);
|
|
531
|
+
port.start?.();
|
|
532
|
+
postBridgeMessage(port, codec, "provision", {
|
|
533
|
+
...(options.storeId ? { storeId: options.storeId } : {}),
|
|
534
|
+
...(options.dataDir ? { dataDir: options.dataDir } : {}),
|
|
535
|
+
});
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** Resolve the transport port from the options: an explicit port, a SharedWorker's `.port`, or a Worker itself. */
|
|
540
|
+
function resolvePort(options: { port?: BridgePort; worker?: WorkerLike }): BridgePort {
|
|
541
|
+
if (options.port) return options.port;
|
|
542
|
+
const worker = options.worker;
|
|
543
|
+
if (!worker) throw new Error("attachSyncClient: provide a `worker` or a `port`.");
|
|
544
|
+
if (worker.port) return worker.port;
|
|
545
|
+
if (worker.postMessage && worker.addEventListener && worker.removeEventListener) {
|
|
546
|
+
return worker as BridgePort;
|
|
547
|
+
}
|
|
548
|
+
throw new Error("attachSyncClient: the provided `worker` is neither a Worker nor a SharedWorker port.");
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/** Rebuild an Error from the bridge's serialized `{message, detail}` shape, carrying `detail` through. */
|
|
552
|
+
function rebuildError(error: RpcResultPayload["error"]): Error {
|
|
553
|
+
const rebuilt = new Error(error?.message ?? "worker rpc failed");
|
|
554
|
+
if (error && "detail" in error && error.detail !== undefined) {
|
|
555
|
+
(rebuilt as Error & { detail?: unknown }).detail = error.detail;
|
|
556
|
+
}
|
|
557
|
+
return rebuilt;
|
|
558
|
+
}
|