@pgxsinkit/server 0.5.1 → 0.6.0-rc.1

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.
@@ -229,6 +229,7 @@ export declare const operationsLogTable: import("drizzle-orm/pg-core").PgTableWi
229
229
  }>;
230
230
  };
231
231
  dialect: 'pg';
232
+ isAlias: false;
232
233
  }>;
233
234
  export type OperationsLogRow = typeof operationsLogTable.$inferSelect;
234
235
  export type NewOperationsLogRow = typeof operationsLogTable.$inferInsert;
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/operations-log/schema.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgC9B,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG,OAAO,kBAAkB,CAAC,YAAY,CAAC;AACtE,MAAM,MAAM,mBAAmB,GAAG,OAAO,kBAAkB,CAAC,YAAY,CAAC"}
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/operations-log/schema.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgC9B,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG,OAAO,kBAAkB,CAAC,YAAY,CAAC;AACtE,MAAM,MAAM,mBAAmB,GAAG,OAAO,kBAAkB,CAAC,YAAY,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pgxsinkit/server",
3
- "version": "0.5.1",
3
+ "version": "0.6.0-rc.1",
4
4
  "keywords": [
5
5
  "tanstack-intent"
6
6
  ],
@@ -32,10 +32,10 @@
32
32
  "build": "bun --cwd ../.. run build:public-packages"
33
33
  },
34
34
  "dependencies": {
35
- "@pgxsinkit/contracts": "0.5.1"
35
+ "@pgxsinkit/contracts": "0.6.0-rc.1"
36
36
  },
37
37
  "peerDependencies": {
38
- "drizzle-orm": "1.0.0-rc.4"
38
+ "drizzle-orm": "rc"
39
39
  },
40
40
  "repository": {
41
41
  "type": "git",
@@ -7,7 +7,7 @@ description: >-
7
7
  strip the function-name path prefix, resolve claims in resolveAuthClaims), the deny-by-default
8
8
  apply-function ACL and --grant-execute-to (ADR-0054), and splitting write, control plane, and edge
9
9
  into three functions — the edge on its own origin, because the cache key is the URL (ADR-0055), plus
10
- the Access-Control-Expose-Headers that mount must set or the client hot-loops.
10
+ the Access-Control-Expose-Headers that mount must set or cross-origin reads fail.
11
11
  Also covers the Event lane (ADR-0053): the /api/events route, the eventGate hook, the pgmq
12
12
  prerequisite and pgxsinkit-generate --events queue DDL, and defineEventConsumer as a long-lived Bun
13
13
  process never deployed serverless — plus its bounded drainOnce mode for platforms with no
@@ -15,7 +15,7 @@ description: >-
15
15
  metadata:
16
16
  type: task
17
17
  library: "@pgxsinkit/server"
18
- library_version: "0.5.1"
18
+ library_version: "0.6.0-rc.1"
19
19
  source: https://pgxsinkit.github.io/start/deploying-the-server/
20
20
  ---
21
21
 
@@ -91,14 +91,16 @@ mounting forecloses ever putting a CDN in front of the shared tier without also
91
91
  `Access-Control-Expose-Headers: <STREAM_READ_EXPOSED_HEADERS>` on the actual (non-preflight) response.**
92
92
  Export that constant from `@pgxsinkit/server` and join it — do not retype the list. CORS lets script read
93
93
  only a short safelist of response headers, and every header durable-streams answers with is outside it, so
94
- a cross-origin browser gets a response whose stream headers are simply _not there_. The ds client steers
95
- its whole read loop off them (`Stream-Next-Offset`, `Stream-Cursor`, `Stream-Closed`,
96
- `Stream-Up-To-Date`), so stripped of them it never learns an offset, never switches to a live long poll,
97
- and re-requests `offset=-1` in a hot loop — hundreds of requests per second per shape, with no error
98
- raised on either side. `createStreamGate` cannot do this for you: it forwards the upstream response's
99
- headers, and an exposure list means nothing without the `Access-Control-Allow-Origin` decision that only
100
- the mount makes. **Do not rely on the gateway.** A permissive `expose_headers: "*"` at istio/envoy makes
101
- the mount look correct behind that one deployment and hot-loop everywhere else.
94
+ a cross-origin browser gets a response whose stream headers are simply _not there_. `@pgxsinkit/client`'s
95
+ reader steers by them (`Stream-Next-Offset`, `Stream-Cursor`, `Stream-Closed`, `Stream-Up-To-Date`;
96
+ `Retry-After` refines its backoff), so stripped of them it cannot make progress and every read fails with an
97
+ error naming the missing `Stream-Next-Offset`. Clients from releases that read through
98
+ `@durable-streams/client` fail worse: they never learn an offset, never switch to a live long poll, and
99
+ re-request `offset=-1` in a hot loop — hundreds of requests per second per shape, with no error raised on
100
+ either side. `createStreamGate` cannot do this for you: it forwards the upstream response's headers, and an
101
+ exposure list means nothing without the `Access-Control-Allow-Origin` decision that only the mount makes.
102
+ **Do not rely on the gateway.** A permissive `expose_headers: "*"` at istio/envoy makes the mount look
103
+ correct behind that one deployment and fail everywhere else.
102
104
 
