@pgxsinkit/server 0.2.5 → 0.2.7

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.
@@ -17,22 +17,32 @@
17
17
 
18
18
  import { spawnSync } from "node:child_process";
19
19
  import { randomUUID } from "node:crypto";
20
- import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
20
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
21
21
  import { isAbsolute, join, resolve } from "node:path";
22
22
  import { pathToFileURL } from "node:url";
23
23
 
24
24
  import type { SyncTableRegistry } from "@pgxsinkit/contracts";
25
25
 
26
+ import { eventLaneDdlFingerprint, eventLaneStreamNames, renderEventLaneMigration } from "../events/ddl";
26
27
  import { renderPgxsinkitUtilitiesMigration } from "../migrations/utilities";
27
- import { buildPlpgsqlBatchFunctionDdl, expectedApplyFingerprint } from "../mutations/plpgsql-apply";
28
-
29
- function parseArgs(argv: string[]) {
28
+ import {
29
+ buildPlpgsqlBatchFunctionDdl,
30
+ expectedApplyFingerprint,
31
+ type ApplyFunctionRenderOptions,
32
+ } from "../mutations/plpgsql-apply";
33
+
34
+ /** Exported for direct unit coverage of the flag surface (repeatable/comma-separated `--grant-execute-to`). */
35
+ export function parseArgs(argv: string[]) {
30
36
  let check = false;
31
37
  let utilities = false;
38
+ let events = false;
32
39
  let functionSchema: string | undefined;
40
+ // ADR-0054: repeatable AND comma-separated, so `--grant-execute-to a --grant-execute-to b` and
41
+ // `--grant-execute-to a,b` are the same list. Empty (the default) is owner-only.
42
+ const grantExecuteTo: string[] = [];
33
43
  let registryPath = "";
34
44
  let projectDir = process.cwd();
35
- let migrationName = "sync_artifact";
45
+ let migrationName: string | undefined;
36
46
  let drizzleConfig = "";
37
47
  let outDir: string | undefined;
38
48
  let exportName: string | undefined;
@@ -55,18 +65,35 @@ function parseArgs(argv: string[]) {
55
65
  check = true;
56
66
  } else if (arg === "--utilities") {
57
67
  utilities = true;
68
+ } else if (arg === "--events") {
69
+ events = true;
58
70
  } else if (arg === "--function-schema" && argv[i + 1]) {
59
71
  functionSchema = argv[++i]!;
72
+ } else if (arg === "--grant-execute-to" && argv[i + 1]) {
73
+ for (const role of argv[++i]!.split(",")) {
74
+ grantExecuteTo.push(role.trim());
75
+ }
60
76
  }
61
77
  }
62
78
 
63
79
  // Utilities mode installs the registry-independent pgxsinkit_clock_us() function, so it needs no
64
- // --registry; the apply-artifact modes do.
80
+ // --registry; the apply-artifact and event-lane modes do (both are derived from the registry).
65
81
  if (!registryPath && !utilities) {
66
82
  console.error(
67
83
  "Usage:\n" +
68
- " pgxsinkit-generate [--check] --registry <path> [--export registry] [--project-dir .] [--name sync_artifact] [--config drizzle.config.ts] [--out drizzle] [--function-schema schema]\n" +
69
- " pgxsinkit-generate --utilities [--check] --name <folder> [--project-dir .] [--config drizzle.config.ts] [--out drizzle]",
84
+ " pgxsinkit-generate [--check] --registry <path> [--export registry] [--project-dir .] [--name sync_artifact] [--config drizzle.config.ts] [--out drizzle] [--function-schema schema] [--grant-execute-to <role>]...\n" +
85
+ "\n" +
86
+ " --grant-execute-to <role> Role granted EXECUTE on the apply function (repeatable, or comma-separated).\n" +
87
+ " Default: NOBODY but the function owner (ADR-0054). Name the role your\n" +
88
+ " SERVER connects as — never a client-facing role (anon/authenticated):\n" +
89
+ " the function trusts the claims it is handed, so this list is the write\n" +
90
+ " path's entire trust boundary. It is part of the artifact fingerprint, so\n" +
91
+ " pass the SAME roles to --check and to createSyncServer.\n" +
92
+ " --function-schema <schema> Install the apply function into <schema> instead of leaving it unqualified.\n" +
93
+ " Also part of the fingerprint AND the name the server must call, so pass the\n" +
94
+ " SAME schema to --check and to createSyncServer({ applyFunctionSchema }).\n" +
95
+ " pgxsinkit-generate --utilities [--check] --name <folder> [--project-dir .] [--config drizzle.config.ts] [--out drizzle]\n" +
96
+ " pgxsinkit-generate --events [--check] --registry <path> [--export registry] [--project-dir .] [--name event_lane_artifact] [--config drizzle.config.ts] [--out drizzle]",
70
97
  );
71
98
  process.exit(1);
72
99
  }
@@ -74,10 +101,12 @@ function parseArgs(argv: string[]) {
74
101
  return {
75
102
  check,
76
103
  utilities,
104
+ events,
77
105
  functionSchema,
106
+ grantExecuteTo,
78
107
  registryPath,
79
108
  projectDir,
80
- migrationName,
109
+ migrationName: migrationName ?? (events ? "event_lane_artifact" : "sync_artifact"),
81
110
  drizzleConfig,
82
111
  outDir,
83
112
  exportName,
@@ -207,6 +236,17 @@ function findNewMigrationFile(drizzleDir: string): string | null {
207
236
  return null;
208
237
  }
209
238
 
239
+ /** The renderer options both `--check` and the generate path derive from the same parsed flags. */
240
+ function buildRenderOptions(options: {
241
+ functionSchema: string | undefined;
242
+ grantExecuteTo: readonly string[];
243
+ }): ApplyFunctionRenderOptions {
244
+ return {
245
+ ...(options.functionSchema ? { functionSchema: options.functionSchema } : {}),
246
+ ...(options.grantExecuteTo.length > 0 ? { grantExecuteTo: options.grantExecuteTo } : {}),
247
+ };
248
+ }
249
+
210
250
  /**
211
251
  * `--check` (ADR-0018): the read-only, pre-deploy half of apply-function drift detection. Computes the
212
252
  * fingerprint the apply function SHOULD carry for this registry + applier codegen and asserts that a
@@ -221,13 +261,13 @@ async function runCheck(
221
261
  drizzleConfig: string | undefined;
222
262
  outDir: string | undefined;
223
263
  functionSchema: string | undefined;
264
+ grantExecuteTo: readonly string[];
224
265
  label: string;
225
266
  },
226
267
  ): Promise<void> {
227
- const fingerprint = expectedApplyFingerprint(
228
- registry,
229
- options.functionSchema ? { functionSchema: options.functionSchema } : {},
230
- );
268
+ // ADR-0054: `grantExecuteTo` is part of the fingerprinted body, so `--check` must be handed the SAME
269
+ // roles the artifact was generated with — otherwise it reports drift on a perfectly current artifact.
270
+ const fingerprint = expectedApplyFingerprint(registry, buildRenderOptions(options));
231
271
 
232
272
  const drizzleDir = await resolveDrizzleOutDir(options.projectDir, options.drizzleConfig, options.outDir);
233
273
  if (!drizzleDir) {
@@ -237,16 +277,9 @@ async function runCheck(
237
277
  process.exit(1);
238
278
  }
239
279
 
240
- for (const entry of readdirSync(drizzleDir, { withFileTypes: true })) {
241
- if (!entry.isDirectory()) {
242
- continue;
243
- }
244
- try {
245
- if (readFileSync(join(drizzleDir, entry.name, "migration.sql"), "utf-8").includes(fingerprint)) {
246
- console.log(`[pgxsinkit-generate --check] ✓ ${options.label}: a committed migration carries ${fingerprint}`);
247
- return;
248
- }
249
- } catch {}
280
+ if (findMigrationCarrying(drizzleDir, fingerprint)) {
281
+ console.log(`[pgxsinkit-generate --check] ✓ ${options.label}: a committed migration carries ${fingerprint}`);
282
+ return;
250
283
  }
251
284
 
252
285
  console.error(
@@ -258,6 +291,25 @@ async function runCheck(
258
291
  process.exit(1);
259
292
  }
260
293
 
294
+ /**
295
+ * The one committed-migration scan every `--check` mode shares: the folder whose `migration.sql` carries
296
+ * `marker`, or `null`. Unreadable folders are skipped — a `--check` reports drift, never filesystem noise.
297
+ * Exported for direct unit coverage.
298
+ */
299
+ export function findMigrationCarrying(drizzleDir: string, marker: string): string | null {
300
+ for (const entry of readdirSync(drizzleDir, { withFileTypes: true })) {
301
+ if (!entry.isDirectory()) {
302
+ continue;
303
+ }
304
+ try {
305
+ if (readFileSync(join(drizzleDir, entry.name, "migration.sql"), "utf-8").includes(marker)) {
306
+ return entry.name;
307
+ }
308
+ } catch {}
309
+ }
310
+ return null;
311
+ }
312
+
261
313
  /** The drizzle-kit "no previous migration" root id (an all-zero UUID), used by a chain's first folder. */
262
314
  const ZERO_MIGRATION_ID = "00000000-0000-0000-0000-000000000000";
263
315
 
@@ -284,15 +336,23 @@ function writeUtilitiesMigration(drizzleDir: string, folderName: string): string
284
336
  // The snapshot mirrors a hand-authored pre-baseline (see board-drizzle/*_board_prereqs): the function
285
337
  // is not part of drizzle-kit's tracked DDL model, so the snapshot's `ddl` is empty and it roots the
286
338
  // chain at the zero id. `version`/`dialect` match the kit's postgres snapshot format.
287
- const snapshot = {
288
- id: randomUUID(),
289
- prevIds: [ZERO_MIGRATION_ID],
290
- version: "8",
291
- dialect: "postgres",
292
- ddl: [] as unknown[],
293
- renames: [] as unknown[],
294
- };
295
- writeFileSync(join(dir, "snapshot.json"), `${JSON.stringify(snapshot, null, 2)}\n`);
339
+ //
340
+ // RE-EMIT KEEPS THE EXISTING IDENTITY. The next folder in the chain records this snapshot's `id` in
341
+ // its own `prevIds`, so minting a fresh UUID on every run would BREAK the chain of any consumer who
342
+ // re-emits this folder in place (which ADR-0054 asks them to do, to pick up the clock function's
343
+ // hardened ACL). Only the SQL is re-rendered; the snapshot is left byte-identical where one exists.
344
+ const snapshotFile = join(dir, "snapshot.json");
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`);
355
+ }
296
356
 
297
357
  return migrationFile;
298
358
  }
@@ -302,18 +362,11 @@ function writeUtilitiesMigration(drizzleDir: string, folderName: string): string
302
362
  * installs the (static, registry-independent) pgxsinkit_clock_us() function. Read-only, no writes.
303
363
  */
304
364
  function checkUtilities(drizzleDir: string, label: string): void {
305
- for (const entry of readdirSync(drizzleDir, { withFileTypes: true })) {
306
- if (!entry.isDirectory()) {
307
- continue;
308
- }
309
- try {
310
- if (readFileSync(join(drizzleDir, entry.name, "migration.sql"), "utf-8").includes(UTILITIES_SIGNATURE)) {
311
- console.log(
312
- `[pgxsinkit-generate --utilities --check] ✓ ${label}: a committed migration installs pgxsinkit_clock_us()`,
313
- );
314
- return;
315
- }
316
- } catch {}
365
+ if (findMigrationCarrying(drizzleDir, UTILITIES_SIGNATURE)) {
366
+ console.log(
367
+ `[pgxsinkit-generate --utilities --check] ✓ ${label}: a committed migration installs pgxsinkit_clock_us()`,
368
+ );
369
+ return;
317
370
  }
318
371
 
319
372
  console.error(
@@ -349,11 +402,92 @@ async function runUtilities(options: {
349
402
  console.log(`Wrote pgxsinkit_clock_us() utilities migration to ${migrationFile}`);
350
403
  }
351
404
 
405
+ /**
406
+ * `--events` (ADR-0053 decision 5): the Event lane's deploy-time artifact — the pgmq extension plus one queue
407
+ * per registered Event stream, derived from the registry. It rides the same generate/`--check` flow as the
408
+ * apply-function artifact, in its OWN migration folder: the queues are provisioned independently of the apply
409
+ * function (Event streams touch no synced table), and a registry with no streams provisions nothing at all.
410
+ *
411
+ * `--check` is the read-only pre-deploy half: it asserts a committed migration carries the fingerprint the
412
+ * current registry's streams imply, so adding or removing an Event stream without regenerating fails in CI
413
+ * rather than at the first enqueue against a queue that does not exist.
414
+ */
415
+ async function runEvents(
416
+ registry: SyncTableRegistry,
417
+ options: {
418
+ check: boolean;
419
+ projectDir: string;
420
+ drizzleConfig: string | undefined;
421
+ outDir: string | undefined;
422
+ migrationName: string;
423
+ label: string;
424
+ },
425
+ ): Promise<void> {
426
+ const streamNames = eventLaneStreamNames(registry);
427
+
428
+ if (streamNames.length === 0) {
429
+ if (options.check) {
430
+ // Nothing to provision is not drift: a registry without Event streams simply has no event lane.
431
+ console.log(`[pgxsinkit-generate --events --check] ✓ ${options.label}: no Event streams registered`);
432
+ return;
433
+ }
434
+ console.error(
435
+ `[pgxsinkit-generate --events] ✗ ${options.label}: this registry registers no Event streams, so there is ` +
436
+ `no event-lane DDL to emit.\n` +
437
+ ` Register one with defineSyncRegistry({ tables, streams: { <name>: defineEventStream({ … }) } }).`,
438
+ );
439
+ process.exit(1);
440
+ }
441
+
442
+ const drizzleDir = await resolveDrizzleOutDir(options.projectDir, options.drizzleConfig, options.outDir);
443
+ if (!drizzleDir) {
444
+ console.error(
445
+ `[pgxsinkit-generate --events] Could not resolve a drizzle migrations directory in ${options.projectDir}.`,
446
+ );
447
+ process.exit(1);
448
+ }
449
+
450
+ const fingerprint = eventLaneDdlFingerprint(registry);
451
+
452
+ if (options.check) {
453
+ if (findMigrationCarrying(drizzleDir, fingerprint)) {
454
+ console.log(
455
+ `[pgxsinkit-generate --events --check] ✓ ${options.label}: a committed migration carries ${fingerprint}`,
456
+ );
457
+ return;
458
+ }
459
+ console.error(
460
+ `[pgxsinkit-generate --events --check] ✗ ${options.label}: no committed migration in ${drizzleDir} carries ` +
461
+ `the current event-lane fingerprint (${fingerprint}).\n` +
462
+ ` The registry's Event streams changed since the event-lane migration was generated ` +
463
+ `(now: ${streamNames.join(", ")}).\n` +
464
+ ` Regenerate it (drop --check) and commit + apply the new migration before deploying — the ingestion ` +
465
+ `endpoint enqueues onto queues the migration provisions.`,
466
+ );
467
+ process.exit(1);
468
+ }
469
+
470
+ console.log(`Generating event-lane DDL for ${streamNames.length} Event stream(s): ${streamNames.join(", ")}...`);
471
+ runDrizzleGenerate(options.projectDir, options.migrationName, options.drizzleConfig);
472
+
473
+ const migrationFile = findNewMigrationFile(drizzleDir);
474
+ if (!migrationFile) {
475
+ console.error("Could not find the newly created migration file.");
476
+ process.exit(1);
477
+ }
478
+
479
+ const header = "-- Generated by pgxsinkit-generate --events\n-- Re-run after adding or removing an Event stream.\n\n";
480
+ writeFileSync(migrationFile, `${header}${renderEventLaneMigration(registry)}\n`);
481
+ console.log(`Wrote event-lane queues to ${migrationFile}`);
482
+ }
483
+
352
484
  async function main() {
353
485
  const {
354
486
  check,
355
487
  utilities,
488
+ events,
356
489
  functionSchema,
490
+ grantExecuteTo,
357
491
  registryPath,
358
492
  projectDir,
359
493
  migrationName,
@@ -370,19 +504,35 @@ async function main() {
370
504
  console.log(`Importing registry from ${registryPath}...`);
371
505
  const registry = await importRegistry(registryPath, exportName);
372
506
 
507
+ if (events) {
508
+ await runEvents(registry, {
509
+ check,
510
+ projectDir,
511
+ drizzleConfig,
512
+ outDir,
513
+ migrationName,
514
+ label: exportName ?? "(conventional registry)",
515
+ });
516
+ return;
517
+ }
518
+
373
519
  if (check) {
374
520
  await runCheck(registry, {
375
521
  projectDir,
376
522
  drizzleConfig,
377
523
  outDir,
378
524
  functionSchema,
525
+ grantExecuteTo,
379
526
  label: exportName ?? "(conventional registry)",
380
527
  });
381
528
  return;
382
529
  }
383
530
 
384
531
  console.log(`Generating DDL for ${Object.keys(registry).length} table(s)...`);
385
- const ddl = buildPlpgsqlBatchFunctionDdl(registry);
532
+ // Both render inputs must reach the renderer here, exactly as `--check` computes them: a
533
+ // `--function-schema` that only reached `--check` silently generated an unqualified artifact whose
534
+ // fingerprint could never match (and `--grant-execute-to` would have the same failure mode).
535
+ const ddl = buildPlpgsqlBatchFunctionDdl(registry, buildRenderOptions({ functionSchema, grantExecuteTo }));
386
536
 
387
537
  console.log(`Creating empty migration via drizzle-kit generate --custom --name ${migrationName}...`);
388
538
  runDrizzleGenerate(projectDir, migrationName, drizzleConfig);