@pgxsinkit/server 0.1.32 → 0.1.36
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/README.md +12 -0
- package/bin/pgxsinkit-generate.mjs +25 -0
- package/dist/cli/generate.d.ts +14 -2
- package/dist/cli/generate.d.ts.map +1 -1
- package/dist/electric-proxy.d.ts +30 -2
- package/dist/electric-proxy.d.ts.map +1 -1
- package/dist/index.d.ts +56 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3935 -936
- package/dist/index.js.map +40 -25
- package/dist/migrations/utilities.d.ts +13 -0
- package/dist/migrations/utilities.d.ts.map +1 -0
- package/dist/mutations/plpgsql-apply.d.ts +36 -0
- package/dist/mutations/plpgsql-apply.d.ts.map +1 -0
- package/dist/mutations/route.d.ts +64 -0
- package/dist/mutations/route.d.ts.map +1 -0
- package/dist/mutations/types.d.ts +4 -0
- package/dist/mutations/types.d.ts.map +1 -0
- package/dist/operations-log/ddl.d.ts +6 -0
- package/dist/operations-log/ddl.d.ts.map +1 -1
- package/dist/operations-log/schema.d.ts +2 -32
- package/dist/operations-log/schema.d.ts.map +1 -1
- package/dist/operations-log/types.d.ts +1 -5
- package/dist/operations-log/types.d.ts.map +1 -1
- package/dist/operations-log/writer.d.ts.map +1 -1
- package/dist/router.d.ts +22 -0
- package/dist/router.d.ts.map +1 -0
- package/dist/sql-state.d.ts +23 -0
- package/dist/sql-state.d.ts.map +1 -0
- package/package.json +11 -6
- package/skills/deploying/SKILL.md +162 -0
- package/src/cli/generate.ts +292 -21
- package/src/electric-proxy.ts +274 -42
- package/src/index.ts +146 -59
- package/src/migrations/utilities.ts +25 -0
- package/src/mutations/plpgsql-apply.ts +658 -0
- package/src/mutations/route.ts +1176 -0
- package/src/mutations/{bulk/types.ts → types.ts} +0 -2
- package/src/operations-log/ddl.ts +13 -3
- package/src/operations-log/schema.ts +9 -6
- package/src/operations-log/types.ts +1 -7
- package/src/operations-log/writer.ts +0 -2
- package/src/router.ts +109 -0
- package/src/sql-state.ts +59 -0
- package/dist/mutations/bulk/plpgsql-strategy.d.ts +0 -17
- package/dist/mutations/bulk/plpgsql-strategy.d.ts.map +0 -1
- package/dist/mutations/bulk/route.d.ts +0 -7
- package/dist/mutations/bulk/route.d.ts.map +0 -1
- package/dist/mutations/bulk/types.d.ts +0 -5
- package/dist/mutations/bulk/types.d.ts.map +0 -1
- package/src/mutations/bulk/plpgsql-strategy.ts +0 -370
- package/src/mutations/bulk/route.ts +0 -580
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The canonical microsecond-clock DB function `public.pgxsinkit_clock_us()` — the ONE home for the
|
|
3
|
+
* `clock_timestamp()`-epoch-microseconds semantics. Every surface (column DEFAULTs, the generated
|
|
4
|
+
* apply function's managed `nowMicroseconds` fields, the operations-log server stamp) CALLS this
|
|
5
|
+
* function; nothing inlines the expression. This migration installs it, and — because the generated
|
|
6
|
+
* apply function calls it — it MUST be the FIRST folder in any consumer's migration chain (before the
|
|
7
|
+
* schema and the sync-artifact folder).
|
|
8
|
+
*
|
|
9
|
+
* The body is composed from the single source {@link NOW_MICROSECONDS_SQL_TEXT} in @pgxsinkit/contracts
|
|
10
|
+
* (CREATE FUNCTION is the sanctioned raw-SQL case — Drizzle cannot express a PL/pgSQL/SQL function body).
|
|
11
|
+
*/
|
|
12
|
+
export declare function renderPgxsinkitUtilitiesMigration(): string;
|
|
13
|
+
//# sourceMappingURL=utilities.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utilities.d.ts","sourceRoot":"","sources":["../../src/migrations/utilities.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;GAUG;AACH,wBAAgB,iCAAiC,IAAI,MAAM,CAW1D"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type PgAsyncDatabase, type PgQueryResultHKT } from "drizzle-orm/pg-core";
|
|
2
|
+
import { type BatchMutationRequest, type RegistryRelations, type SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
3
|
+
import type { TransactionClient } from "./types";
|
|
4
|
+
/**
|
|
5
|
+
* The fingerprint the installed apply function should carry for this registry + applier codegen
|
|
6
|
+
* (ADR-0018). It is a hash of the exact generated DDL body, so it shifts on any registry-shape
|
|
7
|
+
* change AND on any change to how the applier emits SQL (e.g. a @pgxsinkit/server upgrade) — the
|
|
8
|
+
* two drift classes a bare signature check cannot see. It does NOT depend on TS-side row-filter /
|
|
9
|
+
* customWhere logic, which never enters the apply function (that shapes the read proxy, not writes).
|
|
10
|
+
*/
|
|
11
|
+
export declare function expectedApplyFingerprint(registry: SyncTableRegistry, options?: {
|
|
12
|
+
functionSchema?: string;
|
|
13
|
+
}): string;
|
|
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>;
|
|
20
|
+
export declare function verifyRlsAuthHelpers<TRegistry extends SyncTableRegistry>(db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>): Promise<void>;
|
|
21
|
+
/**
|
|
22
|
+
* A conflict the applier rejected under `reject-if-stale` (ADR-0015): either a **stale** write (the
|
|
23
|
+
* Base server version the row has since advanced past — `currentServerVersion` is the row's current
|
|
24
|
+
* version) or an UPDATE whose **target row is missing** (deleted by another writer —
|
|
25
|
+
* `currentServerVersion` is `null`, the #6 discriminator). The handler surfaces it on the
|
|
26
|
+
* `conflicted` ack.
|
|
27
|
+
*/
|
|
28
|
+
export interface MutationConflict {
|
|
29
|
+
mutationId: string;
|
|
30
|
+
tableName: string;
|
|
31
|
+
currentServerVersion: string | null;
|
|
32
|
+
}
|
|
33
|
+
export declare function executePlpgsqlBatch(tx: TransactionClient, batch: BatchMutationRequest, requestPath: string, logEnabled: boolean, rlsEnabled: boolean, userClaims: Record<string, unknown>, expectedFingerprint: string, options?: {
|
|
34
|
+
functionSchema?: string;
|
|
35
|
+
}): Promise<MutationConflict[]>;
|
|
36
|
+
//# sourceMappingURL=plpgsql-apply.d.ts.map
|
|
@@ -0,0 +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,EAOL,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EAEtB,KAAK,iBAAiB,EACvB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAigBjD;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,iBAAiB,EAC3B,OAAO,GAAE;IACP,cAAc,CAAC,EAAE,MAAM,CAAC;CACpB,GACL,MAAM,CAER;AAED,wBAAgB,4BAA4B,CAC1C,QAAQ,EAAE,iBAAiB,EAC3B,OAAO,GAAE;IACP,cAAc,CAAC,EAAE,MAAM,CAAC;CACpB,GACL,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;IACP,cAAc,CAAC,EAAE,MAAM,CAAC;CACpB,GACL,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,CA0B7B"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { PgAsyncDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core";
|
|
2
|
+
import type { BatchMutationRequest, JwtClaims, RegistryRelations, SyncTableEntry, SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
3
|
+
import type { OperationsLogConfig } from "../operations-log/types";
|
|
4
|
+
import type { FetchHandler } from "../router";
|
|
5
|
+
/**
|
|
6
|
+
* How the write path handles its remaining startup query class — the RLS auth-helper verify (ADR-0030
|
|
7
|
+
* decision 3). The apply-function drift guarantee moved into the call itself (self-verifying function),
|
|
8
|
+
* so this now governs ONLY that helper check:
|
|
9
|
+
* - `"in-process"` (default): keep today's boot-time `verifyRlsAuthHelpers` and its clear startup error.
|
|
10
|
+
* - `"deploy-time"`: skip it — the migration pipeline owns that guarantee, so a fresh (serverless)
|
|
11
|
+
* worker sends ZERO queries before the mutation transaction itself.
|
|
12
|
+
*/
|
|
13
|
+
export type StartupVerificationMode = "in-process" | "deploy-time";
|
|
14
|
+
export declare const batchMutationPaths: readonly ["/api/mutations", "/mutations"];
|
|
15
|
+
/** The authoritative (pessimistic) write endpoint (ADR-0022 §3): one atomic write-unit per POST. */
|
|
16
|
+
export declare const authoritativeMutationPaths: readonly ["/api/mutations/unit", "/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): {
|
|
18
|
+
batch: FetchHandler;
|
|
19
|
+
authoritative: FetchHandler;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Map a DB exception to a **client-safe** rejection reason for an authoritative `rejected` ack (ADR-0022 §4).
|
|
23
|
+
* The raw error text (`formatBatchExecutionError`) leaks constraint names, schema/table, the offending
|
|
24
|
+
* VALUES (potential PII), and trigger hints — and a `rejected` ack is success-path copy the app surfaces to
|
|
25
|
+
* users, so it must not echo that. Two cases:
|
|
26
|
+
*
|
|
27
|
+
* - **App-authored `RAISE`** (PL/pgSQL `RAISE EXCEPTION 'cohort is full'`, SQLSTATE `P0001` / a custom `P0…`
|
|
28
|
+
* class): the message IS the consumer's own user-facing copy — pass it through. This is the intended way
|
|
29
|
+
* to give a friendly capacity/quota message.
|
|
30
|
+
* - **Built-in integrity violations** (SQLSTATE class `23`) and everything else: return a stable generic
|
|
31
|
+
* message keyed by SQLSTATE — never the raw message/detail/hint. Full detail stays in the operations log.
|
|
32
|
+
*/
|
|
33
|
+
export declare function toPublicRejectionReason(error: unknown): string;
|
|
34
|
+
/**
|
|
35
|
+
* Warn — **once** per (table, key) per process — when a mutation payload carries a key the apply path
|
|
36
|
+
* will **silently drop**: a key that is neither a writable (projected) column, a server-managed field,
|
|
37
|
+
* nor a projected-away column that request validation already 400-rejects. The generated apply function
|
|
38
|
+
* reads only the table's PROJECTED columns from the payload jsonb, so such a key never lands — were it
|
|
39
|
+
* "applied" the write would collapse to a bare server-version (`updated_at_us`) bump. This is the clean
|
|
40
|
+
* two-case split (ADR-0022 posture docs):
|
|
41
|
+
*
|
|
42
|
+
* - **Projected-away / server-only columns** (`clientProjection.omitColumns`) sent explicitly are
|
|
43
|
+
* **400-rejected** by {@link findProjectedFieldViolations} — they are NOT silently dropped, so this
|
|
44
|
+
* helper deliberately does **not** warn for them (warning "the write still succeeds" and then
|
|
45
|
+
* rejecting was the misleading overlap the review flagged).
|
|
46
|
+
* - **Unknown non-column keys** (a typo, a stale field) are what the apply path silently ignores — those
|
|
47
|
+
* are exactly the keys this warns about, once, as a debugging aid. It is NOT an error and changes no
|
|
48
|
+
* semantics.
|
|
49
|
+
*
|
|
50
|
+
* Exported for direct unit coverage.
|
|
51
|
+
*/
|
|
52
|
+
export declare function warnOnSilentlyDroppedPayloadKeys(entry: SyncTableEntry, tableName: string, mutationKind: BatchMutationRequest["mutations"][number]["kind"], payload: unknown): void;
|
|
53
|
+
/**
|
|
54
|
+
* The zod schema used to validate a `create` payload. Managed-on-create fields (`authUid` /
|
|
55
|
+
* `nowMicroseconds`) are stamped by the server AFTER validation, so the client correctly omits them —
|
|
56
|
+
* and {@link findManagedFieldViolations} already rejects a payload that includes them. They are
|
|
57
|
+
* omitted from the insert schema so a NOT NULL managed column without a SQL DEFAULT (e.g. an `authUid`
|
|
58
|
+
* author/owner/created_by) is not falsely required. (A column carrying a DEFAULT is already optional
|
|
59
|
+
* in the drizzle insert schema; this also covers a managed column that has none.)
|
|
60
|
+
*/
|
|
61
|
+
export declare function buildCreateValidationSchema(entry: SyncTableEntry): import("drizzle-orm/zod").BuildSchema<"insert", import("drizzle-orm/pg-core").PgColumns, undefined, {
|
|
62
|
+
date: true;
|
|
63
|
+
}>;
|
|
64
|
+
//# sourceMappingURL=route.d.ts.map
|
|
@@ -0,0 +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,EAET,iBAAiB,EACjB,cAAc,EACd,iBAAiB,EAClB,MAAM,sBAAsB,CAAC;AAS9B,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAEnE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAU9C;;;;;;;GAOG;AACH,MAAM,MAAM,uBAAuB,GAAG,YAAY,GAAG,aAAa,CAAC;AAQnE,eAAO,MAAM,kBAAkB,YAAI,gBAAgB,EAAE,YAAY,CAAU,CAAC;AAC5E,oGAAoG;AACpG,eAAO,MAAM,0BAA0B,YAAI,qBAAqB,EAAE,iBAAiB,CAAU,CAAC;AAE9F,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,GACjB;IAAE,KAAK,EAAE,YAAY,CAAC;IAAC,aAAa,EAAE,YAAY,CAAA;CAAE,CAwpBtD;AAqCD;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAmD9D;AA+ED;;;;;;;;;;;;;;;;;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;AAmED;;;;;;;GAOG;AACH,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,cAAc;;GAYhE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/mutations/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;CAC/C"}
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import type { PgAsyncDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core";
|
|
2
2
|
import type { RegistryRelations, SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
3
3
|
import type { OperationsLogConfig } from "./types";
|
|
4
|
+
/**
|
|
5
|
+
* The `to_regclass` presence-probe target, derived from the real pgTable so the probe (and the
|
|
6
|
+
* warning below) track a rename of `operationsLogTable`. Exported for the integration suite that
|
|
7
|
+
* asserts the degraded no-log path against the same identity.
|
|
8
|
+
*/
|
|
9
|
+
export declare function operationsLogRegclassTarget(): string;
|
|
4
10
|
/**
|
|
5
11
|
* Ensures the operations_log table exists in the database.
|
|
6
12
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ddl.d.ts","sourceRoot":"","sources":["../../src/operations-log/ddl.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE7E,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"ddl.d.ts","sourceRoot":"","sources":["../../src/operations-log/ddl.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE7E,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAGjF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAMnD;;;;GAIG;AACH,wBAAgB,2BAA2B,IAAI,MAAM,CAEpD;AAED;;;;;;GAMG;AACH,wBAAsB,yBAAyB,CAAC,SAAS,SAAS,iBAAiB,EACjF,EAAE,EAAE,eAAe,CAAC,gBAAgB,EAAE,iBAAiB,CAAC,SAAS,CAAC,CAAC,EACnE,MAAM,EAAE,mBAAmB,GAC1B,OAAO,CAAC,OAAO,CAAC,CA0BlB"}
|
|
@@ -17,36 +17,6 @@ export declare const operationsLogTable: import("drizzle-orm/pg-core").PgTableWi
|
|
|
17
17
|
identity: undefined;
|
|
18
18
|
generated: undefined;
|
|
19
19
|
}>;
|
|
20
|
-
source: import("drizzle-orm/pg-core").PgBuildColumn<"operations_log", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgVarcharBuilder<[string, ...string[]]>>, {
|
|
21
|
-
name: string;
|
|
22
|
-
tableName: "operations_log";
|
|
23
|
-
dataType: "string";
|
|
24
|
-
data: string;
|
|
25
|
-
driverParam: string;
|
|
26
|
-
notNull: true;
|
|
27
|
-
hasDefault: false;
|
|
28
|
-
isPrimaryKey: false;
|
|
29
|
-
isAutoincrement: false;
|
|
30
|
-
hasRuntimeDefault: false;
|
|
31
|
-
enumValues: undefined;
|
|
32
|
-
identity: undefined;
|
|
33
|
-
generated: undefined;
|
|
34
|
-
}>;
|
|
35
|
-
backend: import("drizzle-orm/pg-core").PgBuildColumn<"operations_log", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgVarcharBuilder<[string, ...string[]]>>, {
|
|
36
|
-
name: string;
|
|
37
|
-
tableName: "operations_log";
|
|
38
|
-
dataType: "string";
|
|
39
|
-
data: string;
|
|
40
|
-
driverParam: string;
|
|
41
|
-
notNull: true;
|
|
42
|
-
hasDefault: false;
|
|
43
|
-
isPrimaryKey: false;
|
|
44
|
-
isAutoincrement: false;
|
|
45
|
-
hasRuntimeDefault: false;
|
|
46
|
-
enumValues: undefined;
|
|
47
|
-
identity: undefined;
|
|
48
|
-
generated: undefined;
|
|
49
|
-
}>;
|
|
50
20
|
tableName: import("drizzle-orm/pg-core").PgBuildColumn<"operations_log", import("drizzle-orm/pg-core").PgVarcharBuilder<[string, ...string[]]>, {
|
|
51
21
|
name: string;
|
|
52
22
|
tableName: "operations_log";
|
|
@@ -167,10 +137,10 @@ export declare const operationsLogTable: import("drizzle-orm/pg-core").PgTableWi
|
|
|
167
137
|
identity: undefined;
|
|
168
138
|
generated: undefined;
|
|
169
139
|
}>;
|
|
170
|
-
mutationId: import("drizzle-orm/pg-core").PgBuildColumn<"operations_log", import("drizzle-orm/pg-core").
|
|
140
|
+
mutationId: import("drizzle-orm/pg-core").PgBuildColumn<"operations_log", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
|
|
171
141
|
name: string;
|
|
172
142
|
tableName: "operations_log";
|
|
173
|
-
dataType: "string
|
|
143
|
+
dataType: "string";
|
|
174
144
|
data: string;
|
|
175
145
|
driverParam: string;
|
|
176
146
|
notNull: false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/operations-log/schema.ts"],"names":[],"mappings":"
|
|
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,14 +1,10 @@
|
|
|
1
1
|
import type { SQLWrapper } from "drizzle-orm";
|
|
2
2
|
import type { AnyPgTable } from "drizzle-orm/pg-core";
|
|
3
|
-
export type
|
|
4
|
-
export type OpsLogBackend = "bulk-plpgsql-artifact";
|
|
5
|
-
export type OpsLogStatus = "succeeded" | "validation_failed" | "not_found" | "execution_failed";
|
|
3
|
+
export type OpsLogStatus = "succeeded" | "validation_failed" | "not_found" | "execution_failed" | "conflicted";
|
|
6
4
|
export interface OperationsLogConfig {
|
|
7
5
|
enabled: boolean;
|
|
8
6
|
}
|
|
9
7
|
export interface OpsLogEntry {
|
|
10
|
-
source: OpsLogSource;
|
|
11
|
-
backend: OpsLogBackend;
|
|
12
8
|
tableName?: string | null;
|
|
13
9
|
operationKind?: "create" | "update" | "delete" | null;
|
|
14
10
|
userId?: string | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/operations-log/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEtD,MAAM,MAAM,YAAY,GAAG,
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/operations-log/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEtD,MAAM,MAAM,YAAY,GAAG,WAAW,GAAG,mBAAmB,GAAG,WAAW,GAAG,kBAAkB,GAAG,YAAY,CAAC;AAE/G,MAAM,WAAW,mBAAmB;IAClC,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,WAAW;IAC1B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,aAAa,CAAC,EAAE,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,IAAI,CAAC;IACtD,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAAC;IAC1C,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,MAAM,EAAE,YAAY,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACnE,MAAM,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK;QAC7B,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,WAAW,CAAC,OAAO,CAAC,CAAC;KACnE,CAAC;CACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writer.d.ts","sourceRoot":"","sources":["../../src/operations-log/writer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAkB7E,wBAAsB,YAAY,CAChC,QAAQ,EAAE,WAAW,EACrB,MAAM,EAAE,mBAAmB,EAC3B,KAAK,EAAE,WAAW,GACjB,OAAO,CAAC,IAAI,CAAC,
|
|
1
|
+
{"version":3,"file":"writer.d.ts","sourceRoot":"","sources":["../../src/operations-log/writer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAkB7E,wBAAsB,YAAY,CAChC,QAAQ,EAAE,WAAW,EACrB,MAAM,EAAE,mBAAmB,EAC3B,KAAK,EAAE,WAAW,GACjB,OAAO,CAAC,IAAI,CAAC,CAmBf;AAED,wBAAsB,kBAAkB,CACtC,QAAQ,EAAE,WAAW,EACrB,MAAM,EAAE,mBAAmB,EAC3B,KAAK,EAAE,WAAW,GACjB,OAAO,CAAC,IAAI,CAAC,CAMf"}
|
package/dist/router.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export type FetchHandler = (request: Request) => Response | Promise<Response>;
|
|
2
|
+
export interface CorsConfig {
|
|
3
|
+
origins: string[];
|
|
4
|
+
allowMethods: string[];
|
|
5
|
+
allowHeaders: string[];
|
|
6
|
+
}
|
|
7
|
+
/** A CORS scope is matched either by exact pathname or by pathname prefix (e.g. `/api/`). */
|
|
8
|
+
export type CorsScope = {
|
|
9
|
+
exact: string;
|
|
10
|
+
} | {
|
|
11
|
+
prefix: string;
|
|
12
|
+
};
|
|
13
|
+
export type RouterErrorHandler = (error: unknown, request: Request) => Response | Promise<Response>;
|
|
14
|
+
export declare class FetchRouter {
|
|
15
|
+
#private;
|
|
16
|
+
get(path: string, handler: FetchHandler): void;
|
|
17
|
+
post(path: string, handler: FetchHandler): void;
|
|
18
|
+
setCors(config: CorsConfig, scopes: CorsScope[]): void;
|
|
19
|
+
setErrorHandler(handler: RouterErrorHandler): void;
|
|
20
|
+
readonly fetch: (request: Request) => Promise<Response>;
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=router.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,YAAY,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AAE9E,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,YAAY,EAAE,MAAM,EAAE,CAAC;CACxB;AAED,6FAA6F;AAC7F,MAAM,MAAM,SAAS,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAE/D,MAAM,MAAM,kBAAkB,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,KAAK,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEpG,qBAAa,WAAW;;IAMtB,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,IAAI,CAE7C;IAED,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,IAAI,CAE9C;IAED,OAAO,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAOrD;IAED,eAAe,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI,CAEjD;IAED,QAAQ,CAAC,KAAK,YAAmB,OAAO,KAAG,OAAO,CAAC,QAAQ,CAAC,CAyB1D;CAqCH"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read the Postgres `SQLSTATE` (the five-character error class, e.g. `"23505"` unique_violation) off a
|
|
3
|
+
* thrown database error.
|
|
4
|
+
*
|
|
5
|
+
* **Why this helper exists — the bun-sql gotcha.** Bun's built-in `SQL`/`sql` driver (what pgxsinkit and
|
|
6
|
+
* its consumers run against Postgres) surfaces the server's SQLSTATE on the error's **`errno`** property.
|
|
7
|
+
* Its **`code`** property is bun's own generic string (`"ERR_POSTGRES_SERVER_ERROR"`), NOT the SQLSTATE —
|
|
8
|
+
* so the intuitive `error.code` read (which worked under `postgres.js` / `pg`, where `code` carried the
|
|
9
|
+
* SQLSTATE) silently returns the wrong thing under bun-sql. Consumers reaching for a stable, driver-agnostic
|
|
10
|
+
* SQLSTATE (to map `23505`→"already exists", `P0001`→a raised app rule, etc.) kept re-deriving this by hand;
|
|
11
|
+
* this is the one canonical extraction.
|
|
12
|
+
*
|
|
13
|
+
* Resolution order, returning the first well-formed SQLSTATE found:
|
|
14
|
+
* 1. `errno` on the error (bun-sql),
|
|
15
|
+
* 2. `code` on the error (postgres.js / node-postgres, and any driver that follows that convention),
|
|
16
|
+
* 3. the same two properties walked down the `cause` chain (a wrapped/re-thrown error).
|
|
17
|
+
*
|
|
18
|
+
* A "well-formed" SQLSTATE is exactly five characters of `[0-9A-Z]` — this is what rejects bun's generic
|
|
19
|
+
* `code` string, an `errno` that is a numeric OS errno, and any other non-SQLSTATE noise. A non-object
|
|
20
|
+
* error (string, number, `null`, `undefined`) yields `undefined`.
|
|
21
|
+
*/
|
|
22
|
+
export declare function readSqlState(error: unknown): string | undefined;
|
|
23
|
+
//# sourceMappingURL=sql-state.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sql-state.d.ts","sourceRoot":"","sources":["../src/sql-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAgC/D"}
|
package/package.json
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pgxsinkit/server",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.36",
|
|
4
|
+
"keywords": [
|
|
5
|
+
"tanstack-intent"
|
|
6
|
+
],
|
|
7
|
+
"license": "MIT",
|
|
4
8
|
"bin": {
|
|
5
|
-
"pgxsinkit-generate": "
|
|
9
|
+
"pgxsinkit-generate": "bin/pgxsinkit-generate.mjs"
|
|
6
10
|
},
|
|
7
11
|
"files": [
|
|
12
|
+
"bin",
|
|
8
13
|
"dist",
|
|
9
14
|
"src",
|
|
10
|
-
"README.md"
|
|
15
|
+
"README.md",
|
|
16
|
+
"skills"
|
|
11
17
|
],
|
|
12
18
|
"type": "module",
|
|
13
19
|
"main": "./dist/index.js",
|
|
@@ -25,11 +31,10 @@
|
|
|
25
31
|
"build": "bun --cwd ../.. run build:public-packages"
|
|
26
32
|
},
|
|
27
33
|
"dependencies": {
|
|
28
|
-
"@pgxsinkit/contracts": "0.1.
|
|
34
|
+
"@pgxsinkit/contracts": "0.1.36"
|
|
29
35
|
},
|
|
30
36
|
"peerDependencies": {
|
|
31
|
-
"drizzle-orm": "1.0.0-rc.
|
|
32
|
-
"hono": "^4.12.25"
|
|
37
|
+
"drizzle-orm": "1.0.0-rc.4"
|
|
33
38
|
},
|
|
34
39
|
"repository": {
|
|
35
40
|
"type": "git",
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: deploying
|
|
3
|
+
description: >-
|
|
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 concrete
|
|
6
|
+
steps a non-Bun edge runtime needs (bundle the function so Deno can load the toolkit's bare specifiers
|
|
7
|
+
with node: builtins, strip the function-name path prefix before server.fetch, resolve claims from the
|
|
8
|
+
platform JWT in resolveAuthClaims), splitting write and sync into two functions, setting the worker
|
|
9
|
+
timeout above Electric's ~25s long-poll, and forcing cache-control:no-store on a same-origin shape
|
|
10
|
+
proxy. Load before deploying the server or wiring it into an edge platform.
|
|
11
|
+
metadata:
|
|
12
|
+
type: task
|
|
13
|
+
library: "@pgxsinkit/server"
|
|
14
|
+
library_version: "0.1.32"
|
|
15
|
+
source: https://pgxsinkit.github.io/start/deploying-the-server/
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
# Deploying the pgxsinkit server
|
|
19
|
+
|
|
20
|
+
The server is a web-standard `fetch` handler, so it runs unmodified anywhere that speaks
|
|
21
|
+
`Request -> Response`. "Unmodified" is true at the API level; the steps below are about the runtime
|
|
22
|
+
around it, not the toolkit. On **Bun**, `export default { fetch: server.fetch }` (or `server.start()`,
|
|
23
|
+
the only Bun-specific helper) and you are done. The rest applies to Deno / Edge.
|
|
24
|
+
|
|
25
|
+
## 1. Bundle the function (Deno will not load the toolkit source directly)
|
|
26
|
+
|
|
27
|
+
The packages import dependencies with bare, extensionless specifiers (the Node/bundler convention),
|
|
28
|
+
which Deno's strict resolver rejects, and your registry package is usually unpublished. Bundle each
|
|
29
|
+
function into one self-contained ESM file ahead of time (`bun build` / esbuild, `target: "node"`,
|
|
30
|
+
`format: "esm"`). **The easy miss:** with `target: "node"`, Bun leaves builtins external but **bare**
|
|
31
|
+
(`import net from "net"`); Deno only resolves them under the `node:` scheme, so add an `onResolve` plugin
|
|
32
|
+
that rewrites every builtin to `node:*`. Everything else (drizzle, zod, the toolkit, your registry, plus
|
|
33
|
+
any framework you chose) inlines.
|
|
34
|
+
|
|
35
|
+
## 2. Strip the function-name path prefix before `server.fetch`
|
|
36
|
+
|
|
37
|
+
Edge Functions route by the first path segment, so a POST to `/functions/v1/write` arrives as `/write`.
|
|
38
|
+
The mutation route is served at `/mutations` (and `/api/mutations`), deployment-name-agnostic by design —
|
|
39
|
+
rewrite the path first, exactly as a reverse proxy would:
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
Deno.serve((request) => {
|
|
43
|
+
const url = new URL(request.url);
|
|
44
|
+
url.pathname = "/mutations"; // /write or /write/... -> /mutations
|
|
45
|
+
return server.fetch(new Request(url, request));
|
|
46
|
+
});
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The **read** path needs no rewrite: `proxyElectricShapeRequest` keys off the query string, not the path.
|
|
50
|
+
|
|
51
|
+
## 3. Resolve claims from the platform JWT in `resolveAuthClaims`
|
|
52
|
+
|
|
53
|
+
`verify_jwt` is a gateway concept; the portable move is to verify the token yourself and return its
|
|
54
|
+
claims (or `null` to fail closed — the proxy then blocks all rows and the write route rejects). A GoTrue
|
|
55
|
+
access token is already `JwtClaims`-shaped (`sub`, top-level `role`, `app_metadata`), so return it
|
|
56
|
+
directly after verifying. The applier reads `role` to switch the RLS actor; the read proxy reads `sub` +
|
|
57
|
+
`app_metadata.roles` for the row filter. Both paths share this one adapter, so authorization cannot
|
|
58
|
+
drift.
|
|
59
|
+
|
|
60
|
+
## Read vs write as two functions (a deployment choice)
|
|
61
|
+
|
|
62
|
+
- **write** — `createSyncServer({ registry, db, resolveAuthClaims })` **without** `electricUrl` registers
|
|
63
|
+
only the mutation route; wrap with the path rewrite above.
|
|
64
|
+
- **sync** — call `proxyElectricShapeRequest(request, claims, { registry, electricUrl })` directly. No
|
|
65
|
+
rewrite. **Set the function's idle/wall-clock timeout above Electric's bounded long-poll (~25s)** so a
|
|
66
|
+
live subscription is not recycled mid-cycle. If it is a **same-origin proxy with no CDN**, force
|
|
67
|
+
`cache-control: no-store` on the response, or a rotated shape handle serves stale and the client loops
|
|
68
|
+
on 409s.
|
|
69
|
+
|
|
70
|
+
Both import the same registry and share `resolveAuthClaims`, which keeps the two ingress points honest.
|
|
71
|
+
|
|
72
|
+
## The apply function verifies itself; the `deployment` profile tunes startup (ADR-0030)
|
|
73
|
+
|
|
74
|
+
The generated `pgxsinkit_apply_mutations` is **self-verifying**. The migration stamps it with a
|
|
75
|
+
fingerprint of its own DDL (a `COMMENT ON FUNCTION`); on every call the server passes the fingerprint it
|
|
76
|
+
expects for its registry + codegen, and the function compares that to its own stamped comment **before it
|
|
77
|
+
touches any table**, raising SQLSTATE `PXS01` (and applying nothing) on a mismatch. There is **no startup
|
|
78
|
+
drift check and no `applyFunctionDriftCheck` option** — enforcement is always-on and rides the existing
|
|
79
|
+
call (no extra round trip, no read-then-call race). A **stale** function is refused; a **hand-installed /
|
|
80
|
+
unfingerprinted** function (no comment) is also refused; an **old-signature** function fails at call
|
|
81
|
+
resolution (undefined function). Regenerate + apply the sync-function migration to fix it, and run
|
|
82
|
+
`pgxsinkit-generate --check` in CI to catch the drift before deploy.
|
|
83
|
+
|
|
84
|
+
**Order the utilities migration first.** The generated apply function and the `clockMicrosecondsSql`
|
|
85
|
+
column DEFAULTs both **call** `public.pgxsinkit_clock_us()` — the canonical microsecond clock installed by
|
|
86
|
+
the **utilities migration** (`renderPgxsinkitUtilitiesMigration()`, or the generate CLI's `--utilities`
|
|
87
|
+
mode). It must be the **first folder** in a consumer's migration chain: a chain that omits it or orders it
|
|
88
|
+
after the schema/apply-function migrations fails at **migrate** time with an undefined-function error,
|
|
89
|
+
before the server ever starts.
|
|
90
|
+
|
|
91
|
+
The `deployment` profile on `createSyncServer` owns the remaining **startup query** posture (its defaults
|
|
92
|
+
preserve long-lived-host behavior, so you only set it for serverless):
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
createSyncServer({
|
|
96
|
+
deployment: {
|
|
97
|
+
startupVerification: "in-process" | "deploy-time", // default "in-process": governs ONLY the RLS auth-helper verify
|
|
98
|
+
operationsLog: "probe" | "enabled" | "disabled", // default "probe": ensure-then-warn-disable
|
|
99
|
+
},
|
|
100
|
+
});
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
- `startupVerification: "deploy-time"` skips the boot-time RLS auth-helper verify (the migration pipeline
|
|
104
|
+
owns that guarantee).
|
|
105
|
+
- `operationsLog: "enabled"` assumes the table exists (no query; an actual absence then fails writes
|
|
106
|
+
loudly); `"disabled"` turns logging off with no query.
|
|
107
|
+
- The **serverless posture** is `{ startupVerification: "deploy-time", operationsLog: "enabled" | "disabled" }`
|
|
108
|
+
— a fresh per-request worker sends **zero queries before the mutation transaction itself**, which
|
|
109
|
+
matters where the platform serves one worker per request (each write otherwise replays the whole startup
|
|
110
|
+
gate). Pair it with warming the JWT/JWKS verify at module scope so the first verify does not pay a cold
|
|
111
|
+
key fetch.
|
|
112
|
+
|
|
113
|
+
## Measure before tuning: `logTimings`
|
|
114
|
+
|
|
115
|
+
`createSyncServer({ logTimings: true })` (default off) emits ONE compact `[pgxsinkit-timing]` JSON line
|
|
116
|
+
per request: the mutation route reports `preTxMs` (parse/validation), `txOpenMs` (the driver's LAZY
|
|
117
|
+
connection establishment + BEGIN — invisible to every other timer, and where a serverless worker's
|
|
118
|
+
connect cost lands), `authMs` (resolveAuthClaims), `applyMs` (the apply call), `totalMs`, and `status`;
|
|
119
|
+
the shape proxy reports `table`/`live`/`offset`, `upstreamMs` (the Electric fetch — for live long-polls,
|
|
120
|
+
the hold), and `totalMs`. Pair it with the client's `__pgxsinkitDebug` rail (`operating` skill,
|
|
121
|
+
`@pgxsinkit/client`): client-observed minus server `totalMs` is routing + network, and the phase fields
|
|
122
|
+
attribute the rest. Read the split BEFORE changing anything — every latency class below was found this way.
|
|
123
|
+
|
|
124
|
+
## Serverless geometry: compute follows the caller, data does not
|
|
125
|
+
|
|
126
|
+
On platforms like Supabase Edge Functions, workers execute **near the CALLER** while the database lives
|
|
127
|
+
in ONE region — and worker boots are cheap (~80ms), but each per-request worker opens its own DB
|
|
128
|
+
connection and the wire protocol is **one round trip per statement**. If the caller is far from the
|
|
129
|
+
database, every statement pays the cross-region RTT (measured: 162ms/statement Singapore↔`eu-central-1`
|
|
130
|
+
⇒ ~1.9s connect + ~3s per write, with `applyMs` itself only tens of ms). Fix the geometry, not the code:
|
|
131
|
+
**pin only the DB-bound functions to the DATABASE's region** (Supabase: send the `x-region: <db-region>`
|
|
132
|
+
header — the toolkit client's `writeRequestHeaders` option carries it on the write path; CORS is
|
|
133
|
+
unaffected because the preflight responses echo requested headers). The long hop is then paid once,
|
|
134
|
+
client→function, instead of per statement — measured: function `totalMs` 3,050 → 191.
|
|
135
|
+
|
|
136
|
+
The pin is **per-function, and only right for DB-bound ones.** The mutation ingress (`board-write`) is
|
|
137
|
+
DB-bound and wins from it. A **read proxy** (`board-sync`) is NOT: its upstream is Electric Cloud's
|
|
138
|
+
globally-distributed CDN, so pinning it to the database's region drags every catch-up hop away from a
|
|
139
|
+
distant caller — ~2 intercontinental round trips (~1.2s) versus ~300ms unpinned near the caller, while
|
|
140
|
+
the function itself is lean (`totalMs − upstreamMs` ≈ 2–3ms). So keep read proxies **unpinned** (follow
|
|
141
|
+
the caller) and put the region header in `writeRequestHeaders`, never the shared `requestHeaders`.
|
|
142
|
+
|
|
143
|
+
A browser also opens **one long-poll connection per synced shape**, so over HTTP/1.1 the ~6-per-origin
|
|
144
|
+
cap starves writes — serve the gateway over **HTTP/2**. The JWKS/warming recipe and the connection-budget
|
|
145
|
+
detail live in the `operating` skill.
|
|
146
|
+
|
|
147
|
+
## Common mistakes
|
|
148
|
+
|
|
149
|
+
- Deploying a registry change or a `@pgxsinkit/server` upgrade without regenerating + applying the sync
|
|
150
|
+
function migration. The apply function verifies itself and **refuses to serve writes** (SQLSTATE
|
|
151
|
+
`PXS01`) on a mismatch — enforcement is always-on, there is no override; run `pgxsinkit-generate --check`
|
|
152
|
+
in CI to catch it before deploy.
|
|
153
|
+
- Ordering the utilities migration after the schema/apply-function migration, or omitting it — the apply
|
|
154
|
+
function and column DEFAULTs call `public.pgxsinkit_clock_us()`, so migrate fails with an
|
|
155
|
+
undefined-function error. Generate it first (`--utilities`).
|
|
156
|
+
- Shipping toolkit source to Deno without bundling, or leaving builtins un-prefixed (not `node:*`).
|
|
157
|
+
- Forgetting the path rewrite, so `/mutations` 404s behind the function name.
|
|
158
|
+
- Verifying the JWT only at the gateway instead of in `resolveAuthClaims` (non-portable).
|
|
159
|
+
- A sync function timeout below Electric's ~25s long-poll (constant read-path reconnects).
|
|
160
|
+
- Omitting `cache-control: no-store` on a same-origin shape proxy.
|
|
161
|
+
|
|
162
|
+
Full prose: <https://pgxsinkit.github.io/start/deploying-the-server/>.
|