@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
@@ -0,0 +1,71 @@
1
+ import type { Predicate } from "@pgxsinkit/contracts";
2
+
3
+ /**
4
+ * The engine's shape-creation wire contract (`POST /shapes` → `ShapeResp`), restated here for the
5
+ * same reason {@link Predicate} is: this is the boundary pgxsinkit commits to, and the engine's
6
+ * serde definitions are authoritative for it.
7
+ */
8
+ export interface CreateShapeRequest {
9
+ table: string;
10
+ where?: Predicate;
11
+ /**
12
+ * Output projection. Omitted = the full row; the primary key is always included regardless. The
13
+ * predicate may reference columns outside this set, which is what lets a shape MATCH on a column it
14
+ * does not EMIT — the control column a pre-computed redaction splits on (ADR-0055 decision 5).
15
+ *
16
+ * This is the ENGINE's projection, not the client's. `serverOnlyColumns` are IN it: an egress
17
+ * `serverProjection.rowTransform` must read them, so they are fetched onto the stream on purpose and
18
+ * are stripped from each row at the stream edge after the transform runs (`createStreamGate`). A
19
+ * deployment that puts a cache between the engine and the edge is caching rows that still carry
20
+ * them.
21
+ */
22
+ columns?: string[];
23
+ /** Skip the backfill and stream only future matching changes. Subset queries only. */
24
+ changesOnly?: boolean;
25
+ /**
26
+ * The caller's **subscription id** — the name this claim on the shape is taken under (fork
27
+ * ADR-0008). Any non-empty string up to 128 bytes with no control characters, and never starting
28
+ * with `~` unless it is the `~` id the engine itself returned to you (the engine mints into that
29
+ * namespace, and refuses an unknown `~` id as forged).
30
+ *
31
+ * Optional on the WIRE, because the engine will mint one for a caller that names none. It is not
32
+ * optional for pgxsinkit: every call site here sends one, because an unnamed claim is a claim this
33
+ * control plane cannot renew idempotently — a repeat create would be indistinguishable from a
34
+ * second subscriber. Naming it makes the create a RENEW when repeated, and makes the release
35
+ * (`DELETE /shapes/{id}?subscription=…`) retry-safe.
36
+ */
37
+ subscription?: string;
38
+ }
39
+
40
+ /**
41
+ * The engine's response to a shape CREATE (`POST /shapes` → `ShapeResp`).
42
+ *
43
+ * `subscription` and `leaseSeconds` are present on a create and absent on a bare `GET /shapes/{id}`
44
+ * lookup, which belongs to no subscriber. This client only ever creates, so both are required here
45
+ * and the client refuses a create answer that omits either — see `createShape`.
46
+ */
47
+ export interface CircuitsShapeHandle {
48
+ shapeId: string;
49
+ table: string;
50
+ /** Stream path on the durable-streams server, e.g. `shape/s1`. */
51
+ streamPath: string;
52
+ /** Absolute URL of that stream, as the engine resolves its durable-streams base. */
53
+ streamUrl: string;
54
+ /**
55
+ * The subscription this create was recorded under — echoed back, so a caller that named its own id
56
+ * can confirm it and a caller that named none learns the one the engine minted.
57
+ */
58
+ subscription: string;
59
+ /**
60
+ * How long this subscription may go unrenewed before the engine releases it
61
+ * (`ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS`, default 1800). `0` means leases never lapse, because that
62
+ * setting also disables dormancy.
63
+ *
64
+ * Reported rather than guessed: the renewal cadence is the deployment's to set, and a control plane
65
+ * that renews on a schedule the engine does not accept is a control plane whose live sessions lapse
66
+ * (see `CircuitsLeaseConfigError`).
67
+ */
68
+ leaseSeconds: number;
69
+ /** Retention lifecycle; absent on a freshly created shape, which is always active. */
70
+ state?: "active" | "deactivating" | "dormant" | "reactivating";
71
+ }
@@ -22,6 +22,11 @@ import {
22
22
  * shutdown. Construction stays query-free — the FIRST statement this runner sends is the first poll inside
23
23
  * `start()`.
24
24
  *
25
+ * Because the app owns the process, it also owns the health endpoint — so the runner reports the one thing
26
+ * that endpoint cannot see from outside: {@link DefineEventConsumerOptions.onPoll} fires after EVERY read,
27
+ * productive or empty, in both pacing modes. Beat a liveness probe from that, never from `callback`, which
28
+ * by design says nothing at all while the queue is idle.
29
+ *
25
30
  * One runner hosts many Event streams: each gets its own independent loop (a poison event or slow callback in
26
31
  * one stream must never head-of-line-block another), so small deployments run one process and large ones split
27
32
  * `streams` across processes.
@@ -153,6 +158,31 @@ export interface EventDeadLetterReport {
153
158
  cause?: unknown;
154
159
  }
155
160
 
161
+ /**
162
+ * What {@link DefineEventConsumerOptions.onPoll} is told after each read — the host's liveness heartbeat.
163
+ *
164
+ * One report per read the runner performs, productive or not, in BOTH pacing modes. `delivered` counts the
165
+ * sub-batches that read returned (the queue's unit: one message, one callback invocation), and `empty` is
166
+ * exactly `delivered === 0` — including on a faulted read, which is why `fault` is a separate flag rather
167
+ * than something to infer from the counts.
168
+ */
169
+ export interface EventPollReport {
170
+ /** The Event stream that was read. Each stream has its own loop, so each beats on its own cadence. */
171
+ readonly stream: string;
172
+ /** Sub-batches this read returned. `0` on an empty or faulted read. */
173
+ readonly delivered: number;
174
+ /** `delivered === 0` — nothing came back from this read. */
175
+ readonly empty: boolean;
176
+ /**
177
+ * The read itself FAILED: a queue/database fault, or a message body that could not be parsed (which fails
178
+ * the whole read). The runner backs off and carries on either way — a fault never ends a loop — so a host
179
+ * watching the heartbeat still sees it turning, and this is what tells it the queue is unhealthy.
180
+ */
181
+ readonly fault: boolean;
182
+ /** When the read settled, from the runner's own clock (`Date.now` unless one is injected). */
183
+ readonly at: number;
184
+ }
185
+
156
186
  /**
157
187
  * The deterministic seam the runner waits on. `signal` is aborted by `stop()`, so a stopping runner never
158
188
  * lingers for a full idle ceiling. Injected only by tests; production uses an abortable `setTimeout`.
@@ -233,6 +263,17 @@ export interface DefineEventConsumerOptions<TRegistry extends SyncTableRegistry>
233
263
  * the ADR's requirement and a hook that swallows (or throws) must not be able to make a dead letter silent.
234
264
  */
235
265
  onDeadLetter?: (report: EventDeadLetterReport) => void;
266
+ /**
267
+ * Notified after EVERY read the runner performs — productive or empty, in both pacing modes — which makes it
268
+ * the host's **liveness heartbeat**. The {@link DefineEventConsumerOptions.callback} fires only on delivered
269
+ * batches, so on an idle queue it goes quiet and a liveness/readiness probe answering from it would report a
270
+ * healthy runner as dead; beat from this instead and treat `fault` as the queue-health signal.
271
+ *
272
+ * It fires on the READ, before the batch is delivered, so a slow callback cannot delay the heartbeat. A hook
273
+ * that THROWS can never take a loop down: the throw is caught, warn-logged ONCE per runner (a hook that
274
+ * throws every poll must not drown the log), and the loop carries on.
275
+ */
276
+ onPoll?: (report: EventPollReport) => void;
236
277
  /** @internal The injectable wait — the deterministic seam the pacing tests drive. Defaults to `setTimeout`. */
237
278
  sleep?: EventConsumerSleep;
238
279
  /** @internal The injectable clock `drainOnce` measures its budget against. Defaults to `Date.now`. */
@@ -408,6 +449,34 @@ export function defineEventConsumer<TRegistry extends SyncTableRegistry>(
408
449
  */
409
450
  let drainStats: { delivered: number; deadLettered: number } | null = null;
410
451
 
452
+ // ─── The per-read heartbeat ──────────────────────────────────────────────────────────────────────────
453
+ /** Latched once the `onPoll` hook has thrown: the warn is per RUNNER, not per poll (see the option's doc). */
454
+ let pollHookFailed = false;
455
+ /**
456
+ * Beat once for one completed read. Called from BOTH pacing modes and from the fault paths, so a host
457
+ * watching this sees every turn of every loop; `empty` is derived here so the two modes cannot disagree
458
+ * about what an empty read is.
459
+ */
460
+ const reportPoll = (stream: string, delivered: number, fault: boolean): void => {
461
+ if (!options.onPoll) {
462
+ return;
463
+ }
464
+ try {
465
+ options.onPoll({ stream, delivered, empty: delivered === 0, fault, at: now() });
466
+ } catch (error) {
467
+ // A liveness hook that throws must never be able to stop the loop it is observing — that would turn a
468
+ // reporting bug into an outage. Loud once, then silent: it typically throws on EVERY poll.
469
+ if (!pollHookFailed) {
470
+ pollHookFailed = true;
471
+ console.warn(
472
+ "pgxsinkit: the `onPoll` hook threw; the event consumer carries on regardless (this is warned once " +
473
+ "per runner, not once per poll)",
474
+ error,
475
+ );
476
+ }
477
+ }
478
+ };
479
+
411
480
  // ─── Dead-lettering (ADR-0053 decision 7: the loudness lives HERE) ───────────────────────────────────
412
481
  const reportDeadLetter = (report: EventDeadLetterReport): void => {
413
482
  // Unconditional, and deliberately not the client report surface's "warn only when nobody subscribed"
@@ -644,11 +713,17 @@ export function defineEventConsumer<TRegistry extends SyncTableRegistry>(
644
713
  let productive = false;
645
714
  try {
646
715
  const messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });
716
+ // Beat on the READ, before delivery, so a slow callback cannot delay the heartbeat. `processDelivered`
717
+ // never throws, so this iteration can produce exactly one report: this one, or the fault one below.
718
+ reportPoll(stream, messages.length, false);
647
719
  if (messages.length > 0) {
648
720
  productive = true;
649
721
  await processDelivered(stream, messages, () => stopping);
650
722
  }
651
723
  } catch (error) {
724
+ // The read did not complete. An unparseable body fails the WHOLE read exactly as a queue fault does,
725
+ // so both beat the same way: nothing delivered, `fault: true`, and the loop carries on.
726
+ reportPoll(stream, 0, true);
652
727
  if (error instanceof MalformedEventQueueMessageError) {
653
728
  // The endpoint is the only writer of these queues and it writes contract-shaped bodies, so this is a
654
729
  // hand-inserted or corrupted message. It fails the WHOLE read, so it must go on sight or it wedges
@@ -716,7 +791,11 @@ export function defineEventConsumer<TRegistry extends SyncTableRegistry>(
716
791
  let messages: readonly DeliveredEventMessage[];
717
792
  try {
718
793
  messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });
794
+ // The heartbeat covers this pacing mode too — a scheduled drain is exactly the deployment whose
795
+ // host most wants to know a pass actually reached the queue.
796
+ reportPoll(stream, messages.length, false);
719
797
  } catch (error) {
798
+ reportPoll(stream, 0, true);
720
799
  if (error instanceof MalformedEventQueueMessageError) {
721
800
  // Same policy as the loop: it fails the WHOLE read, so it goes on sight and the stream stays
722
801
  // pending for the re-read that fetches the rest of the batch.
package/src/index.ts CHANGED
@@ -10,7 +10,18 @@ import type {
10
10
  } from "@pgxsinkit/contracts";
11
11
  import { batchEventPaths, getSyncRegistryStreams } from "@pgxsinkit/contracts";
12
12
 
13
- import { proxyElectricShapeRequest } from "./electric-proxy";
13
+ import type { EntitlementSet } from "./circuits/edge";
14
+ import type { CircuitsEngineClient } from "./circuits/engine-client";
15
+ import {
16
+ barrierPath,
17
+ createBarrierHandler,
18
+ createRefreshHandler,
19
+ createReleaseHandler,
20
+ createSubscribeHandler,
21
+ refreshPath,
22
+ releasePath,
23
+ subscribePath,
24
+ } from "./circuits/subscribe";
14
25
  import { createPgmqEventQueue } from "./events/pgmq-queue";
15
26
  import type { EventQueue } from "./events/queue";
16
27
  import { createEventIngestHandler, type EventGate, type EventsEnqueuedHook } from "./events/route";
@@ -77,15 +88,30 @@ export interface CreateSyncServerOptions<
77
88
  db: TDb;
78
89
  resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;
79
90
  /**
80
- * When set, the server serves a read-path Electric shape proxy that shares the
81
- * single `resolveAuthClaims` adapter with the write path (ADR-0003). Without it,
82
- * no shape proxy is registered.
91
+ * When set, the server serves the NATIVE read path's control plane (ADR-0055): subscribe, stream-token
92
+ * re-mint, and the engine convergence barrier. Without it, none of those routes is registered and the
93
+ * deployment is write-only.
94
+ *
95
+ * They share the single `resolveAuthClaims` adapter with the write path (ADR-0003), so read and write
96
+ * authorization cannot diverge.
83
97
  */
84
- electricUrl?: string;
85
- /** Path for the shape proxy route. Defaults to `/api/shape`. */
86
- shapeProxyPath?: string;
87
- /** Optional per-request extra params passed to customWhere/shared filters. */
88
- resolveShapeParams?: (request: Request) => Record<string, unknown> | undefined;
98
+ readPath?: {
99
+ /** The Circuits engine's control API — never client-reachable; only this process calls it. */
100
+ engine: CircuitsEngineClient;
101
+ /**
102
+ * The live entitlement set backing the shared tier. Omit when the registry declares no shared
103
+ * shape — a shared subscription is then refused with that reason rather than silently allowed.
104
+ */
105
+ entitlements?: EntitlementSet;
106
+ /** The stream-token signing key, shared with the edge. */
107
+ key: CryptoKey;
108
+ /** Per-deployment override of ADR-0055's 5-minute token lifetime. */
109
+ ttlSeconds?: number;
110
+ /** How long the barrier answer may be cached. Default 0 — see `createBarrierHandler`. */
111
+ barrierMaxAgeSeconds?: number;
112
+ /** Optional per-request extra params passed to the private tier's row filters. */
113
+ resolveShapeParams?: (request: Request) => Record<string, unknown> | undefined;
114
+ };
89
115
  operationsLog?: {
90
116
  enabled?: boolean;
91
117
  };
@@ -219,12 +245,10 @@ export function createSyncServer<
219
245
  operationsLogReady = Promise.resolve();
220
246
  }
221
247
 
222
- const shapeProxyPath = options.shapeProxyPath ?? "/api/shape";
223
-
224
- // CORS covers the canonical /api/* routes and the shape proxy path when it is relocated outside /api/.
248
+ // CORS covers the canonical /api/* routes, plus the native control plane's own /sync/v1/* prefix.
225
249
  const corsScopes: CorsScope[] = [{ prefix: "/api/" }];
226
- if (options.electricUrl) {
227
- corsScopes.push({ exact: shapeProxyPath });
250
+ if (options.readPath) {
251
+ corsScopes.push({ prefix: "/sync/v1/" });
228
252
  }
229
253
  router.setCors(
230
254
  {
@@ -291,22 +315,53 @@ export function createSyncServer<
291
315
  }
292
316
  }
293
317
 
294
- // The read-path shape proxy shares the same resolveAuthClaims adapter, so read and
295
- // write authorization can never diverge (ADR-0003).
296
- if (options.electricUrl) {
297
- const electricUrl = options.electricUrl;
318
+ // The native control plane (ADR-0055). It shares the same resolveAuthClaims adapter as the write
319
+ // path, so read and write authorization can never diverge (ADR-0003).
320
+ //
321
+ // Note what is NOT here: any route that serves shape DATA. Reads terminate on durable-streams
322
+ // through the edge, which is the whole point of the topology — this process is asked once, at
323
+ // subscribe time, and is then out of the read path entirely.
324
+ if (options.readPath) {
325
+ const readPath = options.readPath;
298
326
  const resolveAuthClaims = options.resolveAuthClaims;
299
- const resolveShapeParams = options.resolveShapeParams;
300
- router.get(shapeProxyPath, async (request) => {
301
- const claims = resolveAuthClaims ? await resolveAuthClaims(request) : null;
302
- const extraParams = resolveShapeParams?.(request);
303
- return proxyElectricShapeRequest(request, claims, {
304
- registry: options.registry,
305
- electricUrl,
306
- ...(extraParams ? { extraParams } : {}),
307
- ...(options.logTimings ? { logTimings: true } : {}),
308
- });
309
- });
327
+ // Refused at construction, not at the first subscribe. Every read is bound to a subject in both
328
+ // tiers (ADR-0055): the private tier fuses it into the predicate and the shared tier checks it
329
+ // against the entitlement set, and a stream token with no subject would name a bearer no
330
+ // revocation could ever reach. So a read path with no way to resolve a subject cannot grant
331
+ // anything — it is a contradiction, and the only useful moment to say so is now, rather than as
332
+ // a 401 every client then sits in.
333
+ if (resolveAuthClaims === undefined) {
334
+ throw new Error(
335
+ "[pgxsinkit] createSyncServer: `readPath` was configured without `resolveAuthClaims`. The native " +
336
+ "read path mints a per-subject stream token, so it cannot serve a deployment that has no way to " +
337
+ "resolve a subject. Provide `resolveAuthClaims`, or drop `readPath` for a write-only deployment.",
338
+ );
339
+ }
340
+ const subscribeOptions = {
341
+ registry: options.registry,
342
+ engine: readPath.engine,
343
+ ...(readPath.entitlements ? { entitlements: readPath.entitlements } : {}),
344
+ key: readPath.key,
345
+ ...(readPath.ttlSeconds !== undefined ? { ttlSeconds: readPath.ttlSeconds } : {}),
346
+ resolveAuthClaims,
347
+ };
348
+
349
+ router.post(subscribePath, createSubscribeHandler(subscribeOptions));
350
+ router.post(refreshPath, createRefreshHandler(subscribeOptions));
351
+ // The close half of subscribe. Every grant subscribe handed out is a named claim on an engine
352
+ // shape, and a live claim blocks dormancy and eviction — so without this route every shape waits
353
+ // out its full lease window before it can be reclaimed. The release is idempotent (each grant
354
+ // names its own claim), and a release that never arrives is reclaimed by the lease anyway; see
355
+ // `releaseStreamGrants`.
356
+ router.post(releasePath, createReleaseHandler({ engine: readPath.engine, key: readPath.key, resolveAuthClaims }));
357
+ router.get(
358
+ barrierPath,
359
+ createBarrierHandler({
360
+ engine: readPath.engine,
361
+ resolveAuthClaims,
362
+ ...(readPath.barrierMaxAgeSeconds !== undefined ? { maxAgeSeconds: readPath.barrierMaxAgeSeconds } : {}),
363
+ }),
364
+ );
310
365
  }
311
366
 
312
367
  const fetch = router.fetch;
@@ -410,8 +465,6 @@ export type { ApplyFunctionRenderOptions } from "./mutations/plpgsql-apply";
410
465
  export { renderPgxsinkitUtilitiesMigration } from "./migrations/utilities";
411
466
  export { ensureOperationsLogSchema, operationsLogRegclassTarget } from "./operations-log/ddl";
412
467
  export { operationsLogTable } from "./operations-log/schema";
413
- export { proxyElectricShapeRequest } from "./electric-proxy";
414
- export type { ElectricProxyOptions } from "./electric-proxy";
415
468
  export { readSqlState } from "./sql-state";
416
469
  export {
417
470
  createEventIngestHandler,
@@ -459,6 +512,7 @@ export type {
459
512
  EventDeadLetterReport,
460
513
  EventDrainOptions,
461
514
  EventDrainSummary,
515
+ EventPollReport,
462
516
  } from "./events/consumer";
463
517
  export {
464
518
  EVENT_LANE_FINGERPRINT_PREFIX,
@@ -468,3 +522,55 @@ export {
468
522
  } from "./events/ddl";
469
523
  export { resolveEventIdentity } from "./events/identity";
470
524
  export type { IdentityResolution } from "./events/identity";
525
+
526
+ // The Circuits-native read path (ADR-0055) — shape lifecycle only. Reads terminate on
527
+ // durable-streams and never traverse the engine.
528
+ export { compileShapeRequest, fingerprintShapeRequest, resolveEntryByShapeKey } from "./circuits/compile";
529
+ export type { CompiledShapeRequest, ShapeRequest } from "./circuits/compile";
530
+ export { CircuitsEngineError, createCircuitsEngineClient } from "./circuits/engine-client";
531
+ export type { CircuitsEngineClient, CircuitsEngineOptions } from "./circuits/engine-client";
532
+ export type { CircuitsShapeHandle, CreateShapeRequest } from "./circuits/wire";
533
+ export {
534
+ DEFAULT_STREAM_TOKEN_TTL_SECONDS,
535
+ findGrant,
536
+ importStreamTokenKey,
537
+ mintStreamToken,
538
+ verifyStreamToken,
539
+ } from "./circuits/stream-token";
540
+ export type {
541
+ MintStreamTokenOptions,
542
+ VerifyStreamTokenOptions,
543
+ StreamGrant,
544
+ StreamTokenClaims,
545
+ StreamTokenVerification,
546
+ } from "./circuits/stream-token";
547
+ export {
548
+ authorizeStreamRead,
549
+ createStreamGate,
550
+ EntitlementsUnavailableError,
551
+ readStreamToken,
552
+ STREAM_READ_EXPOSED_HEADERS,
553
+ } from "./circuits/edge";
554
+ export type { EntitlementSet, GateDecision, StreamAuthorizationOptions, StreamGateOptions } from "./circuits/edge";
555
+ export {
556
+ barrierPath,
557
+ CircuitsLeaseConfigError,
558
+ createBarrierHandler,
559
+ createRefreshHandler,
560
+ createReleaseHandler,
561
+ createSubscribeHandler,
562
+ refreshPath,
563
+ refreshStreamToken,
564
+ releasePath,
565
+ releaseStreamGrants,
566
+ subscribePath,
567
+ subscribeToShapes,
568
+ } from "./circuits/subscribe";
569
+ export type {
570
+ DeniedSubscription,
571
+ GrantedSubscription,
572
+ RefreshResult,
573
+ SubscribeOptions,
574
+ SubscribeResult,
575
+ SubscriptionRequest,
576
+ } from "./circuits/subscribe";
@@ -554,7 +554,7 @@ function resolveGrantExecuteRoles(grantExecuteTo: readonly string[] | undefined)
554
554
  * - **A default (NULL) `proacl` explodes to nothing.** That is why the unconditional
555
555
  * `REVOKE ALL … FROM PUBLIC` is emitted FIRST: revoking materializes the previously-implicit ACL
556
556
  * (`NULL` → `{owner=X/owner}`), so by the time this block runs the catalog states the truth. Pinned by
557
- * the PGlite unit lane, and by the integration lane against a real cluster.
557
+ * the pgwasm unit lane, and by the integration lane against a real cluster.
558
558
  * - **Grantee `0` is PUBLIC**, which has no role name (`pg_get_userbyid(0)` returns a placeholder
559
559
  * string), so it is revoked by the `FROM PUBLIC` spelling rather than by name.
560
560
  *
@@ -610,7 +610,7 @@ $$;`;
610
610
  * `anon`/`authenticated`/`service_role` trio via default privileges; because the artifact begins with
611
611
  * `DROP FUNCTION`, EVERY install recreates that exposure. So the revokes are emitted unconditionally
612
612
  * (convergence must not depend on install history), the Supabase-trio ones through the shared
613
- * role-existence guard so the artifact stays portable to PGlite and plain-Postgres lanes.
613
+ * role-existence guard so the artifact stays portable to pgwasm and plain-Postgres lanes.
614
614
  *
615
615
  * Those named revokes are the READABLE fast path — a reviewer sees the two known exposures closed in
616
616
  * plain SQL. The guarantee is {@link buildApplyFunctionAclConvergerSql}, which then revokes EVERY
@@ -850,7 +850,7 @@ ${aclSql}
850
850
  * (ADR-0018). It is a hash of the exact generated DDL body, so it shifts on any registry-shape
851
851
  * change AND on any change to how the applier emits SQL (e.g. a @pgxsinkit/server upgrade) — the
852
852
  * two drift classes a bare signature check cannot see. It does NOT depend on TS-side row-filter /
853
- * customWhere logic, which never enters the apply function (that shapes the read proxy, not writes).
853
+ * customPredicate logic, which never enters the apply function (that shapes reads, not writes).
854
854
  */
855
855
  export function expectedApplyFingerprint(
856
856
  registry: SyncTableRegistry,
package/src/router.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  // A tiny web-standard `fetch` router for the pgxsinkit server (ADR-0017). The server needs only
2
2
  // exact-path GET/POST routing, a small CORS layer, and an error boundary, so a focused router keeps
3
3
  // `@pgxsinkit/server` dependency-light and runnable on any `fetch` runtime — no web framework required.
4
- // `proxyElectricShapeRequest` and the mutation handler are plain `(Request) => Response` functions, so
5
- // they can equally be mounted in someone else's framework.
4
+ // The mutation handler, the control-plane routes, and the stream edge are all plain
5
+ // `(Request) => Response` functions, so they can equally be mounted in someone else's framework.
6
6
 
7
7
  import { resolveCorsOrigin } from "./cors-origin";
8
8
 
@@ -1,48 +0,0 @@
1
- import { type JwtClaims, type SyncTableRegistry } from "@pgxsinkit/contracts";
2
- export interface ElectricProxyCors {
3
- /**
4
- * Browser origins allowed to read this shape: exact strings (e.g. a hosted SPA + localhost dev),
5
- * or a `"*"` entry to allow every origin by reflection (see {@link resolveCorsOrigin}).
6
- */
7
- origins: string[];
8
- }
9
- export interface ElectricProxyOptions {
10
- registry: SyncTableRegistry;
11
- electricUrl: string;
12
- /** Extra params passed to customWhere functions (e.g. fromLang, toLang). */
13
- extraParams?: Record<string, unknown>;
14
- /**
15
- * CORS for a browser-facing deployment with **no CORS-adding gateway in front** — e.g. a Supabase
16
- * Cloud edge function, which the platform routes to directly. When set, OPTIONS preflights are
17
- * answered here and the response carries the allowed origin plus the Electric headers the client
18
- * must read off each shape. Omit it where a gateway already handles CORS (the local stack's Envoy).
19
- */
20
- cors?: ElectricProxyCors;
21
- /**
22
- * Opt-in per-request timing log (default off). When on, each forwarded shape request emits one compact
23
- * `[pgxsinkit-timing]` line (route `"shape"`) with the request's table/live/offset and the upstream
24
- * Electric fetch duration + status, for attributing read-path latency. Off by default — a pure
25
- * diagnostic surface that adds no standing query or latency when unset.
26
- */
27
- logTimings?: boolean;
28
- /**
29
- * Append a unique `cache-buster` to every `live=true` request forwarded upstream (default ON; set
30
- * `false` to restore upstream CDN collapse of live long-polls). Stopgap for Electric Cloud serving
31
- * live long-polls from a layer blind to fresh commits: consecutive full-hold (~41s) `up-to-date`
32
- * responses at an unmoved offset despite an advancing `cursor`, measured cross-client propagation
33
- * of 40–89s (backlog 0001, 2026-07-04; upstream report alongside it). Only the live tail is busted —
34
- * catch-up responses keep their CDN cold-fanout sharing, and per-user-filtered live polls share
35
- * ~nothing across clients anyway. Remove when Electric fixes the live path (backlog 0001's close).
36
- */
37
- bustLiveUpstreamCache?: boolean;
38
- }
39
- /**
40
- * Proxies an Electric shape request, applying registry-driven row filters and stripping omitted
41
- * columns from JSON shape-log payloads. Optionally answers CORS preflights and adds CORS headers
42
- * ({@link ElectricProxyOptions.cors}) for gateway-less browser deployments.
43
- *
44
- * The caller is responsible for resolving auth claims from the request.
45
- * Pass `claims` as `null` for unauthenticated requests (all rows blocked).
46
- */
47
- export declare function proxyElectricShapeRequest(request: Request, claims: JwtClaims | null, options: ElectricProxyOptions): Promise<Response>;
48
- //# sourceMappingURL=electric-proxy.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"electric-proxy.d.ts","sourceRoot":"","sources":["../src/electric-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,SAAS,EAId,KAAK,iBAAiB,EACvB,MAAM,sBAAsB,CAAC;AAI9B,MAAM,WAAW,iBAAiB;IAChC;;;OAGG;IACH,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB;AAED,MAAM,WAAW,oBAAoB;IACnC,QAAQ,EAAE,iBAAiB,CAAC;IAC5B,WAAW,EAAE,MAAM,CAAC;IACpB,4EAA4E;IAC5E,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC;;;;;OAKG;IACH,IAAI,CAAC,EAAE,iBAAiB,CAAC;IACzB;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;;;;;OAQG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;CACjC;AAeD;;;;;;;GAOG;AACH,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,SAAS,GAAG,IAAI,EACxB,OAAO,EAAE,oBAAoB,GAC5B,OAAO,CAAC,QAAQ,CAAC,CAYnB"}