103
105
  The control plane and the edge share the stream-token signing key, and nothing else. Both read functions
104
106
  import the same registry as the write function and share `resolveAuthClaims`, which keeps the ingress
@@ -140,11 +142,11 @@ bun run pgxsinkit-generate --registry ./sync-registry.ts --export registry \
140
142
  `createSyncServer({ applyFunctionGrantExecuteTo: ["app_writer"] })`.
141
143
  - **The revokes are re-emitted on every install** — the artifact begins with `DROP FUNCTION`, so a fresh
142
144
  creation re-inherits Postgres's PUBLIC default and Supabase's `ALTER DEFAULT PRIVILEGES … TO anon,
143
- authenticated, service_role`. A hand-hardened function would silently un-harden itself; this converges.
145
+ authenticated, service_role`. A hand-hardened function would silently un-harden itself; this converges.
144
146
  - **Grantees the toolkit cannot name are revoked too.** After the named revokes, the artifact enumerates
145
147
  the installed function's real grantees (`aclexplode(pg_proc.proacl)`) and revokes `EXECUTE` from every
146
148
  one that is neither the owner nor on the grant list. Your OWN `ALTER DEFAULT PRIVILEGES … GRANT ALL ON
147
- FUNCTIONS TO <role>` re-grants at the `CREATE` inside every install exactly like Supabase's does, so
149
+ FUNCTIONS TO <role>` re-grants at the `CREATE` inside every install exactly like Supabase's does, so
148
150
  without the enumeration such a role would survive every regenerate. End state: owner + your list.
149
151
  - **Everyone regenerates once.** The ACL moved the fingerprint, so upgrading `@pgxsinkit/server` means
150
152
  re-running the generate command (and `--utilities`, which hardens `pgxsinkit_clock_us()` the same way,
@@ -169,8 +171,8 @@ preserve long-lived-host behavior, so you only set it for serverless):
169
171
  ```ts
170
172
  createSyncServer({
171
173
  deployment: {
172
- startupVerification: "in-process" | "deploy-time", // default "in-process": governs ONLY the RLS auth-helper verify
173
- operationsLog: "probe" | "enabled" | "disabled", // default "probe": ensure-then-warn-disable
174
+ startupVerification: "in-process", // default; use "deploy-time" to skip the RLS auth-helper verify
175
+ operationsLog: "probe", // default; use "enabled" or "disabled" to avoid the startup probe
174
176
  },
175
177
  });
176
178
  ```
