@pgxsinkit/server 0.2.7 → 0.3.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.
@@ -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
+ }
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,
@@ -468,3 +521,55 @@ export {
468
521
  } from "./events/ddl";
469
522
  export { resolveEventIdentity } from "./events/identity";
470
523
  export type { IdentityResolution } from "./events/identity";
524
+
525
+ // The Circuits-native read path (ADR-0055) — shape lifecycle only. Reads terminate on
526
+ // durable-streams and never traverse the engine.
527
+ export { compileShapeRequest, fingerprintShapeRequest, resolveEntryByShapeKey } from "./circuits/compile";
528
+ export type { CompiledShapeRequest, ShapeRequest } from "./circuits/compile";
529
+ export { CircuitsEngineError, createCircuitsEngineClient } from "./circuits/engine-client";
530
+ export type { CircuitsEngineClient, CircuitsEngineOptions } from "./circuits/engine-client";
531
+ export type { CircuitsShapeHandle, CreateShapeRequest } from "./circuits/wire";
532
+ export {
533
+ DEFAULT_STREAM_TOKEN_TTL_SECONDS,
534
+ findGrant,
535
+ importStreamTokenKey,
536
+ mintStreamToken,
537
+ verifyStreamToken,
538
+ } from "./circuits/stream-token";
539
+ export type {
540
+ MintStreamTokenOptions,
541
+ VerifyStreamTokenOptions,
542
+ StreamGrant,
543
+ StreamTokenClaims,
544
+ StreamTokenVerification,
545
+ } from "./circuits/stream-token";
546
+ export {
547
+ authorizeStreamRead,
548
+ createStreamGate,
549
+ EntitlementsUnavailableError,
550
+ readStreamToken,
551
+ STREAM_READ_EXPOSED_HEADERS,
552
+ } from "./circuits/edge";
553
+ export type { EntitlementSet, GateDecision, StreamAuthorizationOptions, StreamGateOptions } from "./circuits/edge";
554
+ export {
555
+ barrierPath,
556
+ CircuitsLeaseConfigError,
557
+ createBarrierHandler,
558
+ createRefreshHandler,
559
+ createReleaseHandler,
560
+ createSubscribeHandler,
561
+ refreshPath,
562
+ refreshStreamToken,
563
+ releasePath,
564
+ releaseStreamGrants,
565
+ subscribePath,
566
+ subscribeToShapes,
567
+ } from "./circuits/subscribe";
568
+ export type {
569
+ DeniedSubscription,
570
+ GrantedSubscription,
571
+ RefreshResult,
572
+ SubscribeOptions,
573
+ SubscribeResult,
574
+ SubscriptionRequest,
575
+ } from "./circuits/subscribe";
@@ -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"}