@pgxsinkit/server 0.1.31 → 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 +15 -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
package/src/index.ts
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import type { PgAsyncDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core";
|
|
2
|
-
import { Hono } from "hono";
|
|
3
|
-
import { cors } from "hono/cors";
|
|
4
2
|
|
|
5
3
|
import type {
|
|
6
4
|
JwtClaims,
|
|
@@ -11,10 +9,16 @@ import type {
|
|
|
11
9
|
SyncTableRegistry,
|
|
12
10
|
} from "@pgxsinkit/contracts";
|
|
13
11
|
|
|
14
|
-
import {
|
|
15
|
-
import
|
|
12
|
+
import { proxyElectricShapeRequest } from "./electric-proxy";
|
|
13
|
+
import {
|
|
14
|
+
authoritativeMutationPaths,
|
|
15
|
+
batchMutationPaths,
|
|
16
|
+
createMutationHandler,
|
|
17
|
+
type StartupVerificationMode,
|
|
18
|
+
} from "./mutations/route";
|
|
16
19
|
import { ensureOperationsLogSchema } from "./operations-log/ddl";
|
|
17
20
|
import type { OperationsLogConfig } from "./operations-log/types";
|
|
21
|
+
import { FetchRouter, type CorsScope } from "./router";
|
|
18
22
|
|
|
19
23
|
const defaultAllowedOrigins = ["http://localhost:5173", "http://localhost:5174"];
|
|
20
24
|
|
|
@@ -31,6 +35,31 @@ interface BunNamespace {
|
|
|
31
35
|
}) => BunServerHandle;
|
|
32
36
|
}
|
|
33
37
|
|
|
38
|
+
/**
|
|
39
|
+
* How the operations-log table's presence is resolved at startup (ADR-0030 decision 3):
|
|
40
|
+
* - `"probe"` (default): today's behavior — one query ensures/confirms the table, and logging is
|
|
41
|
+
* disabled at runtime (with a warning) if it is absent. Preserves the documented degradation.
|
|
42
|
+
* - `"enabled"`: assume the table exists — NO query. If it is actually absent, writes then fail loudly.
|
|
43
|
+
* - `"disabled"`: turn logging off with NO query.
|
|
44
|
+
*
|
|
45
|
+
* `"enabled" | "disabled"` are the serverless posture: paired with `startupVerification: "deploy-time"`,
|
|
46
|
+
* a fresh worker sends zero queries before the mutation transaction itself.
|
|
47
|
+
*/
|
|
48
|
+
export type OperationsLogStartupMode = "probe" | "enabled" | "disabled";
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The `deployment` profile owns the server's startup query posture (ADR-0030 decision 3). Its defaults
|
|
52
|
+
* preserve today's behavior exactly, so long-lived hosts need not set it; serverless / per-request
|
|
53
|
+
* workers set `{ startupVerification: "deploy-time", operationsLog: "enabled" | "disabled" }` for a
|
|
54
|
+
* zero-startup-query first write.
|
|
55
|
+
*/
|
|
56
|
+
export interface DeploymentProfile {
|
|
57
|
+
/** Governs ONLY the RLS auth-helper verify now (apply-fn drift is self-verifying). Default `"in-process"`. */
|
|
58
|
+
startupVerification?: StartupVerificationMode;
|
|
59
|
+
/** How the operations-log table presence is resolved. Default `"probe"`. */
|
|
60
|
+
operationsLog?: OperationsLogStartupMode;
|
|
61
|
+
}
|
|
62
|
+
|
|
34
63
|
export interface CreateSyncServerOptions<
|
|
35
64
|
TRegistry extends SyncTableRegistry,
|
|
36
65
|
TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<
|
|
@@ -40,20 +69,40 @@ export interface CreateSyncServerOptions<
|
|
|
40
69
|
> {
|
|
41
70
|
registry: TRegistry;
|
|
42
71
|
db: TDb;
|
|
43
|
-
/** Existing Hono app to register routes on. If omitted, a new Hono app is created. */
|
|
44
|
-
app?: Hono;
|
|
45
|
-
backend?: BulkMutationBackend;
|
|
46
72
|
resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;
|
|
73
|
+
/**
|
|
74
|
+
* When set, the server serves a read-path Electric shape proxy that shares the
|
|
75
|
+
* single `resolveAuthClaims` adapter with the write path (ADR-0003). Without it,
|
|
76
|
+
* no shape proxy is registered.
|
|
77
|
+
*/
|
|
78
|
+
electricUrl?: string;
|
|
79
|
+
/** Path for the shape proxy route. Defaults to `/api/shape`. */
|
|
80
|
+
shapeProxyPath?: string;
|
|
81
|
+
/** Optional per-request extra params passed to customWhere/shared filters. */
|
|
82
|
+
resolveShapeParams?: (request: Request) => Record<string, unknown> | undefined;
|
|
47
83
|
operationsLog?: {
|
|
48
84
|
enabled?: boolean;
|
|
49
85
|
};
|
|
50
|
-
/** Health check endpoint.
|
|
86
|
+
/** Health check endpoint. Enabled by default at `/health`; `false` disables it, `{ path }` relocates it. */
|
|
51
87
|
healthCheck?: boolean | { path: string };
|
|
52
88
|
port?: number;
|
|
53
89
|
host?: string;
|
|
54
90
|
idleTimeoutSeconds?: number;
|
|
55
91
|
allowedOrigins?: string[];
|
|
56
92
|
onStatusChange?: (status: SyncRuntimeStatus) => void;
|
|
93
|
+
/**
|
|
94
|
+
* The startup query posture (ADR-0030). The apply function now verifies its own ADR-0018 fingerprint
|
|
95
|
+
* in-body on every call (SQLSTATE `PXS01` on drift), so there is no startup drift check to configure;
|
|
96
|
+
* this governs only the RLS auth-helper verify and the operations-log presence resolution. Defaults
|
|
97
|
+
* preserve today's behavior. See {@link DeploymentProfile}.
|
|
98
|
+
*/
|
|
99
|
+
deployment?: DeploymentProfile;
|
|
100
|
+
/**
|
|
101
|
+
* Opt-in per-request timing log (default false). When on, each mutation and shape-proxy request emits
|
|
102
|
+
* one compact `[pgxsinkit-timing]` line with an ISO-8601(ms, UTC) timestamp and phase durations, for
|
|
103
|
+
* attributing wall-clock latency against the client's `syncDebug` lines. Additive; no behaviour change.
|
|
104
|
+
*/
|
|
105
|
+
logTimings?: boolean;
|
|
57
106
|
}
|
|
58
107
|
|
|
59
108
|
export interface ServerDiagnostics<TRegistry extends SyncTableRegistry> {
|
|
@@ -85,9 +134,8 @@ export function createSyncServer<
|
|
|
85
134
|
RegistryRelations<TRegistry>
|
|
86
135
|
>,
|
|
87
136
|
>(options: CreateSyncServerOptions<TRegistry, TDb>): SyncServer<TRegistry, TDb> {
|
|
88
|
-
const ownsApp = !options.app;
|
|
89
137
|
const db = options.db;
|
|
90
|
-
const
|
|
138
|
+
const router = new FetchRouter();
|
|
91
139
|
let bunServer: BunServerHandle | undefined;
|
|
92
140
|
|
|
93
141
|
const status: SyncRuntimeStatus = {
|
|
@@ -97,63 +145,101 @@ export function createSyncServer<
|
|
|
97
145
|
|
|
98
146
|
let address: SyncServerAddress | null = null;
|
|
99
147
|
const operationsLogConfig = resolveOperationsLogConfig(options.operationsLog);
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
148
|
+
const operationsLogStartup = options.deployment?.operationsLog ?? "probe";
|
|
149
|
+
// ADR-0030: how operations_log presence is resolved decides whether startup issues a query at all.
|
|
150
|
+
// - "probe" (default): thread the presence probe into the effective config. operations_log is an
|
|
151
|
+
// *optional* feature (default-enabled), so if logging was requested but the table is absent, disable
|
|
152
|
+
// it at runtime rather than letting every write fail on a missing table — the documented degradation
|
|
153
|
+
// (ensureOperationsLogSchema warns and returns `false`). The route awaits `operationsLogReady` before
|
|
154
|
+
// any logOperation, so the corrected flag is in effect by the time logging runs, and the route holds
|
|
155
|
+
// this same config object. (Board dogfooding: discarding this boolean 500'd every mutation on a
|
|
156
|
+
// missing optional table.)
|
|
157
|
+
// - "enabled": assume the table exists — NO query; logging stays on (an actual absence then fails
|
|
158
|
+
// writes loudly, by design). "disabled": logging off — NO query.
|
|
159
|
+
let operationsLogReady: Promise<void>;
|
|
160
|
+
if (operationsLogStartup === "probe") {
|
|
161
|
+
operationsLogReady = ensureOperationsLogSchema(db, operationsLogConfig).then((present) => {
|
|
162
|
+
operationsLogConfig.enabled = operationsLogConfig.enabled && present;
|
|
108
163
|
});
|
|
164
|
+
} else {
|
|
165
|
+
if (operationsLogStartup === "disabled") {
|
|
166
|
+
operationsLogConfig.enabled = false;
|
|
167
|
+
}
|
|
168
|
+
operationsLogReady = Promise.resolve();
|
|
169
|
+
}
|
|
109
170
|
|
|
110
|
-
|
|
111
|
-
app.use("/mutations", corsMiddleware);
|
|
171
|
+
const shapeProxyPath = options.shapeProxyPath ?? "/api/shape";
|
|
112
172
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
173
|
+
// CORS mirrors the previous middleware scopes: everything under /api/*, the /mutations alias, and
|
|
174
|
+
// the shape proxy path (which may be relocated outside /api/).
|
|
175
|
+
const corsScopes: CorsScope[] = [{ prefix: "/api/" }, { exact: "/mutations" }];
|
|
176
|
+
if (options.electricUrl) {
|
|
177
|
+
corsScopes.push({ exact: shapeProxyPath });
|
|
178
|
+
}
|
|
179
|
+
router.setCors(
|
|
180
|
+
{
|
|
181
|
+
origins: options.allowedOrigins ?? defaultAllowedOrigins,
|
|
182
|
+
allowMethods: ["GET", "POST", "OPTIONS"],
|
|
183
|
+
// `apikey`: a deployment gateway (Supabase) expects it on every request, so the browser client
|
|
184
|
+
// sends it; it must be allowed in the preflight even though the server itself ignores it.
|
|
185
|
+
allowHeaders: ["Content-Type", "Authorization", "apikey"],
|
|
186
|
+
},
|
|
187
|
+
corsScopes,
|
|
188
|
+
);
|
|
117
189
|
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
issues: error.issues,
|
|
123
|
-
},
|
|
124
|
-
400,
|
|
125
|
-
);
|
|
126
|
-
}
|
|
190
|
+
router.setErrorHandler((error) => {
|
|
191
|
+
status.phase = "degraded";
|
|
192
|
+
status.lastError = error instanceof Error ? error.message : "Unexpected error";
|
|
193
|
+
options.onStatusChange?.(status);
|
|
127
194
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
},
|
|
132
|
-
500,
|
|
133
|
-
);
|
|
134
|
-
});
|
|
195
|
+
if (isValidationError(error)) {
|
|
196
|
+
return Response.json({ message: "Validation failed", issues: error.issues }, { status: 400 });
|
|
197
|
+
}
|
|
135
198
|
|
|
136
|
-
|
|
199
|
+
return Response.json({ message: error instanceof Error ? error.message : "Unexpected error" }, { status: 500 });
|
|
200
|
+
});
|
|
137
201
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
});
|
|
142
|
-
}
|
|
202
|
+
const healthCheckPath = resolveHealthCheckPath(options.healthCheck, true);
|
|
203
|
+
if (healthCheckPath) {
|
|
204
|
+
router.get(healthCheckPath, () => Response.json({ ok: true }));
|
|
143
205
|
}
|
|
144
206
|
|
|
145
|
-
// The single mutation ingress point — all writes go through POST /api/mutations
|
|
146
|
-
|
|
147
|
-
app,
|
|
207
|
+
// The single mutation ingress point — all writes go through POST /api/mutations (and the /mutations alias).
|
|
208
|
+
const mutationHandlers = createMutationHandler(
|
|
148
209
|
db,
|
|
149
210
|
options.registry,
|
|
150
|
-
backend,
|
|
151
211
|
operationsLogConfig,
|
|
152
212
|
operationsLogReady,
|
|
153
213
|
options.resolveAuthClaims,
|
|
214
|
+
options.deployment?.startupVerification ?? "in-process",
|
|
215
|
+
options.logTimings ?? false,
|
|
154
216
|
);
|
|
217
|
+
for (const path of batchMutationPaths) {
|
|
218
|
+
router.post(path, mutationHandlers.batch);
|
|
219
|
+
}
|
|
220
|
+
for (const path of authoritativeMutationPaths) {
|
|
221
|
+
router.post(path, mutationHandlers.authoritative);
|
|
222
|
+
}
|
|
155
223
|
|
|
156
|
-
|
|
224
|
+
// The read-path shape proxy shares the same resolveAuthClaims adapter, so read and
|
|
225
|
+
// write authorization can never diverge (ADR-0003).
|
|
226
|
+
if (options.electricUrl) {
|
|
227
|
+
const electricUrl = options.electricUrl;
|
|
228
|
+
const resolveAuthClaims = options.resolveAuthClaims;
|
|
229
|
+
const resolveShapeParams = options.resolveShapeParams;
|
|
230
|
+
router.get(shapeProxyPath, async (request) => {
|
|
231
|
+
const claims = resolveAuthClaims ? await resolveAuthClaims(request) : null;
|
|
232
|
+
const extraParams = resolveShapeParams?.(request);
|
|
233
|
+
return proxyElectricShapeRequest(request, claims, {
|
|
234
|
+
registry: options.registry,
|
|
235
|
+
electricUrl,
|
|
236
|
+
...(extraParams ? { extraParams } : {}),
|
|
237
|
+
...(options.logTimings ? { logTimings: true } : {}),
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const fetch = router.fetch;
|
|
157
243
|
|
|
158
244
|
return {
|
|
159
245
|
drizzle: db,
|
|
@@ -167,10 +253,6 @@ export function createSyncServer<
|
|
|
167
253
|
return;
|
|
168
254
|
}
|
|
169
255
|
|
|
170
|
-
if (!ownsApp) {
|
|
171
|
-
throw new Error("createSyncServer.start() requires pgxsinkit to own the Hono app (no external app provided)");
|
|
172
|
-
}
|
|
173
|
-
|
|
174
256
|
const bun = getBunNamespace();
|
|
175
257
|
if (!bun) {
|
|
176
258
|
throw new Error("createSyncServer.start() requires the Bun runtime");
|
|
@@ -184,7 +266,7 @@ export function createSyncServer<
|
|
|
184
266
|
hostname: host,
|
|
185
267
|
port,
|
|
186
268
|
...(idleTimeout !== undefined ? { idleTimeout } : {}),
|
|
187
|
-
fetch
|
|
269
|
+
fetch,
|
|
188
270
|
});
|
|
189
271
|
|
|
190
272
|
status.isRunning = true;
|
|
@@ -249,9 +331,14 @@ function resolveOperationsLogConfig(options?: { enabled?: boolean }): Operations
|
|
|
249
331
|
};
|
|
250
332
|
}
|
|
251
333
|
|
|
252
|
-
export {
|
|
253
|
-
export {
|
|
254
|
-
export {
|
|
334
|
+
export { authoritativeMutationPaths, batchMutationPaths, createMutationHandler } from "./mutations/route";
|
|
335
|
+
export type { StartupVerificationMode } from "./mutations/route";
|
|
336
|
+
export type { CorsConfig, CorsScope, FetchHandler, RouterErrorHandler } from "./router";
|
|
337
|
+
export { FetchRouter } from "./router";
|
|
338
|
+
export { buildPlpgsqlBatchFunctionDdl, expectedApplyFingerprint } from "./mutations/plpgsql-apply";
|
|
339
|
+
export { renderPgxsinkitUtilitiesMigration } from "./migrations/utilities";
|
|
340
|
+
export { ensureOperationsLogSchema, operationsLogRegclassTarget } from "./operations-log/ddl";
|
|
255
341
|
export { operationsLogTable } from "./operations-log/schema";
|
|
256
342
|
export { proxyElectricShapeRequest } from "./electric-proxy";
|
|
257
343
|
export type { ElectricProxyOptions } from "./electric-proxy";
|
|
344
|
+
export { readSqlState } from "./sql-state";
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { NOW_MICROSECONDS_SQL_TEXT } from "@pgxsinkit/contracts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The canonical microsecond-clock DB function `public.pgxsinkit_clock_us()` — the ONE home for the
|
|
5
|
+
* `clock_timestamp()`-epoch-microseconds semantics. Every surface (column DEFAULTs, the generated
|
|
6
|
+
* apply function's managed `nowMicroseconds` fields, the operations-log server stamp) CALLS this
|
|
7
|
+
* function; nothing inlines the expression. This migration installs it, and — because the generated
|
|
8
|
+
* apply function calls it — it MUST be the FIRST folder in any consumer's migration chain (before the
|
|
9
|
+
* schema and the sync-artifact folder).
|
|
10
|
+
*
|
|
11
|
+
* The body is composed from the single source {@link NOW_MICROSECONDS_SQL_TEXT} in @pgxsinkit/contracts
|
|
12
|
+
* (CREATE FUNCTION is the sanctioned raw-SQL case — Drizzle cannot express a PL/pgSQL/SQL function body).
|
|
13
|
+
*/
|
|
14
|
+
export function renderPgxsinkitUtilitiesMigration(): string {
|
|
15
|
+
return `-- The pgxsinkit canonical microsecond clock. Deliberately clock_timestamp() (advances WITHIN a
|
|
16
|
+
-- transaction — LWW/audit ordering of multi-row applies depends on it), never now()/transaction_timestamp()
|
|
17
|
+
-- (frozen at tx start). FLOOR + BIGINT: whole microseconds since epoch.
|
|
18
|
+
CREATE OR REPLACE FUNCTION public.pgxsinkit_clock_us()
|
|
19
|
+
RETURNS bigint
|
|
20
|
+
LANGUAGE sql
|
|
21
|
+
VOLATILE
|
|
22
|
+
AS $$
|
|
23
|
+
SELECT ${NOW_MICROSECONDS_SQL_TEXT}
|
|
24
|
+
$$;`;
|
|
25
|
+
}
|