@datafn/server 0.2.0 → 0.2.3

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 CHANGED
@@ -435,6 +435,8 @@ The mutation is rejected with `CONFLICT` if the guard condition is not met.
435
435
 
436
436
  Atomic multi-step transactions mixing queries and mutations.
437
437
 
438
+ Atomic execution needs database transactions. When the adapter reports `capabilities.transactions.supported === false` (for example the Drizzle adapter on SQLite or Cloudflare D1), an atomic transact with any mutation step returns HTTP 400 with `DFQL_UNSUPPORTED` (`details.path: "atomic"`) before anything is written. Send `"atomic": false` to apply steps one at a time.
439
+
438
440
  **Request:**
439
441
 
440
442
  ```json
package/dist/index.cjs CHANGED
@@ -8540,8 +8540,9 @@ async function recordChangesWithRetry(changeTracking, entries, maxRetries = 2, l
8540
8540
  }
8541
8541
  }
8542
8542
  }
8543
+ var preparedNamespaces = /* @__PURE__ */ new WeakMap();
8543
8544
  var ChangeTrackingService = class _ChangeTrackingService {
8544
- constructor(db, namespace = "datafn", sequenceStore, onChange, logger, metaEnsured = false, changesEnsured = false) {
8545
+ constructor(db, namespace = "datafn", sequenceStore, onChange, logger, metaEnsured = false, changesEnsured = false, namespaceMetaEnsured = false) {
8545
8546
  this.db = db;
8546
8547
  this.namespace = namespace;
8547
8548
  this.sequenceStore = sequenceStore;
@@ -8549,8 +8550,10 @@ var ChangeTrackingService = class _ChangeTrackingService {
8549
8550
  this.logger = logger;
8550
8551
  this.metaEnsured = false;
8551
8552
  this.changesEnsured = false;
8553
+ this.namespaceMetaEnsured = false;
8552
8554
  this.metaEnsured = metaEnsured;
8553
8555
  this.changesEnsured = changesEnsured;
8556
+ this.namespaceMetaEnsured = namespaceMetaEnsured;
8554
8557
  }
8555
8558
  /** Initialize every durable table before an enclosing transaction begins. */
8556
8559
  async ensureReady() {
@@ -8565,6 +8568,48 @@ var ChangeTrackingService = class _ChangeTrackingService {
8565
8568
  await ensureInternalTable(this.db, "__datafn_meta");
8566
8569
  this.metaEnsured = true;
8567
8570
  }
8571
+ await this.ensureNamespaceMeta();
8572
+ }
8573
+ /**
8574
+ * Creates this namespace's `__datafn_meta` row before an enclosing
8575
+ * transaction begins. Sequence allocation otherwise creates the row inside
8576
+ * the transaction on a namespace's first write, and when two first writes
8577
+ * race, the losing INSERT fails with a unique-key conflict. On PostgreSQL that
8578
+ * aborts the whole transaction, so the recovery read that follows fails with
8579
+ * "current transaction is aborted". Outside a transaction the conflict is
8580
+ * harmless: the row exists either way, and later allocations only read and
8581
+ * CAS-update it. Transaction-bound instances (from `withDb`) never prepare
8582
+ * the row; the base instance does so before the transaction opens.
8583
+ */
8584
+ async ensureNamespaceMeta() {
8585
+ if (this.namespaceMetaEnsured) {
8586
+ return;
8587
+ }
8588
+ let prepared = preparedNamespaces.get(this.db);
8589
+ if (!prepared) {
8590
+ prepared = /* @__PURE__ */ new Set();
8591
+ preparedNamespaces.set(this.db, prepared);
8592
+ }
8593
+ if (prepared.has(this.namespace)) {
8594
+ this.namespaceMetaEnsured = true;
8595
+ return;
8596
+ }
8597
+ const where = [{ field: "namespace", op: "eq", value: this.namespace }];
8598
+ if (!await this.db.internal.findOne("__datafn_meta", where)) {
8599
+ try {
8600
+ await this.db.internal.create("__datafn_meta", {
8601
+ id: `meta:${this.namespace}`,
8602
+ namespace: this.namespace,
8603
+ next_server_seq: 1
8604
+ });
8605
+ } catch (error) {
8606
+ if (!await this.db.internal.findOne("__datafn_meta", where)) {
8607
+ throw error;
8608
+ }
8609
+ }
8610
+ }
8611
+ prepared.add(this.namespace);
8612
+ this.namespaceMetaEnsured = true;
8568
8613
  }
8569
8614
  /**
8570
8615
  * REL-011: Create a new ChangeTrackingService with a different db adapter.
@@ -8580,7 +8625,8 @@ var ChangeTrackingService = class _ChangeTrackingService {
8580
8625
  emitChanges ? this.onChange : void 0,
8581
8626
  this.logger,
8582
8627
  this.metaEnsured,
8583
- this.changesEnsured
8628
+ this.changesEnsured,
8629
+ true
8584
8630
  );
8585
8631
  }
8586
8632
  /**
@@ -10504,6 +10550,9 @@ function isRecord(value) {
10504
10550
  return typeof value === "object" && value !== null && !Array.isArray(value);
10505
10551
  }
10506
10552
  function isNotFoundError(error) {
10553
+ if (error?.name === "KvMergeContentionError" || error?.name === "KvMergeUnsupportedError") {
10554
+ return false;
10555
+ }
10507
10556
  const message = String(error?.message || "").toLowerCase();
10508
10557
  return error?.name === "NotFoundError" || message.includes("not found") || message.includes("zero rows");
10509
10558
  }
@@ -10597,6 +10646,136 @@ async function executeSchemaAwareMerge(params) {
10597
10646
  return { ok: false, code: "INTERNAL", message: "Internal error", path: "$", error: retryError };
10598
10647
  }
10599
10648
  }
10649
+ var KV_SET_MUTATION_ID_PREFIX = "kv-set-";
10650
+ var KV_MERGE_MAX_ATTEMPTS = 16;
10651
+ var KvMergeContentionError = class extends Error {
10652
+ constructor(id) {
10653
+ super(`KV merge of ${id} did not settle after ${KV_MERGE_MAX_ATTEMPTS} concurrent attempts`);
10654
+ this.retryable = true;
10655
+ this.name = "KvMergeContentionError";
10656
+ }
10657
+ };
10658
+ function isKvMergeContentionError(error) {
10659
+ return error?.name === "KvMergeContentionError";
10660
+ }
10661
+ var KvMergeUnsupportedError = class extends Error {
10662
+ constructor() {
10663
+ super(
10664
+ "KV merge needs an adapter with transactions or strictUpdateNotFound to merge an existing record atomically"
10665
+ );
10666
+ this.name = "KvMergeUnsupportedError";
10667
+ }
10668
+ };
10669
+ function isKvMergeUnsupportedError(error) {
10670
+ return error?.name === "KvMergeUnsupportedError";
10671
+ }
10672
+ function isPlainObject(value) {
10673
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10674
+ }
10675
+ function notFound() {
10676
+ return { name: "NotFoundError", message: "Record not found" };
10677
+ }
10678
+ function isKvValueMerge(mutation) {
10679
+ return mutation.resource === core.KV_RESOURCE_NAME && mutation.operation === "merge" && isPlainObject(mutation.record) && Object.prototype.hasOwnProperty.call(mutation.record, "value") && !(typeof mutation.mutationId === "string" && mutation.mutationId.startsWith(KV_SET_MUTATION_ID_PREFIX));
10680
+ }
10681
+ function mergeKvValue(stored, patch) {
10682
+ if (!isPlainObject(stored) || !isPlainObject(patch)) {
10683
+ return patch;
10684
+ }
10685
+ return { ...stored, ...patch };
10686
+ }
10687
+ function supportsTransactions(db) {
10688
+ return db.capabilities?.transactions?.supported !== false && typeof db.transaction === "function";
10689
+ }
10690
+ function isTransactionUnsupportedError(error) {
10691
+ if (error?.name === "OperationNotSupportedError") return true;
10692
+ const message = String(error?.message ?? error).toLowerCase();
10693
+ return message.includes("cannot return a promise") || message.includes("not supported") || message.includes("not implemented");
10694
+ }
10695
+ async function updateKvRecordMerging(params) {
10696
+ const { db, resource, id, namespace, data, inTransaction } = params;
10697
+ const where = [{ field: "id", operator: "eq", value: id }];
10698
+ const strictUpdateNotFound = db.capabilities?.operations?.strictUpdateNotFound === true;
10699
+ const readStored = async (target) => {
10700
+ const row = await target.findOne({
10701
+ model: resource,
10702
+ where,
10703
+ namespace
10704
+ });
10705
+ if (!row) throw notFound();
10706
+ return row;
10707
+ };
10708
+ const tryUpdate = async (target, updateWhere, updateData) => {
10709
+ try {
10710
+ const updated = await target.update({
10711
+ model: resource,
10712
+ where: updateWhere,
10713
+ data: updateData,
10714
+ namespace
10715
+ });
10716
+ return !(strictUpdateNotFound && updated === void 0);
10717
+ } catch (error) {
10718
+ if (isNotFoundError(error)) return false;
10719
+ throw error;
10720
+ }
10721
+ };
10722
+ const withMergedValue = (stored) => ({
10723
+ ...data,
10724
+ value: mergeKvValue(stored.value, data.value)
10725
+ });
10726
+ const mergeLocked = async (trx) => {
10727
+ if (!await tryUpdate(trx, where, { id })) throw notFound();
10728
+ const written = withMergedValue(await readStored(trx));
10729
+ if (!await tryUpdate(trx, where, written)) throw notFound();
10730
+ return written;
10731
+ };
10732
+ if (inTransaction) {
10733
+ return mergeLocked(db);
10734
+ }
10735
+ if (supportsTransactions(db)) {
10736
+ let started = false;
10737
+ try {
10738
+ return await db.transaction(async (trx) => {
10739
+ started = true;
10740
+ return mergeLocked(trx);
10741
+ });
10742
+ } catch (error) {
10743
+ if (started || !isTransactionUnsupportedError(error)) throw error;
10744
+ }
10745
+ }
10746
+ if (!strictUpdateNotFound) {
10747
+ await readStored(db);
10748
+ throw new KvMergeUnsupportedError();
10749
+ }
10750
+ for (let attempt = 0; attempt < KV_MERGE_MAX_ATTEMPTS; attempt += 1) {
10751
+ const stored = await readStored(db);
10752
+ const current = stored.value ?? null;
10753
+ const written = withMergedValue(stored);
10754
+ const updateWhere = [
10755
+ ...where,
10756
+ { field: "value", operator: "eq", value: current }
10757
+ ];
10758
+ if (await tryUpdate(db, updateWhere, written)) {
10759
+ return written;
10760
+ }
10761
+ }
10762
+ throw new KvMergeContentionError(id);
10763
+ }
10764
+ function isKvResource(resource) {
10765
+ return resource === core.KV_RESOURCE_NAME;
10766
+ }
10767
+ async function snapshotKvChange(params) {
10768
+ const { db, id, namespace, op, record } = params;
10769
+ const row = await db.findOne({
10770
+ model: core.KV_RESOURCE_NAME,
10771
+ where: [{ field: "id", operator: "eq", value: id }],
10772
+ namespace
10773
+ });
10774
+ if (!row) return { op: "delete", record: null };
10775
+ const value = row.value ?? null;
10776
+ if (op === "delete" || !record) return { op: "upsert", record: { id, value } };
10777
+ return { op, record: { ...record, id, value } };
10778
+ }
10600
10779
 
10601
10780
  // src/execution/mutation/share.ts
10602
10781
  function getShareableConfig(resolvedCapabilities) {
@@ -12420,7 +12599,7 @@ function hasShareableCapability(resolvedCapabilities) {
12420
12599
  (entry) => typeof entry === "object" && entry !== null && "shareable" in entry
12421
12600
  );
12422
12601
  }
12423
- async function executeMutationCore(mutation, db, schema, namespace, effectiveMutationId, changeTracking, actorId, logger, multiRegionRuntime) {
12602
+ async function executeMutationCore(mutation, db, schema, namespace, effectiveMutationId, changeTracking, actorId, logger, multiRegionRuntime, inTransaction = false) {
12424
12603
  const resolvedCapabilities = resolveCapabilitiesForResource(schema, mutation.resource);
12425
12604
  let opResult;
12426
12605
  let resolvedRecord;
@@ -12494,12 +12673,25 @@ async function executeMutationCore(mutation, db, schema, namespace, effectiveMut
12494
12673
  actorId
12495
12674
  );
12496
12675
  const strictUpdateNotFound = db.capabilities?.operations?.strictUpdateNotFound === true;
12676
+ const kvValueMerge = isKvValueMerge(mutation);
12677
+ let kvMergedData;
12497
12678
  const mergeResult = await executeSchemaAwareMerge({
12498
12679
  schema,
12499
12680
  resource: mutation.resource,
12500
12681
  id: mutation.id,
12501
12682
  delta: mergeData,
12502
12683
  update: async () => {
12684
+ if (kvValueMerge) {
12685
+ kvMergedData = await updateKvRecordMerging({
12686
+ db,
12687
+ resource: mutation.resource,
12688
+ id: mutation.id,
12689
+ namespace,
12690
+ data: mergeData,
12691
+ inTransaction
12692
+ });
12693
+ return;
12694
+ }
12503
12695
  const updated = await db.update({
12504
12696
  model: mutation.resource,
12505
12697
  where: [{ field: "id", operator: "eq", value: mutation.id }],
@@ -12526,7 +12718,7 @@ async function executeMutationCore(mutation, db, schema, namespace, effectiveMut
12526
12718
  }
12527
12719
  });
12528
12720
  if (mergeResult.ok) {
12529
- resolvedRecord = mergeData;
12721
+ resolvedRecord = mergeResult.mode !== "create" && kvMergedData ? kvMergedData : mergeData;
12530
12722
  additionalChanges.push(...await applyInactivePropagation(
12531
12723
  db,
12532
12724
  schema,
@@ -12542,11 +12734,19 @@ async function executeMutationCore(mutation, db, schema, namespace, effectiveMut
12542
12734
  resource: mutation.resource
12543
12735
  });
12544
12736
  }
12545
- opResult = {
12737
+ opResult = isKvMergeUnsupportedError(mergeResult.error) ? {
12738
+ ok: false,
12739
+ code: "DFQL_UNSUPPORTED",
12740
+ message: mergeResult.error.message,
12741
+ path: "record.value"
12742
+ } : {
12546
12743
  ok: false,
12547
12744
  code: mergeResult.code,
12548
12745
  message: mergeResult.message,
12549
- path: mergeResult.path
12746
+ path: mergeResult.path,
12747
+ // A KV merge that gave up under contention wrote nothing;
12748
+ // the same mutation can succeed when retried.
12749
+ retryable: isKvMergeContentionError(mergeResult.error)
12550
12750
  };
12551
12751
  }
12552
12752
  }
@@ -13061,7 +13261,12 @@ async function executeMutationCore(mutation, db, schema, namespace, effectiveMut
13061
13261
  ok: false,
13062
13262
  mutationId: effectiveMutationId,
13063
13263
  affectedIds: [],
13064
- errors: [{ code: opResult.code, message: opResult.message, path: opResult.path, retryable: false }],
13264
+ errors: [{
13265
+ code: opResult.code,
13266
+ message: opResult.message,
13267
+ path: opResult.path,
13268
+ retryable: opResult.retryable === true
13269
+ }],
13065
13270
  deduped: false
13066
13271
  };
13067
13272
  if (failedShareCompensation) {
@@ -13104,8 +13309,21 @@ async function executeMutationCore(mutation, db, schema, namespace, effectiveMut
13104
13309
  primaryChange,
13105
13310
  ...additionalChanges
13106
13311
  ];
13312
+ const snapshotPrimaryKvChange = async () => {
13313
+ if (!isKvResource(primaryChange.resource)) return;
13314
+ const snapshot = await snapshotKvChange({
13315
+ db,
13316
+ id: primaryChange.id,
13317
+ namespace,
13318
+ op: primaryChange.op,
13319
+ record: primaryChange.record
13320
+ });
13321
+ primaryChange.op = snapshot.op;
13322
+ primaryChange.record = snapshot.record;
13323
+ };
13107
13324
  if (allChanges.length > 1) {
13108
13325
  const seqs = await changeTracking.getNextServerSeqBatch(allChanges.length);
13326
+ await snapshotPrimaryKvChange();
13109
13327
  await recordChangesWithRetry(
13110
13328
  changeTracking,
13111
13329
  allChanges.map((change, i) => ({
@@ -13120,6 +13338,7 @@ async function executeMutationCore(mutation, db, schema, namespace, effectiveMut
13120
13338
  );
13121
13339
  } else {
13122
13340
  const serverSeq = await changeTracking.getNextServerSeq();
13341
+ await snapshotPrimaryKvChange();
13123
13342
  await recordChangeWithRetry(changeTracking, {
13124
13343
  serverSeq,
13125
13344
  ...primaryChange
@@ -13353,7 +13572,8 @@ async function executeMutation(mutation, schema, db, idempotencyStore, changeTra
13353
13572
  changeTracking.withDb(txDb),
13354
13573
  actorId,
13355
13574
  logger,
13356
- multiRegionRuntime
13575
+ multiRegionRuntime,
13576
+ true
13357
13577
  );
13358
13578
  if (txMutationResult.ok && shouldQueuePermissionDirectorySync) {
13359
13579
  await queuePermissionDirectorySync(txDb);
@@ -13459,7 +13679,8 @@ async function executeMutation(mutation, schema, db, idempotencyStore, changeTra
13459
13679
  changeTracking.withDb(txDb),
13460
13680
  actorId,
13461
13681
  logger,
13462
- multiRegionRuntime
13682
+ multiRegionRuntime,
13683
+ true
13463
13684
  );
13464
13685
  if (txMutationResult.ok && shouldQueuePermissionDirectorySync) {
13465
13686
  await queuePermissionDirectorySync(txDb);
@@ -13509,7 +13730,8 @@ async function executeMutation(mutation, schema, db, idempotencyStore, changeTra
13509
13730
  changeTracking.withDb(db),
13510
13731
  actorId,
13511
13732
  logger,
13512
- multiRegionRuntime
13733
+ multiRegionRuntime,
13734
+ insideTransaction
13513
13735
  );
13514
13736
  } catch (error) {
13515
13737
  await releasePermissionDirectoryTask();
@@ -13757,6 +13979,16 @@ async function executeTransaction(request, schema, db, idempotencyStore, limits,
13757
13979
  const steps = request.steps;
13758
13980
  const isAtomic = request.atomic !== false;
13759
13981
  const hasMutations = steps.some((step) => Boolean(step.mutation));
13982
+ if (isAtomic && hasMutations && db.capabilities?.transactions?.supported === false) {
13983
+ return {
13984
+ ok: false,
13985
+ error: {
13986
+ code: "DFQL_UNSUPPORTED",
13987
+ message: "Atomic transact with mutations requires database transactions, which this adapter does not support; send atomic: false to apply steps one at a time",
13988
+ details: { path: "atomic" }
13989
+ }
13990
+ };
13991
+ }
13760
13992
  const multiRegionRuntime = getDatafnMultiRegionRuntimeConfig(plugins);
13761
13993
  const needsPermissionDirectoryOutbox = Boolean(
13762
13994
  hasMutations && multiRegionRuntime && steps.some(
@@ -13879,7 +14111,7 @@ async function executeTransaction(request, schema, db, idempotencyStore, limits,
13879
14111
  }
13880
14112
  return null;
13881
14113
  };
13882
- if (isAtomic && typeof db.transaction === "function") {
14114
+ if (isAtomic && db.capabilities?.transactions?.supported !== false && typeof db.transaction === "function") {
13883
14115
  const deferredPermissionDirectorySyncs = [];
13884
14116
  const reconcilePermissionDirectoryAfterSettlement = async () => {
13885
14117
  await drainPrequeuedUnshareTasks();
@@ -15532,6 +15764,26 @@ async function executePush(request, schema, db, idempotencyStore, namespace, seq
15532
15764
  }
15533
15765
  return allocation.pool.shift();
15534
15766
  }
15767
+ async function sequenceChange(change, allocation, targetDb, targetChangeTracking = changeTracking) {
15768
+ if (!isKvResource(change.resource)) {
15769
+ return {
15770
+ seq: await takeNextServerSeq(allocation, targetChangeTracking),
15771
+ op: change.op,
15772
+ record: change.record
15773
+ };
15774
+ }
15775
+ allocation.initialBatchAllocated = true;
15776
+ allocation.pool = [];
15777
+ const seq = await targetChangeTracking.getNextServerSeq();
15778
+ const snapshot = await snapshotKvChange({
15779
+ db: targetDb,
15780
+ id: change.id,
15781
+ namespace,
15782
+ op: change.op,
15783
+ record: change.record
15784
+ });
15785
+ return { seq, ...snapshot };
15786
+ }
15535
15787
  async function collectPropagationChanges(targetDb, seeds) {
15536
15788
  return (await applyInactivePropagation(targetDb, schema, seeds, namespace)).map((change) => ({
15537
15789
  resource: change.resource,
@@ -15621,12 +15873,25 @@ async function executePush(request, schema, db, idempotencyStore, namespace, seq
15621
15873
  actorId
15622
15874
  );
15623
15875
  const strictUpdateNotFound = targetDb.capabilities?.operations?.strictUpdateNotFound === true;
15876
+ const kvValueMerge = isKvValueMerge(mut);
15877
+ let kvMergedData;
15624
15878
  const mergeResult = await executeSchemaAwareMerge({
15625
15879
  schema,
15626
15880
  resource: mut.resource,
15627
15881
  id: mut.id,
15628
15882
  delta: createData,
15629
15883
  update: async () => {
15884
+ if (kvValueMerge) {
15885
+ kvMergedData = await updateKvRecordMerging({
15886
+ db: targetDb,
15887
+ resource: mut.resource,
15888
+ id: mut.id,
15889
+ namespace,
15890
+ data: updateData,
15891
+ inTransaction: hasTransaction
15892
+ });
15893
+ return;
15894
+ }
15630
15895
  const updated = await targetDb.update({ model: mut.resource, where: [{ field: "id", operator: "eq", value: mut.id }], data: updateData, namespace });
15631
15896
  if (strictUpdateNotFound && updated === void 0) {
15632
15897
  throw { name: "NotFoundError", message: "Record not found after update" };
@@ -15640,7 +15905,7 @@ async function executePush(request, schema, db, idempotencyStore, namespace, seq
15640
15905
  }
15641
15906
  });
15642
15907
  if (mergeResult.ok) {
15643
- const changeRecordData = mergeResult.mode === "create" ? createData : updateData;
15908
+ const changeRecordData = mergeResult.mode === "create" ? createData : kvMergedData ?? updateData;
15644
15909
  const propagationChanges = await collectPropagationChanges(
15645
15910
  targetDb,
15646
15911
  [{ resource: mut.resource, id: mut.id }]
@@ -15648,12 +15913,20 @@ async function executePush(request, schema, db, idempotencyStore, namespace, seq
15648
15913
  return {
15649
15914
  ok: true,
15650
15915
  changes: [
15651
- { resource: mut.resource, id: mut.id, op: "merge", record: { id: mut.id, ...changeRecordData } },
15916
+ {
15917
+ resource: mut.resource,
15918
+ id: mut.id,
15919
+ op: "merge",
15920
+ record: { id: mut.id, ...changeRecordData }
15921
+ },
15652
15922
  ...propagationChanges
15653
15923
  ]
15654
15924
  };
15655
15925
  }
15656
15926
  if (mergeResult.code === "NOT_FOUND") return { ok: false, code: "NOT_FOUND", message: `Record not found: ${mut.id}`, path: "id" };
15927
+ if (isKvMergeUnsupportedError(mergeResult.error)) {
15928
+ return { ok: false, code: "DFQL_UNSUPPORTED", message: mergeResult.error.message, path: "record.value" };
15929
+ }
15657
15930
  logger?.error("Push merge failed", { error: String(mergeResult.error), operation: mut.operation, resource: mut.resource, id: mut.id });
15658
15931
  return { ok: false, code: "INTERNAL", message: "Internal error", path: "$" };
15659
15932
  }
@@ -16241,7 +16514,12 @@ async function executePush(request, schema, db, idempotencyStore, namespace, seq
16241
16514
  const changes = opResult.changes;
16242
16515
  const txChangeTracking = changeTracking.withDb(txDb, false);
16243
16516
  for (const change of changes) {
16244
- const seq = await takeNextServerSeq(txSequenceAllocation, txChangeTracking);
16517
+ const { seq, op, record } = await sequenceChange(
16518
+ change,
16519
+ txSequenceAllocation,
16520
+ txDb,
16521
+ txChangeTracking
16522
+ );
16245
16523
  mutationLatestSeq = Math.max(mutationLatestSeq, seq);
16246
16524
  mutationResourceSeqs[change.resource] = Math.max(
16247
16525
  mutationResourceSeqs[change.resource] || 0,
@@ -16251,8 +16529,8 @@ async function executePush(request, schema, db, idempotencyStore, namespace, seq
16251
16529
  serverSeq: seq,
16252
16530
  resource: change.resource,
16253
16531
  id: change.id,
16254
- op: change.op,
16255
- record: change.record
16532
+ op,
16533
+ record
16256
16534
  }, 2, logger);
16257
16535
  pendingChangeEvents.push(seq);
16258
16536
  }
@@ -16331,15 +16609,15 @@ async function executePush(request, schema, db, idempotencyStore, namespace, seq
16331
16609
  let changeTrackingFailed = false;
16332
16610
  try {
16333
16611
  for (const change of changes) {
16334
- const seq = await takeNextServerSeq(sequenceAllocation);
16612
+ const { seq, op, record } = await sequenceChange(change, sequenceAllocation, db);
16335
16613
  latestSeq = Math.max(latestSeq, seq);
16336
16614
  resourceSeqs[change.resource] = Math.max(resourceSeqs[change.resource] || 0, seq);
16337
16615
  await recordChangeWithRetry(changeTracking, {
16338
16616
  serverSeq: seq,
16339
16617
  resource: change.resource,
16340
16618
  id: change.id,
16341
- op: change.op,
16342
- record: change.record
16619
+ op,
16620
+ record
16343
16621
  }, 2, logger);
16344
16622
  }
16345
16623
  } catch (error) {
@@ -17343,7 +17621,7 @@ function analyzeFilterComplexity(node, depth = 1) {
17343
17621
  }
17344
17622
  return { depth: maxDepth, conditions };
17345
17623
  }
17346
- function isPlainObject(value) {
17624
+ function isPlainObject2(value) {
17347
17625
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
17348
17626
  return false;
17349
17627
  }
@@ -17351,9 +17629,9 @@ function isPlainObject(value) {
17351
17629
  return proto === Object.prototype || proto === null;
17352
17630
  }
17353
17631
  async function normalizeSearchTemporalFilters(input) {
17354
- const temporalByResource = isPlainObject(input.raw.temporalByResource) ? input.raw.temporalByResource : void 0;
17632
+ const temporalByResource = isPlainObject2(input.raw.temporalByResource) ? input.raw.temporalByResource : void 0;
17355
17633
  const temporal = input.raw.temporal;
17356
- const baseFilters = isPlainObject(input.raw.filters) ? input.raw.filters : {};
17634
+ const baseFilters = isPlainObject2(input.raw.filters) ? input.raw.filters : {};
17357
17635
  if (!temporalByResource && !temporal) {
17358
17636
  return Object.keys(baseFilters).length > 0 ? baseFilters : void 0;
17359
17637
  }
@@ -17391,7 +17669,7 @@ async function normalizeSearchTemporalFilters(input) {
17391
17669
  },
17392
17670
  temporalConfig
17393
17671
  );
17394
- if (isPlainObject(normalized.filters)) {
17672
+ if (isPlainObject2(normalized.filters)) {
17395
17673
  normalizedFilters[resource] = normalized.filters;
17396
17674
  }
17397
17675
  }
@@ -17514,7 +17792,7 @@ function createSearchHandler(validatedSchema, extractNamespace, extractActorId,
17514
17792
  });
17515
17793
  }
17516
17794
  if (raw.fieldBoosts !== void 0) {
17517
- if (!isPlainObject(raw.fieldBoosts)) {
17795
+ if (!isPlainObject2(raw.fieldBoosts)) {
17518
17796
  return errorResponse({
17519
17797
  code: "DFQL_INVALID",
17520
17798
  message: "Invalid request: fieldBoosts must be an object",