@pgxsinkit/server 0.1.3 → 0.1.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pgxsinkit/server",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "files": [
5
5
  "dist",
6
6
  "src",
@@ -13,6 +13,10 @@
13
13
  ".": {
14
14
  "types": "./src/index.ts",
15
15
  "default": "./dist/index.js"
16
+ },
17
+ "./experimental": {
18
+ "types": "./src/experimental/index.ts",
19
+ "default": "./dist/experimental/index.js"
16
20
  }
17
21
  },
18
22
  "publishConfig": {
@@ -22,7 +26,7 @@
22
26
  "build": "bun --cwd ../.. run build:public-packages"
23
27
  },
24
28
  "dependencies": {
25
- "@pgxsinkit/contracts": "^0.1.3"
29
+ "@pgxsinkit/contracts": "^0.1.4"
26
30
  },
27
31
  "peerDependencies": {
28
32
  "drizzle-orm": "1.0.0-rc.2",
@@ -0,0 +1,6 @@
1
+ export type { ExperimentalBulkMutationBackend } from "./mutations/bulk/types";
2
+ export { executeDynamicMutation, installDynamicMutationFunction } from "./mutations/bulk/dynamic-strategy";
3
+ export {
4
+ executePregeneratedMutation,
5
+ installPregeneratedMutationFunctions,
6
+ } from "./mutations/bulk/pregenerated-strategy";
@@ -0,0 +1,5 @@
1
+ export type ExperimentalBulkMutationBackend = "bulk-dynamic" | "bulk-pregenerated" | "bulk-plpgsql";
2
+
3
+ export interface TransactionClient {
4
+ execute: (query: unknown) => Promise<unknown>;
5
+ }
package/src/index.ts CHANGED
@@ -41,7 +41,7 @@ interface BunNamespace {
41
41
  export interface CreateSyncServerOptions<TRegistry extends SyncTableRegistry> {
42
42
  registry: TRegistry;
43
43
  databaseUrl: string;
44
- backend?: "drizzle" | BulkMutationBackend;
44
+ backend?: BulkMutationBackend;
45
45
  resolveAuthClaims?: (request: Request) => Promise<Record<string, unknown> | null> | Record<string, unknown> | null;
46
46
  operationsLog?: {
47
47
  enabled?: boolean;
@@ -87,7 +87,7 @@ export function createSyncServer<TRegistry extends SyncTableRegistry>(
87
87
  let address: SyncServerAddress | null = null;
88
88
  const operationsLogConfig = resolveOperationsLogConfig(options.operationsLog);
89
89
  const operationsLogReady = ensureOperationsLogSchema(db, operationsLogConfig);
90
- const backend = options.backend ?? "drizzle";
90
+ const backend = options.backend ?? "bulk-plpgsql-artifact";
91
91
 
92
92
  app.use(
93
93
  "/api/*",
@@ -133,17 +133,15 @@ export function createSyncServer<TRegistry extends SyncTableRegistry>(
133
133
  });
134
134
  }
135
135
 
136
- if (backend !== "drizzle") {
137
- registerBulkMutationRoute(
138
- app,
139
- db,
140
- options.registry,
141
- backend,
142
- operationsLogConfig,
143
- operationsLogReady,
144
- options.resolveAuthClaims,
145
- );
146
- }
136
+ registerBulkMutationRoute(
137
+ app,
138
+ db,
139
+ options.registry,
140
+ backend,
141
+ operationsLogConfig,
142
+ operationsLogReady,
143
+ options.resolveAuthClaims,
144
+ );
147
145
 
148
146
  const fetch = async (request: Request) => app.fetch(request);
149
147
 
@@ -18,14 +18,7 @@ import {
18
18
 
19
19
  import type { OperationsLogConfig } from "../../operations-log/types";
20
20
  import { logOperation, logOperationSafely } from "../../operations-log/writer";
21
- import { executeDynamicMutation, installDynamicMutationFunction } from "./dynamic-strategy";
22
- import {
23
- executePlpgsqlBatch,
24
- installPlpgsqlBatchFunction,
25
- verifyArtifactRlsAuthHelpers,
26
- verifyPlpgsqlBatchFunction,
27
- } from "./plpgsql-strategy";
28
- import { executePregeneratedMutation, installPregeneratedMutationFunctions } from "./pregenerated-strategy";
21
+ import { executePlpgsqlBatch, verifyArtifactRlsAuthHelpers, verifyPlpgsqlBatchFunction } from "./plpgsql-strategy";
29
22
  import type { BulkMutationBackend, TransactionClient } from "./types";
30
23
 
31
24
  export function registerBulkMutationRoute<TRegistry extends SyncTableRegistry>(
@@ -37,10 +30,18 @@ export function registerBulkMutationRoute<TRegistry extends SyncTableRegistry>(
37
30
  operationsLogReady: Promise<void>,
38
31
  resolveAuthClaims?: (request: Request) => Promise<Record<string, unknown> | null> | Record<string, unknown> | null,
39
32
  ) {
40
- const startupReady = installBulkStartupDdl(db, registry, backend);
33
+ let startupReadyPromise: Promise<void> | undefined;
34
+
35
+ const startupReady = () => {
36
+ if (!startupReadyPromise) {
37
+ startupReadyPromise = installBulkStartupDdl(db, registry, backend);
38
+ }
39
+
40
+ return startupReadyPromise;
41
+ };
41
42
 
42
43
  app.post("/api/mutations", async (context) => {
43
- await Promise.all([startupReady, operationsLogReady]);
44
+ await Promise.all([startupReady(), operationsLogReady]);
44
45
 
45
46
  let rawBody: unknown;
46
47
 
@@ -123,15 +124,13 @@ export function registerBulkMutationRoute<TRegistry extends SyncTableRegistry>(
123
124
  continue;
124
125
  }
125
126
 
126
- if (backend === "bulk-plpgsql-artifact") {
127
- const managedFieldViolations = findManagedFieldViolations(syncEntry, mutation.kind, normalizedPayload);
127
+ const managedFieldViolations = findManagedFieldViolations(syncEntry, mutation.kind, normalizedPayload);
128
128
 
129
- if (managedFieldViolations.length > 0) {
130
- const message = `${mutation.tableName}/${mutation.mutationId} includes server-managed fields: ${managedFieldViolations.join(", ")}`;
131
- validationErrors.push(message);
132
- invalidMutations.push({ mutation, message });
133
- continue;
134
- }
129
+ if (managedFieldViolations.length > 0) {
130
+ const message = `${mutation.tableName}/${mutation.mutationId} includes server-managed fields: ${managedFieldViolations.join(", ")}`;
131
+ validationErrors.push(message);
132
+ invalidMutations.push({ mutation, message });
133
+ continue;
135
134
  }
136
135
 
137
136
  try {
@@ -173,107 +172,61 @@ export function registerBulkMutationRoute<TRegistry extends SyncTableRegistry>(
173
172
 
174
173
  const acks: MutationAck[] = [];
175
174
  let actorUserId: string | null = null;
176
- const artifactAuthContextRequired = backend === "bulk-plpgsql-artifact" && isArtifactAuthContextRequired(registry);
175
+ const artifactAuthContextRequired = isArtifactAuthContextRequired(registry);
177
176
 
178
177
  try {
179
178
  await db.transaction(async (tx) => {
180
- if (backend === "bulk-plpgsql" || backend === "bulk-plpgsql-artifact") {
181
- const shouldApplyRlsContext = artifactAuthContextRequired;
182
- let userClaims: Record<string, unknown> = {};
183
-
184
- if (shouldApplyRlsContext) {
185
- const resolvedClaims = await resolveAuthClaims?.(context.req.raw);
186
-
187
- if (!isPlainObject(resolvedClaims)) {
188
- await logOperationSafely(db, operationsLogConfig, {
189
- source: "batch",
190
- backend,
191
- tableName: null,
192
- operationKind: null,
193
- entityKey: null,
194
- payload: rawBody,
195
- status: "validation_failed",
196
- errorMessage: "Missing validated JWT claims for RLS-enabled artifact backend",
197
- httpStatus: 401,
198
- requestPath: context.req.path,
199
- });
200
-
201
- throw new UnauthorizedBatchMutationError(
202
- "RLS-enabled artifact backend requires validated JWT claims in request context",
203
- );
204
- }
205
-
206
- userClaims = resolvedClaims;
207
- actorUserId = getUuidClaim(userClaims, "sub");
208
- }
209
-
210
- const batchRequest =
211
- backend === "bulk-plpgsql-artifact" ? sanitizeArtifactRestrictedFields(body, registry) : body;
179
+ const shouldApplyRlsContext = artifactAuthContextRequired;
180
+ let userClaims: Record<string, unknown> = {};
181
+
182
+ if (shouldApplyRlsContext) {
183
+ const resolvedClaims = await resolveAuthClaims?.(context.req.raw);
184
+
185
+ if (!isPlainObject(resolvedClaims)) {
186
+ await logOperationSafely(db, operationsLogConfig, {
187
+ source: "batch",
188
+ backend,
189
+ tableName: null,
190
+ operationKind: null,
191
+ entityKey: null,
192
+ payload: rawBody,
193
+ status: "validation_failed",
194
+ errorMessage: "Missing validated JWT claims for RLS-enabled artifact backend",
195
+ httpStatus: 401,
196
+ requestPath: context.req.path,
197
+ });
212
198
 
213
- if (backend === "bulk-plpgsql-artifact") {
214
- await tx.execute(sql`SET CONSTRAINTS ALL DEFERRED`);
199
+ throw new UnauthorizedBatchMutationError(
200
+ "RLS-enabled artifact backend requires validated JWT claims in request context",
201
+ );
215
202
  }
216
203
 
217
- await executePlpgsqlBatch(
218
- tx as unknown as TransactionClient,
219
- batchRequest,
220
- context.req.path,
221
- operationsLogConfig.enabled && backend === "bulk-plpgsql",
222
- shouldApplyRlsContext,
223
- userClaims,
224
- );
225
-
226
- if (shouldApplyRlsContext) {
227
- await tx.execute(sql`RESET ROLE`);
228
- }
204
+ userClaims = resolvedClaims;
205
+ actorUserId = getUuidClaim(userClaims, "sub");
206
+ }
229
207
 
230
- for (const mutation of batchRequest.mutations) {
231
- const serverUpdatedAtUs = await readServerUpdatedAtUs(
232
- tx as unknown as TransactionClient,
233
- registry[mutation.tableName as keyof TRegistry] as SyncTableEntry,
234
- mutation.entityKey,
235
- );
208
+ const batchRequest = sanitizeArtifactRestrictedFields(body, registry);
209
+ await tx.execute(sql`SET CONSTRAINTS ALL DEFERRED`);
236
210
 
237
- if (backend === "bulk-plpgsql-artifact") {
238
- await logOperation(tx, operationsLogConfig, {
239
- source: "batch",
240
- backend,
241
- tableName: mutation.tableName,
242
- operationKind: mutation.kind,
243
- entityKey: mutation.entityKey,
244
- payload: mutation.payload,
245
- status: "succeeded",
246
- httpStatus: 200,
247
- mutationId: mutation.mutationId,
248
- mutationSeq: mutation.mutationSeq,
249
- clientTimestampUs: mutation.clientTimestampUs,
250
- requestPath: context.req.path,
251
- userId: actorUserId,
252
- });
253
- }
254
-
255
- acks.push({
256
- tableName: mutation.tableName,
257
- entityKey: mutation.entityKey,
258
- mutationId: mutation.mutationId,
259
- mutationSeq: mutation.mutationSeq,
260
- status: "acked",
261
- ...(serverUpdatedAtUs ? { serverUpdatedAtUs } : {}),
262
- });
263
- }
211
+ await executePlpgsqlBatch(
212
+ tx as unknown as TransactionClient,
213
+ batchRequest,
214
+ context.req.path,
215
+ false,
216
+ shouldApplyRlsContext,
217
+ userClaims,
218
+ );
264
219
 
265
- return;
220
+ if (shouldApplyRlsContext) {
221
+ await tx.execute(sql`RESET ROLE`);
266
222
  }
267
223
 
268
- for (const mutation of body.mutations) {
269
- const entry = registry[mutation.tableName as keyof TRegistry]!;
270
- const primaryKeyColumnName = (entry as SyncTableEntry).primaryKey.columns[0]!;
271
-
272
- if (backend === "bulk-dynamic") {
273
- await executeDynamicMutation(tx as unknown as TransactionClient, mutation, primaryKeyColumnName);
274
- } else {
275
- await executePregeneratedMutation(tx as unknown as TransactionClient, mutation);
276
- }
224
+ for (const mutation of batchRequest.mutations) {
225
+ const serverUpdatedAtUs = await readServerUpdatedAtUs(
226
+ tx as unknown as TransactionClient,
227
+ registry[mutation.tableName as keyof TRegistry] as SyncTableEntry,
228
+ mutation.entityKey,
229
+ );
277
230
 
278
231
  await logOperation(tx, operationsLogConfig, {
279
232
  source: "batch",
@@ -291,12 +244,6 @@ export function registerBulkMutationRoute<TRegistry extends SyncTableRegistry>(
291
244
  userId: actorUserId,
292
245
  });
293
246
 
294
- const serverUpdatedAtUs = await readServerUpdatedAtUs(
295
- tx as unknown as TransactionClient,
296
- entry as SyncTableEntry,
297
- mutation.entityKey,
298
- );
299
-
300
247
  acks.push({
301
248
  tableName: mutation.tableName,
302
249
  entityKey: mutation.entityKey,
@@ -587,27 +534,11 @@ function quoteIdentifier(identifier: string) {
587
534
  async function installBulkStartupDdl<TRegistry extends SyncTableRegistry>(
588
535
  db: PostgresJsDatabase<RegistryRelations<TRegistry>>,
589
536
  registry: TRegistry,
590
- backend: BulkMutationBackend,
537
+ _backend: BulkMutationBackend,
591
538
  ): Promise<void> {
592
- if (backend === "bulk-dynamic") {
593
- await installDynamicMutationFunction(db);
594
- return;
595
- }
596
-
597
- if (backend === "bulk-plpgsql") {
598
- await installPlpgsqlBatchFunction(db, registry);
599
- return;
600
- }
601
-
602
- if (backend === "bulk-plpgsql-artifact") {
603
- await verifyPlpgsqlBatchFunction(db);
539
+ await verifyPlpgsqlBatchFunction(db);
604
540
 
605
- if (isArtifactAuthContextRequired(registry)) {
606
- await verifyArtifactRlsAuthHelpers(db);
607
- }
608
-
609
- return;
541
+ if (isArtifactAuthContextRequired(registry)) {
542
+ await verifyArtifactRlsAuthHelpers(db);
610
543
  }
611
-
612
- await installPregeneratedMutationFunctions(db, registry);
613
544
  }
@@ -1,4 +1,4 @@
1
- export type BulkMutationBackend = "bulk-dynamic" | "bulk-pregenerated" | "bulk-plpgsql" | "bulk-plpgsql-artifact";
1
+ export type BulkMutationBackend = "bulk-plpgsql-artifact";
2
2
 
3
3
  export interface TransactionClient {
4
4
  execute: (query: unknown) => Promise<unknown>;
@@ -2,7 +2,7 @@ import type { SQLWrapper } from "drizzle-orm";
2
2
 
3
3
  export type OpsLogSource = "crud" | "batch";
4
4
 
5
- export type OpsLogBackend = "drizzle" | "bulk-dynamic" | "bulk-pregenerated" | "bulk-plpgsql" | "bulk-plpgsql-artifact";
5
+ export type OpsLogBackend = "bulk-plpgsql-artifact";
6
6
 
7
7
  export type OpsLogStatus = "succeeded" | "validation_failed" | "not_found" | "execution_failed";
8
8