@pgxsinkit/server 0.2.7 → 0.5.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.
Files changed (39) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -4
  3. package/dist/circuits/compile.d.ts +66 -0
  4. package/dist/circuits/compile.d.ts.map +1 -0
  5. package/dist/circuits/edge.d.ts +188 -0
  6. package/dist/circuits/edge.d.ts.map +1 -0
  7. package/dist/circuits/engine-client.d.ts +111 -0
  8. package/dist/circuits/engine-client.d.ts.map +1 -0
  9. package/dist/circuits/index.d.ts +7 -0
  10. package/dist/circuits/index.d.ts.map +1 -0
  11. package/dist/circuits/stream-token.d.ts +138 -0
  12. package/dist/circuits/stream-token.d.ts.map +1 -0
  13. package/dist/circuits/subscribe.d.ts +280 -0
  14. package/dist/circuits/subscribe.d.ts.map +1 -0
  15. package/dist/circuits/wire.d.ts +70 -0
  16. package/dist/circuits/wire.d.ts.map +1 -0
  17. package/dist/events/consumer.d.ts +40 -0
  18. package/dist/events/consumer.d.ts.map +1 -1
  19. package/dist/index.d.ts +37 -11
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +837 -286
  22. package/dist/index.js.map +13 -9
  23. package/dist/mutations/plpgsql-apply.d.ts +1 -1
  24. package/package.json +3 -2
  25. package/skills/deploying/SKILL.md +83 -38
  26. package/src/circuits/compile.ts +301 -0
  27. package/src/circuits/edge.ts +411 -0
  28. package/src/circuits/engine-client.ts +195 -0
  29. package/src/circuits/index.ts +6 -0
  30. package/src/circuits/stream-token.ts +224 -0
  31. package/src/circuits/subscribe.ts +832 -0
  32. package/src/circuits/wire.ts +71 -0
  33. package/src/events/consumer.ts +79 -0
  34. package/src/index.ts +137 -31
  35. package/src/mutations/plpgsql-apply.ts +3 -3
  36. package/src/router.ts +2 -2
  37. package/dist/electric-proxy.d.ts +0 -48
  38. package/dist/electric-proxy.d.ts.map +0 -1
  39. package/src/electric-proxy.ts +0 -474
package/dist/index.js CHANGED
@@ -2,248 +2,739 @@
2
2
  // packages/server/src/index.ts
3
3
  import { batchEventPaths, getSyncRegistryStreams as getSyncRegistryStreams4 } from "@pgxsinkit/contracts";
4
4
 
5
- // packages/server/src/electric-proxy.ts
5
+ // packages/server/src/circuits/subscribe.ts
6
6
  import {
7
- buildRowFilterShape,
8
- getOmittedProjectedColumnNames
7
+ readShapeTier as readShapeTier2
9
8
  } from "@pgxsinkit/contracts";
10
9
 
