@pgxsinkit/server 0.2.5 → 0.2.6
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.
- package/dist/cli/generate.d.ts +20 -0
- package/dist/cli/generate.d.ts.map +1 -1
- package/dist/events/consumer.d.ts +282 -0
- package/dist/events/consumer.d.ts.map +1 -0
- package/dist/events/ddl.d.ts +40 -0
- package/dist/events/ddl.d.ts.map +1 -0
- package/dist/events/identity.d.ts +26 -0
- package/dist/events/identity.d.ts.map +1 -0
- package/dist/events/pgmq-queue.d.ts +41 -0
- package/dist/events/pgmq-queue.d.ts.map +1 -0
- package/dist/events/queue.d.ts +119 -0
- package/dist/events/queue.d.ts.map +1 -0
- package/dist/events/route.d.ts +99 -0
- package/dist/events/route.d.ts.map +1 -0
- package/dist/index.d.ts +58 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1022 -54
- package/dist/index.js.map +13 -7
- package/dist/migrations/utilities.d.ts.map +1 -1
- package/dist/mutations/plpgsql-apply.d.ts +30 -9
- package/dist/mutations/plpgsql-apply.d.ts.map +1 -1
- package/dist/mutations/route.d.ts +27 -1
- package/dist/mutations/route.d.ts.map +1 -1
- package/package.json +2 -2
- package/skills/deploying/SKILL.md +195 -7
- package/src/cli/generate.ts +195 -45
- package/src/events/consumer.ts +831 -0
- package/src/events/ddl.ts +79 -0
- package/src/events/identity.ts +86 -0
- package/src/events/pgmq-queue.ts +237 -0
- package/src/events/queue.ts +159 -0
- package/src/events/route.ts +488 -0
- package/src/index.ts +124 -0
- package/src/migrations/utilities.ts +22 -2
- package/src/mutations/plpgsql-apply.ts +357 -38
- package/src/mutations/route.ts +93 -16
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utilities.d.ts","sourceRoot":"","sources":["../../src/migrations/utilities.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"utilities.d.ts","sourceRoot":"","sources":["../../src/migrations/utilities.ts"],"names":[],"mappings":"AAYA;;;;;;;;;;GAUG;AACH,wBAAgB,iCAAiC,IAAI,MAAM,CAqB1D"}
|
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
import { type PgAsyncDatabase, type PgQueryResultHKT } from "drizzle-orm/pg-core";
|
|
2
2
|
import { type BatchMutationRequest, type RegistryRelations, type SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
3
3
|
import type { TransactionClient } from "./types";
|
|
4
|
+
/**
|
|
5
|
+
* How the generated apply function is rendered. Both fields are part of the artifact's IDENTITY: they
|
|
6
|
+
* change the fingerprinted body, so a change to either forces the regenerate-and-commit flow, and the
|
|
7
|
+
* SERVER must be configured with the same values (it recomputes the expected fingerprint at runtime).
|
|
8
|
+
*/
|
|
9
|
+
export interface ApplyFunctionRenderOptions {
|
|
10
|
+
/** Schema to qualify the function with. Default: unqualified (resolved through `search_path`). */
|
|
11
|
+
functionSchema?: string;
|
|
12
|
+
/**
|
|
13
|
+
* Roles that receive `GRANT EXECUTE` on the apply function (ADR-0054 decision 2). Default `[]` —
|
|
14
|
+
* **owner-only**, which is right whenever the server connects as the function's owner or a
|
|
15
|
+
* superuser. Name ONLY server roles: the function trusts the `p_user_claims` it is handed, so a
|
|
16
|
+
* granted role can pass any claims it likes. The grant list IS the write path's trust boundary.
|
|
17
|
+
*/
|
|
18
|
+
grantExecuteTo?: readonly string[];
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Validate a `functionSchema` — the ONE definition, shared by the renderer (which qualifies the emitted
|
|
22
|
+
* DDL with it) and by the running server (`applyFunctionSchema`, which must qualify its invocation the
|
|
23
|
+
* same way and recompute the same fingerprint). A schema name reaches SQL as a quoted identifier, so the
|
|
24
|
+
* rule is the same plain-identifier rule role names get: an unusable name is refused loudly at generate
|
|
25
|
+
* / server-construction time rather than producing an artifact nobody can call.
|
|
26
|
+
*
|
|
27
|
+
* Returns `undefined` for an absent schema — the default, an unqualified name resolved through
|
|
28
|
+
* `search_path`.
|
|
29
|
+
*/
|
|
30
|
+
export declare function resolveApplyFunctionSchema(functionSchema: string | undefined): string | undefined;
|
|
4
31
|
/**
|
|
5
32
|
* The fingerprint the installed apply function should carry for this registry + applier codegen
|
|
6
33
|
* (ADR-0018). It is a hash of the exact generated DDL body, so it shifts on any registry-shape
|
|
@@ -8,15 +35,9 @@ import type { TransactionClient } from "./types";
|
|
|
8
35
|
* two drift classes a bare signature check cannot see. It does NOT depend on TS-side row-filter /
|
|
9
36
|
* customWhere logic, which never enters the apply function (that shapes the read proxy, not writes).
|
|
10
37
|
*/
|
|
11
|
-
export declare function expectedApplyFingerprint(registry: SyncTableRegistry, options?:
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
export declare function buildPlpgsqlBatchFunctionDdl(registry: SyncTableRegistry, options?: {
|
|
15
|
-
functionSchema?: string;
|
|
16
|
-
}): string;
|
|
17
|
-
export declare function installPlpgsqlBatchFunction<TRegistry extends SyncTableRegistry>(db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>, registry: TRegistry, options?: {
|
|
18
|
-
functionSchema?: string;
|
|
19
|
-
}): Promise<void>;
|
|
38
|
+
export declare function expectedApplyFingerprint(registry: SyncTableRegistry, options?: ApplyFunctionRenderOptions): string;
|
|
39
|
+
export declare function buildPlpgsqlBatchFunctionDdl(registry: SyncTableRegistry, options?: ApplyFunctionRenderOptions): string;
|
|
40
|
+
export declare function installPlpgsqlBatchFunction<TRegistry extends SyncTableRegistry>(db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>, registry: TRegistry, options?: ApplyFunctionRenderOptions): Promise<void>;
|
|
20
41
|
export declare function verifyRlsAuthHelpers<TRegistry extends SyncTableRegistry>(db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>): Promise<void>;
|
|
21
42
|
/**
|
|
22
43
|
* A conflict the applier rejected under `reject-if-stale` (ADR-0015): either a **stale** write (the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plpgsql-apply.d.ts","sourceRoot":"","sources":["../../src/mutations/plpgsql-apply.ts"],"names":[],"mappings":"AACA,OAAO,EAAmC,KAAK,eAAe,EAAE,KAAK,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAGnH,OAAO,
|
|
1
|
+
{"version":3,"file":"plpgsql-apply.d.ts","sourceRoot":"","sources":["../../src/mutations/plpgsql-apply.ts"],"names":[],"mappings":"AACA,OAAO,EAAmC,KAAK,eAAe,EAAE,KAAK,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAGnH,OAAO,EASL,KAAK,oBAAoB,EAEzB,KAAK,iBAAiB,EAEtB,KAAK,iBAAiB,EACvB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AA+ajD;;;;GAIG;AACH,MAAM,WAAW,0BAA0B;IACzC,kGAAkG;IAClG,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;;;OAKG;IACH,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACpC;AAKD;;;;;;;;;GASG;AACH,wBAAgB,0BAA0B,CAAC,cAAc,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAmBjG;AA2VD;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,iBAAiB,EAC3B,OAAO,GAAE,0BAA+B,GACvC,MAAM,CAER;AAED,wBAAgB,4BAA4B,CAC1C,QAAQ,EAAE,iBAAiB,EAC3B,OAAO,GAAE,0BAA+B,GACvC,MAAM,CAUR;AAED,wBAAsB,2BAA2B,CAAC,SAAS,SAAS,iBAAiB,EACnF,EAAE,EAAE,eAAe,CAAC,gBAAgB,EAAE,iBAAiB,CAAC,SAAS,CAAC,CAAC,EACnE,QAAQ,EAAE,SAAS,EACnB,OAAO,GAAE,0BAA+B,GACvC,OAAO,CAAC,IAAI,CAAC,CAGf;AAMD,wBAAsB,oBAAoB,CAAC,SAAS,SAAS,iBAAiB,EAC5E,EAAE,EAAE,eAAe,CAAC,gBAAgB,EAAE,iBAAiB,CAAC,SAAS,CAAC,CAAC,GAClE,OAAO,CAAC,IAAI,CAAC,CAef;AAED;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,oBAAoB,EAAE,MAAM,GAAG,IAAI,CAAC;CACrC;AAQD,wBAAsB,mBAAmB,CACvC,EAAE,EAAE,iBAAiB,EACrB,KAAK,EAAE,oBAAoB,EAC3B,WAAW,EAAE,MAAM,EACnB,UAAU,EAAE,OAAO,EACnB,UAAU,EAAE,OAAO,EACnB,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAKnC,mBAAmB,EAAE,MAAM,EAC3B,OAAO,GAAE;IACP,cAAc,CAAC,EAAE,MAAM,CAAC;CACpB,GACL,OAAO,CAAC,gBAAgB,EAAE,CAAC,CA4B7B"}
|
|
@@ -14,7 +14,7 @@ export type StartupVerificationMode = "in-process" | "deploy-time";
|
|
|
14
14
|
export declare const batchMutationPaths: readonly ["/api/mutations"];
|
|
15
15
|
/** The authoritative (pessimistic) write endpoint (ADR-0022 §3): one atomic write-unit per POST. */
|
|
16
16
|
export declare const authoritativeMutationPaths: readonly ["/api/mutations/unit"];
|
|
17
|
-
export declare function createMutationHandler<TRegistry extends SyncTableRegistry>(db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>, registry: TRegistry, operationsLogConfig: OperationsLogConfig, operationsLogReady: Promise<void>, resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null, startupVerification?: StartupVerificationMode, logTimings?: boolean): {
|
|
17
|
+
export declare function createMutationHandler<TRegistry extends SyncTableRegistry>(db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>, registry: TRegistry, operationsLogConfig: OperationsLogConfig, operationsLogReady: Promise<void>, resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null, startupVerification?: StartupVerificationMode, logTimings?: boolean, applyFunctionGrantExecuteTo?: readonly string[], applyFunctionSchema?: string): {
|
|
18
18
|
batch: FetchHandler;
|
|
19
19
|
authoritative: FetchHandler;
|
|
20
20
|
};
|
|
@@ -31,6 +31,12 @@ export declare function createMutationHandler<TRegistry extends SyncTableRegistr
|
|
|
31
31
|
* message keyed by SQLSTATE — never the raw message/detail/hint. Full detail stays in the operations log.
|
|
32
32
|
*/
|
|
33
33
|
export declare function toPublicRejectionReason(error: unknown): string;
|
|
34
|
+
/**
|
|
35
|
+
* The server-managed payload keys a mutation must not carry — the 400 guard (see
|
|
36
|
+
* {@link getGuardedManagedFields} for what counts as managed per operation, notably that a create-only
|
|
37
|
+
* managed field is guarded on update too). Exported for direct unit coverage.
|
|
38
|
+
*/
|
|
39
|
+
export declare function findManagedFieldViolations(entry: SyncTableEntry, mutationKind: BatchMutationRequest["mutations"][number]["kind"], payload: unknown): string[];
|
|
34
40
|
/**
|
|
35
41
|
* Warn — **once** per (table, key) per process — when a mutation payload carries a key the apply path
|
|
36
42
|
* will **silently drop**: a key that is neither a writable (projected) column, a server-managed field,
|
|
@@ -50,6 +56,13 @@ export declare function toPublicRejectionReason(error: unknown): string;
|
|
|
50
56
|
* Exported for direct unit coverage.
|
|
51
57
|
*/
|
|
52
58
|
export declare function warnOnSilentlyDroppedPayloadKeys(entry: SyncTableEntry, tableName: string, mutationKind: BatchMutationRequest["mutations"][number]["kind"], payload: unknown): void;
|
|
59
|
+
/**
|
|
60
|
+
* Defense in depth behind the 400 guard: strip every server-owned key from each payload before apply, so
|
|
61
|
+
* a caller that reaches this code path without the request-level check (or a key spelled as the DB column
|
|
62
|
+
* name rather than the property key) still cannot set a managed or projected-away column. Exported for
|
|
63
|
+
* direct unit coverage.
|
|
64
|
+
*/
|
|
65
|
+
export declare function sanitizeRestrictedFields(batch: BatchMutationRequest, registry: SyncTableRegistry): BatchMutationRequest;
|
|
53
66
|
/**
|
|
54
67
|
* The zod schema used to validate a `create` payload. Managed-on-create fields (`authUid` /
|
|
55
68
|
* `nowMicroseconds`) are stamped by the server AFTER validation, so the client correctly omits them —
|
|
@@ -62,4 +75,17 @@ export declare function buildCreateValidationSchema(entry: SyncTableEntry): impo
|
|
|
62
75
|
date: true;
|
|
63
76
|
bigint: true;
|
|
64
77
|
}>;
|
|
78
|
+
/**
|
|
79
|
+
* The zod schema used to validate an `update` payload: the insert schema made `partial()` (an update is a
|
|
80
|
+
* patch — only the sent keys are validated), minus every server-managed key. This is the update-side
|
|
81
|
+
* counterpart of {@link buildCreateValidationSchema}: a field managed on update is stamped by the server,
|
|
82
|
+
* and a **create-only** managed field is inert on update (the generated apply function omits it from the
|
|
83
|
+
* UPDATE SET candidates), so neither is a settable key of an update payload. Both are already
|
|
84
|
+
* 400-rejected by {@link findManagedFieldViolations}; omitting them keeps the schema an accurate
|
|
85
|
+
* statement of what an update may carry.
|
|
86
|
+
*/
|
|
87
|
+
export declare function buildUpdateValidationSchema(entry: SyncTableEntry): import("zod").ZodObject<{}, {
|
|
88
|
+
out: {};
|
|
89
|
+
in: {};
|
|
90
|
+
}>;
|
|
65
91
|
//# sourceMappingURL=route.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../src/mutations/route.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAI7E,OAAO,KAAK,EAEV,oBAAoB,EACpB,SAAS,
|
|
1
|
+
{"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../src/mutations/route.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAI7E,OAAO,KAAK,EAEV,oBAAoB,EACpB,SAAS,EAGT,iBAAiB,EACjB,cAAc,EACd,iBAAiB,EAClB,MAAM,sBAAsB,CAAC;AAU9B,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAEnE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAY9C;;;;;;;GAOG;AACH,MAAM,MAAM,uBAAuB,GAAG,YAAY,GAAG,aAAa,CAAC;AAUnE,eAAO,MAAM,kBAAkB,YAAI,gBAAgB,CAAU,CAAC;AAC9D,oGAAoG;AACpG,eAAO,MAAM,0BAA0B,YAAI,qBAAqB,CAAU,CAAC;AAE3E,wBAAgB,qBAAqB,CAAC,SAAS,SAAS,iBAAiB,EACvE,EAAE,EAAE,eAAe,CAAC,gBAAgB,EAAE,iBAAiB,CAAC,SAAS,CAAC,CAAC,EACnE,QAAQ,EAAE,SAAS,EACnB,mBAAmB,EAAE,mBAAmB,EACxC,kBAAkB,EAAE,OAAO,CAAC,IAAI,CAAC,EACjC,iBAAiB,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,SAAS,GAAG,IAAI,EACtF,mBAAmB,GAAE,uBAAsC,EAC3D,UAAU,UAAQ,EAGlB,2BAA2B,GAAE,SAAS,MAAM,EAAO,EAKnD,mBAAmB,CAAC,EAAE,MAAM,GAC3B;IAAE,KAAK,EAAE,YAAY,CAAC;IAAC,aAAa,EAAE,YAAY,CAAA;CAAE,CAiqBtD;AAqCD;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAmD9D;AAoDD;;;;GAIG;AACH,wBAAgB,0BAA0B,CACxC,KAAK,EAAE,cAAc,EACrB,YAAY,EAAE,oBAAoB,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,EAC/D,OAAO,EAAE,OAAO,GACf,MAAM,EAAE,CAYV;AAWD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,gCAAgC,CAC9C,KAAK,EAAE,cAAc,EACrB,SAAS,EAAE,MAAM,EACjB,YAAY,EAAE,oBAAoB,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,EAC/D,OAAO,EAAE,OAAO,GACf,IAAI,CA0DN;AA2BD;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,KAAK,EAAE,oBAAoB,EAC3B,QAAQ,EAAE,iBAAiB,GAC1B,oBAAoB,CAsCtB;AAED;;;;;;;GAOG;AACH,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,cAAc;;;GAYhE;AAED;;;;;;;;GAQG;AACH,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,cAAc;;;GAUhE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pgxsinkit/server",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.6",
|
|
4
4
|
"keywords": [
|
|
5
5
|
"tanstack-intent"
|
|
6
6
|
],
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"build": "bun --cwd ../.. run build:public-packages"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@pgxsinkit/contracts": "0.2.
|
|
34
|
+
"@pgxsinkit/contracts": "0.2.6"
|
|
35
35
|
},
|
|
36
36
|
"peerDependencies": {
|
|
37
37
|
"drizzle-orm": "1.0.0-rc.4"
|
|
@@ -2,16 +2,20 @@
|
|
|
2
2
|
name: deploying
|
|
3
3
|
description: >-
|
|
4
4
|
Load when deploying the @pgxsinkit/server write API and Electric shape proxy onto Bun, Deno, Supabase
|
|
5
|
-
Edge Functions, or Cloudflare Workers. Covers the runtime-portable fetch handler, the three
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
timeout above Electric's ~25s long-poll, and
|
|
10
|
-
|
|
5
|
+
Edge Functions, or Cloudflare Workers. Covers the runtime-portable fetch handler, the three steps a
|
|
6
|
+
non-Bun edge runtime needs (bundle for Deno with node: builtins, strip the function-name path prefix,
|
|
7
|
+
resolve claims in resolveAuthClaims), the deny-by-default apply-function ACL and --grant-execute-to
|
|
8
|
+
(ADR-0054), splitting write and sync into two functions, setting the worker
|
|
9
|
+
timeout above Electric's ~25s long-poll, and cache-control:no-store on a same-origin shape proxy. Also
|
|
10
|
+
covers the Event lane (ADR-0053): the auto-mounted /api/events route, the eventGate hook, the pgmq
|
|
11
|
+
prerequisite and pgxsinkit-generate --events queue DDL, and the consumer runner (defineEventConsumer) as a
|
|
12
|
+
long-lived Bun process never deployed serverless — plus its bounded drainOnce mode for platforms with no
|
|
13
|
+
long-lived compute (scheduled invocation + onEventsEnqueued nudge). Load before deploying the server or
|
|
14
|
+
running an event consumer.
|
|
11
15
|
metadata:
|
|
12
16
|
type: task
|
|
13
17
|
library: "@pgxsinkit/server"
|
|
14
|
-
library_version: "0.2.
|
|
18
|
+
library_version: "0.2.6"
|
|
15
19
|
source: https://pgxsinkit.github.io/start/deploying-the-server/
|
|
16
20
|
---
|
|
17
21
|
|
|
@@ -81,6 +85,46 @@ unfingerprinted** function (no comment) is also refused; an **old-signature** fu
|
|
|
81
85
|
resolution (undefined function). Regenerate + apply the sync-function migration to fix it, and run
|
|
82
86
|
`pgxsinkit-generate --check` in CI to catch the drift before deploy.
|
|
83
87
|
|
|
88
|
+
## The apply function is deny-by-default: name your server's DB role (ADR-0054)
|
|
89
|
+
|
|
90
|
+
The apply function takes `p_user_claims` and **trusts them** — it copies them into `request.jwt.claims`
|
|
91
|
+
and switches `role` before running RLS-governed DML. That is correct for your server (which passes claims
|
|
92
|
+
it VERIFIED) and catastrophic for anyone else, who would simply choose their own. So the artifact is
|
|
93
|
+
**deny-by-default**: right after `CREATE`, it `REVOKE`s EXECUTE from `PUBLIC` and (guarded on role
|
|
94
|
+
existence) from `anon`/`authenticated`/`service_role`, then `GRANT`s only to roles you name:
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
bun run pgxsinkit-generate --registry ./sync-registry.ts --export registry \
|
|
98
|
+
--project-dir ./db --config drizzle.config.ts --name sync_artifact \
|
|
99
|
+
--grant-execute-to app_writer # repeatable, or comma-separated
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
- **Default is owner-only** (`[]`). If your server connects as the function's **owner** (the role that
|
|
103
|
+
applies the migrations) or as a **superuser**, you do not need the flag — most deployments do not.
|
|
104
|
+
- **Name only SERVER roles.** A granted role can forge any claims it likes; that is by design (the server
|
|
105
|
+
is the component trusted to verify them), which makes the grant list **the write path's entire trust
|
|
106
|
+
boundary**. Never grant `anon`, `authenticated`, `service_role`, or any other client-facing role.
|
|
107
|
+
- **It is part of the artifact fingerprint**, so pass the SAME roles three places or every write fails
|
|
108
|
+
`PXS01`: the generate command, the CI `--check` command, and
|
|
109
|
+
`createSyncServer({ applyFunctionGrantExecuteTo: ["app_writer"] })`.
|
|
110
|
+
- **The revokes are re-emitted on every install** — the artifact begins with `DROP FUNCTION`, so a fresh
|
|
111
|
+
creation re-inherits Postgres's PUBLIC default and Supabase's `ALTER DEFAULT PRIVILEGES … TO anon,
|
|
112
|
+
authenticated, service_role`. A hand-hardened function would silently un-harden itself; this converges.
|
|
113
|
+
- **Grantees the toolkit cannot name are revoked too.** After the named revokes, the artifact enumerates
|
|
114
|
+
the installed function's real grantees (`aclexplode(pg_proc.proacl)`) and revokes `EXECUTE` from every
|
|
115
|
+
one that is neither the owner nor on the grant list. Your OWN `ALTER DEFAULT PRIVILEGES … GRANT ALL ON
|
|
116
|
+
FUNCTIONS TO <role>` re-grants at the `CREATE` inside every install exactly like Supabase's does, so
|
|
117
|
+
without the enumeration such a role would survive every regenerate. End state: owner + your list.
|
|
118
|
+
- **Everyone regenerates once.** The ACL moved the fingerprint, so upgrading `@pgxsinkit/server` means
|
|
119
|
+
re-running the generate command (and `--utilities`, which hardens `pgxsinkit_clock_us()` the same way,
|
|
120
|
+
keeping its grants to the Supabase trio — a column DEFAULT calling the clock runs as the writing role).
|
|
121
|
+
|
|
122
|
+
**PostgREST is not required, and omitting it is good deployment guidance.** pgxsinkit needs no PostgREST;
|
|
123
|
+
the board stack deliberately omits it, which removes the `/rest/v1/rpc/*` surface that would otherwise
|
|
124
|
+
expose every `public` function over HTTP. But do not treat that as the control: the ACL is, and it holds
|
|
125
|
+
under every topology (lateral movement from a role membership needs no HTTP surface at all, and Studio's
|
|
126
|
+
table editor wants PostgREST back). Ship the grant list right; treat "no PostgREST" as defence in depth.
|
|
127
|
+
|
|
84
128
|
**Order the utilities migration first.** The generated apply function and the `clockMicrosecondsSql`
|
|
85
129
|
column DEFAULTs both **call** `public.pgxsinkit_clock_us()` — the canonical microsecond clock installed by
|
|
86
130
|
the **utilities migration** (`renderPgxsinkitUtilitiesMigration()`, or the generate CLI's `--utilities`
|
|
@@ -110,6 +154,128 @@ createSyncServer({
|
|
|
110
154
|
gate). Pair it with warming the JWT/JWKS verify at module scope so the first verify does not pay a cold
|
|
111
155
|
key fetch.
|
|
112
156
|
|
|
157
|
+
## The Event lane: an auto-mounted route, deploy-time queues, and a runner you host (ADR-0053)
|
|
158
|
+
|
|
159
|
+
If your registry declares `streams` (see the `registry-authoring` skill, `@pgxsinkit/contracts`), the server
|
|
160
|
+
gains a **second lane** beside the sync rail. Three deployment obligations, and one of them is a process.
|
|
161
|
+
|
|
162
|
+
**1. The route mounts itself.** `createSyncServer` registers `POST /api/events` **only** when the registry
|
|
163
|
+
registers at least one Event stream (no streams → the path stays a 404). Nothing is probed or provisioned at
|
|
164
|
+
startup, so the zero-startup-query posture is intact and the edge deployment story is unchanged — the same
|
|
165
|
+
function-name prefix strip that serves `/api/mutations` serves `/api/events`, because they are siblings under
|
|
166
|
+
`/api/`. Two options are yours:
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
createSyncServer({
|
|
170
|
+
registry,
|
|
171
|
+
db,
|
|
172
|
+
resolveAuthClaims,
|
|
173
|
+
// Consent/entitlement refusal, keyed by Event-stream name. ABSENT = every well-formed event is allowed.
|
|
174
|
+
// Called after the payload validated and identity resolved, BEFORE anything is enqueued; a refusal is a
|
|
175
|
+
// per-event `refused` verdict (terminal — the client deletes it and surfaces it on its report).
|
|
176
|
+
eventGate: ({ stream, identity }) => (stream === "issue_viewed" ? consentedViewers.has(identity["viewerId"]!) : true),
|
|
177
|
+
// Defaults to the shipped pgmq backend over this server's own `db`, which is what makes an enqueue join
|
|
178
|
+
// the endpoint's transaction. Override only for another backend or a test fake.
|
|
179
|
+
eventQueue: createPgmqEventQueue({ db }),
|
|
180
|
+
});
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
The gate is called **per event**, not per stream × batch (a consent decision may legitimately depend on the
|
|
184
|
+
payload); the claims are constant across a batch, so memoize on them if the hook consults a store. A gate
|
|
185
|
+
that **throws** fails the whole batch retryably (500, nothing enqueued) — a gate that cannot decide is never
|
|
186
|
+
read as "allow". Any stream your registry declares whose identity comes from claims makes the endpoint
|
|
187
|
+
require verified claims: an unauthenticated request is a batch 401.
|
|
188
|
+
|
|
189
|
+
**Request-shape limits are toolkit constants, enforced server-side independently of any client tuning**:
|
|
190
|
+
1000 events per batch, 64 KiB serialized payload per event, 4 MiB request body. A batch-count/body violation
|
|
191
|
+
is a 413 and a framing failure is a 400 — both reachable only from a non-library caller or under skew, since
|
|
192
|
+
the library validates at append and builds the envelopes. A single oversized payload is a per-event
|
|
193
|
+
`rejected` instead, so one bad row cannot wedge a whole Outbox. When the queue is unavailable the endpoint
|
|
194
|
+
returns **503 + `Retry-After` and enqueues NOTHING** — a batch is atomic, and the server never buffers on the
|
|
195
|
+
queue's behalf.
|
|
196
|
+
|
|
197
|
+
**2. pgmq is a prerequisite, and the queues are deploy-time DDL.** One queue per Event stream
|
|
198
|
+
(`pgxsinkit_events_<stream>`), so a poison event in one stream cannot head-of-line-block another. Generate
|
|
199
|
+
the migration and apply it through your normal flow — never at runtime, because the endpoint may enqueue long
|
|
200
|
+
before any runner first starts:
|
|
201
|
+
|
|
202
|
+
```bash
|
|
203
|
+
bun run pgxsinkit-generate --events --registry ./sync-registry.ts --export registry \
|
|
204
|
+
--project-dir ./db --config drizzle.config.ts --name event_lane_artifact
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
It gets its own migration folder (queues are provisioned independently of the apply function) and carries a
|
|
208
|
+
fingerprint of the registry's stream set. **Add `--events --check` to CI beside the apply-function
|
|
209
|
+
`--check`**: adding or removing a stream without regenerating then fails before deploy, instead of at the
|
|
210
|
+
first enqueue onto a queue that does not exist. (A registry with no streams passes `--check` trivially —
|
|
211
|
+
nothing to provision is not drift.)
|
|
212
|
+
|
|
213
|
+
**3. The consumer runner is a LONG-LIVED process — do not deploy it serverless.** `defineEventConsumer`
|
|
214
|
+
returns a `start()`/`stop()` handle; your app runs it in its own Bun process, deliberately apart from
|
|
215
|
+
`createSyncServer`'s serverless posture. There is no CLI entrypoint, no supervisor and no signal handling
|
|
216
|
+
inside it — the app owns its lifecycle:
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
const consumer = defineEventConsumer({
|
|
220
|
+
registry,
|
|
221
|
+
queue: createPgmqEventQueue({ db }), // required — the runner is backend-agnostic by construction
|
|
222
|
+
streams: ["issue_viewed"], // optional: the knob that splits streams across processes (unknown name → throws)
|
|
223
|
+
callback: async ({ stream, events }) => {
|
|
224
|
+
await db.transaction(async (tx) => {
|
|
225
|
+
await tx.insert(viewArchive).values(events.map(toRow)).onConflictDoNothing({ target: viewArchive.eventId });
|
|
226
|
+
});
|
|
227
|
+
},
|
|
228
|
+
onDeadLetter: (report) => alert(report), // the runner ALSO warn-logs every one, unconditionally
|
|
229
|
+
});
|
|
230
|
+
consumer.start();
|
|
231
|
+
process.on("SIGTERM", () => void consumer.stop()); // graceful: no new reads, in-flight callbacks awaited
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
- **The callback MUST be idempotent.** Delivery is at-least-once; the blessed pattern is deduping on
|
|
235
|
+
`eventId` against your own durable store (`ON CONFLICT (event_id) DO NOTHING`), which composes to
|
|
236
|
+
effectively-exactly-once. Returning acks the sub-batch; **throwing retries it**.
|
|
237
|
+
- **Order is batch-internal only.** Events arrive in append order within one delivered sub-batch; across
|
|
238
|
+
sub-batches there is no promise (a retried one is redelivered after its successors, and `concurrency > 1`
|
|
239
|
+
runs them in parallel). Re-sort from your own archive on `occurredAtUs` if you need temporal order.
|
|
240
|
+
- **Pacing is internal** — adaptive interval polling (immediate re-read after a non-empty read; consecutive
|
|
241
|
+
empty reads grow the wait from ~250 ms toward a ~5 s idle ceiling). Floor/ceiling/factor are tuning, not
|
|
242
|
+
contract; there is no LISTEN/NOTIFY, deliberately (Bun's `SQL` has none, and a held listening connection is
|
|
243
|
+
exactly what a transaction pooler will not give you).
|
|
244
|
+
- **Leases ARE renewed internally; a thrown sub-batch's is deliberately left to lapse.** One read makes the
|
|
245
|
+
whole batch invisible, so while the runner works through it it extends every unsettled receipt (the one in
|
|
246
|
+
flight plus the ones queued behind it) every `visibilityTimeoutSeconds / 2` — ten slow callbacks can no
|
|
247
|
+
longer let message 10 resurface while message 1 is still running. So the timeout is NOT a batch budget: it
|
|
248
|
+
is the **redelivery delay** of a sub-batch whose callback threw (which stops being renewed at once — that
|
|
249
|
+
lapse IS the retry pacing) and the crash-recovery bound. Size it above ONE callback's worst case. Renewal
|
|
250
|
+
is best-effort: a failed renewal warns and the loop continues, because redelivery is the fallback anyway.
|
|
251
|
+
- After `maxAttempts` (default 5) a sub-batch **dead-letters into pgmq's own per-queue archive** — there is
|
|
252
|
+
no library-owned DLQ table. Requeue is a deliberate act (`requeueDeadLetter`), never automatic.
|
|
253
|
+
- One runner hosts many streams (independent loops each), so a small deployment runs one process and a large
|
|
254
|
+
one splits `streams` across processes. Construction is query-free: the first statement is the first poll.
|
|
255
|
+
|
|
256
|
+
**3b. No long-lived compute at all? `drainOnce()` on a schedule.** On a platform whose only server-side unit
|
|
257
|
+
is a per-request function (managed Supabase, say), there is nowhere to put `start()` — and the queue would
|
|
258
|
+
never drain. The SAME handle answers a bounded pass instead; everything else (delivery path, renewal, retry,
|
|
259
|
+
dead-lettering) is identical code, which is possible because pacing was never contract:
|
|
260
|
+
|
|
261
|
+
```ts
|
|
262
|
+
// In the scheduled function. Query-free construction ⇒ building one per invocation costs nothing.
|
|
263
|
+
const consumer = defineEventConsumer({ registry, queue: createPgmqEventQueue({ db }), callback });
|
|
264
|
+
const { delivered, deadLettered, empty } = await consumer.drainOnce({ budgetMs: 20_000 });
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
- **`budgetMs` goes UNDER the platform's invocation cap, with head-room for one callback** — it is checked
|
|
268
|
+
between sub-batches, never inside one, so a running callback is always awaited and acked first.
|
|
269
|
+
- **`empty: false` = "there is more"** (budget cut it short, or a read faulted): invoke again rather than
|
|
270
|
+
waiting out the period. A sub-batch whose callback threw near the edge redelivers next pass — at-least-once.
|
|
271
|
+
- **Overlapping invocations are safe** (visibility timeouts arbitrate, as with two runners). Two passes on
|
|
272
|
+
ONE handle are not: `drainOnce` beside a live `start()`, beside another pass, or after `stop()`, throws.
|
|
273
|
+
- **Pair it with the ingest nudge for latency, never for delivery:**
|
|
274
|
+
`createSyncServer({ onEventsEnqueued: ({ streams }) => void fetch(drainUrl, …) })` fires after a
|
|
275
|
+
successful enqueue with the request's deduplicated stream names, fire-and-forget (a throw is caught and
|
|
276
|
+
warn-logged). **The schedule is the guarantee**; a lost nudge costs only time. Keep the long-lived runner
|
|
277
|
+
wherever you can run one — it is still the primary mode.
|
|
278
|
+
|
|
113
279
|
## Measure before tuning: `logTimings`
|
|
114
280
|
|
|
115
281
|
`createSyncServer({ logTimings: true })` (default off) emits ONE compact `[pgxsinkit-timing]` JSON line
|
|
@@ -154,9 +320,31 @@ detail live in the `operating` skill.
|
|
|
154
320
|
function migration. The apply function verifies itself and **refuses to serve writes** (SQLSTATE
|
|
155
321
|
`PXS01`) on a mismatch — enforcement is always-on, there is no override; run `pgxsinkit-generate --check`
|
|
156
322
|
in CI to catch it before deploy.
|
|
323
|
+
- Passing `--grant-execute-to` to the generate command but not to CI's `--check` and
|
|
324
|
+
`createSyncServer({ applyFunctionGrantExecuteTo })` — the ACL is inside the fingerprinted body, so the
|
|
325
|
+
three lists must agree or every write fails `PXS01`. (The list is order-insensitive: the renderer sorts
|
|
326
|
+
it, so the same roles in any order are one artifact.)
|
|
327
|
+
- The same mistake with `--function-schema`: generating into a schema without
|
|
328
|
+
`createSyncServer({ applyFunctionSchema: "<schema>" })`. That option is BOTH halves — the fingerprint
|
|
329
|
+
input and the qualification of the call the server makes — so without it the server calls
|
|
330
|
+
`pgxsinkit_apply_mutations` unqualified and either finds nothing (`42883`) or finds a `search_path`
|
|
331
|
+
namesake and fails `PXS01`. Set the flag and the option to the same schema, or neither.
|
|
332
|
+
- Granting EXECUTE on the apply function to `authenticated` (or any client-facing role) to "make writes
|
|
333
|
+
work". That re-creates the forged-claims impersonation the deny-by-default ACL exists to close: name the
|
|
334
|
+
role your SERVER connects as, or connect as the owner and grant nobody.
|
|
157
335
|
- Ordering the utilities migration after the schema/apply-function migration, or omitting it — the apply
|
|
158
336
|
function and column DEFAULTs call `public.pgxsinkit_clock_us()`, so migrate fails with an
|
|
159
337
|
undefined-function error. Generate it first (`--utilities`).
|
|
338
|
+
- Deploying the event **consumer runner** as a serverless function or a route on the sync server. It is a
|
|
339
|
+
long-lived polling process by design; a per-request worker would poll once and die. If the platform has no
|
|
340
|
+
long-lived compute, use `drainOnce()` on a schedule — never `start()` in a request handler.
|
|
341
|
+
- Treating the `onEventsEnqueued` nudge as the delivery mechanism. It is fire-and-forget latency relief; the
|
|
342
|
+
scheduled sweep is what guarantees the queue drains.
|
|
343
|
+
- Registering an Event stream without generating + applying the `--events` migration (the endpoint then
|
|
344
|
+
enqueues onto a queue that does not exist), or leaving `--events --check` out of CI.
|
|
345
|
+
- A consumer callback that is not idempotent. Delivery is at-least-once; dedupe on `eventId`.
|
|
346
|
+
- A `visibilityTimeoutSeconds` below a SINGLE callback's worst-case duration — renewal runs at half of it, so
|
|
347
|
+
a callback slower than that window can still be redelivered while the first invocation is running.
|
|
160
348
|
- Shipping toolkit source to Deno without bundling, or leaving builtins un-prefixed (not `node:*`).
|
|
161
349
|
- Forgetting to strip the function-name prefix, so `/write/api/mutations` 404s.
|
|
162
350
|
- Verifying the JWT only at the gateway instead of in `resolveAuthClaims` (non-portable).
|