@@ -85,7 +85,7 @@ export interface StreamGateOptions {
85
85
  entitlements?: EntitlementSet;
86
86
  /**
87
87
  * Base URL of the durable-streams server, with whatever stream prefix it is mounted under — the
88
- * same value the engine is given as `ELECTRIC_CIRCUITS_DS_URL`, since both address the same paths.
88
+ * same value the engine is given as `CIRCUITS_DS_URL`, since both address the same paths.
89
89
  */
90
90
  durableStreamsUrl: string;
91
91
  /**
@@ -188,21 +188,22 @@ export function readStreamToken(request: Request): string | null {
188
188
  * durable-streams protocol answers with is outside it, so a CROSS-ORIGIN reader sees NONE of them
189
189
  * unless the mount names them on `Access-Control-Expose-Headers`.
190
190
  *
191
- * The failure that follows is silent and expensive rather than loud. `@durable-streams/client` drives
192
- * its entire read loop off these headers — verified by grepping the installed 0.2.6 dist
193
- * (`@durable-streams/client/dist/index.js`, mirrored in its shipped `src/`): `Stream-Next-Offset`,
194
- * `Stream-Cursor` and `Stream-Closed` are read per response, `Stream-Up-To-Date` is a presence check
195
- * (`headers.has`, which is why it is easy to miss), `stream-sse-data-encoding` decides SSE payload
196
- * decoding, and `etag` is read on the stream-metadata path. Stripped of them, the client never learns
197
- * an offset: it re-requests `offset=-1` forever and never switches to a live long poll, which presents
198
- * as a hot loop of hundreds of requests per second per shape with no error raised anywhere.
191
+ * Two generations of client read these. `@pgxsinkit/client`'s own reader (`READ_RESPONSE_HEADERS` in
192
+ * its `circuits/long-poll.ts`, which a unit test holds to this list) steers by `Stream-Next-Offset`,
193
+ * `Stream-Up-To-Date` (a presence check, which is why it is easy to miss), `Stream-Cursor` and
194
+ * `Stream-Closed`. Stripped of them it cannot make progress and fails the read, loudly. Clients still
195
+ * in the field on `@durable-streams/client` (0.2.x, which pgxsinkit read through until ADR-0065
196
+ * decision 6) drive their whole read loop off the same four and also read `stream-sse-data-encoding`
197
+ * (SSE payload decoding) and `etag` (the stream-metadata path). Stripped of them, that client never
198
+ * learns an offset: it re-requests `offset=-1` forever and never switches to a live long poll, which
199
+ * presents as a hot loop of hundreds of requests per second per shape with no error raised anywhere.
200
+ * Both floor their retry backoff on `Retry-After`; without it they fall back on their own schedule.
199
201
  *
200
- * `Stream-Seq`, `Stream-TTL` and `Stream-Expires-At` are request headers in that client version. They
201
- * are named here anyway because this list is a statement about the ds protocol's response namespace
202
- * rather than about which subset one client version happens to read today — exposing a header a
203
- * response never carries is inert, while omitting one that it does carry wedges the reader. The
204
- * `Producer-*` headers are deliberately absent: they belong to the write path, which does not come
205
- * through this gate.
202
+ * `Stream-Seq`, `Stream-TTL` and `Stream-Expires-At` are read by neither. They are named here
203
+ * anyway because this list is a statement about the ds protocol's response namespace rather than about
204
+ * which subset one client version happens to read today — exposing a header a response never carries
205
+ * is inert, while omitting one that it does carry wedges the reader. The `Producer-*` headers are
206
+ * deliberately absent: they belong to the write path, which does not come through this gate.
206
207
  *
207
208
  * EVERY mount of `createStreamGate` must put these on `Access-Control-Expose-Headers` of the ACTUAL
208
209
  * (non-preflight) response. The gate cannot do it itself — it forwards the upstream response's
@@ -220,6 +221,7 @@ export const STREAM_READ_EXPOSED_HEADERS: readonly string[] = [
220
221
  "stream-expires-at",
221
222
  "stream-sse-data-encoding",
222
223
  "etag",
224
+ "retry-after",
223
225
  ];
224
226
 
225
227
  /**
@@ -248,7 +250,8 @@ interface ProxiedEnvelope {
248
250
  *
249
251
  * Everything else is kept VERBATIM — every `stream-*` header and the content type. The client's whole
250
252
  * read loop drives off them (see {@link STREAM_READ_EXPOSED_HEADERS}); an edge that dropped
251
- * `stream-next-offset` while rewriting would present as a hot loop, not as a redaction bug.
253
+ * `stream-next-offset` while rewriting would present as a failed read (to a client still on
254
+ * `@durable-streams/client`, a hot loop), not as a redaction bug.
252
255
  */
253
256
  function rewrittenEgressHeaders(upstream: Headers): Headers {
254
257
  const headers = new Headers(upstream);
@@ -132,7 +132,7 @@ export function createCircuitsEngineClient(options: CircuitsEngineOptions) {
132
132
  * `flipFailures > 0` means a batch was **abandoned** after exhausting its propagation retries:
133
133
  * those membership effects are gone rather than late. The engine keeps the abandoned batch's
134
134
  * `pendingFlips` count held — so the waiting terms never falsely read converged — and latches
135
- * itself degraded: `/v1/health` answers 503, so do its membership-bearing routes, and a reaper
135
+ * itself degraded: `/ready` answers 503, so do its membership-bearing routes, and a reaper
136
136
  * deletes every subquery shape stream. Recovery is an operator restart.
137
137
  *
138
138
  * The answer is VALIDATED, not cast. An engine that does not report both counters cannot answer
@@ -81,7 +81,7 @@ export interface SubscribeOptions {
81
81
  *
82
82
  * The control plane renews every live claim on exactly one cadence: the token re-mint, which the
83
83
  * client drives at `expiresAt - skew` and which therefore lands at most `ttlSeconds` apart. The
84
- * engine releases a claim not renewed within `leaseSeconds` (`ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS`).
84
+ * engine releases a claim not renewed within `leaseSeconds` (`CIRCUITS_SHAPE_IDLE_SECS`).
85
85
  * So a deployment whose lease window is under two TTLs has no margin at all: one refresh delayed by a
86
86
  * retry, a redeploy, or a sleeping tab, and a live session's shape goes dormant underneath it. The
87
87
  * factor of two is the margin for exactly one missed refresh.
@@ -91,7 +91,7 @@ export interface SubscribeOptions {
91
91
  * you" — and never a denial: a client told it lost entitlement truncates its rows.
92
92
  */
93
93
  export class CircuitsLeaseConfigError extends Error {
94
- /** The engine's `ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS`, as the create response reported it. */
94
+ /** The engine's `CIRCUITS_SHAPE_IDLE_SECS`, as the create response reported it. */
95
95
  readonly leaseSeconds: number;
96
96
  /** The stream-token TTL this control plane is configured with. */
97
97
  readonly ttlSeconds: number;
@@ -99,11 +99,11 @@ export class CircuitsLeaseConfigError extends Error {
99
99
  constructor(leaseSeconds: number, ttlSeconds: number) {
100
100
  super(
101
101
  `[pgxsinkit] the sync engine's shape lease window (${leaseSeconds}s, ` +
102
- `ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS) is shorter than twice this control plane's stream-token TTL ` +
102
+ `CIRCUITS_SHAPE_IDLE_SECS) is shorter than twice this control plane's stream-token TTL ` +
103
103
  `(${ttlSeconds}s, the \`ttlSeconds\` option). Claims are renewed on the token re-mint, so a single ` +
104
104
  `missed refresh would let a live session's subscription lapse and its shape go dormant underneath ` +
105
- `it. Raise ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS to at least ${2 * ttlSeconds}, lower \`ttlSeconds\` to ` +
106
- `at most ${Math.floor(leaseSeconds / 2)}, or set ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS=0 to disable ` +
105
+ `it. Raise CIRCUITS_SHAPE_IDLE_SECS to at least ${2 * ttlSeconds}, lower \`ttlSeconds\` to ` +
106
+ `at most ${Math.floor(leaseSeconds / 2)}, or set CIRCUITS_SHAPE_IDLE_SECS=0 to disable ` +
107
107
  `leases entirely.`,
108
108
  );
109
109
  this.name = "CircuitsLeaseConfigError";
@@ -58,7 +58,7 @@ export interface CircuitsShapeHandle {
58
58
  subscription: string;
59
59
  /**
60
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
61
+ * (`CIRCUITS_SHAPE_IDLE_SECS`, default 1800). `0` means leases never lapse, because that
62
62
  * setting also disables dormancy.
63
63
  *
64
64
  * Reported rather than guessed: the renewal cadence is the deployment's to set, and a control plane
@@ -16,8 +16,17 @@
16
16
  */
17
17
 
18
18
  import { spawnSync } from "node:child_process";
19
- import { randomUUID } from "node:crypto";
20
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
19
+ import {
20
+ copyFileSync,
21
+ existsSync,
22
+ mkdirSync,
23
+ mkdtempSync,
24
+ readdirSync,
25
+ readFileSync,
26
+ rmSync,
27
+ writeFileSync,
28
+ } from "node:fs";
29
+ import { tmpdir } from "node:os";
21
30
  import { isAbsolute, join, resolve } from "node:path";
22
31
  import { pathToFileURL } from "node:url";
23
32
 
@@ -155,10 +164,11 @@ async function importRegistry(registryPath: string, exportName?: string): Promis
155
164
  return selectRegistryExport(moduleExports, exportName);
156
165
  }
157
166
 
158
- function runDrizzleGenerate(projectDir: string, name: string, drizzleConfig?: string): void {
159
- const cwd = join(process.cwd(), projectDir);
167
+ function runDrizzleGenerate(projectDir: string, name: string, drizzleConfig?: string, extraArgs: string[] = []): void {
168
+ const cwd = resolve(projectDir);
160
169
  const args = ["run", "drizzle-kit", "generate", "--custom", "--name", name];
161
170
  if (drizzleConfig) args.push("--config", drizzleConfig);
171
+ args.push(...extraArgs);
162
172
  const result = spawnSync("bun", args, {
163
173
  cwd,
164
174
  stdio: "inherit",
@@ -310,20 +320,14 @@ export function findMigrationCarrying(drizzleDir: string, marker: string): strin
310
320
  return null;
311
321
  }
312
322
 
313
- /** The drizzle-kit "no previous migration" root id (an all-zero UUID), used by a chain's first folder. */
314
- const ZERO_MIGRATION_ID = "00000000-0000-0000-0000-000000000000";
315
-
316
323
  /** A committed migration carries the utilities function when its DDL declares this signature. */
317
324
  const UTILITIES_SIGNATURE = "CREATE OR REPLACE FUNCTION public.pgxsinkit_clock_us()";
318
325
 
319
326
  /**
320
- * Writes the utilities migration as a NON-KIT folder (a hand-authored pre-baseline, mirroring the
321
- * board-prereqs pattern): an empty-`ddl` snapshot rooted at the zero id, so it sorts and applies
322
- * FIRST. Unlike the artifact path this does NOT invoke `drizzle-kit generate` — that stamps the
323
- * current time and would sort the folder LAST, after the schema and artifact it must precede — so the
324
- * caller supplies the full, early-sorting folder name via `--name` (e.g. 20260101000000_pgxsinkit_utilities).
327
+ * Writes the utilities first, using a kit-generated empty baseline snapshot. The caller supplies
328
+ * the early-sorting folder name: these functions must precede schema defaults that call them.
325
329
  */
326
- function writeUtilitiesMigration(drizzleDir: string, folderName: string): string {
330
+ function writeUtilitiesMigration(projectDir: string, drizzleDir: string, folderName: string): string {
327
331
  const dir = join(drizzleDir, folderName);
328
332
  mkdirSync(dir, { recursive: true });
329
333
 
@@ -333,25 +337,36 @@ function writeUtilitiesMigration(drizzleDir: string, folderName: string): string
333
337
  const migrationFile = join(dir, "migration.sql");
334
338
  writeFileSync(migrationFile, header + renderPgxsinkitUtilitiesMigration() + "\n");
335
339
 
336
- // The snapshot mirrors a hand-authored pre-baseline (see board-drizzle/*_board_prereqs): the function
337
- // is not part of drizzle-kit's tracked DDL model, so the snapshot's `ddl` is empty and it roots the
338
- // chain at the zero id. `version`/`dialect` match the kit's postgres snapshot format.
339
- //
340
340
  // RE-EMIT KEEPS THE EXISTING IDENTITY. The next folder in the chain records this snapshot's `id` in
341
341
  // its own `prevIds`, so minting a fresh UUID on every run would BREAK the chain of any consumer who
342
342
  // re-emits this folder in place (which ADR-0054 asks them to do, to pick up the clock function's
343
343
  // hardened ACL). Only the SQL is re-rendered; the snapshot is left byte-identical where one exists.
344
344
  const snapshotFile = join(dir, "snapshot.json");
345
345
  if (!existsSync(snapshotFile)) {
346
- const snapshot = {
347
- id: randomUUID(),
348
- prevIds: [ZERO_MIGRATION_ID],
349
- version: "8",
350
- dialect: "postgres",
351
- ddl: [] as unknown[],
352
- renames: [] as unknown[],
353
- };
354
- writeFileSync(snapshotFile, `${JSON.stringify(snapshot, null, 2)}\n`);
346
+ // Let the consumer's installed kit own its snapshot format. Generate against an empty
347
+ // schema in an isolated runtime directory, then copy the unchanged baseline into the
348
+ // caller's first folder. No current-time folder is added to their actual history.
349
+ const scratch = mkdtempSync(join(tmpdir(), "pgxsinkit-utilities-"));
350
+ try {
351
+ const schema = join(scratch, "schema.ts");
352
+ const out = join(scratch, "migrations");
353
+ writeFileSync(schema, "export {};\n");
354
+ runDrizzleGenerate(projectDir, "utilities", undefined, [
355
+ "--dialect",
356
+ "postgresql",
357
+ "--schema",
358
+ schema,
359
+ "--out",
360
+ out,
361
+ "--output",
362
+ "json",
363
+ ]);
364
+ const folders = readdirSync(out, { withFileTypes: true }).filter((entry) => entry.isDirectory());
365
+ if (folders.length !== 1) throw new Error("Drizzle Kit did not generate one utilities baseline");
366
+ copyFileSync(join(out, folders[0]!.name, "snapshot.json"), snapshotFile);
367
+ } finally {
368
+ rmSync(scratch, { recursive: true, force: true });
369
+ }
355
370
  }
356
371
 
357
372
  return migrationFile;
@@ -398,7 +413,7 @@ async function runUtilities(options: {
398
413
  return;
399
414
  }
400
415
 
401
- const migrationFile = writeUtilitiesMigration(drizzleDir, options.migrationName);
416
+ const migrationFile = writeUtilitiesMigration(options.projectDir, drizzleDir, options.migrationName);
402
417
  console.log(`Wrote pgxsinkit_clock_us() utilities migration to ${migrationFile}`);
403
418
  }
404
419