11
- // packages/server/src/cors-origin.ts
12
- function resolveCorsOrigin(request, origins) {
13
- const origin = request.headers.get("origin");
14
- if (!origin) {
15
- return null;
16
- }
17
- return origins.includes("*") || origins.includes(origin) ? origin : null;
10
+ // packages/server/src/circuits/compile.ts
11
+ import { getTableConfig } from "drizzle-orm/pg-core";
12
+ import {
13
+ conjoinPredicates,
14
+ DENY_ALL_PREDICATE,
15
+ isAndPredicate,
16
+ isIsNullPredicate,
17
+ isLeafPredicate,
18
+ readShapeTier
19
+ } from "@pgxsinkit/contracts";
20
+ function resolveEntryByShapeKey(registry, shapeKey) {
21
+ return Object.values(registry).find((entry) => entry?.shape?.shapeKey === shapeKey);
22
+ }
23
+ function resolveShapeTarget(shape) {
24
+ const target = shape.physicalTable ?? shape.tableName;
25
+ if (!target.includes("."))
26
+ return { table: target };
27
+ const [schema] = target.split(".");
28
+ if (schema === "public")
29
+ return { table: target.slice("public.".length) };
30
+ return {
31
+ refusal: `shape "${shape.shapeKey}" reads "${target}", but the engine introspects the public schema ` + `only and names tables bare \u2014 a non-public target has no shape it can be created under.`
32
+ };
18
33
  }
19
-
20
- // packages/server/src/electric-proxy.ts
21
- var perfNow = () => typeof performance !== "undefined" ? performance.now() : Date.now();
22
- var ELECTRIC_EXPOSED_HEADERS = "electric-offset,electric-handle,electric-schema,electric-cursor,electric-up-to-date";
23
- async function proxyElectricShapeRequest(request, claims, options) {
24
- if (options.cors && request.method === "OPTIONS") {
25
- return corsPreflightResponse(request, options.cors);
26
- }
27
- const timing = options.logTimings ? { upstreamMs: 0, upstreamStatus: 0 } : undefined;
28
- const start = timing ? perfNow() : 0;
29
- const response = await forwardShapeRequest(request, claims, options, timing);
30
- const finalResponse = options.cors ? withCorsResponseHeaders(request, response, options.cors) : response;
31
- if (timing) {
32
- logShapeTiming(request, timing, perfNow() - start);
33
- }
34
- return finalResponse;
35
- }
36
- function logShapeTiming(request, timing, totalMs) {
37
- const params = new URL(request.url).searchParams;
38
- console.log("[pgxsinkit-timing]", JSON.stringify({
39
- route: "shape",
40
- table: params.get("table") ?? undefined,
41
- live: params.get("live") === "true",
42
- offset: params.get("offset") ?? undefined,
43
- upstreamMs: Math.round(timing.upstreamMs),
44
- upstreamStatus: timing.upstreamStatus,
45
- totalMs: Math.round(totalMs)
46
- }));
34
+ function emittedColumns(entry) {
35
+ const explicit = entry.shape?.rowFilter?.columns;
36
+ if (explicit != null && explicit.length > 0)
37
+ return [...explicit];
38
+ if (entry.clientProjection?.omitColumns == null)
39
+ return;
40
+ return getTableConfig(entry.localTable).columns.map((column) => column.name);
47
41
  }
48
- async function forwardShapeRequest(request, claims, options, timing) {
49
- const decision = decideProxyTarget(request, claims, options);
50
- if (decision.kind === "reject") {
51
- return new Response(JSON.stringify({ message: decision.message }), {
52
- status: decision.status,
53
- headers: { "content-type": "application/json" }
54
- });
55
- }
56
- const upstreamStart = timing ? perfNow() : 0;
57
- const response = await fetch(decision.targetUrl, {
58
- method: "GET",
59
- signal: request.signal
60
- }).catch((error) => {
61
- if (request.signal.aborted || isAbortError(error)) {
62
- return new Response(null, { status: 499, statusText: "Client Closed Request" });
63
- }
64
- throw error;
65
- });
66
- if (timing) {
67
- timing.upstreamMs = perfNow() - upstreamStart;
68
- timing.upstreamStatus = response.status;
69
- }
70
- const responseHeaders = new Headers(response.headers);
71
- responseHeaders.delete("content-encoding");
72
- responseHeaders.delete("content-length");
73
- const shapeKey = new URL(request.url).searchParams.get("table");
74
- const omittedColumns = shapeKey ? getOmittedProjectedColumnsForTable(options.registry, shapeKey) : [];
75
- const rowTransform = shapeKey ? getRowTransformForTable(options.registry, shapeKey) : undefined;
76
- const contentType = responseHeaders.get("content-type") ?? "";
77
- if ((omittedColumns.length > 0 || rowTransform) && contentType.includes("application/json")) {
78
- const payload = await response.clone().json().catch(() => {
79
- return;
80
- });
81
- if (Array.isArray(payload)) {
82
- const context = { claims, ...options.extraParams ? { params: options.extraParams } : {} };
83
- const rewritten = rewriteShapeLogEntries(payload, omittedColumns, rowTransform, context);
84
- return new Response(JSON.stringify(rewritten), {
85
- status: response.status,
86
- statusText: response.statusText,
87
- headers: responseHeaders
88
- });
42
+ function compileShapeRequest(registry, request) {
43
+ const entry = resolveEntryByShapeKey(registry, request.shapeKey);
44
+ const shape = entry?.shape;
45
+ if (entry == null || shape == null) {
46
+ return { outcome: "deny", reason: `no shape declares shapeKey "${request.shapeKey}"` };
47
+ }
48
+ const target = resolveShapeTarget(shape);
49
+ if ("refusal" in target)
50
+ return { outcome: "deny", reason: target.refusal };
51
+ const tier = readShapeTier(shape);
52
+ const subject = tier === "shared" ? scopePredicate(shape, request.scope) : privatePredicate(shape, request.claims, request.params);
53
+ if ("refusal" in subject)
54
+ return { outcome: "deny", reason: subject.refusal };
55
+ const where = conjoinPredicates(subject.predicate, shape.where);
56
+ const narrowing = assertLocalPrimaryKeyIsPinned(entry, where);
57
+ if (narrowing != null)
58
+ return { outcome: "deny", reason: narrowing };
59
+ const columns = emittedColumns(entry);
60
+ return {
61
+ outcome: "create",
62
+ tier,
63
+ request: {
64
+ table: target.table,
65
+ ...where !== undefined ? { where } : {},
66
+ ...columns !== undefined ? { columns } : {}
89
67
  }
68
+ };
69
+ }
70
+ function scopePredicate(shape, values) {
71
+ const columns = shape.scope ?? [];
72
+ if (values == null) {
73
+ return { refusal: `shape "${shape.shapeKey}" is shared-tier and requires ${columns.length} scope value(s)` };
74
+ }
75
+ if (values.length !== columns.length) {
76
+ return {
77
+ refusal: `shape "${shape.shapeKey}" takes ${columns.length} scope value(s) ` + `(${columns.join(", ")}) but got ${values.length}`
78
+ };
90
79
  }
91
- return new Response(response.body, {
92
- status: response.status,
93
- statusText: response.statusText,
94
- headers: responseHeaders
80
+ const equalities = columns.map((col, index) => {
81
+ const value = values[index];
82
+ return value === null ? { col, isNull: true } : { col, op: "eq", value };
95
83
  });
84
+ return { predicate: conjoinPredicates(...equalities) };
96
85
  }
97
- function decideProxyTarget(request, claims, options) {
98
- const requestedShapeKey = new URL(request.url).searchParams.get("table");
99
- if (!requestedShapeKey) {
100
- return { kind: "reject", status: 400, message: "Shape request must specify a table" };
101
- }
102
- if (!resolveEntryByShapeKey(options.registry, requestedShapeKey)) {
103
- return { kind: "reject", status: 403, message: `Shape is not in the sync registry: ${requestedShapeKey}` };
104
- }
105
- return { kind: "forward", targetUrl: buildProxyTargetUrl(request, claims, options) };
106
- }
107
- var ELECTRIC_CONTROL_QUERY_PARAMS = new Set([
108
- "offset",
109
- "handle",
110
- "live",
111
- "cursor",
112
- "cache-buster",
113
- "expired_handle",
114
- "experimental_live_sse",
115
- "live_sse",
116
- "log"
117
- ]);
118
- function buildProxyTargetUrl(request, claims, options) {
119
- const requestUrl = new URL(request.url);
120
- const targetUrl = new URL(options.electricUrl);
121
- targetUrl.searchParams.delete("where");
122
- targetUrl.searchParams.delete("columns");
123
- const entry = resolveEntryByShapeKey(options.registry, requestUrl.searchParams.get("table") ?? "");
124
- const electricTarget = electricTargetForEntry(entry);
125
- if (!electricTarget) {
126
- return targetUrl.toString();
127
- }
128
- targetUrl.searchParams.set("table", electricTarget);
129
- requestUrl.searchParams.forEach((value, key) => {
130
- if (ELECTRIC_CONTROL_QUERY_PARAMS.has(key)) {
131
- targetUrl.searchParams.set(key, value);
132
- }
133
- });
134
- if (options.bustLiveUpstreamCache !== false && targetUrl.searchParams.get("live") === "true") {
135
- targetUrl.searchParams.set("cache-buster", crypto.randomUUID());
136
- }
137
- const rowFilter = entry?.shape?.rowFilter;
138
- if (!rowFilter) {
139
- return targetUrl.toString();
140
- }
141
- const shape = buildRowFilterShape(rowFilter, claims, options.extraParams);
142
- if (shape) {
143
- targetUrl.searchParams.set("where", shape.where);
144
- shape.params.forEach((param, index) => {
145
- targetUrl.searchParams.set(`params[${index + 1}]`, param);
146
- });
86
+ function pinnedColumns(node, into = new Set) {
87
+ if (node == null)
88
+ return into;
89
+ if (isAndPredicate(node)) {
90
+ for (const child of node.and)
91
+ pinnedColumns(child, into);
92
+ return into;
93
+ }
94
+ if (isIsNullPredicate(node)) {
95
+ into.add(node.col);
96
+ return into;
147
97
  }
148
- if (rowFilter.columns && rowFilter.columns.length > 0) {
149
- targetUrl.searchParams.set("columns", rowFilter.columns.join(","));
98
+ if (isLeafPredicate(node) && node.op === "eq") {
99
+ into.add(node.col);
150
100
  }
151
- return targetUrl.toString();
101
+ return into;
152
102
  }
153
- function electricTargetForEntry(entry) {
154
- const shape = entry?.shape;
155
- if (!shape) {
103
+ function assertLocalPrimaryKeyIsPinned(entry, where) {
104
+ const localKey = entry.clientProjection?.localPrimaryKey?.columns;
105
+ if (localKey == null || localKey.length === 0)
106
+ return null;
107
+ const localKeySet = new Set(localKey);
108
+ const dropped = entry.primaryKey.columns.filter((column) => !localKeySet.has(column));
109
+ if (dropped.length === 0)
156
110
  return null;
111
+ const pinned = pinnedColumns(where);
112
+ const unpinned = dropped.filter((column) => !pinned.has(column));
113
+ if (unpinned.length === 0)
114
+ return null;
115
+ return `shape "${entry.shape.shapeKey}" declares clientProjection.localPrimaryKey ` + `(${localKey.join(", ")}), dropping ${unpinned.join(", ")} from the server primary key ` + `(${entry.primaryKey.columns.join(", ")}) \u2014 but this caller's predicate does not pin ` + `${unpinned.length === 1 ? "that column" : "those columns"} to a single value, so two server rows ` + `could collapse onto one local key. Pin it with a top-level equality in the shape's rowFilter (or ` + `its scope), or widen localPrimaryKey to include it.`;
116
+ }
117
+ function privatePredicate(shape, claims, params) {
118
+ const filter = shape.rowFilter?.customPredicate;
119
+ if (filter == null)
120
+ return { predicate: undefined };
121
+ const resolved = filter(claims ?? {}, params);
122
+ if (resolved === DENY_ALL_PREDICATE) {
123
+ return { refusal: `shape "${shape.shapeKey}" denies this caller` };
124
+ }
125
+ return { predicate: resolved ?? undefined };
126
+ }
127
+ function canonicalJson(value) {
128
+ if (value === null || typeof value !== "object")
129
+ return JSON.stringify(value ?? null);
130
+ if (Array.isArray(value))
131
+ return `[${value.map((member) => canonicalJson(member ?? null)).join(",")}]`;
132
+ const entries = Object.entries(value).filter(([, member]) => member !== undefined).sort(([left], [right]) => left < right ? -1 : 1);
133
+ return `{${entries.map(([key, member]) => `${JSON.stringify(key)}:${canonicalJson(member)}`).join(",")}}`;
134
+ }
135
+ async function fingerprintShapeRequest(request) {
136
+ const canonical = canonicalJson({
137
+ table: request.table,
138
+ where: request.where,
139
+ columns: request.columns,
140
+ changesOnly: request.changesOnly
141
+ });
142
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical));
143
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
144
+ }
145
+
146
+ // packages/server/src/circuits/edge.ts
147
+ import { getTableConfig as getTableConfig2 } from "drizzle-orm/pg-core";
148
+
149
+ // packages/server/src/circuits/stream-token.ts
150
+ var DEFAULT_STREAM_TOKEN_TTL_SECONDS = 300;
151
+ async function importStreamTokenKey(secret) {
152
+ return crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
153
+ "sign",
154
+ "verify"
155
+ ]);
156
+ }
157
+ function base64UrlEncode(bytes) {
158
+ return btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
159
+ }
160
+ function base64UrlDecode(value) {
161
+ const padded = value.replaceAll("-", "+").replaceAll("_", "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
162
+ const binary = atob(padded);
163
+ const bytes = new Uint8Array(new ArrayBuffer(binary.length));
164
+ for (let index = 0;index < binary.length; index += 1)
165
+ bytes[index] = binary.charCodeAt(index);
166
+ return bytes;
167
+ }
168
+ var HEADER = base64UrlEncode(new TextEncoder().encode(JSON.stringify({ alg: "HS256", typ: "JWT" })));
169
+ async function mintStreamToken(key, options) {
170
+ const ttl = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;
171
+ const claims = {
172
+ sub: options.sub,
173
+ grants: options.grants.map((grant) => ({
174
+ path: grant.path,
175
+ shapeKey: grant.shapeKey,
176
+ shapeId: grant.shapeId,
177
+ claim: grant.claim,
178
+ ...grant.scope !== undefined ? { scope: [...grant.scope] } : {},
179
+ ...grant.fp !== undefined ? { fp: grant.fp } : {}
180
+ })),
181
+ iat: options.now,
182
+ exp: options.now + ttl
183
+ };
184
+ const body = base64UrlEncode(new TextEncoder().encode(JSON.stringify(claims)));
185
+ const signingInput = `${HEADER}.${body}`;
186
+ const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(signingInput));
187
+ return `${signingInput}.${base64UrlEncode(new Uint8Array(signature))}`;
188
+ }
189
+ async function verifyStreamToken(key, token, now, options) {
190
+ const parts = token.split(".");
191
+ if (parts.length !== 3)
192
+ return { ok: false, reason: "malformed token" };
193
+ const [header, body, signature] = parts;
194
+ if (header !== HEADER)
195
+ return { ok: false, reason: "unexpected token header" };
196
+ let valid;
197
+ try {
198
+ valid = await crypto.subtle.verify("HMAC", key, base64UrlDecode(signature), new TextEncoder().encode(`${header}.${body}`));
199
+ } catch {
200
+ return { ok: false, reason: "malformed signature" };
201
+ }
202
+ if (!valid)
203
+ return { ok: false, reason: "bad signature" };
204
+ let claims;
205
+ try {
206
+ claims = JSON.parse(new TextDecoder().decode(base64UrlDecode(body)));
207
+ } catch {
208
+ return { ok: false, reason: "malformed payload" };
157
209
  }
158
- return shape.electricTable ?? shape.tableName;
210
+ if (typeof claims.sub !== "string" || !Array.isArray(claims.grants) || typeof claims.exp !== "number") {
211
+ return { ok: false, reason: "malformed payload" };
212
+ }
213
+ if (claims.exp <= now && options?.allowExpired !== true)
214
+ return { ok: false, reason: "expired" };
215
+ return { ok: true, claims };
216
+ }
217
+ function findGrant(claims, path) {
218
+ return claims.grants.find((grant) => grant.path === path);
159
219
  }
160
- function resolveEntryByShapeKey(registry, requestedShapeKey) {
161
- for (const key of Object.keys(registry)) {
162
- const entry = registry[key];
163
- if (entry?.shape?.shapeKey === requestedShapeKey) {
164
- return entry;
220
+
221
+ // packages/server/src/circuits/edge.ts
222
+ class EntitlementsUnavailableError extends Error {
223
+ constructor() {
224
+ super("[pgxsinkit] the entitlement set is unavailable \u2014 it is catching up, degraded or stale; " + "shared-tier subscriptions cannot be decided right now");
225
+ this.name = "EntitlementsUnavailableError";
226
+ }
227
+ }
228
+ async function authorizeStreamRead(options, token, path, now) {
229
+ if (token == null || token === "")
230
+ return { allow: false, reason: "no stream token" };
231
+ const verified = await verifyStreamToken(options.key, token, now);
232
+ if (!verified.ok)
233
+ return { allow: false, reason: verified.reason };
234
+ const grant = findGrant(verified.claims, path);
235
+ if (grant == null)
236
+ return { allow: false, reason: "token grants no such stream" };
237
+ const subject = verified.claims.sub;
238
+ if (grant.scope === undefined)
239
+ return { allow: true, grant, subject };
240
+ const entitlements = options.entitlements;
241
+ if (entitlements === undefined) {
242
+ return { allow: false, reason: "shared-tier grant, but this deployment configured no entitlement set" };
243
+ }
244
+ if (!entitlements.ready)
245
+ return { allow: false, reason: "entitlements unavailable" };
246
+ if (!entitlements.permits(subject, grant.shapeKey, grant.scope)) {
247
+ return { allow: false, reason: "not entitled to this scope" };
248
+ }
249
+ return { allow: true, grant, subject };
250
+ }
251
+ function readStreamToken(request) {
252
+ const header = request.headers.get("authorization");
253
+ if (header == null)
254
+ return null;
255
+ const [scheme, value] = header.split(" ");
256
+ return scheme?.toLowerCase() === "bearer" && value ? value : null;
257
+ }
258
+ var STREAM_READ_EXPOSED_HEADERS = [
259
+ "stream-next-offset",
260
+ "stream-up-to-date",
261
+ "stream-cursor",
262
+ "stream-closed",
263
+ "stream-seq",
264
+ "stream-ttl",
265
+ "stream-expires-at",
266
+ "stream-sse-data-encoding",
267
+ "etag"
268
+ ];
269
+ function rewrittenEgressHeaders(upstream) {
270
+ const headers = new Headers(upstream);
271
+ headers.delete("content-length");
272
+ headers.delete("content-encoding");
273
+ headers.delete("etag");
274
+ headers.set("cache-control", "private, no-store");
275
+ return headers;
276
+ }
277
+ function asksForSse(request) {
278
+ return new URL(request.url).searchParams.get("live") === "sse" || (request.headers.get("accept") ?? "").includes("text/event-stream");
279
+ }
280
+ function createStreamGate(options) {
281
+ const doFetch = options.fetch ?? fetch;
282
+ const base = options.durableStreamsUrl.replace(/\/+$/, "");
283
+ return async function handleStreamRead(request, path, now) {
284
+ const decision = await authorizeStreamRead(options, readStreamToken(request), path, now);
285
+ if (!decision.allow) {
286
+ return new Response(JSON.stringify({ error: decision.reason }), {
287
+ status: 403,
288
+ headers: { "content-type": "application/json" }
289
+ });
165
290
  }
166
- }
167
- return;
291
+ const entry = resolveEntryByShapeKey(options.registry, decision.grant.shapeKey);
292
+ const transform = entry?.serverProjection?.rowTransform;
293
+ if (transform != null && asksForSse(request)) {
294
+ return new Response(JSON.stringify({ error: "this shape is rewritten at egress and is served as JSON long-poll only" }), { status: 406, headers: { "content-type": "application/json" } });
295
+ }
296
+ const upstreamUrl = new URL(`${base}/${path}`);
297
+ upstreamUrl.search = new URL(request.url).search;
298
+ const forwarded = new Headers(request.headers);
299
+ forwarded.delete("authorization");
300
+ forwarded.delete("host");
301
+ const init = { method: request.method, headers: forwarded, signal: request.signal };
302
+ const upstreamFetch = async () => {
303
+ try {
304
+ return await doFetch(upstreamUrl, init);
305
+ } catch (error) {
306
+ if (request.signal.aborted)
307
+ return new Response(null, { status: 499 });
308
+ throw error;
309
+ }
310
+ };
311
+ if (transform == null || entry == null)
312
+ return upstreamFetch();
313
+ const upstream = await upstreamFetch();
314
+ if (upstream.status === 499)
315
+ return upstream;
316
+ const headers = rewrittenEgressHeaders(upstream.headers);
317
+ if (request.method === "HEAD" || upstream.status !== 200 || !(upstream.headers.get("content-type") ?? "").includes("application/json")) {
318
+ return new Response(upstream.body, { status: upstream.status, statusText: upstream.statusText, headers });
319
+ }
320
+ let parsed;
321
+ try {
322
+ parsed = await upstream.json();
323
+ } catch (error) {
324
+ if (request.signal.aborted)
325
+ return new Response(null, { status: 499 });
326
+ throw error;
327
+ }
328
+ const isBatch = Array.isArray(parsed);
329
+ const envelopes = isBatch ? parsed : [parsed];
330
+ const keep = new Set(getTableConfig2(entry.localTable).columns.map((column) => column.name));
331
+ const context = {
332
+ claims: { sub: decision.subject },
333
+ ...options.params ? { params: options.params } : {}
334
+ };
335
+ const rewritten = envelopes.map((envelope) => {
336
+ const value = envelope?.value;
337
+ if (value == null || typeof value !== "object")
338
+ return envelope;
339
+ const transformed = transform(value, context);
340
+ const stripped = {};
341
+ for (const [column, cell] of Object.entries(transformed)) {
342
+ if (keep.has(column))
343
+ stripped[column] = cell;
344
+ }
345
+ return { ...envelope, value: stripped };
346
+ });
347
+ return new Response(JSON.stringify(isBatch ? rewritten : rewritten[0]), {
348
+ status: upstream.status,
349
+ statusText: upstream.statusText,
350
+ headers
351
+ });
352
+ };
168
353
  }
169
- function getOmittedProjectedColumnsForTable(registry, shapeKey) {
170
- const entry = resolveEntryByShapeKey(registry, shapeKey);
171
- return entry ? getOmittedProjectedColumnNames(entry) : [];
354
+
355
+ // packages/server/src/circuits/engine-client.ts
356
+ class CircuitsEngineError extends Error {
357
+ status;
358
+ body;
359
+ constructor(status, body, message) {
360
+ super(message);
361
+ this.name = "CircuitsEngineError";
362
+ this.status = status;
363
+ this.body = body;
364
+ }
365
+ }
366
+ function createCircuitsEngineClient(options) {
367
+ const doFetch = options.fetch ?? fetch;
368
+ const base = options.baseUrl.replace(/\/+$/, "");
369
+ async function call(path, init) {
370
+ const headers = new Headers(init.headers);
371
+ headers.set("content-type", "application/json");
372
+ const response = await doFetch(`${base}${path}`, { ...init, headers });
373
+ const body = await response.text();
374
+ if (!response.ok) {
375
+ throw new CircuitsEngineError(response.status, body, `[pgxsinkit] circuits engine ${init.method ?? "GET"} ${path} \u2192 ${response.status}: ${body}`);
376
+ }
377
+ return body === "" ? undefined : JSON.parse(body);
378
+ }
379
+ return {
380
+ async createShape(request) {
381
+ const body = await call("/shapes", {
382
+ method: "POST",
383
+ body: JSON.stringify(request)
384
+ });
385
+ if (body === null || typeof body !== "object")
386
+ throw unusableCreate("the body", body);
387
+ if (typeof body.shapeId !== "string")
388
+ throw unusableCreate("shapeId", body.shapeId);
389
+ if (typeof body.streamPath !== "string")
390
+ throw unusableCreate("streamPath", body.streamPath);
391
+ if (typeof body.subscription !== "string" || body.subscription === "") {
392
+ throw unusableCreate("subscription", body.subscription);
393
+ }
394
+ if (typeof body.leaseSeconds !== "number")
395
+ throw unusableCreate("leaseSeconds", body.leaseSeconds);
396
+ return body;
397
+ },
398
+ async releaseShape(shapeId, subscription) {
399
+ const query = `?subscription=${encodeURIComponent(subscription)}`;
400
+ await call(`/shapes/${encodeURIComponent(shapeId)}${query}`, { method: "DELETE" });
401
+ },
402
+ async replicationState() {
403
+ const body = await call("/replication/lsn", { method: "GET" });
404
+ if (body === null || typeof body !== "object")
405
+ throw unusableBarrier("the body", body);
406
+ if (body.lsn !== null && typeof body.lsn !== "string")
407
+ throw unusableBarrier("lsn", body.lsn);
408
+ if (typeof body.pendingFlips !== "number")
409
+ throw unusableBarrier("pendingFlips", body.pendingFlips);
410
+ if (typeof body.flipFailures !== "number")
411
+ throw unusableBarrier("flipFailures", body.flipFailures);
412
+ return { lsn: body.lsn, pendingFlips: body.pendingFlips, flipFailures: body.flipFailures };
413
+ }
414
+ };
172
415
  }
173
- function getRowTransformForTable(registry, shapeKey) {
174
- return resolveEntryByShapeKey(registry, shapeKey)?.serverProjection?.rowTransform;
416
+ function unusableBarrier(field, value) {
417
+ return new Error(`[pgxsinkit] the engine's GET /replication/lsn answered with an unusable \`${field}\` (${JSON.stringify(value)}). ` + `This client requires an engine reporting the whole convergence barrier \u2014 \`lsn\`, \`pendingFlips\` and ` + `\`flipFailures\` (ADR-0056 decision 3); the engine at this URL is not the one this client targets.`);
175
418
  }
176
- function isObjectRecord(value) {
177
- return typeof value === "object" && value !== null && !Array.isArray(value);
419
+ function unusableCreate(field, value) {
420
+ return new Error(`[pgxsinkit] the engine's POST /shapes answered with an unusable \`${field}\` (${JSON.stringify(value)}). ` + `This client requires an engine that records every shape claim under a named, leased subscription \u2014 ` + `\`shapeId\`, \`streamPath\`, \`subscription\` and \`leaseSeconds\` (fork ADR-0008); the engine at this ` + `URL is not the one this client targets.`);
178
421
  }
179
- function isShapeLogEntry(value) {
180
- return isObjectRecord(value);
422
+
423
+ // packages/server/src/circuits/subscribe.ts
424
+ class CircuitsLeaseConfigError extends Error {
425
+ leaseSeconds;
426
+ ttlSeconds;
427
+ constructor(leaseSeconds, ttlSeconds) {
428
+ super(`[pgxsinkit] the sync engine's shape lease window (${leaseSeconds}s, ` + `ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS) is shorter than twice this control plane's stream-token TTL ` + `(${ttlSeconds}s, the \`ttlSeconds\` option). Claims are renewed on the token re-mint, so a single ` + `missed refresh would let a live session's subscription lapse and its shape go dormant underneath ` + `it. Raise ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS to at least ${2 * ttlSeconds}, lower \`ttlSeconds\` to ` + `at most ${Math.floor(leaseSeconds / 2)}, or set ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS=0 to disable ` + `leases entirely.`);
429
+ this.name = "CircuitsLeaseConfigError";
430
+ this.leaseSeconds = leaseSeconds;
431
+ this.ttlSeconds = ttlSeconds;
432
+ }
433
+ }
434
+ function assertLeaseCoversTtl(leaseSeconds, ttlSeconds) {
435
+ if (leaseSeconds !== 0 && leaseSeconds < 2 * ttlSeconds)
436
+ throw new CircuitsLeaseConfigError(leaseSeconds, ttlSeconds);
437
+ }
438
+ function assertClaimRecorded(handle, claim) {
439
+ if (handle.subscription === claim)
440
+ return;
441
+ throw new Error(`[pgxsinkit] the engine recorded this shape claim under \`${handle.subscription}\` rather than the ` + `subscription id it was sent (\`${claim}\`). Renewal and release are BY that id (fork ADR-0008), ` + `so an engine that renames a claim is not the one this client targets.`);
442
+ }
443
+ function compileGrant(options, claims, shapeKey, scope) {
444
+ return compileShapeRequest(options.registry, {
445
+ shapeKey,
446
+ claims,
447
+ ...scope !== undefined ? { scope } : {},
448
+ ...options.params ? { params: options.params } : {}
449
+ });
181
450
  }
182
- function rewriteRow(row, omittedColumns, rowTransform, context) {
183
- const transformed = rowTransform ? rowTransform(row, context) : row;
184
- return omittedColumns.length > 0 ? omitColumnsFromRow(transformed, omittedColumns) : transformed;
451
+ async function renewGrantClaim(engine, request, grant, ttlSeconds) {
452
+ let handle;
453
+ try {
454
+ handle = await engine.createShape({ ...request, subscription: grant.claim });
455
+ } catch (error) {
456
+ if (error instanceof CircuitsEngineError && error.status === 409) {
457
+ return { revoked: "subscription id is held by another shape; re-subscribe" };
458
+ }
459
+ throw error;
460
+ }
461
+ assertClaimRecorded(handle, grant.claim);
462
+ if (handle.shapeId !== grant.shapeId || handle.streamPath !== grant.path) {
463
+ await engine.releaseShape(handle.shapeId, grant.claim);
464
+ return { revoked: "shape stream changed; re-subscribe" };
465
+ }
466
+ assertLeaseCoversTtl(handle.leaseSeconds, ttlSeconds);
467
+ return { renewed: true };
185
468
  }
186
- function rewriteShapeLogEntries(payload, omittedColumns, rowTransform, context) {
187
- return payload.map((entry) => {
188
- if (!isShapeLogEntry(entry)) {
189
- return entry;
469
+ function expandToScopes(options, subject, shapeKey) {
470
+ const entry = resolveEntryByShapeKey(options.registry, shapeKey);
471
+ const shape = entry?.shape;
472
+ if (shape == null)
473
+ return { scopes: [undefined] };
474
+ if (readShapeTier2(shape) === "private")
475
+ return { scopes: [undefined] };
476
+ if (options.entitlements === undefined) {
477
+ return { refusal: "shared-tier shape, but this deployment configured no entitlement set" };
478
+ }
479
+ if (!options.entitlements.ready)
480
+ throw new EntitlementsUnavailableError;
481
+ const held = options.entitlements.scopesFor(subject, shapeKey);
482
+ if (held.length === 0)
483
+ return { refusal: "no entitled scopes" };
484
+ return { scopes: held };
485
+ }
486
+ async function subscribeToShapes(options, claims, requests, now) {
487
+ const subject = typeof claims?.sub === "string" ? claims.sub : null;
488
+ const granted = [];
489
+ const denied = [];
490
+ const grants = [];
491
+ const ttlSeconds = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;
492
+ for (const request of requests) {
493
+ const deny = (reason, scope) => denied.push({ shapeKey: request.shapeKey, ...scope !== undefined ? { scope } : {}, reason });
494
+ if (subject === null) {
495
+ deny("no subject");
496
+ continue;
190
497
  }
191
- let currentEntry = entry;
192
- if (isObjectRecord(entry.value)) {
193
- const nextValue = rewriteRow(entry.value, omittedColumns, rowTransform, context);
194
- if (nextValue !== entry.value) {
195
- currentEntry = { ...currentEntry, value: nextValue };
196
- }
498
+ const expanded = expandToScopes(options, subject, request.shapeKey);
499
+ if ("refusal" in expanded) {
500
+ deny(expanded.refusal);
501
+ continue;
197
502
  }
198
- if (isObjectRecord(currentEntry.old_value)) {
199
- const nextOldValue = rewriteRow(currentEntry.old_value, omittedColumns, rowTransform, context);
200
- if (nextOldValue !== currentEntry.old_value) {
201
- currentEntry = { ...currentEntry, old_value: nextOldValue };
503
+ for (const scope of expanded.scopes) {
504
+ const scoped = scope !== undefined ? { scope } : {};
505
+ const compiled = compileGrant(options, claims, request.shapeKey, scope);
506
+ if (compiled.outcome === "deny") {
507
+ deny(compiled.reason, scope);
508
+ continue;
202
509
  }
510
+ if (compiled.tier === "shared" && !options.entitlements?.permits(subject, request.shapeKey, scope ?? [])) {
511
+ deny("not entitled to this scope", scope);
512
+ continue;
513
+ }
514
+ const fp = compiled.tier === "private" ? { fp: await fingerprintShapeRequest(compiled.request) } : {};
515
+ const claim = crypto.randomUUID();
516
+ const handle = await options.engine.createShape({ ...compiled.request, subscription: claim });
517
+ assertClaimRecorded(handle, claim);
518
+ try {
519
+ assertLeaseCoversTtl(handle.leaseSeconds, ttlSeconds);
520
+ } catch (error) {
521
+ await options.engine.releaseShape(handle.shapeId, claim).catch(() => {});
522
+ throw error;
523
+ }
524
+ granted.push({ shapeKey: request.shapeKey, ...scoped, shapeId: handle.shapeId, streamPath: handle.streamPath });
525
+ grants.push({
526
+ path: handle.streamPath,
527
+ shapeKey: request.shapeKey,
528
+ shapeId: handle.shapeId,
529
+ claim,
530
+ ...scoped,
531
+ ...fp
532
+ });
203
533
  }
204
- return currentEntry;
205
- });
206
- }
207
- function isAbortError(error) {
208
- return error instanceof Error && (error.name === "AbortError" || typeof error.code === "number" && error.code === 20);
534
+ }
535
+ if (subject === null || grants.length === 0)
536
+ return { granted, denied };
537
+ const token = await mintStreamToken(options.key, { sub: subject, grants, ttlSeconds, now });
538
+ return { token, expiresAt: now + ttlSeconds, granted, denied };
209
539
  }
210
- function allowedCorsOrigin(request, cors) {
211
- return resolveCorsOrigin(request, cors.origins);
540
+ function createSubscribeHandler(options) {
541
+ return async function handleSubscribe(request) {
542
+ let body;
543
+ try {
544
+ body = await request.json();
545
+ } catch {
546
+ return Response.json({ error: "malformed body" }, { status: 400 });
547
+ }
548
+ if (!Array.isArray(body.subscriptions)) {
549
+ return Response.json({ error: "subscriptions must be an array" }, { status: 400 });
550
+ }
551
+ const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;
552
+ if (typeof claims?.sub !== "string" || claims.sub === "") {
553
+ return Response.json({ error: "unauthenticated" }, { status: 401 });
554
+ }
555
+ let result;
556
+ try {
557
+ result = await subscribeToShapes(options, claims, body.subscriptions, Math.floor(Date.now() / 1000));
558
+ } catch (error) {
559
+ if (error instanceof CircuitsEngineError) {
560
+ return Response.json({ error: "sync engine unavailable" }, { status: 503 });
561
+ }
562
+ if (error instanceof CircuitsLeaseConfigError) {
563
+ return Response.json({ error: "sync engine lease window shorter than the token TTL" }, { status: 503 });
564
+ }
565
+ if (error instanceof EntitlementsUnavailableError) {
566
+ return Response.json({ error: "entitlements unavailable" }, { status: 503 });
567
+ }
568
+ throw error;
569
+ }
570
+ return Response.json(result);
571
+ };
212
572
  }
213
- function corsPreflightResponse(request, cors) {
214
- const headers = new Headers;
215
- const origin = allowedCorsOrigin(request, cors);
216
- if (origin) {
217
- headers.set("Access-Control-Allow-Origin", origin);
218
- headers.append("Vary", "Origin");
573
+ async function refreshStreamToken(options, claims, expiringToken, now) {
574
+ const subject = typeof claims?.sub === "string" ? claims.sub : null;
575
+ const verified = await verifyStreamToken(options.key, expiringToken, now, { allowExpired: true });
576
+ if (!verified.ok || subject === null)
577
+ return { granted: [], revoked: [] };
578
+ if (verified.claims.sub !== subject)
579
+ return { granted: [], revoked: [] };
580
+ const granted = [];
581
+ const revoked = [];
582
+ const ttlSeconds = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;
583
+ for (const grant of verified.claims.grants) {
584
+ const scoped = grant.scope !== undefined ? { scope: grant.scope } : {};
585
+ if (grant.scope === undefined) {
586
+ const compiled = compileGrant(options, claims, grant.shapeKey);
587
+ if (compiled.outcome === "deny") {
588
+ revoked.push({ shapeKey: grant.shapeKey, reason: compiled.reason });
589
+ continue;
590
+ }
591
+ if (grant.fp === undefined) {
592
+ revoked.push({
593
+ shapeKey: grant.shapeKey,
594
+ reason: "private grant carries no fingerprint and cannot be re-authorized"
595
+ });
596
+ continue;
597
+ }
598
+ if (await fingerprintShapeRequest(compiled.request) !== grant.fp) {
599
+ revoked.push({ shapeKey: grant.shapeKey, reason: "shape predicate changed for this subject" });
600
+ continue;
601
+ }
602
+ const renewal = await renewGrantClaim(options.engine, compiled.request, grant, ttlSeconds);
603
+ if ("revoked" in renewal) {
604
+ revoked.push({ shapeKey: grant.shapeKey, reason: renewal.revoked });
605
+ continue;
606
+ }
607
+ granted.push(grant);
608
+ continue;
609
+ }
610
+ if (options.entitlements === undefined) {
611
+ revoked.push({
612
+ shapeKey: grant.shapeKey,
613
+ ...scoped,
614
+ reason: "shared-tier grant, but this deployment configured no entitlement set"
615
+ });
616
+ continue;
617
+ }
618
+ if (!options.entitlements.ready)
619
+ throw new EntitlementsUnavailableError;
620
+ if (!options.entitlements.permits(subject, grant.shapeKey, grant.scope)) {
621
+ revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: "not entitled to this scope" });
622
+ continue;
623
+ }
624
+ const compiled = compileGrant(options, claims, grant.shapeKey, grant.scope);
625
+ if (compiled.outcome === "deny") {
626
+ revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: compiled.reason });
627
+ continue;
628
+ }
629
+ const renewal = await renewGrantClaim(options.engine, compiled.request, grant, ttlSeconds);
630
+ if ("revoked" in renewal) {
631
+ revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: renewal.revoked });
632
+ continue;
633
+ }
634
+ granted.push(grant);
219
635
  }
220
- headers.set("Access-Control-Allow-Methods", "GET,OPTIONS");
221
- headers.set("Access-Control-Allow-Headers", request.headers.get("access-control-request-headers") ?? "authorization,apikey,content-type");
222
- headers.set("Access-Control-Max-Age", "3600");
223
- return new Response(null, { status: 204, headers });
636
+ if (granted.length === 0)
637
+ return { granted, revoked };
638
+ const token = await mintStreamToken(options.key, { sub: subject, grants: granted, ttlSeconds, now });
639
+ return { token, expiresAt: now + ttlSeconds, granted, revoked };
224
640
  }
225
- function withCorsResponseHeaders(request, response, cors) {
226
- const origin = allowedCorsOrigin(request, cors);
227
- if (!origin) {
228
- return response;
229
- }
230
- const headers = new Headers(response.headers);
231
- headers.set("Access-Control-Allow-Origin", origin);
232
- headers.append("Vary", "Origin");
233
- headers.set("Access-Control-Expose-Headers", ELECTRIC_EXPOSED_HEADERS);
234
- return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
641
+ function createRefreshHandler(options) {
642
+ return async function handleRefresh(request) {
643
+ let body;
644
+ try {
645
+ body = await request.json();
646
+ } catch {
647
+ return Response.json({ error: "malformed body" }, { status: 400 });
648
+ }
649
+ if (typeof body.token !== "string") {
650
+ return Response.json({ error: "token must be a string" }, { status: 400 });
651
+ }
652
+ const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;
653
+ if (typeof claims?.sub !== "string" || claims.sub === "") {
654
+ return Response.json({ error: "unauthenticated" }, { status: 401 });
655
+ }
656
+ let result;
657
+ try {
658
+ result = await refreshStreamToken(options, claims, body.token, Math.floor(Date.now() / 1000));
659
+ } catch (error) {
660
+ if (error instanceof EntitlementsUnavailableError) {
661
+ return Response.json({ error: "entitlements unavailable" }, { status: 503 });
662
+ }
663
+ if (error instanceof CircuitsEngineError) {
664
+ return Response.json({ error: "sync engine unavailable" }, { status: 503 });
665
+ }
666
+ if (error instanceof CircuitsLeaseConfigError) {
667
+ return Response.json({ error: "sync engine lease window shorter than the token TTL" }, { status: 503 });
668
+ }
669
+ throw error;
670
+ }
671
+ return Response.json(result);
672
+ };
235
673
  }
236
- function omitColumnsFromRow(row, omittedColumns) {
237
- let changed = false;
238
- const nextRow = { ...row };
239
- for (const column of omittedColumns) {
240
- if (Object.prototype.hasOwnProperty.call(nextRow, column)) {
241
- delete nextRow[column];
242
- changed = true;
674
+ async function releaseStreamGrants(options, claims, token, now) {
675
+ const subject = typeof claims?.sub === "string" && claims.sub !== "" ? claims.sub : null;
676
+ if (subject === null)
677
+ return { refused: "unauthenticated" };
678
+ const verified = await verifyStreamToken(options.key, token, now, { allowExpired: true });
679
+ if (!verified.ok)
680
+ return { refused: verified.reason };
681
+ if (verified.claims.sub !== subject)
682
+ return { refused: "token subject does not match the caller" };
683
+ for (const grant of verified.claims.grants) {
684
+ await options.engine.releaseShape(grant.shapeId, grant.claim);
685
+ }
686
+ return { released: verified.claims.grants.length };
687
+ }
688
+ function createReleaseHandler(options) {
689
+ return async function handleRelease(request) {
690
+ let body;
691
+ try {
692
+ body = await request.json();
693
+ } catch {
694
+ return Response.json({ error: "malformed body" }, { status: 400 });
243
695
  }
244
- }
245
- return changed ? nextRow : row;
696
+ if (typeof body.token !== "string") {
697
+ return Response.json({ error: "token must be a string" }, { status: 400 });
698
+ }
699
+ const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;
700
+ if (typeof claims?.sub !== "string" || claims.sub === "") {
701
+ return Response.json({ error: "unauthenticated" }, { status: 401 });
702
+ }
703
+ let result;
704
+ try {
705
+ result = await releaseStreamGrants(options, claims, body.token, Math.floor(Date.now() / 1000));
706
+ } catch (error) {
707
+ if (error instanceof CircuitsEngineError) {
708
+ return Response.json({ error: "sync engine unavailable" }, { status: 503 });
709
+ }
710
+ throw error;
711
+ }
712
+ if ("refused" in result)
713
+ return Response.json({ error: result.refused }, { status: 403 });
714
+ return Response.json(result);
715
+ };
716
+ }
717
+ var subscribePath = "/sync/v1/subscribe";
718
+ var refreshPath = "/sync/v1/refresh";
719
+ var releasePath = "/sync/v1/release";
720
+ function createBarrierHandler(options) {
721
+ let cached = null;
722
+ const maxAge = options.maxAgeSeconds ?? 0;
723
+ return async function handleBarrier(request) {
724
+ const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;
725
+ if (options.resolveAuthClaims && claims === null) {
726
+ return Response.json({ error: "unauthenticated" }, { status: 401 });
727
+ }
728
+ const now = Date.now() / 1000;
729
+ if (cached && now - cached.at < maxAge)
730
+ return Response.json(cached.body);
731
+ const state = await options.engine.replicationState();
732
+ const body = { pendingFlips: state.pendingFlips, flipFailures: state.flipFailures };
733
+ cached = body.flipFailures > 0 ? null : { at: now, body };
734
+ return Response.json(body);
735
+ };
246
736
  }
737
+ var barrierPath = "/sync/v1/barrier";
247
738
 
248
739
  // packages/server/src/events/pgmq-queue.ts
249
740
  import { sql } from "drizzle-orm";
@@ -490,9 +981,9 @@ function eventIngestRequiresClaims(streams) {
490
981
  function createEventIngestHandler(db, registry, queue, options = {}) {
491
982
  const streams = getSyncRegistryStreams(registry) ?? {};
492
983
  const requiresClaims = eventIngestRequiresClaims(streams);
493
- const perfNow2 = () => typeof performance !== "undefined" ? performance.now() : Date.now();
984
+ const perfNow = () => typeof performance !== "undefined" ? performance.now() : Date.now();
494
985
  const handle = async (request) => {
495
- const started = options.logTimings ? perfNow2() : 0;
986
+ const started = options.logTimings ? perfNow() : 0;
496
987
  let authMs = 0;
497
988
  let enqueueMs = 0;
498
989
  const finish = (response, eventCount) => {
@@ -501,7 +992,7 @@ function createEventIngestHandler(db, registry, queue, options = {}) {
501
992
  route: "events",
502
993
  authMs: Math.round(authMs),
503
994
  enqueueMs: Math.round(enqueueMs),
504
- totalMs: Math.round(perfNow2() - started),
995
+ totalMs: Math.round(perfNow() - started),
505
996
  events: eventCount,
506
997
  status: response.status
507
998
  }));
@@ -531,10 +1022,10 @@ function createEventIngestHandler(db, registry, queue, options = {}) {
531
1022
  return finish(errorResponse(`Invalid batch event request: ${framing.error.message}`, 400), 0);
532
1023
  }
533
1024
  const events = framing.data.events;
534
- const authStart = options.logTimings ? perfNow2() : 0;
1025
+ const authStart = options.logTimings ? perfNow() : 0;
535
1026
  const resolvedClaims = await options.resolveAuthClaims?.(request);
536
1027
  if (options.logTimings)
537
- authMs = perfNow2() - authStart;
1028
+ authMs = perfNow() - authStart;
538
1029
  if (requiresClaims && !isPlainObject(resolvedClaims)) {
539
1030
  return finish(errorResponse("Event streams with claim-stamped identity require validated JWT claims", 401), events.length);
540
1031
  }
@@ -645,7 +1136,7 @@ function createEventIngestHandler(db, registry, queue, options = {}) {
645
1136
  events: streamEvents
646
1137
  }));
647
1138
  if (messages.length > 0) {
648
- const enqueueStart = options.logTimings ? perfNow2() : 0;
1139
+ const enqueueStart = options.logTimings ? perfNow() : 0;
649
1140
  try {
650
1141
  await db.transaction(async (tx) => {
651
1142
  await queue.enqueueBatch(messages, tx);
@@ -657,7 +1148,7 @@ function createEventIngestHandler(db, registry, queue, options = {}) {
657
1148
  }), events.length);
658
1149
  }
659
1150
  if (options.logTimings)
660
- enqueueMs = perfNow2() - enqueueStart;
1151
+ enqueueMs = perfNow() - enqueueStart;
661
1152
  if (options.onEventsEnqueued) {
662
1153
  try {
663
1154
  options.onEventsEnqueued({ streams: [...byStream.keys()] });
@@ -673,7 +1164,7 @@ function createEventIngestHandler(db, registry, queue, options = {}) {
673
1164
 
674
1165
  // packages/server/src/mutations/route.ts
675
1166
  import { and, eq, sql as sql3 } from "drizzle-orm";
676
- import { getTableConfig as getTableConfig2 } from "drizzle-orm/pg-core";
1167
+ import { getTableConfig as getTableConfig4 } from "drizzle-orm/pg-core";
677
1168
  import { getColumns as getColumns2 } from "drizzle-orm/utils";
678
1169
  import { createSchemaFactory } from "drizzle-orm/zod";
679
1170
  import {
@@ -780,7 +1271,7 @@ function asSqlState(value) {
780
1271
 
781
1272
  // packages/server/src/mutations/plpgsql-apply.ts
782
1273
  import { getTableName, sql as sql2 } from "drizzle-orm";
783
- import { getTableConfig } from "drizzle-orm/pg-core";
1274
+ import { getTableConfig as getTableConfig3 } from "drizzle-orm/pg-core";
784
1275
  import { getColumns } from "drizzle-orm/utils";
785
1276
  import {
786
1277
  buildRoleGuardedStatement,
@@ -860,7 +1351,7 @@ function resolveManagedFields(entry) {
860
1351
  }
861
1352
  function buildTableBranch(entry) {
862
1353
  const tableName = getTableName(entry.table);
863
- const { schema } = getTableConfig(entry.table);
1354
+ const { schema } = getTableConfig3(entry.table);
864
1355
  const qualifiedTableName = qualifyIdent(schema, tableName);
865
1356
  const columns = getColumns(entry.table);
866
1357
  const projectedColumns = getProjectedColumns(entry);
@@ -1328,13 +1819,13 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1328
1819
  const resolvedApplyFunctionSchema = resolveApplyFunctionSchema(applyFunctionRenderOptions.functionSchema);
1329
1820
  const applyInvocationOptions = resolvedApplyFunctionSchema ? { functionSchema: resolvedApplyFunctionSchema } : {};
1330
1821
  const expectedFingerprint = expectedApplyFingerprint(registry, applyFunctionRenderOptions);
1331
- const perfNow2 = () => typeof performance !== "undefined" ? performance.now() : Date.now();
1822
+ const perfNow = () => typeof performance !== "undefined" ? performance.now() : Date.now();
1332
1823
  const withTiming = (route, handler) => {
1333
1824
  if (!logTimings) {
1334
1825
  return (request) => handler(request);
1335
1826
  }
1336
1827
  return async (request) => {
1337
- const start = perfNow2();
1828
+ const start = perfNow();
1338
1829
  const timing = {
1339
1830
  handlerStart: start,
1340
1831
  preTxMs: 0,
@@ -1350,7 +1841,7 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1350
1841
  txOpenMs: Math.round(timing.txOpenMs),
1351
1842
  authMs: Math.round(timing.authMs),
1352
1843
  applyMs: Math.round(timing.applyMs),
1353
- totalMs: Math.round(perfNow2() - start),
1844
+ totalMs: Math.round(perfNow() - start),
1354
1845
  mutations: timing.mutations,
1355
1846
  status: response.status
1356
1847
  }));
@@ -1359,12 +1850,12 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1359
1850
  };
1360
1851
  const stampPreTx = (timing) => {
1361
1852
  if (timing)
1362
- timing.preTxMs = perfNow2() - timing.handlerStart;
1363
- return timing ? perfNow2() : 0;
1853
+ timing.preTxMs = perfNow() - timing.handlerStart;
1854
+ return timing ? perfNow() : 0;
1364
1855
  };
1365
1856
  const stampTxOpen = (timing, txCallAt) => {
1366
1857
  if (timing)
1367
- timing.txOpenMs = perfNow2() - txCallAt;
1858
+ timing.txOpenMs = perfNow() - txCallAt;
1368
1859
  };
1369
1860
  const startupReady = () => {
1370
1861
  if (!startupReadyPromise) {
@@ -1502,10 +1993,10 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1502
1993
  const shouldApplyRlsContext = rlsAuthContextRequired;
1503
1994
  let userClaims = {};
1504
1995
  if (shouldApplyRlsContext) {
1505
- const authStart = timing ? perfNow2() : 0;
1996
+ const authStart = timing ? perfNow() : 0;
1506
1997
  const resolvedClaims = await resolveAuthClaims?.(request);
1507
1998
  if (timing)
1508
- timing.authMs = perfNow2() - authStart;
1999
+ timing.authMs = perfNow() - authStart;
1509
2000
  if (!isPlainObject2(resolvedClaims)) {
1510
2001
  await logOperationSafely(db, operationsLogConfig, {
1511
2002
  tableName: null,
@@ -1524,10 +2015,10 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1524
2015
  }
1525
2016
  const batchRequest = sanitizeRestrictedFields(body, registry);
1526
2017
  await tx.execute(sql3`SET CONSTRAINTS ALL DEFERRED`);
1527
- const applyStart = timing ? perfNow2() : 0;
2018
+ const applyStart = timing ? perfNow() : 0;
1528
2019
  const conflicts = await executePlpgsqlBatch(tx, batchRequest, requestPath, false, shouldApplyRlsContext, userClaims, expectedFingerprint, applyInvocationOptions);
1529
2020
  if (timing)
1530
- timing.applyMs = perfNow2() - applyStart;
2021
+ timing.applyMs = perfNow() - applyStart;
1531
2022
  if (shouldApplyRlsContext) {
1532
2023
  await tx.execute(sql3`RESET ROLE`);
1533
2024
  }
@@ -1666,10 +2157,10 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1666
2157
  const shouldApplyRlsContext = rlsAuthContextRequired;
1667
2158
  let userClaims = {};
1668
2159
  if (shouldApplyRlsContext) {
1669
- const authStart = timing ? perfNow2() : 0;
2160
+ const authStart = timing ? perfNow() : 0;
1670
2161
  const resolvedClaims = await resolveAuthClaims?.(request);
1671
2162
  if (timing)
1672
- timing.authMs = perfNow2() - authStart;
2163
+ timing.authMs = perfNow() - authStart;
1673
2164
  if (!isPlainObject2(resolvedClaims)) {
1674
2165
  await logOperationSafely(db, operationsLogConfig, {
1675
2166
  tableName: null,
@@ -1688,10 +2179,10 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1688
2179
  }
1689
2180
  const unitRequest = sanitizeRestrictedFields(body, registry);
1690
2181
  await tx.execute(sql3`SET CONSTRAINTS ALL DEFERRED`);
1691
- const applyStart = timing ? perfNow2() : 0;
2182
+ const applyStart = timing ? perfNow() : 0;
1692
2183
  const conflicts = await executePlpgsqlBatch(tx, unitRequest, requestPath, false, shouldApplyRlsContext, userClaims, expectedFingerprint, applyInvocationOptions);
1693
2184
  if (timing)
1694
- timing.applyMs = perfNow2() - applyStart;
2185
+ timing.applyMs = perfNow() - applyStart;
1695
2186
  if (shouldApplyRlsContext) {
1696
2187
  await tx.execute(sql3`RESET ROLE`);
1697
2188
  }
@@ -1880,7 +2371,7 @@ function getErrorStringProperty(error, key) {
1880
2371
  return typeof value === "string" && value.length > 0 ? value : null;
1881
2372
  }
1882
2373
  function isRlsAuthContextRequired(registry) {
1883
- return Object.values(registry).some((entry) => getTableConfig2(entry.table).policies.length > 0 || (entry.governance?.managedFields ?? []).some((field) => field.strategy === "authClaim"));
2374
+ return Object.values(registry).some((entry) => getTableConfig4(entry.table).policies.length > 0 || (entry.governance?.managedFields ?? []).some((field) => field.strategy === "authClaim"));
1884
2375
  }
1885
2376
 
1886
2377
  class UnauthorizedBatchMutationError extends Error {
@@ -2100,6 +2591,15 @@ async function ensureOperationsLogSchema(db, config) {
2100
2591
  }
2101
2592
  }
2102
2593
 
2594
+ // packages/server/src/cors-origin.ts
2595
+ function resolveCorsOrigin(request, origins) {
2596
+ const origin = request.headers.get("origin");
2597
+ if (!origin) {
2598
+ return null;
2599
+ }
2600
+ return origins.includes("*") || origins.includes(origin) ? origin : null;
2601
+ }
2602
+
2103
2603
  // packages/server/src/router.ts
2104
2604
  class FetchRouter {
2105
2605
  #routes = new Map;
@@ -2274,6 +2774,20 @@ function defineEventConsumer(options) {
2274
2774
  let stopPromise = null;
2275
2775
  let activeDrain = null;
2276
2776
  let drainStats = null;
2777
+ let pollHookFailed = false;
2778
+ const reportPoll = (stream, delivered, fault) => {
2779
+ if (!options.onPoll) {
2780
+ return;
2781
+ }
2782
+ try {
2783
+ options.onPoll({ stream, delivered, empty: delivered === 0, fault, at: now() });
2784
+ } catch (error) {
2785
+ if (!pollHookFailed) {
2786
+ pollHookFailed = true;
2787
+ console.warn("pgxsinkit: the `onPoll` hook threw; the event consumer carries on regardless (this is warned once " + "per runner, not once per poll)", error);
2788
+ }
2789
+ }
2790
+ };
2277
2791
  const reportDeadLetter = (report) => {
2278
2792
  console.warn(`pgxsinkit: dead-lettered an event sub-batch on Event stream "${report.stream}" (receipt ${report.receipt}, ` + `${report.attempts} delivery attempt(s)) \u2014 ${report.reason}. It is in the queue's dead-letter storage; ` + "requeue it deliberately with `requeueDeadLetter` once the cause is fixed.", report.cause);
2279
2793
  if (!options.onDeadLetter) {
@@ -2399,11 +2913,13 @@ function defineEventConsumer(options) {
2399
2913
  let productive = false;
2400
2914
  try {
2401
2915
  const messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });
2916
+ reportPoll(stream, messages.length, false);
2402
2917
  if (messages.length > 0) {
2403
2918
  productive = true;
2404
2919
  await processDelivered(stream, messages, () => stopping);
2405
2920
  }
2406
2921
  } catch (error) {
2922
+ reportPoll(stream, 0, true);
2407
2923
  if (error instanceof MalformedEventQueueMessageError) {
2408
2924
  productive = await deadLetter(stream, error.receipt, 0, `the queue message body is not a valid event queue message: ${error.message}`, error);
2409
2925
  } else {
@@ -2442,7 +2958,9 @@ function defineEventConsumer(options) {
2442
2958
  let messages;
2443
2959
  try {
2444
2960
  messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });
2961
+ reportPoll(stream, messages.length, false);
2445
2962
  } catch (error) {
2963
+ reportPoll(stream, 0, true);
2446
2964
  if (error instanceof MalformedEventQueueMessageError) {
2447
2965
  await deadLetter(stream, error.receipt, 0, `the queue message body is not a valid event queue message: ${error.message}`, error);
2448
2966
  continue;
@@ -2568,10 +3086,9 @@ function createSyncServer(options) {
2568
3086
  }
2569
3087
  operationsLogReady = Promise.resolve();
2570
3088
  }
2571
- const shapeProxyPath = options.shapeProxyPath ?? "/api/shape";
2572
3089
  const corsScopes = [{ prefix: "/api/" }];
2573
- if (options.electricUrl) {
2574
- corsScopes.push({ exact: shapeProxyPath });
3090
+ if (options.readPath) {
3091
+ corsScopes.push({ prefix: "/sync/v1/" });
2575
3092
  }
2576
3093
  router.setCors({
2577
3094
  origins: options.allowedOrigins ?? defaultAllowedOrigins,
@@ -2611,20 +3128,28 @@ function createSyncServer(options) {
2611
3128
  router.post(path, eventHandler);
2612
3129
  }
2613
3130
  }
2614
- if (options.electricUrl) {
2615
- const electricUrl = options.electricUrl;
3131
+ if (options.readPath) {
3132
+ const readPath = options.readPath;
2616
3133
  const resolveAuthClaims = options.resolveAuthClaims;
2617
- const resolveShapeParams = options.resolveShapeParams;
2618
- router.get(shapeProxyPath, async (request) => {
2619
- const claims = resolveAuthClaims ? await resolveAuthClaims(request) : null;
2620
- const extraParams = resolveShapeParams?.(request);
2621
- return proxyElectricShapeRequest(request, claims, {
2622
- registry: options.registry,
2623
- electricUrl,
2624
- ...extraParams ? { extraParams } : {},
2625
- ...options.logTimings ? { logTimings: true } : {}
2626
- });
2627
- });
3134
+ if (resolveAuthClaims === undefined) {
3135
+ throw new Error("[pgxsinkit] createSyncServer: `readPath` was configured without `resolveAuthClaims`. The native " + "read path mints a per-subject stream token, so it cannot serve a deployment that has no way to " + "resolve a subject. Provide `resolveAuthClaims`, or drop `readPath` for a write-only deployment.");
3136
+ }
3137
+ const subscribeOptions = {
3138
+ registry: options.registry,
3139
+ engine: readPath.engine,
3140
+ ...readPath.entitlements ? { entitlements: readPath.entitlements } : {},
3141
+ key: readPath.key,
3142
+ ...readPath.ttlSeconds !== undefined ? { ttlSeconds: readPath.ttlSeconds } : {},
3143
+ resolveAuthClaims
3144
+ };
3145
+ router.post(subscribePath, createSubscribeHandler(subscribeOptions));
3146
+ router.post(refreshPath, createRefreshHandler(subscribeOptions));
3147
+ router.post(releasePath, createReleaseHandler({ engine: readPath.engine, key: readPath.key, resolveAuthClaims }));
3148
+ router.get(barrierPath, createBarrierHandler({
3149
+ engine: readPath.engine,
3150
+ resolveAuthClaims,
3151
+ ...readPath.barrierMaxAgeSeconds !== undefined ? { maxAgeSeconds: readPath.barrierMaxAgeSeconds } : {}
3152
+ }));
2628
3153
  }
2629
3154
  const fetch2 = router.fetch;
2630
3155
  return {
@@ -2701,42 +3226,68 @@ function resolveOperationsLogConfig(options) {
2701
3226
  };
2702
3227
  }
2703
3228
  export {
2704
- resolveEventIdentity,
2705
- renderPgxsinkitUtilitiesMigration,
2706
- renderEventLaneMigration,
2707
- readSqlState,
2708
- proxyElectricShapeRequest,
2709
- operationsLogTable,
2710
- operationsLogRegclassTarget,
2711
- expectedApplyFingerprint,
2712
- eventStreamQueueName,
2713
- eventLaneStreamNames,
2714
- eventLaneDdlFingerprint,
2715
- eventIngestRequiresClaims,
2716
- ensureOperationsLogSchema,
2717
- defineEventConsumer,
2718
- createSyncServer,
2719
- createPgmqEventQueue,
2720
- createMutationHandler,
2721
- createEventIngestHandler,
2722
- computeEventPollWaitMs,
2723
- buildRegistrySchema,
2724
- buildPlpgsqlBatchFunctionDdl,
2725
- batchMutationPaths,
2726
- authoritativeMutationPaths,
2727
- assertEventQueueReceipts,
2728
- PGMQ_DEAD_LETTER_KEY,
2729
- MalformedEventQueueMessageError,
2730
- FetchRouter,
2731
- EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS,
2732
- EVENT_LANE_FINGERPRINT_PREFIX,
2733
- DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,
2734
- DEFAULT_EVENT_POLL_FLOOR_MS,
2735
- DEFAULT_EVENT_POLL_FACTOR,
2736
- DEFAULT_EVENT_POLL_CEILING_MS,
2737
- DEFAULT_EVENT_MAX_ATTEMPTS,
3229
+ CircuitsEngineError,
3230
+ CircuitsLeaseConfigError,
3231
+ DEFAULT_EVENT_CONSUMER_BATCH_SIZE,
2738
3232
  DEFAULT_EVENT_DRAIN_BUDGET_MS,
2739
- DEFAULT_EVENT_CONSUMER_BATCH_SIZE
3233
+ DEFAULT_EVENT_MAX_ATTEMPTS,
3234
+ DEFAULT_EVENT_POLL_CEILING_MS,
3235
+ DEFAULT_EVENT_POLL_FACTOR,
3236
+ DEFAULT_EVENT_POLL_FLOOR_MS,
3237
+ DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,
3238
+ DEFAULT_STREAM_TOKEN_TTL_SECONDS,
3239
+ EVENT_LANE_FINGERPRINT_PREFIX,
3240
+ EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS,
3241
+ EntitlementsUnavailableError,
3242
+ FetchRouter,
3243
+ MalformedEventQueueMessageError,
3244
+ PGMQ_DEAD_LETTER_KEY,
3245
+ STREAM_READ_EXPOSED_HEADERS,
3246
+ assertEventQueueReceipts,
3247
+ authoritativeMutationPaths,
3248
+ authorizeStreamRead,
3249
+ barrierPath,
3250
+ batchMutationPaths,
3251
+ buildPlpgsqlBatchFunctionDdl,
3252
+ buildRegistrySchema,
3253
+ compileShapeRequest,
3254
+ computeEventPollWaitMs,
3255
+ createBarrierHandler,
3256
+ createCircuitsEngineClient,
3257
+ createEventIngestHandler,
3258
+ createMutationHandler,
3259
+ createPgmqEventQueue,
3260
+ createRefreshHandler,
3261
+ createReleaseHandler,
3262
+ createStreamGate,
3263
+ createSubscribeHandler,
3264
+ createSyncServer,
3265
+ defineEventConsumer,
3266
+ ensureOperationsLogSchema,
3267
+ eventIngestRequiresClaims,
3268
+ eventLaneDdlFingerprint,
3269
+ eventLaneStreamNames,
3270
+ eventStreamQueueName,
3271
+ expectedApplyFingerprint,
3272
+ findGrant,
3273
+ fingerprintShapeRequest,
3274
+ importStreamTokenKey,
3275
+ mintStreamToken,
3276
+ operationsLogRegclassTarget,
3277
+ operationsLogTable,
3278
+ readSqlState,
3279
+ readStreamToken,
3280
+ refreshPath,
3281
+ refreshStreamToken,
3282
+ releasePath,
3283
+ releaseStreamGrants,
3284
+ renderEventLaneMigration,
3285
+ renderPgxsinkitUtilitiesMigration,
3286
+ resolveEntryByShapeKey,
3287
+ resolveEventIdentity,
3288
+ subscribePath,
3289
+ subscribeToShapes,
3290
+ verifyStreamToken
2740
3291
  };
2741
3292
 
2742
- //# debugId=5CEE23A5C2F9E5C264756E2164756E21
3293
+ //# debugId=51F8EC2D39BDA31B64756E2164756E21