@pgxsinkit/client 0.6.1 → 0.6.2

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/index.js CHANGED
@@ -4631,7 +4631,7 @@ var init_mutation_state = __esm(() => {
4631
4631
  MUTATION_TRANSITIONS = {
4632
4632
  pending: ["sending", "quarantined"],
4633
4633
  sending: ["acked", "failed", "quarantined", "conflicted", "rejected", "pending"],
4634
- failed: ["pending", "quarantined"],
4634
+ failed: ["pending", "quarantined", "rejected"],
4635
4635
  quarantined: [],
4636
4636
  conflicted: [],
4637
4637
  rejected: [],
@@ -4643,6 +4643,7 @@ var init_mutation_state = __esm(() => {
4643
4643
  // packages/client/src/mutation.ts
4644
4644
  import {
4645
4645
  and as and5,
4646
+ asc as asc2,
4646
4647
  desc,
4647
4648
  eq as eq6,
4648
4649
  exists,
@@ -4652,6 +4653,7 @@ import {
4652
4653
  is,
4653
4654
  isNotNull,
4654
4655
  isNull as isNull3,
4656
+ like as like2,
4655
4657
  lt,
4656
4658
  ne,
4657
4659
  notExists as notExists2,
@@ -4938,7 +4940,8 @@ function createMutationRuntime(options) {
4938
4940
  mutationKind: "create",
4939
4941
  payloadJson: jsonStringifyPayload({
4940
4942
  kind: "create",
4941
- value: item.input
4943
+ value: item.input,
4944
+ localValue: item.optimisticRecord
4942
4945
  }),
4943
4946
  nowUs: item.nowUs,
4944
4947
  baseServerVersion: null
@@ -5224,6 +5227,7 @@ function createMutationRuntime(options) {
5224
5227
  }));
5225
5228
  const url = mutationUrls.authoritative;
5226
5229
  let acksByMutationId;
5230
+ let rejectedRequest;
5227
5231
  try {
5228
5232
  const authToken = await untilAborted(Promise.resolve(options.getAuthToken?.()));
5229
5233
  let response = await fetch(url, {
@@ -5248,96 +5252,116 @@ function createMutationRuntime(options) {
5248
5252
  const responseJson = await response.json();
5249
5253
  acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));
5250
5254
  } catch (error) {
5251
- const failedAtUs = nowMicroseconds();
5252
- const httpStatus = error instanceof MutationRequestError ? error.status : null;
5253
- const errorMessage = error instanceof Error ? error.message : "Authoritative write failed";
5254
- for (const rows of byContext.values()) {
5255
- await applyMutationStatusUpdates(options.db, rows[0].context, rows.map((row) => {
5256
- const attemptCount = row.attemptCount + 1;
5257
- const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs);
5258
- return {
5259
- mutationId: row.mutationId,
5260
- status: outcome.status,
5261
- attemptCount,
5262
- updatedAtUs: failedAtUs,
5263
- lastError: errorMessage,
5264
- nextRetryAtUs: outcome.nextRetryAtUs,
5265
- lastHttpStatus: httpStatus,
5266
- conflictReason: null
5267
- };
5268
- }));
5255
+ if (error instanceof MutationRequestError && classifyFailureStatus(error.status) === "quarantined") {
5256
+ rejectedRequest = error;
5257
+ acksByMutationId = new Map(mutations.map((mutation) => [
5258
+ mutation.mutationId,
5259
+ { ...mutation, status: "rejected", httpStatus: error.status, rejectionReason: error.message }
5260
+ ]));
5261
+ } else {
5262
+ const failedAtUs = nowMicroseconds();
5263
+ const httpStatus = error instanceof MutationRequestError ? error.status : null;
5264
+ const errorMessage = error instanceof Error ? error.message : "Authoritative write failed";
5265
+ for (const rows of byContext.values()) {
5266
+ await applyMutationStatusUpdates(options.db, rows[0].context, rows.map((row) => {
5267
+ const attemptCount = row.attemptCount + 1;
5268
+ const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs);
5269
+ return {
5270
+ mutationId: row.mutationId,
5271
+ status: outcome.status,
5272
+ attemptCount,
5273
+ updatedAtUs: failedAtUs,
5274
+ lastError: errorMessage,
5275
+ nextRetryAtUs: outcome.nextRetryAtUs,
5276
+ lastHttpStatus: httpStatus,
5277
+ conflictReason: null
5278
+ };
5279
+ }));
5280
+ }
5281
+ throw error;
5269
5282
  }
5270
- throw error;
5271
5283
  }
5272
5284
  const ackedAtUs = nowMicroseconds();
5273
5285
  const failedAtUs = nowMicroseconds();
5274
- const rejectedIds = new Set;
5286
+ const rejectedIds = new Set(prepared.filter((row) => acksByMutationId.get(row.mutationId)?.status === "rejected").map((row) => row.mutationId));
5275
5287
  const conflictedIds = new Set;
5276
- for (const rows of byContext.values()) {
5277
- await applyMutationStatusUpdates(options.db, rows[0].context, rows.map((row) => {
5278
- const ack = acksByMutationId.get(row.mutationId);
5279
- if (ack?.status === "rejected") {
5280
- rejectedIds.add(row.mutationId);
5281
- return {
5282
- mutationId: row.mutationId,
5283
- status: "rejected",
5284
- attemptCount: row.attemptCount + 1,
5285
- updatedAtUs: failedAtUs,
5286
- lastError: ack.rejectionReason ?? "Rejected by the authoritative endpoint",
5287
- nextRetryAtUs: null,
5288
- lastHttpStatus: ack.httpStatus ?? 409,
5289
- conflictReason: ack.rejectionReason ?? "Rejected by the authoritative endpoint"
5290
- };
5291
- }
5292
- if (ack?.status === "conflicted") {
5293
- conflictedIds.add(row.mutationId);
5288
+ const settleUnit = async () => {
5289
+ for (const rows of byContext.values()) {
5290
+ await applyMutationStatusUpdates(options.db, rows[0].context, rows.map((row) => {
5291
+ const ack = acksByMutationId.get(row.mutationId);
5292
+ if (ack?.status === "rejected") {
5293
+ rejectedIds.add(row.mutationId);
5294
+ return {
5295
+ mutationId: row.mutationId,
5296
+ status: "rejected",
5297
+ attemptCount: row.attemptCount + 1,
5298
+ updatedAtUs: failedAtUs,
5299
+ lastError: ack.rejectionReason ?? "Rejected by the authoritative endpoint",
5300
+ nextRetryAtUs: null,
5301
+ lastHttpStatus: ack.httpStatus ?? 409,
5302
+ conflictReason: ack.rejectionReason ?? "Rejected by the authoritative endpoint"
5303
+ };
5304
+ }
5305
+ if (ack?.status === "conflicted") {
5306
+ conflictedIds.add(row.mutationId);
5307
+ return {
5308
+ mutationId: row.mutationId,
5309
+ status: "conflicted",
5310
+ attemptCount: row.attemptCount + 1,
5311
+ updatedAtUs: failedAtUs,
5312
+ serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
5313
+ replaceServerUpdatedAtUs: true,
5314
+ lastError: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
5315
+ nextRetryAtUs: null,
5316
+ lastHttpStatus: ack.httpStatus ?? 409,
5317
+ conflictReason: ack.conflictReason ?? "Stale write rejected (reject-if-stale)"
5318
+ };
5319
+ }
5320
+ if (!ack || ack.status !== "acked") {
5321
+ const attemptCount = row.attemptCount + 1;
5322
+ const outcome = resolveFailureOutcome(ack?.httpStatus ?? null, attemptCount, maxMutationAttempts, failedAtUs);
5323
+ return {
5324
+ mutationId: row.mutationId,
5325
+ status: outcome.status,
5326
+ attemptCount,
5327
+ updatedAtUs: failedAtUs,
5328
+ lastError: ack?.conflictReason ?? "Authoritative write not acknowledged",
5329
+ nextRetryAtUs: outcome.nextRetryAtUs,
5330
+ lastHttpStatus: ack?.httpStatus ?? null,
5331
+ conflictReason: null
5332
+ };
5333
+ }
5294
5334
  return {
5295
5335
  mutationId: row.mutationId,
5296
- status: "conflicted",
5336
+ status: "acked",
5297
5337
  attemptCount: row.attemptCount + 1,
5298
- updatedAtUs: failedAtUs,
5338
+ updatedAtUs: ackedAtUs,
5339
+ ackedAtUs,
5340
+ replaceAckedAtUs: true,
5299
5341
  serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
5300
5342
  replaceServerUpdatedAtUs: true,
5301
- lastError: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
5343
+ lastError: null,
5302
5344
  nextRetryAtUs: null,
5303
- lastHttpStatus: ack.httpStatus ?? 409,
5304
- conflictReason: ack.conflictReason ?? "Stale write rejected (reject-if-stale)"
5305
- };
5306
- }
5307
- if (!ack || ack.status !== "acked") {
5308
- const attemptCount = row.attemptCount + 1;
5309
- const outcome = resolveFailureOutcome(ack?.httpStatus ?? null, attemptCount, maxMutationAttempts, failedAtUs);
5310
- return {
5311
- mutationId: row.mutationId,
5312
- status: outcome.status,
5313
- attemptCount,
5314
- updatedAtUs: failedAtUs,
5315
- lastError: ack?.conflictReason ?? "Authoritative write not acknowledged",
5316
- nextRetryAtUs: outcome.nextRetryAtUs,
5317
- lastHttpStatus: ack?.httpStatus ?? null,
5345
+ lastHttpStatus: row.mutationKind === "delete" ? 204 : 200,
5318
5346
  conflictReason: null
5319
5347
  };
5348
+ }));
5349
+ }
5350
+ if (rejectedIds.size > 0) {
5351
+ const restored = new Set;
5352
+ for (const row of prepared) {
5353
+ const key = `${row.context.key}:${row.entityKeyJson}`;
5354
+ if (rejectedIds.has(row.mutationId) && !restored.has(key)) {
5355
+ await restoreOverlayAfterRejection(options.db, row.context, row.entityKey, row.entityKeyJson);
5356
+ restored.add(key);
5357
+ }
5320
5358
  }
5321
- return {
5322
- mutationId: row.mutationId,
5323
- status: "acked",
5324
- attemptCount: row.attemptCount + 1,
5325
- updatedAtUs: ackedAtUs,
5326
- ackedAtUs,
5327
- replaceAckedAtUs: true,
5328
- serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
5329
- replaceServerUpdatedAtUs: true,
5330
- lastError: null,
5331
- nextRetryAtUs: null,
5332
- lastHttpStatus: row.mutationKind === "delete" ? 204 : 200,
5333
- conflictReason: null
5334
- };
5335
- }));
5336
- }
5337
- for (const row of prepared) {
5338
- if (rejectedIds.has(row.mutationId)) {
5339
- await discardOverlayForSettledEntity(options.db, row.context, row.entityKey, row.entityKeyJson);
5340
5359
  }
5360
+ };
5361
+ if (rejectedIds.size > 0) {
5362
+ await runInTransaction(settleUnit);
5363
+ } else {
5364
+ await settleUnit();
5341
5365
  }
5342
5366
  const affectedContexts = [...byContext.keys()].map((key) => tableContexts[key]).filter((context) => context != null);
5343
5367
  for (const context of affectedContexts) {
@@ -5356,6 +5380,8 @@ function createMutationRuntime(options) {
5356
5380
  }
5357
5381
  }
5358
5382
  await settleRecoveryMarker();
5383
+ if (rejectedRequest)
5384
+ throw rejectedRequest;
5359
5385
  return { acks: [...acksByMutationId.values()] };
5360
5386
  },
5361
5387
  reconcile: async (table) => {
@@ -5366,13 +5392,62 @@ function createMutationRuntime(options) {
5366
5392
  },
5367
5393
  retryFailed: async (table) => {
5368
5394
  assertValidMutationTransition("failed", "pending");
5395
+ assertValidMutationTransition("failed", "rejected");
5369
5396
  const contexts = filterContexts(tableContexts, table);
5370
5397
  const nowUs = nowMicroseconds();
5398
+ const allContexts = filterContexts(tableContexts, undefined);
5399
+ const declinedUnits = new Set;
5400
+ for (const context of contexts) {
5401
+ const journal = context.tables.journal;
5402
+ const query = queryBuilder.select({
5403
+ unit: sql6`${journal.writeUnit}`.as("unit"),
5404
+ httpStatus: sql6`${journal.lastHttpStatus}`.as("httpStatus")
5405
+ }).from(journal).where(and5(eq6(journal.status, "failed"), like2(journal.writeMode, "pessimistic%"), isNotNull(journal.writeUnit))).toSQL();
5406
+ for (const row of (await options.db.query(query.sql, query.params)).rows) {
5407
+ if (classifyFailureStatus(row.httpStatus) === "quarantined")
5408
+ declinedUnits.add(row.unit);
5409
+ }
5410
+ }
5411
+ const repaired = new Set;
5412
+ for (const unitId of declinedUnits) {
5413
+ await runInTransaction(async () => {
5414
+ const rows = await readUnitPendingRows(options.db, allContexts, unitId, null);
5415
+ if (!rows.length || rows.some((row) => row.status !== "failed" || classifyFailureStatus(row.lastHttpStatus) !== "quarantined"))
5416
+ return;
5417
+ const entities = new Set;
5418
+ for (const row of rows) {
5419
+ const context = tableContexts[row.tableKey];
5420
+ await applyMutationStatusUpdates(options.db, context, [
5421
+ {
5422
+ mutationId: row.mutationId,
5423
+ status: "rejected",
5424
+ attemptCount: row.attemptCount,
5425
+ updatedAtUs: nowUs,
5426
+ lastError: row.lastError,
5427
+ conflictReason: row.lastError ?? "Rejected by the authoritative endpoint",
5428
+ lastHttpStatus: row.lastHttpStatus,
5429
+ nextRetryAtUs: null
5430
+ }
5431
+ ]);
5432
+ repaired.add(row.mutationId);
5433
+ }
5434
+ for (const row of rows) {
5435
+ const key = `${row.tableKey}:${row.entityKeyJson}`;
5436
+ if (!entities.has(key)) {
5437
+ await restoreOverlayAfterRejection(options.db, tableContexts[row.tableKey], JSON.parse(row.entityKeyJson), row.entityKeyJson);
5438
+ entities.add(key);
5439
+ }
5440
+ }
5441
+ });
5442
+ }
5371
5443
  for (const context of contexts) {
5372
5444
  const journal = context.tables.journal;
5373
5445
  const query = queryBuilder.update(journal).set({ status: "pending", nextRetryAtUs: nowUs, updatedAtUs: nowUs, conflictReason: null }).where(eq6(journal.status, "failed")).toSQL();
5374
5446
  await options.db.query(query.sql, query.params);
5375
5447
  }
5448
+ if (repaired.size > 0 && options.onReject) {
5449
+ await options.onReject(await readMutationDetailsForContexts(options.db, allContexts, repaired));
5450
+ }
5376
5451
  },
5377
5452
  recoverSending: async (table) => {
5378
5453
  assertValidMutationTransition("sending", "pending");
@@ -5916,13 +5991,13 @@ async function readPendingBatchRows(db, contexts, nowUs, batchSize) {
5916
5991
  const result = await db.query(query.sql, query.params);
5917
5992
  return result.rows;
5918
5993
  }
5919
- async function readUnitPendingRows(db, contexts, unitId) {
5994
+ async function readUnitPendingRows(db, contexts, unitId, statuses = ["pending", "failed"]) {
5920
5995
  if (contexts.length === 0) {
5921
5996
  return [];
5922
5997
  }
5923
5998
  const branches = contexts.map((context) => {
5924
5999
  const journal = context.tables.journal;
5925
- return queryBuilder.select(buildPendingRowsProjection(context)).from(journal).where(and5(eq6(journal.writeUnit, unitId), inArray2(journal.status, ["pending", "failed"])));
6000
+ return queryBuilder.select(buildPendingRowsProjection(context)).from(journal).where(and5(eq6(journal.writeUnit, unitId), statuses ? inArray2(journal.status, statuses) : undefined));
5926
6001
  });
5927
6002
  const query = queryDialect.sqlToQuery(sql6`SELECT * FROM (${sql6.join(branches, sql6` UNION ALL `)}) AS unit ORDER BY unit."mutationSeq" ASC`);
5928
6003
  const result = await db.query(query.sql, query.params);
@@ -6253,15 +6328,60 @@ async function discardTerminalEntity(db, context, entityKey, entityKeyJson, term
6253
6328
  throw error;
6254
6329
  }
6255
6330
  }
6256
- function buildOverlayDiscardQuery(context, entityKey, entityKeyJson, owedStatuses) {
6331
+ function buildOverlayDiscardQuery(context, entityKey, entityKeyJson) {
6257
6332
  const overlay = context.tables.overlay;
6258
6333
  const journal = context.tables.journal;
6259
- const owed = queryBuilder.select({ one: sql6`1` }).from(journal).where(owedStatuses ? and5(eq6(journal.entityKeyJson, entityKeyJson), inArray2(journal.status, owedStatuses)) : eq6(journal.entityKeyJson, entityKeyJson));
6334
+ const owed = queryBuilder.select({ one: sql6`1` }).from(journal).where(eq6(journal.entityKeyJson, entityKeyJson));
6260
6335
  return queryBuilder.delete(overlay).where(and5(...context.pkColumnNames.map((columnName, index) => eq6(context.overlayPkColumns[index], entityKey[columnName])), notExists2(owed))).toSQL();
6261
6336
  }
6262
- async function discardOverlayForSettledEntity(db, context, entityKey, entityKeyJson) {
6263
- const query = buildOverlayDiscardQuery(context, entityKey, entityKeyJson, ["pending", "sending", "failed"]);
6264
- await db.query(query.sql, query.params);
6337
+ async function restoreOverlayAfterRejection(db, context, entityKey, entityKeyJson) {
6338
+ const syncedQuery = queryDialect.sqlToQuery(sql6`SELECT ${buildProjectedSelectColumns(context, context.syncedColumnsByPropertyKey)}
6339
+ FROM ${context.tables.synced}
6340
+ WHERE ${and5(...context.pkColumnNames.map((name, i) => eq6(context.syncedPkColumns[i], entityKey[name])))}`);
6341
+ const synced = (await db.query(syncedQuery.sql, syncedQuery.params)).rows[0];
6342
+ const journal = context.tables.journal;
6343
+ const query = queryBuilder.select({
6344
+ kind: sql6`${journal.mutationKind}`.as("kind"),
6345
+ payload: sql6`${journal.payloadJson}`.as("payload"),
6346
+ status: journal.status,
6347
+ writeMode: sql6`${journal.writeMode}`.as("writeMode"),
6348
+ enqueuedAtUs: sql6`${journal.enqueuedAtUs}::text`.as("enqueuedAtUs"),
6349
+ serverUpdatedAtUs: sql6`${journal.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs")
6350
+ }).from(journal).where(and5(eq6(journal.entityKeyJson, entityKeyJson), ne(journal.status, "rejected"))).orderBy(asc2(journal.mutationSeq)).toSQL();
6351
+ const rows = (await db.query(query.sql, query.params)).rows;
6352
+ let record = synced ?? null;
6353
+ let overlayKind = "pending_update";
6354
+ let localUpdatedAtUs = "0";
6355
+ let hasOverlay = false;
6356
+ const rawVersion = context.serverVersionPropertyKey && synced?.[context.serverVersionPropertyKey];
6357
+ const syncedVersion = typeof rawVersion === "string" || typeof rawVersion === "number" || typeof rawVersion === "bigint" ? BigInt(rawVersion) : null;
6358
+ for (const row of rows) {
6359
+ if (row.writeMode === "pessimistic-blind" || row.status === "acked" && row.serverUpdatedAtUs !== null && syncedVersion != null && BigInt(row.serverUpdatedAtUs) <= syncedVersion)
6360
+ continue;
6361
+ const payload = ensureRecord(JSON.parse(row.payload));
6362
+ if (row.kind === "create") {
6363
+ record = ensureRecord(payload["localValue"] ?? createOptimisticRecordFromContext(context, payload["value"]));
6364
+ overlayKind = "pending_create";
6365
+ } else if (record && row.kind === "update") {
6366
+ record = {
6367
+ ...record,
6368
+ ...ensureRecord(payload["patch"]),
6369
+ ...buildUpdateManagedNowStamp(context, row.enqueuedAtUs)
6370
+ };
6371
+ } else if (record && row.kind === "delete") {
6372
+ overlayKind = "pending_delete";
6373
+ }
6374
+ if (record) {
6375
+ hasOverlay = true;
6376
+ localUpdatedAtUs = row.enqueuedAtUs;
6377
+ }
6378
+ }
6379
+ if (hasOverlay && record) {
6380
+ await upsertOverlayRecordsBulk(db, context, [{ entityKey, record, overlayKind, localUpdatedAtUs }]);
6381
+ } else {
6382
+ const remove = queryBuilder.delete(context.tables.overlay).where(and5(...context.pkColumnNames.map((name, i) => eq6(context.overlayPkColumns[i], entityKey[name])))).toSQL();
6383
+ await db.query(remove.sql, remove.params);
6384
+ }
6265
6385
  }
6266
6386
  async function reconcileTable(db, context) {
6267
6387
  const journal = context.tables.journal;
@@ -12934,4 +13054,4 @@ export {
12934
13054
  wrapLiveQueryForMaterialization
12935
13055
  };
12936
13056
 
12937
- //# debugId=0070DC25354F3B0A64756E2164756E21
13057
+ //# debugId=B3DC27AFF4BE52A064756E2164756E21