@salesforce/lds-worker-api 1.466.0 → 1.468.0

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.
@@ -4282,7 +4282,7 @@
4282
4282
  }
4283
4283
  callbacks.push(callback);
4284
4284
  }
4285
- // version: 1.466.0-b7b08a8e3c
4285
+ // version: 1.468.0-9ef0fbdaee
4286
4286
 
4287
4287
  // TODO [TD-0081508]: once that TD is fulfilled we can probably change this file
4288
4288
  function instrumentAdapter$1(createFunction, _metadata) {
@@ -5326,7 +5326,7 @@
5326
5326
  const { apiFamily, name } = metadata;
5327
5327
  return createGraphQLWireAdapterConstructor$1(adapter, `${apiFamily}.${name}`, luvio, astResolver);
5328
5328
  }
5329
- // version: 1.466.0-b7b08a8e3c
5329
+ // version: 1.468.0-9ef0fbdaee
5330
5330
 
5331
5331
  function isSupportedEntity(_objectApiName) {
5332
5332
  return true;
@@ -32571,7 +32571,7 @@
32571
32571
  throttle(60, 60000, setupNotifyAllListRecordUpdateAvailable(luvio));
32572
32572
  throttle(60, 60000, setupNotifyAllListInfoSummaryUpdateAvailable(luvio));
32573
32573
  });
32574
- // version: 1.466.0-ba624febc8
32574
+ // version: 1.468.0-c060a9b9c6
32575
32575
 
32576
32576
  var draftQueueMaxRetryAttemptsGate = {
32577
32577
  isOpen: function (e) {
@@ -32652,6 +32652,15 @@
32652
32652
  },
32653
32653
  };
32654
32654
 
32655
+ var sideEffectRefreshKillSwitch = {
32656
+ isOpen: function (e) {
32657
+ return e.fallback;
32658
+ },
32659
+ hasError: function () {
32660
+ return !0;
32661
+ },
32662
+ };
32663
+
32655
32664
  var caseSensitiveUserId = '005B0000000GR4OIAW';
32656
32665
 
32657
32666
  /**
@@ -44103,6 +44112,15 @@
44103
44112
  return luvioDocumentNode;
44104
44113
  }
44105
44114
 
44115
+ var parentRelationshipPrefetchKillSwitch = {
44116
+ isOpen: function (e) {
44117
+ return e.fallback;
44118
+ },
44119
+ hasError: function () {
44120
+ return !0;
44121
+ },
44122
+ };
44123
+
44106
44124
  var graphqlRelationshipFieldsPerf = {
44107
44125
  isOpen: function (e) {
44108
44126
  return e.fallback;
@@ -48056,6 +48074,14 @@
48056
48074
  * Triggered after the Draft Queue state changes
48057
48075
  */
48058
48076
  DraftQueueEventType["QueueStateChanged"] = "state";
48077
+ /**
48078
+ * Triggered when batch-journal crash recovery (B2, Performance Upload path)
48079
+ * could not complete: a maybe-committed all-or-none batch's members could not
48080
+ * be durably quarantined this session, a startup reconcile failed, or a
48081
+ * resolved journal row could not be cleared. Carries only a bounded reason
48082
+ * code (no ids/messages) so it is safe to surface to o11y.
48083
+ */
48084
+ DraftQueueEventType["BatchRecoveryFailed"] = "batchRecoveryFailed";
48059
48085
  })(DraftQueueEventType || (DraftQueueEventType = {}));
48060
48086
  var QueueOperationType;
48061
48087
  (function (QueueOperationType) {
@@ -48265,6 +48291,8 @@
48265
48291
  mergeActions: () => {
48266
48292
  throw Error('mergeActions not supported for custom actions');
48267
48293
  },
48294
+ getDraftIdsFromAction: (action) => [action.targetId],
48295
+ getRedirectMappings: () => undefined,
48268
48296
  };
48269
48297
  }
48270
48298
 
@@ -48348,6 +48376,13 @@
48348
48376
  const handler = customActionHandler(executor, id, this);
48349
48377
  return this.addHandler(handler);
48350
48378
  }
48379
+ /**
48380
+ * True when a handler for `id` is registered on this queue — i.e. this queue owns
48381
+ * (and drains) the actions carrying that handlerId.
48382
+ */
48383
+ isHandlerRegistered(id) {
48384
+ return this.handlers[id] !== undefined;
48385
+ }
48351
48386
  getQueueState() {
48352
48387
  return this.state;
48353
48388
  }
@@ -48372,6 +48407,11 @@
48372
48407
  }
48373
48408
  this.retryIntervalMilliseconds = 0;
48374
48409
  this.state = DraftQueueState.Started;
48410
+ // Stuck-queue detection: a live upload keeps the queue Started (filtered by the early
48411
+ // return above), so a stale uploadingActionId here strands processNextAction() on it.
48412
+ if (this.uploadingActionId !== undefined && this.logger) {
48413
+ this.logger.logWarning(`Draft queue restarting with action still marked uploading (stale uploadingActionId=${this.uploadingActionId}); possible abandoned-upload stuck queue`);
48414
+ }
48375
48415
  await this.notifyChangedListeners({
48376
48416
  type: DraftQueueEventType.QueueStateChanged,
48377
48417
  state: this.state,
@@ -48676,6 +48716,48 @@
48676
48716
  await this.startQueue();
48677
48717
  }
48678
48718
  }
48719
+ /**
48720
+ * Builds the set of actions deleted by removing `action`, validating
48721
+ * before any store mutation. Same-tag actions are ordered newest-first so
48722
+ * the clicked create is handled last and each intermediate side-effect
48723
+ * replay reflects a valid undo prefix.
48724
+ */
48725
+ resolveActionsToRemove(action, queue, isUploading) {
48726
+ const shouldDeleteRelated = this.getHandler(action.handler).shouldDeleteActionByTagOnRemoval(action);
48727
+ const removedActions = shouldDeleteRelated
48728
+ ? queue.filter((a) => a.tag === action.tag).reverse()
48729
+ : [action];
48730
+ const uploading = removedActions.find((a) => isUploading(a.id));
48731
+ if (uploading !== undefined) {
48732
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
48733
+ throw new Error(`Cannot remove an uploading draft action with ID ${uploading.id}`);
48734
+ }
48735
+ return {
48736
+ shouldDeleteRelated,
48737
+ removed: removedActions.map((a) => ({
48738
+ action: a,
48739
+ handler: this.getHandler(a.handler),
48740
+ })),
48741
+ };
48742
+ }
48743
+ /**
48744
+ * Runs every removed action's handler cleanup before emitting any
48745
+ * ActionDeleted event, so listeners observe the final side-effect state.
48746
+ */
48747
+ async notifyActionsRemoved(removed, queue) {
48748
+ const removedIds = new Set(removed.map(({ action }) => action.id));
48749
+ const remaining = queue.filter((a) => !removedIds.has(a.id));
48750
+ for (const { action, handler } of removed) {
48751
+ await handler.handleActionRemoved(action, remaining);
48752
+ }
48753
+ for (const { action } of removed) {
48754
+ await this.notifyChangedListeners({
48755
+ type: DraftQueueEventType.ActionDeleted,
48756
+ action,
48757
+ draftCount: this.draftStore.getCount(),
48758
+ });
48759
+ }
48760
+ }
48679
48761
  async removeDraftAction(actionId) {
48680
48762
  const queue = await this.getQueueActions();
48681
48763
  //Get the store key for the removed action
@@ -48685,32 +48767,18 @@
48685
48767
  throw new Error(`No removable action with id ${actionId}`);
48686
48768
  }
48687
48769
  const action = actions[0];
48688
- if (action.id === this.uploadingActionId) {
48689
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
48690
- throw new Error(`Cannot remove an uploading draft action with ID ${actionId}`);
48691
- }
48692
- const handler = this.getHandler(action.handler);
48693
- const shouldDeleteRelated = handler.shouldDeleteActionByTagOnRemoval(action);
48770
+ const { shouldDeleteRelated, removed } = this.resolveActionsToRemove(action, queue, (id) => id === this.uploadingActionId);
48694
48771
  if (shouldDeleteRelated) {
48695
48772
  await this.draftStore.deleteByTag(action.tag);
48696
- queue.forEach((queuedAction) => {
48697
- if (queuedAction.tag === action.tag) {
48698
- this.uploadStartTimes.delete(queuedAction.id);
48699
- this.actionQueueWaitEmittedIds.delete(queuedAction.id);
48700
- }
48701
- });
48702
48773
  }
48703
48774
  else {
48704
48775
  await this.draftStore.deleteDraft(action.id);
48705
- this.uploadStartTimes.delete(action.id);
48706
- this.actionQueueWaitEmittedIds.delete(action.id);
48707
48776
  }
48708
- await handler.handleActionRemoved(action, queue.filter((x) => x.id !== actionId));
48709
- await this.notifyChangedListeners({
48710
- type: DraftQueueEventType.ActionDeleted,
48711
- action,
48712
- draftCount: this.draftStore.getCount(),
48777
+ removed.forEach(({ action: a }) => {
48778
+ this.uploadStartTimes.delete(a.id);
48779
+ this.actionQueueWaitEmittedIds.delete(a.id);
48713
48780
  });
48781
+ await this.notifyActionsRemoved(removed, queue);
48714
48782
  if (this.userState === DraftQueueState.Started &&
48715
48783
  this.state !== DraftQueueState.Started &&
48716
48784
  this.replacingAction === undefined) {
@@ -48749,15 +48817,12 @@
48749
48817
  return this.replaceOrMergeActions(targetActionId, sourceActionId, true);
48750
48818
  }
48751
48819
  async retryAction(actionId) {
48752
- this.stopQueueManually(true);
48753
- const actions = await this.getQueueActions();
48754
- const target = actions[0];
48755
- if (!target || target.id !== actionId) {
48756
- throw Error(`Action ${actionId} not found at the head of the draft queue`);
48757
- }
48820
+ // Validate before stopping so a rejected retry leaves the queue state untouched.
48821
+ const target = await this.getRetryTarget(actionId);
48758
48822
  if (!isDraftError(target)) {
48759
48823
  throw Error(`Action ${actionId} is not in Error state`);
48760
48824
  }
48825
+ this.stopQueueManually(true);
48761
48826
  // A manual retry is a fresh start: clear the persisted upload retry-attempt
48762
48827
  // count so the action doesn't immediately re-cap after a single failure.
48763
48828
  const { [DRAFT_ACTION_RETRY_COUNT_METADATA_KEY]: _retryCount, ...metadataWithoutRetryCount } = target.metadata || {};
@@ -48776,6 +48841,18 @@
48776
48841
  await this.startQueueSafe();
48777
48842
  return pendingAction;
48778
48843
  }
48844
+ /**
48845
+ * The action `retryAction` may retry. Only the head: an errored head is what blocks a
48846
+ * strictly ordered queue.
48847
+ */
48848
+ async getRetryTarget(actionId) {
48849
+ const actions = await this.getQueueActions();
48850
+ const target = actions[0];
48851
+ if (!target || target.id !== actionId) {
48852
+ throw Error(`Action ${actionId} not found at the head of the draft queue`);
48853
+ }
48854
+ return target;
48855
+ }
48779
48856
  async setMetadata(actionId, metadata) {
48780
48857
  const keys$1 = keys$4(metadata);
48781
48858
  const compatibleKeys = keys$1.filter((key) => {
@@ -48902,239 +48979,1827 @@
48902
48979
  }
48903
48980
  }
48904
48981
 
48905
- function clone$1(obj) {
48906
- return parse$6(stringify$6(obj));
48982
+ /**
48983
+ * Narrows a peer DraftQueue to one that also participates in cross-queue
48984
+ * coordination. A peer may be a NimbusDraftQueue (gate-ON on-device path),
48985
+ * which implements DraftQueue but NOT CrossQueueCoordination, so this check
48986
+ * is load-bearing, not defensive.
48987
+ */
48988
+ function isCrossQueueCoordination(queue) {
48989
+ const candidate = queue;
48990
+ return (typeof candidate.applyDraftIdRedirects === 'function' &&
48991
+ typeof candidate.resumeDeferredActions === 'function' &&
48992
+ typeof candidate.getInFlightRewritableDraftIds === 'function' &&
48993
+ typeof candidate.getOwnedQueueActions === 'function');
48907
48994
  }
48908
-
48909
- const DRAFT_ACTION_KEY_JUNCTION = '__DraftAction__';
48910
- function buildDraftDurableStoreKey(recordKey, draftActionId) {
48911
- return `${recordKey}${DRAFT_ACTION_KEY_JUNCTION}${draftActionId}`;
48995
+ /**
48996
+ * Maximum number of draft actions to combine into a single UI-API Batch
48997
+ * request when batching is enabled. Tunable; chosen as a conservative starting
48998
+ * point that bounds payload size and retry cost while still amortizing TTFB
48999
+ * across many actions.
49000
+ */
49001
+ const MAX_BATCH_SIZE$1 = 25;
49002
+ /**
49003
+ * How many times clearBatchJournalIfSupported retries a failed journal clear
49004
+ * before giving up and escalating the log line. Bounded so a permanently-failing
49005
+ * store can't spin. A leftover row is mainly a scale concern (unbounded restart
49006
+ * reconcile); it can also cause a rare, fail-safe over-quarantine — a definitively
49007
+ * rolled-back batch's still-Pending siblings surface as commit-ambiguous on the
49008
+ * next restart (never a replay, since the envelope records no rolled-back outcome).
49009
+ * A small bound suffices for the spin guard; a durable rolled-back/resolved
49010
+ * tombstone is the follow-up to close the over-quarantine before queueBatching is
49011
+ * enabled (4077120435).
49012
+ */
49013
+ const CLEAR_JOURNAL_MAX_ATTEMPTS = 3;
49014
+ /**
49015
+ * Diagnostic log line for the local-experimental batching path. Routes through
49016
+ * JSLoggerPlugin.logInfo so messages surface in the iOS device log, each line
49017
+ * prefixed with `Batch `. Silently no-ops outside the LWR JSC environment.
49018
+ */
49019
+ function batchLog$1(line) {
49020
+ try {
49021
+ globalThis.__nimbus?.plugins?.JSLoggerPlugin?.logInfo(`Batch ${line}`);
49022
+ }
49023
+ catch {
49024
+ // debug-only; never fail real work because of logging
49025
+ }
48912
49026
  }
48913
49027
  /**
48914
- * Implements a write-through InMemoryStore for Drafts, storing all drafts in a
48915
- * in-memory store with a write through to the DurableStore.
48916
- *
48917
- * Before any reads or writes come in from the draft queue, we need to revive the draft
48918
- * queue into memory. During this initial revive, any writes are queued up and operated on the
48919
- * queue once it's in memory. Similarly any reads are delayed until the queue is in memory.
48920
- *
49028
+ * Bounded, scrubbed rendering of a caught value for the device log. Emits only
49029
+ * the error constructor NAME (e.g. "TypeError"), never the free-text message,
49030
+ * which can embed record ids (URL path segments) or server field-validation
49031
+ * strings. Mirrors the device-log PII policy in metrics.ts
49032
+ * (reportDraftActionUploadError): bounded metadata only; full detail belongs on
49033
+ * the structured, scrubbed o11y path (4065667273).
48921
49034
  */
48922
- class DurableDraftStore {
48923
- constructor(durableStore, instrumentation, useSnapshot = true) {
48924
- this.draftStore = {};
48925
- // Snapshot: holds deep clones of each draft, refreshed at write time.
48926
- // getAllDrafts serves from this snapshot with zero deep clones per read.
48927
- this.cleanSnapshot = {};
48928
- // queue of writes that were made during the initial sync
48929
- this.writeQueue = [];
48930
- this.durableStore = durableStore;
48931
- this.instrumentation = instrumentation;
48932
- this.useSnapshot = useSnapshot;
48933
- this.resyncDraftStore();
49035
+ function errName(e) {
49036
+ try {
49037
+ const name = e?.name;
49038
+ if (typeof name !== 'string' || name.length === 0) {
49039
+ return 'Error';
49040
+ }
49041
+ // Strip everything outside printable ASCII, then bound the length. The
49042
+ // id/free-text PII vector is already closed by reading `.name` (a
49043
+ // constructor name) and never `.message` (see above) — but a thrown object
49044
+ // can carry an arbitrary `name` (and reading it can trip a getter), so a
49045
+ // newline or control character could still break device-log-line integrity
49046
+ // and a pathological length could blow up a log entry. This drops control
49047
+ // sequences and bounds length; it does NOT attempt to strip a printable
49048
+ // identifier, since nothing in this path populates `.name` with one
49049
+ // (4077120502).
49050
+ const cleaned = name.replace(/[^\x20-\x7E]/g, '');
49051
+ if (cleaned.length === 0) {
49052
+ return 'Error';
49053
+ }
49054
+ return cleaned.length > 64 ? cleaned.slice(0, 64) : cleaned;
48934
49055
  }
48935
- // When no instrumentation is injected the promise is returned as-is (zero overhead).
48936
- timeDurableOp(op, segment, run) {
48937
- const onDurableOperation = this.instrumentation?.onDurableOperation;
48938
- if (onDurableOperation === undefined) {
48939
- return run();
48940
- }
48941
- const start = Date.now();
48942
- return run().finally(() => {
48943
- onDurableOperation(op, segment, Date.now() - start);
48944
- });
49056
+ catch {
49057
+ // Reading `.name` threw (a hostile getter). Scrubbing a value for the
49058
+ // log must never itself throw and take down the caller's error path.
49059
+ return 'Error';
48945
49060
  }
48946
- writeAction(action) {
48947
- const addAction = () => {
48948
- const { id, tag } = action;
48949
- this.draftStore[id] = action;
48950
- this.cleanSnapshot[id] = clone$1(action);
48951
- const durableEntryKey = buildDraftDurableStoreKey(tag, id);
48952
- const entry = {
48953
- data: action,
48954
- };
48955
- const entries = { [durableEntryKey]: entry };
48956
- return this.timeDurableOp('setEntries', DRAFT_SEGMENT, () => this.durableStore.setEntries(entries, DRAFT_SEGMENT));
49061
+ }
49062
+ /**
49063
+ * Builds the queue operations needed to rewrite every queued action whose
49064
+ * basePath/body text contains a draft id from `redirects`. If a queued
49065
+ * action's tag matches a redirect's draftKey, the action is deleted and
49066
+ * re-added at the canonical key. Pure function — no draft-store side
49067
+ * effects. Used by PerformanceDraftQueue.applyDraftIdRedirects to propagate
49068
+ * a peer queue's POST completion across queues.
49069
+ */
49070
+ function rewriteQueueActionsForRedirects(queue, redirects) {
49071
+ const queueOperations = [];
49072
+ if (redirects.length === 0) {
49073
+ return queueOperations;
49074
+ }
49075
+ for (let i = 0, len = queue.length; i < len; i++) {
49076
+ const queueAction = queue[i];
49077
+ const data = queueAction.data;
49078
+ if (data === undefined ||
49079
+ data === null ||
49080
+ typeof data.method !== 'string' ||
49081
+ data.body === undefined) {
49082
+ continue;
49083
+ }
49084
+ let basePath = data.basePath || '';
49085
+ let stringifiedBody = JSON.stringify(data.body || '');
49086
+ let mutated = false;
49087
+ let updatedTag;
49088
+ let updatedTargetId;
49089
+ for (const r of redirects) {
49090
+ if (basePath.indexOf(r.draftId) >= 0 || stringifiedBody.indexOf(r.draftId) >= 0) {
49091
+ const re = new RegExp(r.draftId, 'g');
49092
+ basePath = basePath.replace(re, r.canonicalId);
49093
+ stringifiedBody = stringifiedBody.replace(re, r.canonicalId);
49094
+ mutated = true;
49095
+ }
49096
+ if (queueAction.tag === r.draftKey) {
49097
+ updatedTag = r.canonicalKey;
49098
+ updatedTargetId = r.canonicalId;
49099
+ }
49100
+ }
49101
+ if (!mutated) {
49102
+ continue;
49103
+ }
49104
+ const baseUpdated = {
49105
+ ...queueAction,
49106
+ data: { ...data, basePath, body: JSON.parse(stringifiedBody) },
48957
49107
  };
48958
- return this.enqueueAction(addAction);
49108
+ if (updatedTag !== undefined && updatedTargetId !== undefined) {
49109
+ queueOperations.push({ type: QueueOperationType.Delete, id: queueAction.id });
49110
+ queueOperations.push({
49111
+ type: QueueOperationType.Add,
49112
+ action: { ...baseUpdated, tag: updatedTag, targetId: updatedTargetId },
49113
+ });
49114
+ }
49115
+ else {
49116
+ queueOperations.push({
49117
+ type: QueueOperationType.Update,
49118
+ id: queueAction.id,
49119
+ action: baseUpdated,
49120
+ });
49121
+ }
48959
49122
  }
48960
- getAllDrafts() {
48961
- const waitForOngoingSync = this.syncPromise || Promise.resolve();
48962
- return waitForOngoingSync.then(() => {
48963
- const actionArray = [];
48964
- if (this.useSnapshot) {
48965
- const { cleanSnapshot } = this;
48966
- const keys$1 = keys$4(cleanSnapshot);
48967
- for (let i = 0, len = keys$1.length; i < len; i++) {
48968
- const key = keys$1[i];
48969
- // Return shallow spread of snapshot entries so top-level caller mutations
48970
- // (e.g., .status =) don't persist into the snapshot. The snapshot itself
48971
- // is a deep clone of draftStore, so no nested mutation reaches draftStore.
48972
- actionArray.push({ ...cleanSnapshot[key] });
48973
- }
49123
+ return queueOperations;
49124
+ }
49125
+ /**
49126
+ * The Performance Upload draft queue. Extends {@link DurableDraftQueue} — the
49127
+ * base class is byte-identical to today's shipped serial queue — and adds the
49128
+ * multi-candidate concurrent scheduler, Set-based in-flight tracking,
49129
+ * cross-queue redirect propagation, and UI-API batching. Only constructed on
49130
+ * the gate-ON code path; gate-off customers never run any of this.
49131
+ */
49132
+ class PerformanceDraftQueue extends DurableDraftQueue {
49133
+ constructor(draftStore, { getPeerQueues = () => [], concurrency = 1, strictOrdering = true, queueBatching = false, } = {}) {
49134
+ super(draftStore);
49135
+ this.uploadingActionIds = new Set();
49136
+ // Reentrancy guard for processNextAction, which dispatches into free concurrency
49137
+ // slots with eligible actions. It is invoked un-awaited from several sites
49138
+ // (actionCompleted, applyDraftIdRedirects, resumeDeferredActions, enqueue)
49139
+ // and awaits mid-pass to read peer state, so without this two passes could
49140
+ // clear the concurrency guard, select the same action, and dispatch it
49141
+ // twice. `isDispatching` is set synchronously before any await; a concurrent
49142
+ // entrant records `redispatchRequested` and bails, and the active pass re-runs
49143
+ // to honor the missed wakeup.
49144
+ this.isDispatching = false;
49145
+ this.redispatchRequested = false;
49146
+ // Monotonic counter used to mint a unique batchId per dispatched batch
49147
+ // (combined with the head action id). Deterministic and dependency-free —
49148
+ // no Date/random — and unique within a session; across restarts a journal
49149
+ // is either cleared on completion or consumed by reconcile, so ids never
49150
+ // collide meaningfully.
49151
+ this.batchSequence = 0;
49152
+ // Guards the one-time batch-completion journal reconcile so it runs on the
49153
+ // first startQueue of the process (crash recovery) and not on every
49154
+ // stop/start cycle. Holds the in-flight reconcile promise rather than a
49155
+ // set-first boolean: startQueue can be called concurrently at launch (the
49156
+ // first call's reconcile awaits before super.startQueue() marks the queue
49157
+ // Started, so a second call still passes the base state guard). A boolean
49158
+ // set before the await would let that second call skip reconcile and begin
49159
+ // dispatching — re-batching a journaled, committed, not-yet-resolved member
49160
+ // and dropping its idempotency key. Every caller awaits the same promise,
49161
+ // so no dispatch begins until the members are surfaced as errors.
49162
+ this.reconcileBatchJournalsPromise = undefined;
49163
+ // Actions currently in retry backoff. A failed-but-retryable action stays
49164
+ // Pending in the store, so without this a re-entrant dispatch pass (a peer
49165
+ // kick or a sibling completion) could re-select and re-dispatch it before
49166
+ // its backoff timer fires. Populated in actionFailed's retry branch and
49167
+ // cleared per-action when that action's own backoff timer elapses, plus on
49168
+ // permanent failure / removal.
49169
+ this.retryingActionIds = new Set();
49170
+ // Members of a maybe-committed batch whose commit status could NOT be moved
49171
+ // to a durable Error this session (both the atomic completion and the
49172
+ // commit-ambiguous quarantine write failed — the store was rejecting writes
49173
+ // right after the server committed). They are still Pending in the store, so
49174
+ // without this guard a later startQueue / retryAllErrors / reconnect would
49175
+ // re-select them and re-batch keyless, replaying a maybe-committed write
49176
+ // (Option A forbids that). Excluded from dispatch (isDispatchable and the
49177
+ // single-action candidate loop) until they are durably resolved. In-memory
49178
+ // only: it bridges the current session; a restart clears it and the retained
49179
+ // batch journal is surfaced by reconcile before dispatch instead.
49180
+ this.commitAmbiguousUnresolvedIds = new Set();
49181
+ // Per-action retry backoff state. The serial base tracks a single
49182
+ // `timeoutHandler` + single `retryIntervalMilliseconds`, which conflate
49183
+ // concurrent retries: two actions failing at different times would overwrite
49184
+ // each other's timer (leaking the earlier one) and share one exponential
49185
+ // interval, so the first timer to fire would unpark every retrying action on
49186
+ // whichever backoff happened to be shortest. A concurrent queue instead
49187
+ // parks each action under its OWN timer and its OWN growing interval, keyed
49188
+ // by action id, so each retries on its own schedule independent of siblings.
49189
+ this.retryTimers = new Map();
49190
+ this.retryIntervals = new Map();
49191
+ // Draft ids of in-flight/just-completed POSTs whose redirects have not yet
49192
+ // been applied to peer queues. actionCompleted resolves a completing POST
49193
+ // out of the store (completeAction) BEFORE propagateRedirectsToPeers
49194
+ // fire-and-forgets the rewrite to peers, so between those two points
49195
+ // getInFlightRewritableDraftIds would no longer see the id in the store and
49196
+ // a peer could dispatch a queued action still carrying the stale draft id.
49197
+ // Ids are retained here before completeAction and released only once the
49198
+ // peer applyDraftIdRedirects calls settle; getInFlightRewritableDraftIds
49199
+ // unions this set so peers keep deferring across the gap.
49200
+ this.redirectingDraftIds = new Set();
49201
+ this.getPeerQueues = getPeerQueues;
49202
+ this.concurrency = concurrency;
49203
+ this.strictOrdering = strictOrdering;
49204
+ this.queueBatching = queueBatching;
49205
+ }
49206
+ /**
49207
+ * One-time batch-journal crash recovery (B2). A journal entry that survives
49208
+ * a restart means a batch was dispatched but its members were never
49209
+ * confirmed removed — the app may have died after the server committed the
49210
+ * all-or-none request. Any journaled member still Pending might therefore be
49211
+ * committed already, and the batch envelope carried no server-visible
49212
+ * idempotency key, so it must not be re-batched OR re-dispatched (either
49213
+ * would risk replaying a committed write). Surface every still-Pending member
49214
+ * as a commit-ambiguous error for manual resolution (Option A). The journal
49215
+ * entry is cleared only once its members are resolved (surfaced or already
49216
+ * gone), so a failure to record the error leaves the entry for the next
49217
+ * startup.
49218
+ */
49219
+ reconcileBatchJournalsOnce() {
49220
+ // Memoize the in-flight promise so concurrent startQueue calls all await
49221
+ // the same reconcile (see reconcileBatchJournalsPromise). Assigning
49222
+ // before the first await is the point: a later caller reuses this
49223
+ // promise instead of racing past a boolean that was flipped before the
49224
+ // pinning work ran.
49225
+ //
49226
+ // Reconcile must fail CLOSED (4065665821): if it rejects, startQueue does
49227
+ // NOT dispatch. But the failure must be RETRYABLE — clear the memo on
49228
+ // rejection so the next startQueue re-runs the reconcile rather than
49229
+ // reusing a cached rejection and never recovering. Success stays memoized
49230
+ // (runs at most once per process).
49231
+ if (this.reconcileBatchJournalsPromise === undefined) {
49232
+ this.reconcileBatchJournalsPromise = this.runBatchJournalReconcile().catch((e) => {
49233
+ this.reconcileBatchJournalsPromise = undefined;
49234
+ // Single choke point for every reconcile failure (journal read
49235
+ // error, resolve failure, or missing journal support): surface one
49236
+ // bounded o11y signal before re-throwing so startQueue still fails
49237
+ // closed. Fire-and-forget — the rejection must propagate unchanged.
49238
+ this.signalBatchRecoveryFailed('reconcile-failed');
49239
+ throw e;
49240
+ });
49241
+ }
49242
+ return this.reconcileBatchJournalsPromise;
49243
+ }
49244
+ async runBatchJournalReconcile() {
49245
+ // Nothing journals when batching is off, so there is nothing to reconcile.
49246
+ if (!this.queueBatching) {
49247
+ return;
49248
+ }
49249
+ const store = this.draftStore;
49250
+ if (typeof store.readRecoverableBatchJournals !== 'function' ||
49251
+ typeof store.clearBatchJournal !== 'function' ||
49252
+ typeof store.writeBatchJournal !== 'function') {
49253
+ // Batching is ON but the store cannot journal. Dispatching would batch
49254
+ // keyless writes with no crash backstop, so refuse to start rather than
49255
+ // silently run unprotected (4065665821). Throwing keeps startQueue
49256
+ // stopped; a store misconfigured this way will keep failing, which is
49257
+ // the intended fail-closed outcome.
49258
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
49259
+ throw new Error('PerformanceDraftQueue: batching enabled but the DraftStore lacks batch-journal support');
49260
+ }
49261
+ // A read failure THROWS here (not swallowed): it propagates through
49262
+ // reconcileBatchJournalsOnce so startQueue stays stopped and retries,
49263
+ // rather than proceeding to dispatch a member of a batch that may have
49264
+ // already committed (4065665821). Only RECOVERABLE journals are read —
49265
+ // crash residue from a dead process. A journal stamped with the live
49266
+ // session's token is a batch still in flight (possibly on a sibling queue
49267
+ // sharing this store); reconciling it would quarantine live members out
49268
+ // from under their owner, so the store filters those out.
49269
+ const journals = await store.readRecoverableBatchJournals();
49270
+ if (journals.length === 0) {
49271
+ return;
49272
+ }
49273
+ for (const journal of journals) {
49274
+ // A journaled member that never completed was in-flight when the
49275
+ // process died: the batch MAY have committed, and the envelope carried
49276
+ // no server-visible idempotency key, so we do NOT re-batch or
49277
+ // re-dispatch it. Surface every still-Pending member as commit-ambiguous
49278
+ // for manual resolution (Option A), then clear the journal once resolved.
49279
+ // A resolve failure THROWS (via reconcileBatchJournalsOnce) so startup
49280
+ // stays stopped-but-retryable and the journal is retained.
49281
+ //
49282
+ // errorAmbiguousActions reads its own fresh draft snapshot per call
49283
+ // rather than sharing one across this loop: each iteration awaits
49284
+ // completeAction and listener callbacks, which can delete a member
49285
+ // (listener re-entrancy, or a concurrent removeDraftAction/deleteByTag),
49286
+ // and a snapshot held across the loop would let a later journal
49287
+ // resurrect that just-deleted member as an Error draft via the blind
49288
+ // Update in completeAction (4077120311). A fresh read per journal costs
49289
+ // O(journals × drafts), acceptable on this once-per-process
49290
+ // crash-recovery path.
49291
+ const resolved = await this.errorAmbiguousActions(journal.memberIds);
49292
+ if (resolved) {
49293
+ await this.clearBatchJournalIfSupported(journal.batchId);
48974
49294
  }
48975
49295
  else {
48976
- // Killswitch (W-23515682): original pre-fix behavior — deep-clone every draft on
48977
- // every read so the internal draft store is never exposed. O(N) clones per read.
48978
- const { draftStore } = this;
48979
- const keys$1 = keys$4(draftStore);
48980
- for (let i = 0, len = keys$1.length; i < len; i++) {
48981
- actionArray.push(clone$1(draftStore[keys$1[i]]));
48982
- }
49296
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
49297
+ throw new Error(`PerformanceDraftQueue: batch journal ${journal.batchId} could not be reconciled`);
48983
49298
  }
48984
- return actionArray;
48985
- });
49299
+ }
48986
49300
  }
48987
- deleteDraft(id) {
48988
- const deleteAction = () => {
48989
- const draft = this.draftStore[id];
48990
- if (draft !== undefined) {
48991
- delete this.draftStore[id];
48992
- delete this.cleanSnapshot[id];
48993
- const durableKey = buildDraftDurableStoreKey(draft.tag, draft.id);
48994
- return this.timeDurableOp('evictEntries', DRAFT_SEGMENT, () => this.durableStore.evictEntries([durableKey], DRAFT_SEGMENT));
49301
+ // Overrides DurableDraftQueue.getQueueActions rather than reusing it: the
49302
+ // base marks the single in-flight action from its private `uploadingActionId`
49303
+ // (serial path), while the concurrent path tracks many in-flight ids in
49304
+ // `uploadingActionIds`. The base field is private, so the uploading check
49305
+ // cannot be shared without a base refactor; the rest of the body (sort) is
49306
+ // deliberately kept identical. If the base sort changes, mirror it here.
49307
+ async getQueueActions() {
49308
+ const drafts = (await this.draftStore.getAllDrafts());
49309
+ const queue = [];
49310
+ drafts.forEach((draft) => {
49311
+ if (this.uploadingActionIds.has(draft.id)) {
49312
+ draft.status = DraftActionStatus.Uploading;
49313
+ }
49314
+ queue.push(draft);
49315
+ });
49316
+ return queue.sort((a, b) => {
49317
+ const aTime = parseInt(a.id, 10);
49318
+ const bTime = parseInt(b.id, 10);
49319
+ // safety check
49320
+ if (isNaN(aTime)) {
49321
+ return 1;
49322
+ }
49323
+ if (isNaN(bTime)) {
49324
+ return -1;
48995
49325
  }
49326
+ return aTime - bTime;
49327
+ });
49328
+ }
49329
+ async getOwnedQueueActions() {
49330
+ const all = await this.getQueueActions();
49331
+ return all.filter((a) => this.handlers[a.handler] !== undefined);
49332
+ }
49333
+ /** Draft ids `action` creates — the same set the dispatch-time dependency check uses. */
49334
+ getCreatedDraftIds(action) {
49335
+ const ids = new Set();
49336
+ this.collectDraftIds(action, ids);
49337
+ return Array.from(ids);
49338
+ }
49339
+ /** Owned actions whose basePath or body references any of `draftIds`. */
49340
+ async getOwnedActionsReferencing(draftIds) {
49341
+ const ids = new Set(draftIds);
49342
+ const owned = await this.getOwnedQueueActions();
49343
+ return owned.filter((action) => this.actionReferencesAny(action, ids));
49344
+ }
49345
+ async actionCompleted(action) {
49346
+ return this.workerPool.push({
49347
+ workFn: async () => {
49348
+ const handler = this.getHandler(action.handler);
49349
+ // Compute the redirects this completion produces BEFORE
49350
+ // completeAction resolves the POST out of the store, and retain
49351
+ // the draft ids they resolve. completeAction below removes the
49352
+ // completing POST from the store, so getInFlightRewritableDraftIds
49353
+ // would stop reporting its draft id — but the fire-and-forget
49354
+ // propagation to peers hasn't run yet, so a peer could dispatch a
49355
+ // queued action still carrying that stale draft id. Retaining the
49356
+ // ids (released only once the peer rewrites settle, below) keeps
49357
+ // peers deferring across that gap. Only bother when there are
49358
+ // peers to propagate to — with none, there is nothing to retain
49359
+ // for and no handler consultation to pay for.
49360
+ const peers = this.getPeerQueues().filter(isCrossQueueCoordination);
49361
+ const redirects = peers.length > 0 && handler.getRedirectMappings !== undefined
49362
+ ? handler.getRedirectMappings(action)
49363
+ : undefined;
49364
+ const retainedDraftIds = this.retainRedirectingDraftIds(redirects);
49365
+ try {
49366
+ let queue = await this.getQueueActions();
49367
+ const queueOperations = handler.getQueueOperationsForCompletingDrafts(queue, action);
49368
+ // write the queue operations to the store prior to ingesting the result
49369
+ await this.draftStore.completeAction(queueOperations);
49370
+ await this.finalizeCompletedAction(action, handler, queueOperations);
49371
+ if (this.state === DraftQueueState.Started) {
49372
+ this.processNextAction();
49373
+ }
49374
+ // Propagate redirects to peer queues; fire-and-forget. Awaiting
49375
+ // peer.applyDraftIdRedirects from inside this worker callback
49376
+ // produces a cross-queue worker-pool deadlock when the peer is
49377
+ // also propagating back to this queue. Release the retained ids
49378
+ // only once every peer's rewrite settles.
49379
+ this.propagateRedirectsToPeers(redirects, () => this.releaseRedirectingDraftIds(retainedDraftIds));
49380
+ }
49381
+ catch (e) {
49382
+ // Any step above can throw before propagateRedirectsToPeers
49383
+ // schedules the release. Release the retained ids here so they
49384
+ // don't leak into redirectingDraftIds permanently (which would
49385
+ // make getInFlightRewritableDraftIds report them forever and
49386
+ // strand peers deferring on them). Must be a catch, not a
49387
+ // finally — on the success path release happens only after
49388
+ // peers apply the rewrites, so releasing here too early would
49389
+ // reopen the cross-queue stale-id race.
49390
+ this.releaseRedirectingDraftIds(retainedDraftIds);
49391
+ throw e;
49392
+ }
49393
+ },
49394
+ });
49395
+ }
49396
+ /**
49397
+ * Shared in-memory finalization for a completed action, run after its durable
49398
+ * removal: ingest the response and apply side effects (handleActionCompleted),
49399
+ * drop any retry backoff state, release the in-flight claim, and notify
49400
+ * listeners. Used by both the single-action completion path (actionCompleted)
49401
+ * and the atomic batch completion path (completeBatchAtomically), which each
49402
+ * wrap it in their own error handling.
49403
+ */
49404
+ async finalizeCompletedAction(action, handler, queueOperations) {
49405
+ await handler.handleActionCompleted(action, queueOperations, values$2(this.handlers));
49406
+ // A completed action is no longer backing off: drop its timer, interval,
49407
+ // and parked flag.
49408
+ this.clearActionRetry(action.id);
49409
+ this.uploadingActionIds.delete(action.id);
49410
+ await this.notifyChangedListeners({
49411
+ type: DraftQueueEventType.ActionCompleted,
49412
+ action,
49413
+ draftCount: this.draftStore.getCount(),
49414
+ });
49415
+ }
49416
+ async actionFailed(action, retry, retryDelayInMs, actionDataChanged) {
49417
+ if (actionDataChanged === true) {
49418
+ await this.draftStore.writeAction({
49419
+ ...action,
49420
+ status: DraftActionStatus.Pending,
49421
+ });
49422
+ }
49423
+ this.uploadingActionIds.delete(action.id);
49424
+ if (retry && this.state !== DraftQueueState.Stopped) {
49425
+ // Park the action so a re-entrant dispatch pass (peer kick / sibling
49426
+ // completion) can't re-select it while it's Pending in the store and
49427
+ // waiting on its backoff timer. Cleared when this action's own timer
49428
+ // fires.
49429
+ this.retryingActionIds.add(action.id);
49430
+ await this.scheduleActionRetry(action.id, retryDelayInMs);
49431
+ return;
49432
+ }
49433
+ // Permanent failure. Awaiting handleServerError (rather than returning
49434
+ // it) guarantees the errored action is persisted before this method
49435
+ // resolves, so any dispatch pass on the next tick observes the error
49436
+ // state instead of racing the write.
49437
+ if (isDraftError(action)) {
49438
+ this.clearActionRetry(action.id);
49439
+ await this.handleServerError(action, action.error);
49440
+ // A permanently-failed POST never resolves the draft ids it would
49441
+ // have created, so peers that deferred actions on those ids would
49442
+ // otherwise stall until an unrelated success on a later tick wakes
49443
+ // them. Wake them explicitly so they can re-evaluate (and surface
49444
+ // their own error, rather than hang).
49445
+ this.getPeerQueues()
49446
+ .filter(isCrossQueueCoordination)
49447
+ .forEach((peer) => peer.resumeDeferredActions());
49448
+ }
49449
+ }
49450
+ async handleBatch(actions) {
49451
+ const handler = this.getHandler(actions[0].handler);
49452
+ if (handler === undefined) {
49453
+ return Promise.reject(`No handler for ${actions[0].handler}.`);
49454
+ }
49455
+ if (handler.handleBatchActions === undefined) {
49456
+ return Promise.reject(`Handler ${actions[0].handler} does not support batching.`);
49457
+ }
49458
+ const batchIds = actions.map((a) => a.id);
49459
+ // B2: buffer the members the handler reports completed instead of
49460
+ // removing each from the store as its callback fires. On success they
49461
+ // are removed in ONE atomic durable write (completeBatchAtomically), so
49462
+ // there is no partial-removal window that a crash — or a completion
49463
+ // callback throwing mid-loop — could strand. The stranded-member bug it
49464
+ // prevents: a batch commits all-or-none on the server exactly once, but
49465
+ // members removed one-at-a-time can leave committed members Pending,
49466
+ // which restart (or the handler's broad retry) would re-batch WITHOUT
49467
+ // their per-action idempotency keys (the batch envelope drops them),
49468
+ // replaying a committed PATCH's automation or failing a committed DELETE.
49469
+ const completed = [];
49470
+ const batchActionCompleted = (action) => {
49471
+ completed.push(action);
48996
49472
  return Promise.resolve();
48997
49473
  };
48998
- return this.enqueueAction(deleteAction);
48999
- }
49000
- deleteByTag(tag) {
49001
- const deleteAction = () => {
49002
- const { draftStore } = this;
49003
- const keys$1 = keys$4(draftStore);
49004
- const durableKeys = [];
49005
- for (let i = 0, len = keys$1.length; i < len; i++) {
49006
- const key = keys$1[i];
49007
- const action = draftStore[key];
49008
- if (action.tag === tag) {
49009
- delete draftStore[action.id];
49010
- delete this.cleanSnapshot[action.id];
49011
- durableKeys.push(buildDraftDurableStoreKey(action.tag, action.id));
49474
+ // Mint a unique id for this batch and journal its members BEFORE
49475
+ // dispatch (B2). If the process dies — or the atomic removal below fails
49476
+ // — between the server committing the request and the members being
49477
+ // removed, the next startQueue reconcile finds this journal and surfaces
49478
+ // any still-Pending member as commit-ambiguous (Option A: not auto-replayed,
49479
+ // because the batch envelope carries no server-visible idempotency key).
49480
+ // Journal support is optional; a store without it (never the gate-ON path)
49481
+ // skips this.
49482
+ const batchId = `${actions[0].id}:${(this.batchSequence += 1)}`;
49483
+ try {
49484
+ await this.writeBatchJournalIfSupported(batchId, batchIds);
49485
+ }
49486
+ catch (e) {
49487
+ // Fail CLOSED (4048061181): without a durable journal a mid-flight crash
49488
+ // would revive these members Pending with no record that they were
49489
+ // in-flight, so they would be re-batched — replaying a maybe-committed
49490
+ // write. Do NOT dispatch the batch. Release every member's in-flight
49491
+ // claim and dispatch the head alone via the single-action path, which
49492
+ // sends its idempotency key on the first attempt and so is replay-safe;
49493
+ // the remaining members re-arm and drain one-at-a-time single-action
49494
+ // while journaling is unavailable.
49495
+ batchLog$1(`journal write failed, single-action fallback batchId=${batchId} err=${errName(e)}`);
49496
+ for (const id of batchIds) {
49497
+ this.uploadingActionIds.delete(id);
49498
+ }
49499
+ this.uploadingActionIds.add(actions[0].id);
49500
+ return this.handle(actions[0]);
49501
+ }
49502
+ // Shared post-dispatch bookkeeping: release every batch member's uploading
49503
+ // claim, then handle the batch journal + still-Pending members per the
49504
+ // outcome, and issue the single trailing processNextAction. Two shapes:
49505
+ //
49506
+ // - Commit-AMBIGUOUS (result === NETWORK_ERROR, or a promise rejection):
49507
+ // the batch was dispatched but its outcome could not be confirmed
49508
+ // (network throw, empty-body 2xx, misaligned response, a retryable
49509
+ // 5xx/408/dropped-connection or generic-400 envelope that may have
49510
+ // committed with the 2xx lost — see executeBatch / classifyBatchFailure).
49511
+ // A rejection likewise implies a dispatch attempt whose cleanup then
49512
+ // threw, so it is treated as ambiguous too (it must NOT be read as
49513
+ // "nothing was sent"). The all-or-none request MAY have committed, and
49514
+ // the batch envelope carries no server-visible idempotency key, so a
49515
+ // re-send (batch OR serial) could replay a committed write. Do NOT
49516
+ // auto-replay (Option A): surface every still-Pending member as an error
49517
+ // for manual resolution, then clear the now-resolved journal (its job —
49518
+ // catching a mid-flight crash before we could record the ambiguity — is
49519
+ // done once the members carry the durable error).
49520
+ //
49521
+ // - Definitive non-success (any other non-success result): a terminal or
49522
+ // rolled-back envelope (server-generated 4xx, 429) or a partial
49523
+ // all-or-none failure — the server rolled the whole batch back or
49524
+ // rejected it before commit, so nothing committed and re-batching on
49525
+ // retry is replay-safe. The journal is stale: clear it. The handler
49526
+ // routed the offender (terminal, or parked in retryingActionIds) and
49527
+ // deliberately left innocent rolled-back siblings Pending/unparked (B5);
49528
+ // we only re-notify still-Pending members to clear the "uploading" UI
49529
+ // state.
49530
+ const finalize = async (result, rejected) => {
49531
+ for (const id of batchIds) {
49532
+ this.uploadingActionIds.delete(id);
49533
+ }
49534
+ if (rejected || result === ProcessActionResult.NETWORK_ERROR) {
49535
+ // Commit-ambiguous: surface members for manual resolution, then
49536
+ // clear the journal ONLY once the ambiguity is durably recorded on
49537
+ // every still-Pending member. If a member could not be moved to
49538
+ // Error, retain the journal so the next startQueue reconcile can
49539
+ // surface it — clearing now would strand it Pending with no backstop
49540
+ // and let a restart re-batch it (the replay Option A prevents).
49541
+ const resolved = await this.errorAmbiguousActions(batchIds);
49542
+ if (resolved) {
49543
+ await this.clearBatchJournalIfSupported(batchId);
49544
+ }
49545
+ else {
49546
+ // errorAmbiguousActions could not durably move the members to
49547
+ // Error (its bulk write failed); it stopped the queue and
49548
+ // quarantined them in-memory, and the journal is retained for
49549
+ // the next reconcile. Surface the failure as a bounded signal.
49550
+ await this.signalBatchRecoveryFailed('quarantine-failed');
49012
49551
  }
49013
49552
  }
49014
- return this.timeDurableOp('evictEntries', DRAFT_SEGMENT, () => this.durableStore.evictEntries(durableKeys, DRAFT_SEGMENT));
49553
+ else if (result !== ProcessActionResult.ACTION_SUCCEEDED) {
49554
+ // Definitively rolled back: journal is stale, clear it.
49555
+ await this.clearBatchJournalIfSupported(batchId);
49556
+ const queue = await this.getQueueActions();
49557
+ for (const id of batchIds) {
49558
+ const action = queue.find((a) => a.id === id);
49559
+ if (action && action.status === DraftActionStatus.Pending) {
49560
+ await this.notifyChangedListeners({
49561
+ type: DraftQueueEventType.ActionUpdated,
49562
+ action,
49563
+ draftCount: this.draftStore.getCount(),
49564
+ });
49565
+ }
49566
+ }
49567
+ }
49568
+ if (this.state === DraftQueueState.Started) {
49569
+ this.processNextAction();
49570
+ }
49571
+ return result;
49015
49572
  };
49016
- return this.enqueueAction(deleteAction);
49573
+ return handler
49574
+ .handleBatchActions(actions, batchActionCompleted, this.actionFailed.bind(this))
49575
+ .then(async (result) => {
49576
+ batchLog$1(`dispatch done result=${result} size=${actions.length}`);
49577
+ if (result === ProcessActionResult.ACTION_SUCCEEDED) {
49578
+ // Atomically remove every committed member and clear the
49579
+ // journal. Never rejects — it protects members itself if
49580
+ // the durable write fails (see below).
49581
+ await this.completeBatchAtomically(batchId, completed);
49582
+ }
49583
+ return finalize(result, false);
49584
+ }, (e) => {
49585
+ batchLog$1(`dispatch rejected err=${errName(e)} size=${actions.length}`);
49586
+ return finalize(ProcessActionResult.ACTION_ERRORED, true);
49587
+ });
49017
49588
  }
49018
- completeAction(queueOperations) {
49019
- const action = () => {
49020
- const durableStoreOperations = [];
49021
- const { draftStore } = this;
49022
- for (let i = 0, len = queueOperations.length; i < len; i++) {
49023
- const operation = queueOperations[i];
49024
- if (operation.type === QueueOperationType.Delete) {
49025
- const action = draftStore[operation.id];
49026
- if (action !== undefined) {
49027
- delete draftStore[operation.id];
49028
- delete this.cleanSnapshot[operation.id];
49029
- const key = buildDraftDurableStoreKey(action.tag, action.id);
49030
- durableStoreOperations.push({
49031
- ids: [key],
49032
- type: 'evictEntries',
49033
- segment: DRAFT_SEGMENT,
49589
+ /**
49590
+ * Atomically completes every successfully-uploaded member of a batch (B2).
49591
+ *
49592
+ * The server commits an all-or-none batch exactly once; the old path removed
49593
+ * members one-at-a-time, so a crash — or a completion callback throwing
49594
+ * mid-loop — could strand already-committed members Pending, which restart
49595
+ * (or the handler's broad retry) would re-batch WITHOUT their idempotency
49596
+ * keys and replay. This removes ALL members in ONE durable batchOperations
49597
+ * (the base completeAction applies the whole QueueOperation[] in a single
49598
+ * transaction), so there is no partial-removal state, then clears the
49599
+ * pre-dispatch journal. If any step throws after the server committed, this
49600
+ * fails CLOSED (4065665227): it quarantines every still-Pending member as a
49601
+ * commit-ambiguous error and retains the journal unless every member is
49602
+ * durably resolved, so the trailing finalize's claim release cannot let
49603
+ * collectBatch re-batch a keyless, maybe-committed member (Option A — the
49604
+ * batch envelope drops the idempotency key, so a re-send could replay a
49605
+ * committed write). Whatever the journal does not resolve this session is
49606
+ * surfaced by the next startQueue reconcile. The per-member cache ingest and
49607
+ * listener notification run afterward: they are best-effort cache updates, so
49608
+ * a throw there cannot corrupt the already-correct durable state.
49609
+ *
49610
+ * Batched members are UPDATE/DELETE only (collectBatch excludes POSTs), so
49611
+ * none mint server ids — getRedirectMappings returns undefined and each
49612
+ * member's queue ops reduce to a single self-delete, independent of the
49613
+ * others. That is why one queue snapshot yields correct ops for every member
49614
+ * and why the cross-queue redirect machinery on the single-action completion
49615
+ * path is not needed here. Never rejects.
49616
+ */
49617
+ completeBatchAtomically(batchId, completed) {
49618
+ return this.workerPool.push({
49619
+ workFn: async () => {
49620
+ if (completed.length === 0) {
49621
+ await this.clearBatchJournalIfSupported(batchId);
49622
+ return;
49623
+ }
49624
+ const memberIds = completed.map((a) => a.id);
49625
+ let perMember;
49626
+ try {
49627
+ // The setup (snapshot, handler lookup, op construction) is
49628
+ // inside the try too (4065666785): it runs in the success
49629
+ // callback, so a throw here would otherwise reject this task,
49630
+ // bypass finalize, and strand every member marked Uploading for
49631
+ // the session. Every exit below either removes the members or
49632
+ // quarantines them, so this method still never rejects.
49633
+ const queue = await this.getQueueActions();
49634
+ perMember = [];
49635
+ const allOps = [];
49636
+ for (const action of completed) {
49637
+ const handler = this.getHandler(action.handler);
49638
+ const ops = handler.getQueueOperationsForCompletingDrafts(queue, action);
49639
+ perMember.push({ action, ops, handler });
49640
+ for (let i = 0, len = ops.length; i < len; i++) {
49641
+ allOps.push(ops[i]);
49642
+ }
49643
+ }
49644
+ // ONE transaction removes every committed member — no
49645
+ // partial-removal window (B2).
49646
+ await this.draftStore.completeAction(allOps);
49647
+ await this.clearBatchJournalIfSupported(batchId);
49648
+ }
49649
+ catch (e) {
49650
+ // The server committed the all-or-none request but the local
49651
+ // completion could not be applied (snapshot read, op
49652
+ // construction, or the durable write failed). Do NOT assume the
49653
+ // members were evicted from memory: completeAction is part of the
49654
+ // public DraftStore contract and an implementation may reject
49655
+ // without removing its Pending rows (4065665227). If we simply
49656
+ // returned, the trailing finalize would release the uploading
49657
+ // claims and re-arm dispatch, letting collectBatch re-batch a
49658
+ // keyless, maybe-committed member and replay it. Fail CLOSED:
49659
+ // quarantine every still-Pending member as commit-ambiguous
49660
+ // BEFORE finalize releases the claims. treatMissingAsResolved is
49661
+ // false because the base store evicts a member from memory before
49662
+ // its durable row settles, so an absent member's durable state is
49663
+ // unknown here — leave the journal so the next startQueue reconcile
49664
+ // (which reads freshly-synced durable state) is the authority
49665
+ // (4065666287). Only clear the journal once every member is durably
49666
+ // resolved.
49667
+ batchLog$1(`atomic completion failed batchId=${batchId} err=${errName(e)}`);
49668
+ let resolved = false;
49669
+ try {
49670
+ resolved = await this.errorAmbiguousActions(memberIds, {
49671
+ treatMissingAsResolved: false,
49034
49672
  });
49035
49673
  }
49674
+ catch (qe) {
49675
+ batchLog$1(`atomic completion quarantine failed batchId=${batchId} err=${errName(qe)}`);
49676
+ }
49677
+ if (resolved) {
49678
+ await this.clearBatchJournalIfSupported(batchId);
49679
+ }
49680
+ else {
49681
+ // Not resolved: errorAmbiguousActions either failed its
49682
+ // durable write (it already stopped the queue + quarantined)
49683
+ // or threw before quarantining (e.g. its snapshot read
49684
+ // failed). Handle both uniformly — force the queue
49685
+ // non-dispatchable and quarantine every member in-memory so
49686
+ // the trailing finalize's unconditional claim release cannot
49687
+ // let collectBatch re-batch a keyless, maybe-committed member
49688
+ // and replay it (Option A). The journal is deliberately NOT
49689
+ // cleared; the next process-restart reconcile is the backstop.
49690
+ this.state = DraftQueueState.Error;
49691
+ for (const id of memberIds) {
49692
+ this.commitAmbiguousUnresolvedIds.add(id);
49693
+ }
49694
+ // The server committed but the members could not be durably
49695
+ // quarantined this session — surface a bounded o11y signal.
49696
+ await this.signalBatchRecoveryFailed('quarantine-failed');
49697
+ }
49698
+ return;
49036
49699
  }
49037
- else {
49038
- const { action } = operation;
49039
- const key = buildDraftDurableStoreKey(action.tag, action.id);
49040
- draftStore[action.id] = action;
49041
- this.cleanSnapshot[action.id] = clone$1(action);
49042
- durableStoreOperations.push({
49043
- type: 'setEntries',
49044
- segment: DRAFT_SEGMENT,
49045
- entries: {
49046
- [key]: {
49047
- data: operation.action,
49048
- },
49049
- },
49700
+ // Durable state is now correct. Per-member in-memory
49701
+ // finalization (cache ingest, retry-state clear, listener
49702
+ // notify) is best-effort; isolate each so one failure can't skip
49703
+ // the others or reject this task (which would surface as an
49704
+ // unhandled dispatch rejection).
49705
+ let finalizeFailed = false;
49706
+ for (const { action, ops, handler } of perMember) {
49707
+ try {
49708
+ await this.finalizeCompletedAction(action, handler, ops);
49709
+ }
49710
+ catch (e) {
49711
+ // Still release the in-flight claim so the id isn't stuck
49712
+ // marked uploading.
49713
+ this.uploadingActionIds.delete(action.id);
49714
+ finalizeFailed = true;
49715
+ batchLog$1(`post-completion finalize failed id=${action.id} err=${errName(e)}`);
49716
+ }
49717
+ }
49718
+ if (finalizeFailed) {
49719
+ // The write committed and was durably removed exactly once — no
49720
+ // replay/duplication risk — but some member's local cache/notify
49721
+ // work was lost with no retry path. Emit one bounded structured
49722
+ // signal per batch (o11y counter) so this is monitorable beyond
49723
+ // the per-member device log (4077120522).
49724
+ await this.signalBatchRecoveryFailed('finalize-failed');
49725
+ }
49726
+ },
49727
+ });
49728
+ }
49729
+ /**
49730
+ * Surfaces the given still-Pending actions as commit-ambiguous errors (Option
49731
+ * A). A batch that MAY have committed cannot be safely re-sent because the batch
49732
+ * envelope drops the per-action idempotency keys, so instead of auto-replaying
49733
+ * (batch OR serial — both would present keys the server never saw on the
49734
+ * original batch) we move each member to Error for manual resolution. Used by
49735
+ * finalize on a commit-ambiguous dispatch outcome and by startQueue reconcile
49736
+ * for members a prior batch journaled but never completed (in-flight at a
49737
+ * crash). Reads the raw store status (not the uploading overlay); a member
49738
+ * already Error is left as-is (counts as resolved).
49739
+ *
49740
+ * All still-Pending members are moved to Error in ONE completeAction
49741
+ * transaction rather than one writeAction (and one getQueueActions snapshot)
49742
+ * per member (4065667688): a 25-member batch is a single durable
49743
+ * batchOperations, not 25 writes plus 25 snapshots. The in-memory effects
49744
+ * handleServerError applies per member (drop the uploading claim + retry
49745
+ * state, set queue Error state, notify listeners) are mirrored here once for
49746
+ * the whole set.
49747
+ *
49748
+ * A fresh draft snapshot (id → action) is read per call — never shared across
49749
+ * the reconcile loop — because each call awaits completeAction and listener
49750
+ * callbacks that can delete a member, and a stale shared snapshot would let a
49751
+ * later call resurrect a just-deleted member as an Error draft (4077120311).
49752
+ * `options.treatMissingAsResolved` controls how an id absent from the snapshot
49753
+ * is scored: true (default) when the snapshot authoritatively reflects durable
49754
+ * state (restart reconcile runs against a freshly-synced store, so absent means
49755
+ * genuinely gone); false in the live post-commit failure path, where the base
49756
+ * store evicts a member from memory BEFORE its durable row settles (4065666287),
49757
+ * so an absent member's durable state is unknown and must be treated as
49758
+ * unresolved to keep the journal. An id already in commitAmbiguousUnresolvedIds
49759
+ * is likewise treated as unresolved regardless of its (possibly stale) in-memory
49760
+ * status: its durable Error write failed earlier this session, so its durable
49761
+ * row is still Pending and the journal must be retained for the next
49762
+ * fresh-process reconcile (4077120459). Returns true only when every targeted id
49763
+ * is resolved.
49764
+ */
49765
+ async errorAmbiguousActions(ids, options) {
49766
+ if (ids.length === 0) {
49767
+ return true;
49768
+ }
49769
+ const treatMissingAsResolved = options?.treatMissingAsResolved ?? true;
49770
+ // Read a fresh snapshot and index it by id so each targeted id is an O(1)
49771
+ // lookup instead of a full scan. Deliberately NOT shared across the
49772
+ // reconcile loop: a snapshot held across this call's awaited completeAction
49773
+ // and listener callbacks could go stale and let a later call resurrect a
49774
+ // just-deleted member as an Error draft (4077120311).
49775
+ const draftsById = new Map((await this.draftStore.getAllDrafts()).map((d) => [d.id, d]));
49776
+ const ops = [];
49777
+ const erroredActions = [];
49778
+ const seen = new Set();
49779
+ // An id whose durable Error write already failed this session (still in the
49780
+ // quarantine set) is NOT resolved even if its in-memory status now reads
49781
+ // Error: that in-memory Error is the write-through cache mutation that was
49782
+ // never rolled back after its durable batchOperations rejected, so the
49783
+ // durable row is still Pending. Retain the journal (return false) so the
49784
+ // next fresh-process reconcile — running against a re-synced store — is the
49785
+ // authority, rather than clearing the journal on unpersisted state and
49786
+ // re-batching the still-Pending row keyless after a later restart
49787
+ // (4077120459).
49788
+ let quarantinedUnresolved = false;
49789
+ for (const id of ids) {
49790
+ if (seen.has(id)) {
49791
+ continue;
49792
+ }
49793
+ if (this.commitAmbiguousUnresolvedIds.has(id)) {
49794
+ quarantinedUnresolved = true;
49795
+ continue;
49796
+ }
49797
+ const action = draftsById.get(id);
49798
+ if (action === undefined) {
49799
+ continue;
49800
+ }
49801
+ seen.add(id);
49802
+ if (action.status !== DraftActionStatus.Pending) {
49803
+ continue;
49804
+ }
49805
+ const errored = {
49806
+ ...action,
49807
+ status: DraftActionStatus.Error,
49808
+ error: PerformanceDraftQueue.COMMIT_AMBIGUOUS_ERROR,
49809
+ metadata: action.metadata || {},
49810
+ };
49811
+ ops.push({ type: QueueOperationType.Update, id: action.id, action: errored });
49812
+ erroredActions.push(errored);
49813
+ }
49814
+ if (ops.length > 0) {
49815
+ try {
49816
+ // One durable transaction moves every still-Pending member to Error.
49817
+ await this.draftStore.completeAction(ops);
49818
+ }
49819
+ catch (e) {
49820
+ // Nothing was durably moved: the members are still Pending and MAY
49821
+ // have committed. Fail CLOSED — stop the queue and quarantine them
49822
+ // in-memory so no later dispatch (a re-arm, retryAllErrors, or a
49823
+ // reconnect-driven startQueue) re-batches them keyless and replays a
49824
+ // committed write (Option A). Report unresolved so the caller retains
49825
+ // the journal for the next reconcile.
49826
+ batchLog$1(`commit-ambiguous bulk error failed count=${ops.length} err=${errName(e)}`);
49827
+ this.state = DraftQueueState.Error;
49828
+ for (const errored of erroredActions) {
49829
+ this.commitAmbiguousUnresolvedIds.add(errored.id);
49830
+ }
49831
+ return false;
49832
+ }
49833
+ // Durable Error state is written; mirror handleServerError's in-memory
49834
+ // effects once for the whole set rather than per member. Batched members
49835
+ // are UPDATE/DELETE (never POST — collectBatch excludes POSTs), so no
49836
+ // peer deferred on a draft id these would have created; the peer-wake
49837
+ // that actionFailed does for permanently-failed POSTs is not needed.
49838
+ this.state = DraftQueueState.Error;
49839
+ for (const errored of erroredActions) {
49840
+ this.uploadingActionIds.delete(errored.id);
49841
+ // Durably Error now (already excluded from dispatch by status), so
49842
+ // drop any prior in-memory quarantine — otherwise a later
49843
+ // retryAllErrors that re-pends this action would find it wrongly
49844
+ // blocked from ever dispatching again.
49845
+ this.commitAmbiguousUnresolvedIds.delete(errored.id);
49846
+ this.clearActionRetry(errored.id);
49847
+ try {
49848
+ await this.notifyChangedListeners({
49849
+ type: DraftQueueEventType.ActionFailed,
49850
+ action: errored,
49851
+ draftCount: this.draftStore.getCount(),
49050
49852
  });
49051
49853
  }
49854
+ catch (e) {
49855
+ batchLog$1(`commit-ambiguous notify failed id=${errored.id} err=${errName(e)}`);
49856
+ }
49052
49857
  }
49053
- return this.timeDurableOp('batchOperations', DRAFT_SEGMENT, () => this.durableStore.batchOperations(durableStoreOperations));
49054
- };
49055
- return this.enqueueAction(action);
49056
- }
49057
- getCount() {
49058
- return keys$4(this.draftStore).length;
49858
+ }
49859
+ if (quarantinedUnresolved) {
49860
+ return false;
49861
+ }
49862
+ if (treatMissingAsResolved) {
49863
+ return true;
49864
+ }
49865
+ for (let i = 0, len = ids.length; i < len; i++) {
49866
+ if (!seen.has(ids[i])) {
49867
+ return false;
49868
+ }
49869
+ }
49870
+ return true;
49059
49871
  }
49060
49872
  /**
49061
- * Runs a write operation against the draft store, if the initial
49062
- * revive is still in progress, the action gets enqueued to run once the
49063
- * initial revive is complete
49064
- * @param action
49065
- * @returns a promise that is resolved once the action has run
49873
+ * Feature-detecting wrapper: journals a batch's members if the store supports
49874
+ * it. A store without journal support (never the gate-ON path) resolves as a
49875
+ * no-op. When supported, the write REJECTION propagates so handleBatch can fail
49876
+ * CLOSED (4048061181) — the journal is the only record that these members were
49877
+ * in-flight, so a failed write must abort the batch dispatch rather than send
49878
+ * unrecorded.
49066
49879
  */
49067
- enqueueAction(action) {
49068
- const { syncPromise, writeQueue: pendingMerges } = this;
49069
- // if the initial sync is done and existing operations have been run, no need to queue, just run
49070
- if (syncPromise === undefined && pendingMerges.length === 0) {
49071
- return action();
49880
+ writeBatchJournalIfSupported(batchId, memberIds) {
49881
+ const store = this.draftStore;
49882
+ if (typeof store.writeBatchJournal !== 'function') {
49883
+ return Promise.resolve();
49072
49884
  }
49073
- const deferred = new Promise((resolve, reject) => {
49074
- this.writeQueue.push(() => {
49075
- return action()
49076
- .then((x) => {
49077
- resolve(x);
49078
- })
49079
- .catch((err) => reject(err));
49885
+ return store.writeBatchJournal(batchId, memberIds);
49886
+ }
49887
+ /**
49888
+ * Surfaces a batch-journal crash-recovery failure (B2) to listeners as a
49889
+ * bounded structured signal, so instrumentDraftQueue can map it to o11y —
49890
+ * these paths are otherwise visible only in device logs. Carries ONLY the
49891
+ * reason code and the queue depth (never ids or messages — device-log PII
49892
+ * policy). Best-effort and never rejects: a listener throw must not break the
49893
+ * recovery path, so it is swallowed to the batch log.
49894
+ */
49895
+ async signalBatchRecoveryFailed(reason) {
49896
+ try {
49897
+ await this.notifyChangedListeners({
49898
+ type: DraftQueueEventType.BatchRecoveryFailed,
49899
+ reason,
49900
+ draftCount: this.draftStore.getCount(),
49080
49901
  });
49902
+ }
49903
+ catch (e) {
49904
+ batchLog$1(`batch recovery signal failed reason=${reason} err=${errName(e)}`);
49905
+ }
49906
+ }
49907
+ /**
49908
+ * Feature-detecting wrapper: clears a batch journal entry if the store
49909
+ * supports it. A resolved batch's journal is stale, but a swallowed clear
49910
+ * failure would leave a recovery row behind on EVERY dispatch, so restart
49911
+ * reconcile grows unbounded (4065667688). Retry the clear a bounded number of
49912
+ * times, and if it still fails escalate the log line (leftover=true) so a
49913
+ * persistently-failing clear is greppable rather than silent. Never rejects:
49914
+ * callers (finalize, completeBatchAtomically) treat the clear as best-effort
49915
+ * cleanup of an already-resolved journal — a leftover row is caught by the
49916
+ * next reconcile, it does not risk a replay.
49917
+ */
49918
+ async clearBatchJournalIfSupported(batchId) {
49919
+ const store = this.draftStore;
49920
+ if (typeof store.clearBatchJournal !== 'function') {
49921
+ return;
49922
+ }
49923
+ for (let attempt = 1; attempt <= CLEAR_JOURNAL_MAX_ATTEMPTS; attempt++) {
49924
+ try {
49925
+ await store.clearBatchJournal(batchId);
49926
+ return;
49927
+ }
49928
+ catch (e) {
49929
+ const leftover = attempt === CLEAR_JOURNAL_MAX_ATTEMPTS;
49930
+ batchLog$1(`journal clear failed batchId=${batchId} attempt=${attempt} leftover=${leftover} err=${errName(e)}`);
49931
+ }
49932
+ }
49933
+ // Every attempt failed (the loop returns on success): the resolved journal
49934
+ // row leaks, so the next reconcile keeps re-reading it (unbounded growth).
49935
+ // Surface a bounded o11y signal — the device log alone is not enough.
49936
+ // Still never rejects: signalBatchRecoveryFailed swallows its own errors.
49937
+ await this.signalBatchRecoveryFailed('clear-exhausted');
49938
+ }
49939
+ /**
49940
+ * A queued action is eligible to be selected or batched only when it is
49941
+ * Pending in the store and this queue is neither already uploading it nor
49942
+ * holding it in retry backoff. A retrying action stays Pending in the
49943
+ * store, so without the retryingActionIds guard collectBatch would pull a
49944
+ * parked action into a batch before its backoff timer fires (C5).
49945
+ */
49946
+ isDispatchable(action) {
49947
+ return (action.status === DraftActionStatus.Pending &&
49948
+ !this.uploadingActionIds.has(action.id) &&
49949
+ !this.retryingActionIds.has(action.id) &&
49950
+ // A member left Pending because its commit-ambiguous quarantine could
49951
+ // not be durably written must never be re-batched keyless (Option A).
49952
+ !this.commitAmbiguousUnresolvedIds.has(action.id));
49953
+ }
49954
+ /**
49955
+ * Walks the queue from `headIndex` and returns the longest contiguous prefix
49956
+ * of actions that are eligible to batch together. Eligibility:
49957
+ * - same handler id as the head action
49958
+ * - dispatchable (Pending, not in-flight, not parked in retry backoff)
49959
+ * - not a POST/CREATE (POSTs are never batched — see BatchCutReason.PostBoundary)
49960
+ * - tag does not collide with any tag already in the batch
49961
+ * (UI-API Batch rejects two operations on the same record per request)
49962
+ * - body/basePath does not reference an unresolved draft id from a peer
49963
+ * queue's (or this queue's) pending POST (would dispatch with a draft id)
49964
+ * - targetId is not already being written by an in-flight request
49965
+ * (per-record serialization; the head is pre-checked by the caller,
49966
+ * but later members must be checked here too — see BatchCutReason.TargetInFlight)
49967
+ * - batch size capped at MAX_BATCH_SIZE
49968
+ */
49969
+ collectBatch(queue, headIndex, peerPendingPostDraftIds, inFlightTargetIds) {
49970
+ if (queue.length === 0 || headIndex >= queue.length) {
49971
+ return [];
49972
+ }
49973
+ const head = queue[headIndex];
49974
+ const handler = this.handlers[head.handler];
49975
+ // CREATEs are never batched (C1): a POST head falls back to single-action
49976
+ // dispatch, which preserves its per-action idempotency key.
49977
+ const headData = head.data;
49978
+ if (headData !== undefined && headData.method === 'post') {
49979
+ batchLog$1('head is POST — not batchable, fall back to single-action');
49980
+ return [head];
49981
+ }
49982
+ // The head carries semantics the batch envelope cannot represent (B1):
49983
+ // fall back to single-action dispatch so those semantics (e.g. a
49984
+ // conditional-update header) are preserved.
49985
+ if (handler !== undefined &&
49986
+ typeof handler.isActionBatchable === 'function' &&
49987
+ !handler.isActionBatchable(head)) {
49988
+ batchLog$1('head not batchable — fall back to single-action');
49989
+ return [head];
49990
+ }
49991
+ const batch = [head];
49992
+ const seenTags = new Set();
49993
+ seenTags.add(head.tag);
49994
+ let reason = "END_OF_QUEUE" /* BatchCutReason.EndOfQueue */;
49995
+ let detail = '';
49996
+ for (let i = headIndex + 1; i < queue.length; i++) {
49997
+ if (batch.length >= MAX_BATCH_SIZE$1) {
49998
+ reason = "MAX_BATCH_SIZE" /* BatchCutReason.MaxBatchSize */;
49999
+ break;
50000
+ }
50001
+ const candidate = queue[i];
50002
+ if (candidate.handler !== head.handler) {
50003
+ reason = "HANDLER_CHANGE" /* BatchCutReason.HandlerChange */;
50004
+ detail = `nextHandler=${candidate.handler}`;
50005
+ break;
50006
+ }
50007
+ if (!this.isDispatchable(candidate)) {
50008
+ reason = "NOT_PENDING" /* BatchCutReason.NotPending */;
50009
+ detail = `nextStatus=${candidate.status}`;
50010
+ break;
50011
+ }
50012
+ // Stop at any POST: CREATEs are excluded from batching (C1). Only
50013
+ // naturally-idempotent UPDATE/DELETE actions batch, so there are no
50014
+ // in-batch POST draft ids to track — the blocking set below is the
50015
+ // caller's peer/owned pending-POST set alone.
50016
+ const candData = candidate.data;
50017
+ if (candData !== undefined && candData.method === 'post') {
50018
+ reason = "POST_BOUNDARY" /* BatchCutReason.PostBoundary */;
50019
+ break;
50020
+ }
50021
+ // Candidate carries semantics the batch envelope cannot represent
50022
+ // (B1): end the batch here so it is dispatched via single-action
50023
+ // handleAction on a later pass rather than folded in and stripped.
50024
+ if (handler !== undefined &&
50025
+ typeof handler.isActionBatchable === 'function' &&
50026
+ !handler.isActionBatchable(candidate)) {
50027
+ reason = "NOT_BATCHABLE" /* BatchCutReason.NotBatchable */;
50028
+ break;
50029
+ }
50030
+ // Per-record serialization (see BatchCutReason.TargetInFlight): the
50031
+ // caller pre-checks the head; later members must be checked here too.
50032
+ if (candidate.targetId && inFlightTargetIds.has(candidate.targetId)) {
50033
+ reason = "TARGET_IN_FLIGHT" /* BatchCutReason.TargetInFlight */;
50034
+ // Log the cut position, NOT the targetId: a targetId is a record id
50035
+ // and even a 24-char suffix preserves the full 18-char id, which the
50036
+ // device-log PII policy (metrics.ts) forbids (4065667273). The
50037
+ // BatchCutReason already says why; the offset says where.
50038
+ detail = `atOffset=${i - headIndex}`;
50039
+ break;
50040
+ }
50041
+ if (seenTags.has(candidate.tag)) {
50042
+ reason = "TAG_COLLISION" /* BatchCutReason.TagCollision */;
50043
+ // Log the cut position, NOT the tag: the tag embeds the record id
50044
+ // (same PII concern as targetId above).
50045
+ detail = `atOffset=${i - headIndex}`;
50046
+ break;
50047
+ }
50048
+ // Block a candidate that references a draft id still unresolved on a
50049
+ // peer queue's (or this queue's) in-flight POST, minus the
50050
+ // candidate's own draft ids (an action mustn't self-block on its own
50051
+ // targetId).
50052
+ const candidateOwnIds = new Set();
50053
+ this.collectDraftIds(candidate, candidateOwnIds);
50054
+ const blockingIds = new Set(peerPendingPostDraftIds);
50055
+ for (const id of candidateOwnIds) {
50056
+ blockingIds.delete(id);
50057
+ }
50058
+ if (this.actionReferencesAny(candidate, blockingIds)) {
50059
+ reason = "REF_BLOCKED" /* BatchCutReason.RefBlocked */;
50060
+ break;
50061
+ }
50062
+ batch.push(candidate);
50063
+ seenTags.add(candidate.tag);
50064
+ }
50065
+ const queuedAfterBatch = queue.length - headIndex - batch.length;
50066
+ batchLog$1(`collected size=${batch.length} reason=${reason}` +
50067
+ ` queueRemaining=${queuedAfterBatch}` +
50068
+ (detail.length > 0 ? ` ${detail}` : ''));
50069
+ return batch;
50070
+ }
50071
+ /**
50072
+ * Returns all draft ids "created" by this action (i.e., ids that don't yet
50073
+ * exist on the server). Defaults to `[targetId]`; handlers may override
50074
+ * `getDraftIdsFromAction` to return additional ids (e.g., the CD composite
50075
+ * handler returns CD + CV + CDL).
50076
+ */
50077
+ collectDraftIds(action, into) {
50078
+ const handler = this.handlers[action.handler];
50079
+ if (handler !== undefined && typeof handler.getDraftIdsFromAction === 'function') {
50080
+ for (const id of handler.getDraftIdsFromAction(action)) {
50081
+ if (id !== undefined && id !== null && id !== '') {
50082
+ into.add(id);
50083
+ }
50084
+ }
50085
+ return;
50086
+ }
50087
+ if (action.targetId) {
50088
+ into.add(action.targetId);
50089
+ }
50090
+ }
50091
+ /**
50092
+ * Returns true if any of the given draft ids appears in the action's
50093
+ * basePath or stringified body. Mirrors the substring scan used by
50094
+ * `getQueueOperationsForCompletingDrafts` so blocking and rewriting agree.
50095
+ *
50096
+ * TODO [W-23515682]: this re-scans basePath/body on every dispatch pass.
50097
+ * The referenced-id set could instead be computed once and cached on the
50098
+ * DraftAction, recomputed only when rewriteQueueActionsForRedirects mutates
50099
+ * basePath/body (the only place they change), so the hot path is a set
50100
+ * lookup rather than a stringify+substring scan.
50101
+ */
50102
+ actionReferencesAny(action, draftIds) {
50103
+ if (draftIds.size === 0) {
50104
+ return false;
50105
+ }
50106
+ const data = action.data;
50107
+ if (data === undefined) {
50108
+ return false;
50109
+ }
50110
+ const body = typeof data.body === 'string' ? data.body : JSON.stringify(data.body || '');
50111
+ const haystack = `${data.basePath || ''}${body}`;
50112
+ return [...draftIds].some((id) => haystack.includes(id));
50113
+ }
50114
+ async getInFlightRewritableDraftIds() {
50115
+ const allDrafts = await this.draftStore.getAllDrafts();
50116
+ // Seed with draft ids retained across the completeAction →
50117
+ // propagateRedirectsToPeers gap so a peer keeps deferring even though the
50118
+ // completing POST has already left the store but its redirects have not
50119
+ // yet reached peers.
50120
+ const ids = new Set(this.redirectingDraftIds);
50121
+ for (const action of allDrafts) {
50122
+ if (this.handlers[action.handler] !== undefined &&
50123
+ (action.status === DraftActionStatus.Pending ||
50124
+ action.status === DraftActionStatus.Uploading) &&
50125
+ action.data &&
50126
+ action.data.method === 'post') {
50127
+ this.collectDraftIds(action, ids);
50128
+ }
50129
+ }
50130
+ return Array.from(ids);
50131
+ }
50132
+ resumeDeferredActions() {
50133
+ if (this.state === DraftQueueState.Started) {
50134
+ this.processNextAction();
50135
+ }
50136
+ }
50137
+ // Applies a set of draft → canonical id rewrites to every action queued
50138
+ // on this queue. Called by a peer queue after one of its POSTs completes
50139
+ // and produced redirects. Walks this queue, rewrites any action whose
50140
+ // basePath/body/tag references a draft id, persists via the shared
50141
+ // store, and kicks processNextAction so newly-resolvable actions dispatch.
50142
+ async applyDraftIdRedirects(redirects) {
50143
+ if (!redirects || redirects.length === 0) {
50144
+ return;
50145
+ }
50146
+ return this.workerPool.push({
50147
+ workFn: async () => {
50148
+ const queue = await this.getQueueActions();
50149
+ const queueOperations = rewriteQueueActionsForRedirects(queue, redirects);
50150
+ if (queueOperations.length > 0) {
50151
+ await this.draftStore.completeAction(queueOperations);
50152
+ }
50153
+ if (this.state === DraftQueueState.Started) {
50154
+ this.processNextAction();
50155
+ }
50156
+ },
49081
50157
  });
49082
- return deferred;
49083
50158
  }
49084
50159
  /**
49085
- * Revives the draft store from the durable store. Once the draft store is
49086
- * revived, executes any queued up draft store operations that came in while
49087
- * reviving
50160
+ * Retains the draft ids resolved by `redirects` in `redirectingDraftIds` so
50161
+ * getInFlightRewritableDraftIds keeps reporting them across the
50162
+ * completeAction → propagateRedirectsToPeers fire-and-forget gap. Returns
50163
+ * only the ids this call newly added (so a concurrent completion touching
50164
+ * the same id doesn't release it early). Called before completeAction on the
50165
+ * single-action completion path (actionCompleted).
49088
50166
  */
49089
- resyncDraftStore() {
49090
- const sync = () => {
49091
- this.syncPromise = this.durableStore
49092
- .getAllEntries(DRAFT_SEGMENT)
49093
- .then((durableEntries) => {
49094
- if (durableEntries === undefined) {
49095
- this.draftStore = {};
49096
- this.cleanSnapshot = {};
49097
- return this.runQueuedOperations();
50167
+ retainRedirectingDraftIds(redirects) {
50168
+ const retainedDraftIds = [];
50169
+ if (redirects !== undefined) {
50170
+ for (const redirect of redirects) {
50171
+ if (redirect.draftId && !this.redirectingDraftIds.has(redirect.draftId)) {
50172
+ this.redirectingDraftIds.add(redirect.draftId);
50173
+ retainedDraftIds.push(redirect.draftId);
49098
50174
  }
49099
- const { draftStore } = this;
49100
- const keys$1 = keys$4(durableEntries);
49101
- for (let i = 0, len = keys$1.length; i < len; i++) {
49102
- const entry = durableEntries[keys$1[i]];
49103
- const action = entry.data;
49104
- draftStore[action.id] = action;
49105
- this.cleanSnapshot[action.id] = clone$1(action);
50175
+ }
50176
+ }
50177
+ return retainedDraftIds;
50178
+ }
50179
+ /** Releases the ids retained by a prior retainRedirectingDraftIds call. */
50180
+ releaseRedirectingDraftIds(retainedDraftIds) {
50181
+ for (const id of retainedDraftIds) {
50182
+ this.redirectingDraftIds.delete(id);
50183
+ }
50184
+ }
50185
+ /**
50186
+ * After an action on this queue completes, propagates the draft → canonical
50187
+ * id rewrites it produced to the peer queues so their queued actions that
50188
+ * reference the resolved id are rewritten before dispatch. When there are no
50189
+ * redirects (or none apply), falls back to a bare wake of each peer so their
50190
+ * previously-deferred actions re-evaluate.
50191
+ *
50192
+ * `redirects` is precomputed by the caller (before completeAction resolves
50193
+ * the POST out of the store) so the redirecting draft ids can be retained
50194
+ * across the fire-and-forget gap. `onSettled` runs once every peer's rewrite
50195
+ * has settled, so the caller can release those retained ids.
50196
+ */
50197
+ propagateRedirectsToPeers(redirects, onSettled) {
50198
+ // Peers are typed DraftQueue[]; only those that also implement
50199
+ // CrossQueueCoordination can participate. Narrow once up front so the
50200
+ // calls below need no per-method guards.
50201
+ const peers = this.getPeerQueues().filter(isCrossQueueCoordination);
50202
+ if (peers.length === 0) {
50203
+ onSettled();
50204
+ return;
50205
+ }
50206
+ if (redirects !== undefined && redirects.length > 0) {
50207
+ const settlements = peers.map((peer) => {
50208
+ // Fire-and-forget: peer.applyDraftIdRedirects schedules its own
50209
+ // work on the peer's worker pool. Don't await — that deadlocks
50210
+ // when the peer is propagating redirects back to this queue.
50211
+ const promise = peer.applyDraftIdRedirects(redirects);
50212
+ if (promise && typeof promise.catch === 'function') {
50213
+ return promise.catch((e) => {
50214
+ if (this.logger) {
50215
+ this.logger.logError(`PerformanceDraftQueue: cross-queue redirect propagation to peer failed: ${errName(e)}`);
50216
+ }
50217
+ });
49106
50218
  }
49107
- return this.runQueuedOperations();
49108
- })
49109
- .finally(() => {
49110
- this.syncPromise = undefined;
50219
+ return Promise.resolve();
49111
50220
  });
49112
- return this.syncPromise;
49113
- };
49114
- // if there's an ongoing sync populating the in memory store, wait for it to complete before re-syncing
49115
- const { syncPromise } = this;
49116
- if (syncPromise === undefined) {
49117
- return sync();
50221
+ // Release the retained draft ids only once every peer has applied
50222
+ // (or failed to apply) the rewrites, so getInFlightRewritableDraftIds
50223
+ // keeps reporting them until peers no longer reference the stale id.
50224
+ Promise.all(settlements).then(onSettled, onSettled);
50225
+ }
50226
+ else {
50227
+ peers.forEach((peer) => peer.resumeDeferredActions());
50228
+ onSettled();
50229
+ }
50230
+ }
50231
+ async processNextAction() {
50232
+ // Serialize dispatch passes. A pass awaits peer state before
50233
+ // claiming a slot, so overlapping passes could double-dispatch. If a
50234
+ // pass is already running, record the wakeup and let it re-run.
50235
+ if (this.isDispatching) {
50236
+ this.redispatchRequested = true;
50237
+ return ProcessActionResult.ACTION_ALREADY_PROCESSING;
50238
+ }
50239
+ this.isDispatching = true;
50240
+ try {
50241
+ let result = ProcessActionResult.NO_ACTION_TO_PROCESS;
50242
+ do {
50243
+ this.redispatchRequested = false;
50244
+ result = await this.dispatchFreeSlots();
50245
+ } while (this.redispatchRequested);
50246
+ return result;
50247
+ }
50248
+ finally {
50249
+ this.isDispatching = false;
50250
+ }
50251
+ }
50252
+ async dispatchFreeSlots() {
50253
+ if (this.uploadingActionIds.size >= this.concurrency) {
50254
+ return ProcessActionResult.ACTION_ALREADY_PROCESSING;
50255
+ }
50256
+ // Gather the set of pending POST draft ids whose creators are still in
50257
+ // flight on any peer queue. A candidate action that references one of
50258
+ // those ids would otherwise dispatch with an unresolved draft id
50259
+ // (ContentDocument 069... etc.) instead of waiting for the upstream
50260
+ // POST to rewrite it to canonical. These peer reads each await, so they
50261
+ // run BEFORE the owned-queue snapshot below — otherwise an await would
50262
+ // sit between snapshotting the queue and claiming from it, letting the
50263
+ // store change underneath the selection (the candidate we picked could
50264
+ // already be gone or completed by the time we claim it).
50265
+ const blockingDraftIds = new Set();
50266
+ const peers = this.getPeerQueues().filter(isCrossQueueCoordination);
50267
+ for (const peer of peers) {
50268
+ try {
50269
+ const ids = await peer.getInFlightRewritableDraftIds();
50270
+ for (const id of ids) {
50271
+ blockingDraftIds.add(id);
50272
+ }
50273
+ }
50274
+ catch (e) {
50275
+ // Peers are already narrowed to CrossQueueCoordination, so this
50276
+ // is a genuine failure to read a peer's in-flight ids, not a
50277
+ // missing capability. Log it: on failure we fall through with an
50278
+ // incomplete blocking set, which can let a dependent action
50279
+ // dispatch against an unresolved draft id.
50280
+ if (this.logger) {
50281
+ this.logger.logError(`PerformanceDraftQueue: failed to read peer in-flight rewritable draft ids: ${errName(e)}`);
50282
+ }
50283
+ }
50284
+ }
50285
+ // Snapshot the owned queue AFTER the peer reads. From here to the claims
50286
+ // below there is no await, so the snapshot and the slot claims see a
50287
+ // consistent view of the store.
50288
+ const queue = await this.getQueueActions();
50289
+ // The shared DurableDraftStore returns actions for every queue, so we
50290
+ // restrict candidate selection to actions whose handler is registered
50291
+ // on this queue. This keeps a queue from claiming or being
50292
+ // error-blocked by its peer's actions.
50293
+ const ownedQueue = queue.filter((a) => this.handlers[a.handler] !== undefined);
50294
+ // Head-of-queue error block: only applies when strictOrdering is enabled.
50295
+ // With strictOrdering=false the candidate loop will skip errored items.
50296
+ if (this.strictOrdering) {
50297
+ const head = ownedQueue[0];
50298
+ if (head !== undefined && head.status === DraftActionStatus.Error) {
50299
+ this.state = DraftQueueState.Error;
50300
+ await this.notifyChangedListeners({
50301
+ type: DraftQueueEventType.ActionFailed,
50302
+ action: head,
50303
+ draftCount: this.draftStore.getCount(),
50304
+ });
50305
+ return ProcessActionResult.BLOCKED_ON_ERROR;
50306
+ }
50307
+ }
50308
+ // Single pass over ownedQueue derives everything the selection loop
50309
+ // needs: candidates (actions neither already claimed in-flight nor
50310
+ // parked in retry backoff), the targetIds of in-flight actions
50311
+ // (per-record serialization), and every owned pending/uploading POST's
50312
+ // draft ids (this queue's contribution to the blocking set).
50313
+ const candidates = [];
50314
+ const inFlightTargetIds = new Set();
50315
+ for (const a of ownedQueue) {
50316
+ if (this.uploadingActionIds.has(a.id)) {
50317
+ if (a.targetId) {
50318
+ inFlightTargetIds.add(a.targetId);
50319
+ }
50320
+ }
50321
+ else if (!this.retryingActionIds.has(a.id) &&
50322
+ // Same guard as isDispatchable: a commit-ambiguous member whose
50323
+ // quarantine could not be durably written stays out of
50324
+ // single-action dispatch too, not just batching.
50325
+ !this.commitAmbiguousUnresolvedIds.has(a.id)) {
50326
+ candidates.push(a);
50327
+ }
50328
+ if ((a.status === DraftActionStatus.Pending ||
50329
+ a.status === DraftActionStatus.Uploading) &&
50330
+ a.data &&
50331
+ a.data.method === 'post') {
50332
+ this.collectDraftIds(a, blockingDraftIds);
50333
+ }
50334
+ }
50335
+ // Fill every free concurrency slot from this single snapshot rather than
50336
+ // claiming one and bouncing back through processNextAction — that would
50337
+ // re-run getQueueActions (and its deep clone) per slot. Claims are
50338
+ // synchronous (no await inside the loop), so inFlightTargetIds stays
50339
+ // authoritative for per-record serialization of later picks in the same
50340
+ // pass. Blocked candidates are skipped (strictOrdering=false) or halt
50341
+ // the scan (strictOrdering=true head-of-line semantics).
50342
+ const toDispatch = [];
50343
+ let blockedCount = 0;
50344
+ for (const candidate of candidates) {
50345
+ if (this.uploadingActionIds.size >= this.concurrency) {
50346
+ break;
50347
+ }
50348
+ if (candidate.status === DraftActionStatus.Error) {
50349
+ continue;
50350
+ }
50351
+ // Per-record serialization: skip if another action on the same record is in-flight.
50352
+ if (candidate.targetId && inFlightTargetIds.has(candidate.targetId)) {
50353
+ blockedCount++;
50354
+ if (this.strictOrdering) {
50355
+ break;
50356
+ }
50357
+ continue;
50358
+ }
50359
+ // Exclude the candidate's own draft IDs so a POST doesn't self-block
50360
+ // on its own targetId.
50361
+ const ownIds = new Set();
50362
+ this.collectDraftIds(candidate, ownIds);
50363
+ const effectiveBlockingIds = new Set(blockingDraftIds);
50364
+ for (const id of ownIds) {
50365
+ effectiveBlockingIds.delete(id);
50366
+ }
50367
+ if (this.actionReferencesAny(candidate, effectiveBlockingIds)) {
50368
+ blockedCount++;
50369
+ if (this.strictOrdering) {
50370
+ break;
50371
+ }
50372
+ continue;
50373
+ }
50374
+ // Batching path: only when enabled, on the first action dispatched
50375
+ // this pass, and only if its handler implements handleBatchActions
50376
+ // and the eligible batch is larger than 1. collectBatch enforces the
50377
+ // same ref-blocking rule applied above so a candidate referencing a
50378
+ // peer's pending POST id won't be batched alongside the head. When a
50379
+ // batch dispatches it consumes the pass (returns), matching the
50380
+ // pre-fill-all behavior. It is also passed inFlightTargetIds so a
50381
+ // batch member can't write a record that another in-flight request
50382
+ // is already writing (the head candidate is pre-checked above).
50383
+ if (this.queueBatching && toDispatch.length === 0) {
50384
+ const handler = this.getHandler(candidate.handler);
50385
+ if (handler.handleBatchActions !== undefined) {
50386
+ const actionIndex = ownedQueue.indexOf(candidate);
50387
+ const batch = this.collectBatch(ownedQueue, actionIndex, blockingDraftIds, inFlightTargetIds);
50388
+ if (batch.length > 1) {
50389
+ batchLog$1(`dispatching batch size=${batch.length}`);
50390
+ if (this.state === DraftQueueState.Waiting) {
50391
+ this.state = DraftQueueState.Started;
50392
+ }
50393
+ // Claim every batch member so a re-entrant
50394
+ // processNextAction (e.g. a peer kick during the await
50395
+ // below) doesn't re-claim any of them.
50396
+ for (const batched of batch) {
50397
+ this.uploadingActionIds.add(batched.id);
50398
+ }
50399
+ for (const batched of batch) {
50400
+ await this.notifyChangedListeners({
50401
+ type: DraftQueueEventType.ActionUploading,
50402
+ action: { ...batched, status: DraftActionStatus.Uploading },
50403
+ draftCount: this.draftStore.getCount(),
50404
+ });
50405
+ }
50406
+ return this.handleBatch(batch);
50407
+ }
50408
+ }
50409
+ }
50410
+ // Eligible — claim the slot now (synchronously) so the next
50411
+ // iteration serializes against it.
50412
+ this.uploadingActionIds.add(candidate.id);
50413
+ if (candidate.targetId) {
50414
+ inFlightTargetIds.add(candidate.targetId);
50415
+ }
50416
+ toDispatch.push(candidate);
50417
+ }
50418
+ if (toDispatch.length === 0) {
50419
+ if (blockedCount > 0 && this.logger) {
50420
+ this.logger.logInfo(`[DraftQueue c=${this.concurrency}] processNextAction: ${blockedCount} action(s) deferred waiting on upstream draft ids`);
50421
+ }
50422
+ if (this.uploadingActionIds.size === 0) {
50423
+ if (this.state === DraftQueueState.Waiting) {
50424
+ this.state = DraftQueueState.Started;
50425
+ }
50426
+ return ProcessActionResult.NO_ACTION_TO_PROCESS;
50427
+ }
50428
+ return ProcessActionResult.ACTION_ALREADY_PROCESSING;
50429
+ }
50430
+ if (this.state === DraftQueueState.Waiting) {
50431
+ this.state = DraftQueueState.Started;
50432
+ }
50433
+ for (const action of toDispatch) {
50434
+ await this.notifyChangedListeners({
50435
+ type: DraftQueueEventType.ActionUploading,
50436
+ action: { ...action, status: DraftActionStatus.Uploading },
50437
+ draftCount: this.draftStore.getCount(),
50438
+ });
50439
+ this.handle(action);
50440
+ }
50441
+ return ProcessActionResult.ACTION_ALREADY_PROCESSING;
50442
+ }
50443
+ // Overrides DurableDraftQueue.removeDraftAction rather than reusing it: the
50444
+ // uploading guard reads the concurrent `uploadingActionIds` set (the base
50445
+ // reads its private single `uploadingActionId`, which this path never sets,
50446
+ // so delegating would defeat the guard), and it additionally clears the
50447
+ // per-action retry timer — a concept that exists only on this subclass. The
50448
+ // rest of the body is kept identical to the base; keep them in sync.
50449
+ async removeDraftAction(actionId) {
50450
+ const queue = await this.getQueueActions();
50451
+ //Get the store key for the removed action
50452
+ const actions = queue.filter((action) => action.id === actionId);
50453
+ if (actions.length === 0) {
50454
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
50455
+ throw new Error(`No removable action with id ${actionId}`);
50456
+ }
50457
+ const action = actions[0];
50458
+ const { shouldDeleteRelated, removed } = this.resolveActionsToRemove(action, queue, (id) => this.uploadingActionIds.has(id));
50459
+ // A removed action must not leave a dangling backoff timer that would
50460
+ // later fire and re-drive the scheduler for an id that no longer exists.
50461
+ removed.forEach(({ action: a }) => this.clearActionRetry(a.id));
50462
+ if (shouldDeleteRelated) {
50463
+ await this.draftStore.deleteByTag(action.tag);
50464
+ }
50465
+ else {
50466
+ await this.draftStore.deleteDraft(action.id);
50467
+ }
50468
+ await this.notifyActionsRemoved(removed, queue);
50469
+ if (this.userState === DraftQueueState.Started &&
50470
+ this.state !== DraftQueueState.Started &&
50471
+ this.replacingAction === undefined) {
50472
+ await this.startQueue();
49118
50473
  }
49119
- return syncPromise.then(() => {
49120
- return sync();
49121
- });
49122
50474
  }
49123
50475
  /**
49124
- * Runs the operations that were queued up while reviving the
49125
- * draft store from the durable store
50476
+ * Concurrent-aware, per-action retry scheduler. The serial base parks the
50477
+ * whole queue under one shared timer + one shared exponential interval,
50478
+ * which conflate concurrent retries. This instead gives the failed action
50479
+ * its own timer and its own growing backoff, keyed by id, so it retries on
50480
+ * its own schedule without disturbing siblings still uploading in other
50481
+ * slots.
50482
+ *
50483
+ * Only broadcasts `Waiting` when the queue is genuinely idle (nothing in
50484
+ * flight): a concurrent queue with other slots live is still `Started`, and
50485
+ * on the serial path the failed action was already removed from
50486
+ * `uploadingActionIds` above (size 0), so the Waiting broadcast the regular
50487
+ * queue emits today is preserved.
49126
50488
  */
49127
- runQueuedOperations() {
49128
- const { writeQueue } = this;
49129
- if (writeQueue.length > 0) {
49130
- const queueItem = writeQueue.shift();
49131
- if (queueItem !== undefined) {
49132
- return queueItem().then(() => {
49133
- return this.runQueuedOperations();
49134
- });
50489
+ async scheduleActionRetry(actionId, retryDelayInMs) {
50490
+ const delay = retryDelayInMs !== undefined ? retryDelayInMs : this.nextBackoffInterval(actionId);
50491
+ // Only move to Waiting when the queue is genuinely idle (nothing in
50492
+ // flight). A concurrent queue with other slots still uploading must stay
50493
+ // Started — otherwise sibling completions (which gate their
50494
+ // processNextAction on state === Started) would stop advancing the queue
50495
+ // and free slots would sit idle until this action's retry timer fired.
50496
+ // Only dispatchFreeSlots flips Waiting back to Started, and nothing
50497
+ // reaches it while state is Waiting. On the serial path the failed action
50498
+ // was already removed above (size 0), so the Waiting transition the
50499
+ // regular queue emits today is preserved.
50500
+ if (this.uploadingActionIds.size === 0) {
50501
+ this.state = DraftQueueState.Waiting;
50502
+ await this.notifyChangedListeners({
50503
+ type: DraftQueueEventType.QueueStateChanged,
50504
+ state: DraftQueueState.Waiting,
50505
+ draftCount: this.draftStore.getCount(),
50506
+ });
50507
+ }
50508
+ // Replace any existing timer for this action so a fresh failure resets
50509
+ // its own backoff window without leaking the prior timer.
50510
+ const existing = this.retryTimers.get(actionId);
50511
+ if (existing !== undefined) {
50512
+ clearTimeout(existing);
50513
+ }
50514
+ this.retryTimers.set(actionId, setTimeout(() => {
50515
+ // Only this action becomes eligible again; siblings keep their
50516
+ // own backoff windows.
50517
+ this.retryTimers.delete(actionId);
50518
+ this.retryingActionIds.delete(actionId);
50519
+ if (this.state !== DraftQueueState.Stopped) {
50520
+ this.processNextAction();
49135
50521
  }
50522
+ }, delay));
50523
+ }
50524
+ /**
50525
+ * Per-action exponential backoff, mirroring the base's doubling within the
50526
+ * same [minimum, maximum] bounds but tracked per id so each retrying action
50527
+ * grows its own interval independently.
50528
+ */
50529
+ nextBackoffInterval(actionId) {
50530
+ const current = this.retryIntervals.get(actionId) ?? 0;
50531
+ const next = Math.min(Math.max(current * 2, this.minimumRetryInterval), this.maximumRetryInterval);
50532
+ this.retryIntervals.set(actionId, next);
50533
+ return next;
50534
+ }
50535
+ /**
50536
+ * Drops all retry bookkeeping for an action: cancels its pending timer,
50537
+ * un-parks it, and forgets its backoff interval. Called on completion,
50538
+ * permanent failure, and removal.
50539
+ */
50540
+ clearActionRetry(actionId) {
50541
+ const timer = this.retryTimers.get(actionId);
50542
+ if (timer !== undefined) {
50543
+ clearTimeout(timer);
50544
+ this.retryTimers.delete(actionId);
50545
+ }
50546
+ this.retryIntervals.delete(actionId);
50547
+ this.retryingActionIds.delete(actionId);
50548
+ }
50549
+ /**
50550
+ * Cancels every per-action retry timer. The base clears only its single
50551
+ * `timeoutHandler`; a concurrent queue may have many parked actions, so on
50552
+ * any full stop we must clear them all to avoid a dangling timer firing
50553
+ * against a stopped queue.
50554
+ */
50555
+ clearAllRetryTimers() {
50556
+ for (const timer of this.retryTimers.values()) {
50557
+ clearTimeout(timer);
50558
+ }
50559
+ this.retryTimers.clear();
50560
+ this.retryIntervals.clear();
50561
+ this.retryingActionIds.clear();
50562
+ }
50563
+ stopQueueManually(internalReason) {
50564
+ this.clearAllRetryTimers();
50565
+ super.stopQueueManually(internalReason);
50566
+ }
50567
+ /**
50568
+ * Clears every per-action retry timer on (re)start for the same reason the
50569
+ * base clears its single `timeoutHandler`: a dangling backoff timer must not
50570
+ * fire against a freshly-started queue. Guarded by the same conditions under
50571
+ * which the base actually restarts (not already Started, not mid-replace) so
50572
+ * a `startQueue()` that is a no-op — or a replace-driven restart — doesn't
50573
+ * wipe legitimately-parked backoff windows out from under in-flight retries.
50574
+ */
50575
+ async startQueue() {
50576
+ // Record the caller's intent up front, exactly as the base startQueue does
50577
+ // synchronously. The reconcile below awaits, so a stopQueue() can interleave
50578
+ // with it; capturing intent here lets that later stop flip userState and win
50579
+ // (see the revalidation after the await, R4-6).
50580
+ this.userState = DraftQueueState.Started;
50581
+ if (this.state !== DraftQueueState.Started && this.replacingAction === undefined) {
50582
+ this.clearAllRetryTimers();
50583
+ // Concurrent counterpart: the base scalar is never set here, so check the Set.
50584
+ // Stale ids in uploadingActionIds at restart strand the dispatcher's uploading guard.
50585
+ if (this.uploadingActionIds.size > 0 && this.logger) {
50586
+ this.logger.logWarning(`Draft queue restarting with ${this.uploadingActionIds.size} action(s) still marked uploading (stale uploadingActionIds=${[
50587
+ ...this.uploadingActionIds,
50588
+ ].join(',')}); possible abandoned-upload stuck queue`);
50589
+ }
50590
+ }
50591
+ // Recover from any batch journaled but never confirmed removed (B2)
50592
+ // before the base starts dispatching, so a committed-but-unremoved
50593
+ // member is surfaced as a commit-ambiguous error before collectBatch can
50594
+ // re-batch it (Option A). Guarded to run at most once per process; a no-op
50595
+ // when batching is disabled or the store keeps no journal.
50596
+ await this.reconcileBatchJournalsOnce();
50597
+ // The reconcile awaited above yields the event loop. If a stopQueue() ran
50598
+ // while it was pending, that stop already completed and set
50599
+ // userState=Stopped; honor it rather than clobbering the queue back to
50600
+ // Started via super.startQueue() and dispatching after the caller stopped
50601
+ // it (R4-6).
50602
+ if (this.userState !== DraftQueueState.Started) {
50603
+ return;
50604
+ }
50605
+ return super.startQueue();
50606
+ }
50607
+ /**
50608
+ * The head of the shared store may belong to the other queue, so targets are resolved
50609
+ * against the actions this queue owns. With strict ordering only the owned head can be
50610
+ * retried (it is what blocks dispatch); without it an errored action blocks nothing, so
50611
+ * any errored action this queue owns can be retried.
50612
+ */
50613
+ async getRetryTarget(actionId) {
50614
+ const owned = await this.getOwnedQueueActions();
50615
+ if (this.strictOrdering) {
50616
+ const head = owned[0];
50617
+ if (!head || head.id !== actionId) {
50618
+ throw Error(`Action ${actionId} not found at the head of the draft queue`);
50619
+ }
50620
+ return head;
50621
+ }
50622
+ const target = owned.find((action) => action.id === actionId);
50623
+ if (target === undefined) {
50624
+ throw Error(`Action ${actionId} not found in the draft queue`);
50625
+ }
50626
+ return target;
50627
+ }
50628
+ async retryAllErrors() {
50629
+ const actions = await this.getOwnedQueueActions();
50630
+ const errored = actions.filter((a) => a.status === DraftActionStatus.Error);
50631
+ if (errored.length === 0) {
50632
+ return;
50633
+ }
50634
+ // Stop the queue before rewriting errored actions to Pending. With
50635
+ // strictOrdering=false the queue keeps running while errored items are
50636
+ // skipped, so a live pass could observe the store mid-rewrite. Stop,
50637
+ // rewrite, then restart safely.
50638
+ this.stopQueueManually(true);
50639
+ for (const action of errored) {
50640
+ // Drop the `error` field that's only present on ErrorDraftAction so
50641
+ // the resulting object structurally matches PendingDraftAction and
50642
+ // satisfies the discriminated-union narrower.
50643
+ const { error: _droppedError, ...rest } = action;
50644
+ const pendingAction = {
50645
+ ...rest,
50646
+ status: DraftActionStatus.Pending,
50647
+ };
50648
+ await this.draftStore.writeAction(pendingAction);
50649
+ await this.notifyChangedListeners({
50650
+ type: DraftQueueEventType.ActionUpdated,
50651
+ action: pendingAction,
50652
+ draftCount: this.draftStore.getCount(),
50653
+ });
50654
+ }
50655
+ await this.startQueueSafe();
50656
+ }
50657
+ }
50658
+ /**
50659
+ * Error surfaced on a batch member whose commit status could not be confirmed:
50660
+ * the batch response was lost (network throw, empty/misaligned 2xx, a retryable
50661
+ * gateway envelope) or the process died mid-flight. Because the batch envelope
50662
+ * carries no server-visible idempotency key, such a write cannot be safely
50663
+ * re-sent without risking a duplicate, so the member is surfaced as an error for
50664
+ * manual resolution rather than auto-replayed (Option A). Shaped like a
50665
+ * FetchResponse so downstream consumers that read action.error.status/.body
50666
+ * behave consistently with a server error.
50667
+ */
50668
+ PerformanceDraftQueue.COMMIT_AMBIGUOUS_ERROR = {
50669
+ status: 0,
50670
+ statusText: 'Batch commit ambiguous',
50671
+ ok: false,
50672
+ headers: {},
50673
+ body: {
50674
+ errorCode: 'BATCH_COMMIT_AMBIGUOUS',
50675
+ message: 'The batched change may or may not have been saved (the server response ' +
50676
+ 'was not received). It was not retried automatically to avoid saving it ' +
50677
+ 'twice; please verify the record and retry or discard the draft.',
50678
+ },
50679
+ };
50680
+
50681
+ class RoutingDraftQueue {
50682
+ /**
50683
+ * @param primaryLane the serial/fallback lane: it owns unregistered handlers and backs
50684
+ * every store read. Passed explicitly so routing never depends on array ordering.
50685
+ * @param secondaryLanes the remaining routed lanes (e.g. the concurrent binary lane).
50686
+ */
50687
+ constructor(primaryLane, secondaryLanes = []) {
50688
+ this.primaryLane = primaryLane;
50689
+ this.lanes = [primaryLane, ...secondaryLanes];
50690
+ }
50691
+ get primary() {
50692
+ return this.primaryLane.queue;
50693
+ }
50694
+ /** Resolve the lane that owns `handlerId`, falling back to the primary lane. */
50695
+ laneForHandler(handlerId) {
50696
+ return (this.lanes.find(({ queue }) => queue.isHandlerRegistered(handlerId)) ?? this.primaryLane);
50697
+ }
50698
+ /** Resolve the sub-queue that owns `handlerId`, falling back to the primary queue. */
50699
+ routeByHandler(handlerId) {
50700
+ return this.laneForHandler(handlerId).queue;
50701
+ }
50702
+ /**
50703
+ * Resolve the sub-queue that owns the action identified by `actionId` by
50704
+ * reading its stamped handler from the shared store (visible via the primary
50705
+ * queue), then routing by handler ownership. Falls back to the primary queue
50706
+ * when the action can't be found.
50707
+ */
50708
+ async routeByActionId(actionId) {
50709
+ const actions = await this.primary.getQueueActions();
50710
+ const action = actions.find((candidate) => candidate.id === actionId);
50711
+ return action !== undefined ? this.routeByHandler(action.handler) : this.primary;
50712
+ }
50713
+ enqueue(handlerId, data, observabilityContext) {
50714
+ return this.routeByHandler(handlerId).enqueue(handlerId, data, observabilityContext);
50715
+ }
50716
+ async getQueueActions() {
50717
+ const actions = await this.primary.getQueueActions();
50718
+ return actions.map((action) => ({
50719
+ ...action,
50720
+ lane: this.laneForHandler(action.handler).lane,
50721
+ }));
50722
+ }
50723
+ addHandler(handler) {
50724
+ return this.primary.addHandler(handler);
50725
+ }
50726
+ addCustomHandler(id, executor) {
50727
+ return this.primary.addCustomHandler(id, executor);
50728
+ }
50729
+ removeHandler(id) {
50730
+ return this.primary.removeHandler(id);
50731
+ }
50732
+ // Removes only the action itself. Removing a binary action through RoutingDraftManager also
50733
+ // removes the serial actions that depend on it; this façade does not.
50734
+ async removeDraftAction(actionId) {
50735
+ const owner = await this.routeByActionId(actionId);
50736
+ return owner.removeDraftAction(actionId);
50737
+ }
50738
+ updateDraftAction(action) {
50739
+ return this.routeByHandler(action.handler).updateDraftAction(action);
50740
+ }
50741
+ async retryAction(actionId) {
50742
+ const owner = await this.routeByActionId(actionId);
50743
+ return owner.retryAction(actionId);
50744
+ }
50745
+ async setMetadata(actionId, metadata) {
50746
+ const owner = await this.routeByActionId(actionId);
50747
+ return owner.setMetadata(actionId, metadata);
50748
+ }
50749
+ async replaceAction(targetActionId, sourceActionId) {
50750
+ const owner = await this.routeByActionId(targetActionId);
50751
+ return owner.replaceAction(targetActionId, sourceActionId);
50752
+ }
50753
+ async mergeActions(targetActionId, sourceActionId) {
50754
+ const owner = await this.routeByActionId(targetActionId);
50755
+ return owner.mergeActions(targetActionId, sourceActionId);
50756
+ }
50757
+ registerOnChangedListener(listener) {
50758
+ const unsubscribes = this.lanes.map(({ queue }) => queue.registerOnChangedListener(listener));
50759
+ return () => Promise.all(unsubscribes.map((unsubscribe) => unsubscribe())).then(() => undefined);
50760
+ }
50761
+ async processNextAction() {
50762
+ const [primaryResult] = await Promise.all(this.lanes.map(({ queue }) => queue.processNextAction()));
50763
+ return primaryResult;
50764
+ }
50765
+ /**
50766
+ * Conservative aggregate of the sub-queue states, most-attention-needed first:
50767
+ * Error (blocked, needs intervention) > Stopped (explicitly halted) > Waiting
50768
+ * (transient network backoff) > Started. Not bridged — DraftManager reports
50769
+ * per-queue state separately; this exists only to satisfy the interface.
50770
+ */
50771
+ getQueueState() {
50772
+ const states = this.lanes.map(({ queue }) => queue.getQueueState());
50773
+ if (states.includes(DraftQueueState.Error)) {
50774
+ return DraftQueueState.Error;
50775
+ }
50776
+ if (states.includes(DraftQueueState.Stopped)) {
50777
+ return DraftQueueState.Stopped;
50778
+ }
50779
+ if (states.includes(DraftQueueState.Waiting)) {
50780
+ return DraftQueueState.Waiting;
50781
+ }
50782
+ return DraftQueueState.Started;
50783
+ }
50784
+ async startQueue() {
50785
+ await Promise.all(this.lanes.map(({ queue }) => queue.startQueue()));
50786
+ }
50787
+ async stopQueue() {
50788
+ await Promise.all(this.lanes.map(({ queue }) => queue.stopQueue()));
50789
+ }
50790
+ /**
50791
+ * Stops every sub-queue, runs `action` once, then restarts every sub-queue.
50792
+ * Not bridged; the per-queue variant preserves userState via an internal stop,
50793
+ * which isn't reachable from here, so this uses the public stop/start pair.
50794
+ */
50795
+ async stopQueueWhileRunning(action) {
50796
+ await Promise.all(this.lanes.map(({ queue }) => queue.stopQueue()));
50797
+ try {
50798
+ await action();
50799
+ }
50800
+ finally {
50801
+ await Promise.all(this.lanes.map(({ queue }) => queue.startQueue()));
49136
50802
  }
49137
- return Promise.resolve();
49138
50803
  }
49139
50804
  }
49140
50805
 
@@ -49202,6 +50867,16 @@
49202
50867
  shouldEmitEvent(event) {
49203
50868
  return this.draftEventsShouldBeEmitted.includes(event.type);
49204
50869
  }
50870
+ /**
50871
+ * Routes a sub-queue change event into the listener pipeline. Exposed to subclasses so they
50872
+ * can register it on an additional queue without duplicating the emit-gating logic.
50873
+ */
50874
+ handleQueueChange(event) {
50875
+ if (this.shouldEmitEvent(event)) {
50876
+ return this.callListeners(event);
50877
+ }
50878
+ return Promise.resolve();
50879
+ }
49205
50880
  constructor(draftQueue) {
49206
50881
  this.listeners = [];
49207
50882
  this.draftEventsShouldBeEmitted = [
@@ -49214,12 +50889,7 @@
49214
50889
  DraftQueueEventType.QueueStateChanged,
49215
50890
  ];
49216
50891
  this.draftQueue = draftQueue;
49217
- draftQueue.registerOnChangedListener((event) => {
49218
- if (this.shouldEmitEvent(event)) {
49219
- return this.callListeners(event);
49220
- }
49221
- return Promise.resolve();
49222
- });
50892
+ draftQueue.registerOnChangedListener((event) => this.handleQueueChange(event));
49223
50893
  }
49224
50894
  draftQueueEventTypeToOperationType(type) {
49225
50895
  switch (type) {
@@ -49419,6 +51089,11 @@
49419
51089
  if (isDraftQueueStateChangeEvent(event)) {
49420
51090
  operationType = DraftQueueOperationType.QueueStateChanged;
49421
51091
  }
51092
+ else if (event.type === DraftQueueEventType.BatchRecoveryFailed) {
51093
+ // Telemetry-only signal (batch-recovery failure): it carries no
51094
+ // draft item, so DraftManager has nothing to surface to its listeners.
51095
+ return;
51096
+ }
49422
51097
  else {
49423
51098
  const { action, type } = event;
49424
51099
  item = this.buildDraftQueueItem(action);
@@ -49497,6 +51172,537 @@
49497
51172
  return (dataAsAny !== undefined && dataAsAny.method !== undefined && dataAsAny.body !== undefined);
49498
51173
  }
49499
51174
 
51175
+ /**
51176
+ * Gate-ON DraftManager: the concurrent-binary upload variant, instantiated only when the
51177
+ * `concurrentBinaryQueue` feature flag is on. It wraps a strict-ordering serial draft queue
51178
+ * plus a parallel binary queue over one shared store, stamps each draft's routing `lane`, and
51179
+ * routes lifecycle, remove, and retry calls to the queue that owns each action. Current
51180
+ * (non-SCE) users never instantiate this class — they run the unchanged base.
51181
+ */
51182
+ class RoutingDraftManager extends DraftManager {
51183
+ constructor(draftQueue, binaryQueue, laneLabels) {
51184
+ super(draftQueue);
51185
+ this.logger = typeof __nimbus !== 'undefined' &&
51186
+ __nimbus.plugins !== undefined &&
51187
+ __nimbus.plugins.JSLoggerPlugin !== undefined
51188
+ ? __nimbus.plugins.JSLoggerPlugin
51189
+ : undefined;
51190
+ this.serialQueue = draftQueue;
51191
+ this.binaryQueue = binaryQueue;
51192
+ this.laneLabels = laneLabels;
51193
+ // Surface binary-queue change events through the same listener pipeline as the serial
51194
+ // queue (super already registered the serial queue; reuse the inherited handler here).
51195
+ this.binaryQueue.registerOnChangedListener((event) => this.handleQueueChange(event));
51196
+ }
51197
+ getQueue() {
51198
+ return Promise.all([this.draftQueue.getQueueActions(), this.binaryActionsById()])
51199
+ .then(([queueActions, binaryById]) => queueActions.map((action) => {
51200
+ const binaryAction = binaryById.get(action.id);
51201
+ return this.buildDraftQueueItem(this.stampLane(binaryAction ?? action, binaryAction !== undefined));
51202
+ }))
51203
+ .then(toQueueState(this.draftQueue));
51204
+ }
51205
+ /**
51206
+ * Starts both the serial and binary draft queues and begins processing their items.
51207
+ */
51208
+ startQueue() {
51209
+ return Promise.all([this.draftQueue.startQueue(), this.binaryQueue.startQueue()]).then(() => undefined);
51210
+ }
51211
+ /**
51212
+ * Stops both the serial and binary draft queues from processing more draft items after
51213
+ * any in-progress items are finished.
51214
+ */
51215
+ stopQueue() {
51216
+ return Promise.all([this.draftQueue.stopQueue(), this.binaryQueue.stopQueue()]).then(() => undefined);
51217
+ }
51218
+ /**
51219
+ * Pauses both queues while `action` runs. Nests each queue's own stopQueueWhileRunning so
51220
+ * each restarts afterwards only if it was user-started before.
51221
+ */
51222
+ stopQueueWhileRunning(action) {
51223
+ return this.draftQueue.stopQueueWhileRunning(() => this.binaryQueue.stopQueueWhileRunning(action));
51224
+ }
51225
+ async retryAllErrors() {
51226
+ await this.serialQueue.retryAllErrors();
51227
+ await this.binaryQueue.retryAllErrors();
51228
+ }
51229
+ /**
51230
+ * Routes the remove to the queue that owns the action. The serial queue reads the shared
51231
+ * store, so it sees binary-owned actions too, but has no handler registered for them and
51232
+ * would throw.
51233
+ *
51234
+ * A binary remove pauses the serial queue so a dependent can't start uploading between the
51235
+ * uploading check and its removal. Only the serial queue: stopping the binary queue would
51236
+ * clear every binary action's retry backoff. The serial queue's own removeDraftAction
51237
+ * restarts it, so the pause covers the first dependent only.
51238
+ */
51239
+ removeDraftAction(actionId) {
51240
+ return this.binaryActionsById()
51241
+ .then((binaryById) => {
51242
+ const binaryAction = binaryById.get(actionId);
51243
+ return binaryAction !== undefined
51244
+ ? this.serialQueue.stopQueueWhileRunning(() => this.removeBinaryActionAndDependents(binaryAction))
51245
+ : this.draftQueue.removeDraftAction(actionId);
51246
+ })
51247
+ .then(() => this.getQueue());
51248
+ }
51249
+ /**
51250
+ * Routes to the queue that owns the action, for the same reason as removeDraftAction.
51251
+ * Native sets metadata on every image upload right after enqueueing it, so a serial-only
51252
+ * setMetadata fails the upload call and native never links the image to its record.
51253
+ */
51254
+ async setMetadata(actionId, metadata) {
51255
+ const binaryById = await this.binaryActionsById();
51256
+ if (!binaryById.has(actionId)) {
51257
+ return super.setMetadata(actionId, metadata);
51258
+ }
51259
+ const updated = await this.binaryQueue.setMetadata(actionId, metadata);
51260
+ return this.buildDraftQueueItem(this.stampLane(updated, true));
51261
+ }
51262
+ /** Routes to the queue that owns the action, for the same reason as removeDraftAction. */
51263
+ async retryAction(actionId) {
51264
+ const binaryById = await this.binaryActionsById();
51265
+ if (!binaryById.has(actionId)) {
51266
+ return super.retryAction(actionId);
51267
+ }
51268
+ const retried = await this.binaryQueue.retryAction(actionId);
51269
+ return this.buildDraftQueueItem(this.stampLane(retried, true));
51270
+ }
51271
+ /**
51272
+ * Removes a binary action plus the serial actions that reference a draft id it creates
51273
+ * (e.g. the ContentDocumentLink native enqueues to link an uploaded image to a record).
51274
+ * Nothing resolves those ids once the binary action is gone, so a dependent left behind
51275
+ * would dispatch with an unresolved draft id, fail, and block the serial queue.
51276
+ *
51277
+ * Rejects up front when a dependent is uploading: an errored binary action no longer holds
51278
+ * its dependents back, so one can be mid-dispatch. Otherwise the binary action goes first
51279
+ * so a rejected remove (e.g. it is uploading) leaves its dependents untouched.
51280
+ */
51281
+ async removeBinaryActionAndDependents(action) {
51282
+ const dependents = await this.serialActionsDependingOn(action);
51283
+ const uploading = dependents.find((d) => d.status === DraftActionStatus.Uploading);
51284
+ if (uploading !== undefined) {
51285
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
51286
+ throw new Error(`Cannot remove draft action ${action.id} while its dependent draft action ${uploading.id} is uploading`);
51287
+ }
51288
+ await this.binaryQueue.removeDraftAction(action.id);
51289
+ for (const dependent of dependents) {
51290
+ const current = (await this.draftQueue.getQueueActions()).find((a) => a.id === dependent.id);
51291
+ // Removing an earlier dependent may already have deleted this one by shared tag.
51292
+ if (current === undefined) {
51293
+ continue;
51294
+ }
51295
+ // It started uploading after the check above. The binary action is already gone,
51296
+ // so keep going rather than report a failed remove; this one will error and can be
51297
+ // removed on its own.
51298
+ if (current.status === DraftActionStatus.Uploading) {
51299
+ if (this.logger) {
51300
+ this.logger.logWarning(`RoutingDraftManager: dependent draft action ${dependent.id} of removed draft action ${action.id} started uploading and was not removed`);
51301
+ }
51302
+ continue;
51303
+ }
51304
+ await this.draftQueue.removeDraftAction(dependent.id);
51305
+ }
51306
+ }
51307
+ serialActionsDependingOn(action) {
51308
+ const draftIds = this.binaryQueue.getCreatedDraftIds(action);
51309
+ return draftIds.length === 0
51310
+ ? Promise.resolve([])
51311
+ : this.serialQueue.getOwnedActionsReferencing(draftIds);
51312
+ }
51313
+ /**
51314
+ * Binary-lane actions keyed by id, carrying the lane's transient `Uploading` status.
51315
+ * `getQueue` uses it to stamp the `concurrentBinary` lane and source the correct status.
51316
+ */
51317
+ binaryActionsById() {
51318
+ return this.binaryQueue
51319
+ .getOwnedQueueActions()
51320
+ .then((actions) => new Map(actions.map((action) => [action.id, action])));
51321
+ }
51322
+ /** Stamp `action`'s routing `lane` from lane membership. */
51323
+ stampLane(action, isBinaryOwned) {
51324
+ const lane = isBinaryOwned ? this.laneLabels.concurrentBinary : this.laneLabels.serial;
51325
+ return { ...action, lane };
51326
+ }
51327
+ /**
51328
+ * Extends the base projection with the routing `lane` stamped onto the action. Only the
51329
+ * gate-ON path carries a lane; the base DraftManager never emits the field, so the gate-OFF
51330
+ * projection stays identical to before the concurrent-binary queue existed.
51331
+ */
51332
+ buildDraftQueueItem(action) {
51333
+ const item = super.buildDraftQueueItem(action);
51334
+ if (action.lane !== undefined) {
51335
+ item.lane = action.lane;
51336
+ }
51337
+ return item;
51338
+ }
51339
+ }
51340
+
51341
+ function clone$1(obj) {
51342
+ return parse$6(stringify$6(obj));
51343
+ }
51344
+
51345
+ const DRAFT_ACTION_KEY_JUNCTION = '__DraftAction__';
51346
+ function buildDraftDurableStoreKey(recordKey, draftActionId) {
51347
+ return `${recordKey}${DRAFT_ACTION_KEY_JUNCTION}${draftActionId}`;
51348
+ }
51349
+ /**
51350
+ * Implements a write-through InMemoryStore for Drafts, storing all drafts in a
51351
+ * in-memory store with a write through to the DurableStore.
51352
+ *
51353
+ * Before any reads or writes come in from the draft queue, we need to revive the draft
51354
+ * queue into memory. During this initial revive, any writes are queued up and operated on the
51355
+ * queue once it's in memory. Similarly any reads are delayed until the queue is in memory.
51356
+ *
51357
+ */
51358
+ class DurableDraftStore {
51359
+ constructor(durableStore, instrumentation, useSnapshot = true) {
51360
+ this.draftStore = {};
51361
+ // Snapshot: holds deep clones of each draft, refreshed at write time.
51362
+ // getAllDrafts serves from this snapshot with zero deep clones per read.
51363
+ this.cleanSnapshot = {};
51364
+ // queue of writes that were made during the initial sync
51365
+ this.writeQueue = [];
51366
+ this.durableStore = durableStore;
51367
+ this.instrumentation = instrumentation;
51368
+ this.useSnapshot = useSnapshot;
51369
+ this.resyncDraftStore();
51370
+ }
51371
+ // When no instrumentation is injected the promise is returned as-is (zero overhead).
51372
+ timeDurableOp(op, segment, run) {
51373
+ const onDurableOperation = this.instrumentation?.onDurableOperation;
51374
+ if (onDurableOperation === undefined) {
51375
+ return run();
51376
+ }
51377
+ const start = Date.now();
51378
+ return run().finally(() => {
51379
+ onDurableOperation(op, segment, Date.now() - start);
51380
+ });
51381
+ }
51382
+ writeAction(action) {
51383
+ const addAction = () => {
51384
+ const { id, tag } = action;
51385
+ this.draftStore[id] = action;
51386
+ this.cleanSnapshot[id] = clone$1(action);
51387
+ const durableEntryKey = buildDraftDurableStoreKey(tag, id);
51388
+ const entry = {
51389
+ data: action,
51390
+ };
51391
+ const entries = { [durableEntryKey]: entry };
51392
+ return this.timeDurableOp('setEntries', DRAFT_SEGMENT, () => this.durableStore.setEntries(entries, DRAFT_SEGMENT));
51393
+ };
51394
+ return this.enqueueAction(addAction);
51395
+ }
51396
+ getAllDrafts() {
51397
+ const waitForOngoingSync = this.syncPromise || Promise.resolve();
51398
+ return waitForOngoingSync.then(() => {
51399
+ const actionArray = [];
51400
+ if (this.useSnapshot) {
51401
+ const { cleanSnapshot } = this;
51402
+ const keys$1 = keys$4(cleanSnapshot);
51403
+ for (let i = 0, len = keys$1.length; i < len; i++) {
51404
+ const key = keys$1[i];
51405
+ // Return shallow spread of snapshot entries so top-level caller mutations
51406
+ // (e.g., .status =) don't persist into the snapshot. The snapshot itself
51407
+ // is a deep clone of draftStore, so no nested mutation reaches draftStore.
51408
+ actionArray.push({ ...cleanSnapshot[key] });
51409
+ }
51410
+ }
51411
+ else {
51412
+ // Killswitch (W-23515682): original pre-fix behavior — deep-clone every draft on
51413
+ // every read so the internal draft store is never exposed. O(N) clones per read.
51414
+ const { draftStore } = this;
51415
+ const keys$1 = keys$4(draftStore);
51416
+ for (let i = 0, len = keys$1.length; i < len; i++) {
51417
+ actionArray.push(clone$1(draftStore[keys$1[i]]));
51418
+ }
51419
+ }
51420
+ return actionArray;
51421
+ });
51422
+ }
51423
+ deleteDraft(id) {
51424
+ const deleteAction = () => {
51425
+ const draft = this.draftStore[id];
51426
+ if (draft !== undefined) {
51427
+ delete this.draftStore[id];
51428
+ delete this.cleanSnapshot[id];
51429
+ const durableKey = buildDraftDurableStoreKey(draft.tag, draft.id);
51430
+ return this.timeDurableOp('evictEntries', DRAFT_SEGMENT, () => this.durableStore.evictEntries([durableKey], DRAFT_SEGMENT));
51431
+ }
51432
+ return Promise.resolve();
51433
+ };
51434
+ return this.enqueueAction(deleteAction);
51435
+ }
51436
+ deleteByTag(tag) {
51437
+ const deleteAction = () => {
51438
+ const { draftStore } = this;
51439
+ const keys$1 = keys$4(draftStore);
51440
+ const durableKeys = [];
51441
+ for (let i = 0, len = keys$1.length; i < len; i++) {
51442
+ const key = keys$1[i];
51443
+ const action = draftStore[key];
51444
+ if (action.tag === tag) {
51445
+ delete draftStore[action.id];
51446
+ delete this.cleanSnapshot[action.id];
51447
+ durableKeys.push(buildDraftDurableStoreKey(action.tag, action.id));
51448
+ }
51449
+ }
51450
+ return this.timeDurableOp('evictEntries', DRAFT_SEGMENT, () => this.durableStore.evictEntries(durableKeys, DRAFT_SEGMENT));
51451
+ };
51452
+ return this.enqueueAction(deleteAction);
51453
+ }
51454
+ completeAction(queueOperations) {
51455
+ const action = () => {
51456
+ const durableStoreOperations = [];
51457
+ const { draftStore } = this;
51458
+ for (let i = 0, len = queueOperations.length; i < len; i++) {
51459
+ const operation = queueOperations[i];
51460
+ if (operation.type === QueueOperationType.Delete) {
51461
+ const action = draftStore[operation.id];
51462
+ if (action !== undefined) {
51463
+ delete draftStore[operation.id];
51464
+ delete this.cleanSnapshot[operation.id];
51465
+ const key = buildDraftDurableStoreKey(action.tag, action.id);
51466
+ durableStoreOperations.push({
51467
+ ids: [key],
51468
+ type: 'evictEntries',
51469
+ segment: DRAFT_SEGMENT,
51470
+ });
51471
+ }
51472
+ }
51473
+ else {
51474
+ const { action } = operation;
51475
+ const key = buildDraftDurableStoreKey(action.tag, action.id);
51476
+ draftStore[action.id] = action;
51477
+ this.cleanSnapshot[action.id] = clone$1(action);
51478
+ durableStoreOperations.push({
51479
+ type: 'setEntries',
51480
+ segment: DRAFT_SEGMENT,
51481
+ entries: {
51482
+ [key]: {
51483
+ data: operation.action,
51484
+ },
51485
+ },
51486
+ });
51487
+ }
51488
+ }
51489
+ return this.timeDurableOp('batchOperations', DRAFT_SEGMENT, () => this.durableStore.batchOperations(durableStoreOperations));
51490
+ };
51491
+ return this.enqueueAction(action);
51492
+ }
51493
+ getCount() {
51494
+ return keys$4(this.draftStore).length;
51495
+ }
51496
+ /**
51497
+ * Runs a write operation against the draft store, if the initial
51498
+ * revive is still in progress, the action gets enqueued to run once the
51499
+ * initial revive is complete
51500
+ * @param action
51501
+ * @returns a promise that is resolved once the action has run
51502
+ */
51503
+ enqueueAction(action) {
51504
+ const { syncPromise, writeQueue: pendingMerges } = this;
51505
+ // if the initial sync is done and existing operations have been run, no need to queue, just run
51506
+ if (syncPromise === undefined && pendingMerges.length === 0) {
51507
+ return action();
51508
+ }
51509
+ const deferred = new Promise((resolve, reject) => {
51510
+ this.writeQueue.push(() => {
51511
+ return action()
51512
+ .then((x) => {
51513
+ resolve(x);
51514
+ })
51515
+ .catch((err) => reject(err));
51516
+ });
51517
+ });
51518
+ return deferred;
51519
+ }
51520
+ /**
51521
+ * Revives the draft store from the durable store. Once the draft store is
51522
+ * revived, executes any queued up draft store operations that came in while
51523
+ * reviving
51524
+ */
51525
+ resyncDraftStore() {
51526
+ const sync = () => {
51527
+ this.syncPromise = this.durableStore
51528
+ .getAllEntries(DRAFT_SEGMENT)
51529
+ .then((durableEntries) => {
51530
+ if (durableEntries === undefined) {
51531
+ this.draftStore = {};
51532
+ this.cleanSnapshot = {};
51533
+ return this.runQueuedOperations();
51534
+ }
51535
+ const { draftStore } = this;
51536
+ const keys$1 = keys$4(durableEntries);
51537
+ for (let i = 0, len = keys$1.length; i < len; i++) {
51538
+ const entry = durableEntries[keys$1[i]];
51539
+ const action = entry.data;
51540
+ draftStore[action.id] = action;
51541
+ this.cleanSnapshot[action.id] = clone$1(action);
51542
+ }
51543
+ return this.runQueuedOperations();
51544
+ })
51545
+ .finally(() => {
51546
+ this.syncPromise = undefined;
51547
+ });
51548
+ return this.syncPromise;
51549
+ };
51550
+ // if there's an ongoing sync populating the in memory store, wait for it to complete before re-syncing
51551
+ const { syncPromise } = this;
51552
+ if (syncPromise === undefined) {
51553
+ return sync();
51554
+ }
51555
+ return syncPromise.then(() => {
51556
+ return sync();
51557
+ });
51558
+ }
51559
+ /**
51560
+ * Runs the operations that were queued up while reviving the
51561
+ * draft store from the durable store
51562
+ */
51563
+ runQueuedOperations() {
51564
+ const { writeQueue } = this;
51565
+ if (writeQueue.length > 0) {
51566
+ const queueItem = writeQueue.shift();
51567
+ if (queueItem !== undefined) {
51568
+ return queueItem().then(() => {
51569
+ return this.runQueuedOperations();
51570
+ });
51571
+ }
51572
+ }
51573
+ return Promise.resolve();
51574
+ }
51575
+ }
51576
+
51577
+ /**
51578
+ * Durable-store segment holding batch-completion journal entries (B2). Kept
51579
+ * separate from DRAFT_SEGMENT so journal rows are never mistaken for draft
51580
+ * actions by DurableDraftStore's resync (which parses every DRAFT_SEGMENT entry
51581
+ * as a DraftAction).
51582
+ */
51583
+ const DRAFT_BATCH_JOURNAL_SEGMENT = 'DRAFT_BATCH_JOURNAL';
51584
+ /**
51585
+ * The Performance Upload draft store. Extends {@link DurableDraftStore} — whose
51586
+ * body is byte-identical to today's shipped store — and serializes concurrent
51587
+ * writes through a `writeChain` so that when two queues share a single store
51588
+ * their snapshot-then-mutate sequences cannot interleave (which would otherwise
51589
+ * let one queue's queue-operation rewrites clobber another's). Only constructed
51590
+ * on the gate-ON code path; gate-off customers use a plain DurableDraftStore.
51591
+ */
51592
+ class PerformanceDraftStore extends DurableDraftStore {
51593
+ constructor(durableStore) {
51594
+ super(durableStore);
51595
+ // Serializes writes so two queues sharing this store can't interleave; see
51596
+ // class doc.
51597
+ this.writeChain = Promise.resolve();
51598
+ // Identifies THIS store session (process launch). Minted fresh per
51599
+ // construction and never persisted, so a journal entry stamped with a
51600
+ // different token is crash residue from a dead process (recoverable), while
51601
+ // one stamped with this token is a batch still in flight this session. Sibling
51602
+ // queues share one store instance (the Performance Upload model) and therefore
51603
+ // one token; see readRecoverableBatchJournals.
51604
+ this.sessionToken = uuidv4();
51605
+ this.durableStoreRef = durableStore;
51606
+ }
51607
+ /**
51608
+ * Records, BEFORE a batch is dispatched, the ids of the members about to be
51609
+ * sent as one all-or-none request (B2). If the app dies — or the durable
51610
+ * removal fails — between the server commit and the client removing the
51611
+ * committed members, the next startQueue reconcile reads this journal and
51612
+ * pins any still-Pending member to the key-preserving serial path instead
51613
+ * of re-batching it (which would drop its idempotency key and replay a
51614
+ * committed write). Journal rows live in their own segment and never flow
51615
+ * through the draft writeChain — they are keyed by batchId, independent of
51616
+ * the draft snapshot-then-mutate sequence the chain serializes.
51617
+ */
51618
+ writeBatchJournal(batchId, memberIds) {
51619
+ const entry = {
51620
+ // Stamp the live session token so a later reconcile can tell this
51621
+ // in-flight batch apart from crash residue (see sessionToken).
51622
+ data: { batchId, memberIds, owner: this.sessionToken },
51623
+ };
51624
+ return this.durableStoreRef.setEntries({ [batchId]: entry }, DRAFT_BATCH_JOURNAL_SEGMENT);
51625
+ }
51626
+ /** Removes a batch-completion journal entry once its members are durably resolved. */
51627
+ clearBatchJournal(batchId) {
51628
+ return this.durableStoreRef.evictEntries([batchId], DRAFT_BATCH_JOURNAL_SEGMENT);
51629
+ }
51630
+ /**
51631
+ * Returns only crash-residue journals — those written by a PRIOR store session
51632
+ * (owner token != this session's). Entries stamped with the live session's
51633
+ * token are batches still in flight this launch (possibly on a sibling queue
51634
+ * sharing this store) and are deliberately excluded, so a startup reconcile can
51635
+ * never quarantine a live peer batch's members out from under it. This is the
51636
+ * only read the queue reconcile uses; readBatchJournals (all entries) is kept
51637
+ * for inspection/tests.
51638
+ *
51639
+ * Relies on sibling queues sharing ONE store INSTANCE (the documented
51640
+ * Performance Upload model), so they share one session token. If two queues
51641
+ * were ever given separate store instances over the same durable store, the
51642
+ * token would have to move down to the durable store.
51643
+ */
51644
+ readRecoverableBatchJournals() {
51645
+ return this.readBatchJournals().then((journals) => journals.filter((journal) => journal.owner !== this.sessionToken));
51646
+ }
51647
+ /** Returns every persisted batch-completion journal entry (inspection/tests). */
51648
+ readBatchJournals() {
51649
+ return this.durableStoreRef
51650
+ .getAllEntries(DRAFT_BATCH_JOURNAL_SEGMENT)
51651
+ .then((entries) => {
51652
+ if (entries === undefined) {
51653
+ return [];
51654
+ }
51655
+ const keys$1 = keys$4(entries);
51656
+ const journals = [];
51657
+ for (let i = 0, len = keys$1.length; i < len; i++) {
51658
+ journals.push(entries[keys$1[i]].data);
51659
+ }
51660
+ return journals;
51661
+ });
51662
+ }
51663
+ getAllDrafts() {
51664
+ const waitForOngoingSync = this.syncPromise || Promise.resolve();
51665
+ // Also wait for any outstanding writes serialized through the
51666
+ // write chain so callers observe writes initiated before this read.
51667
+ const waitForOutstandingWrites = this.writeChain;
51668
+ return Promise.all([waitForOngoingSync, waitForOutstandingWrites]).then(() => {
51669
+ const { draftStore } = this;
51670
+ const keys$1 = keys$4(draftStore);
51671
+ const actionArray = [];
51672
+ for (let i = 0, len = keys$1.length; i < len; i++) {
51673
+ const key = keys$1[i];
51674
+ // clone draft so we don't expose the internal draft store
51675
+ actionArray.push(clone$1(draftStore[key]));
51676
+ }
51677
+ return actionArray;
51678
+ });
51679
+ }
51680
+ enqueueAction(action) {
51681
+ const { syncPromise, writeQueue: pendingMerges } = this;
51682
+ // During initial sync, queue the write to run after sync completes.
51683
+ if (syncPromise !== undefined || pendingMerges.length > 0) {
51684
+ const deferred = new Promise((resolve, reject) => {
51685
+ this.writeQueue.push(() => {
51686
+ return action()
51687
+ .then((x) => {
51688
+ resolve(x);
51689
+ })
51690
+ .catch((err) => reject(err));
51691
+ });
51692
+ });
51693
+ return deferred;
51694
+ }
51695
+ // Sync done. Serialize concurrent writes through writeChain so that
51696
+ // when two queues share this store, their snapshot-then-mutate
51697
+ // sequences cannot interleave.
51698
+ const next = this.writeChain.then(action, action);
51699
+ // Don't propagate failures into the chain — every caller awaits its own
51700
+ // result and a single rejection must not poison subsequent writes.
51701
+ this.writeChain = next.catch(() => undefined);
51702
+ return next;
51703
+ }
51704
+ }
51705
+
49500
51706
  const { hasOwnProperty: ObjectPrototypeHasOwnProperty$1$1 } = Object.prototype;
49501
51707
  const { keys: ObjectKeys$1$2, create: ObjectCreate$1$2 } = Object;
49502
51708
  const { stringify: JSONStringify$1 } = JSON;
@@ -80322,6 +82528,7 @@
80322
82528
  const DRAFT_QUEUE_ACTION_UPDATED = 'draft-queue-action-updated';
80323
82529
  const DRAFT_QUEUE_ACTION_FAILED = 'draft-queue-action-failed';
80324
82530
  const DRAFT_QUEUE_ACTION_UPLOAD_ERROR = 'draft-queue-action-upload-error';
82531
+ const DRAFT_QUEUE_BATCH_RECOVERY_FAILED = 'draft-queue-batch-recovery-failed';
80325
82532
  const DRAFT_QUEUE_TOTAL_MERGE_ACTIONS_CALLS = 'draft-queue-total-mergeActions-calls';
80326
82533
  // Emitted every time a draft's Idempotency-Key is rotated (replaced with a fresh uuid).
80327
82534
  // Used to triage the WOLI duplicate-record investigation in Splunk — correlate by draftId
@@ -80372,6 +82579,11 @@
80372
82579
  __nimbus.plugins.JSLoggerPlugin !== undefined
80373
82580
  ? __nimbus.plugins.JSLoggerPlugin
80374
82581
  : undefined;
82582
+ function logInfo(message) {
82583
+ if (nimbusLogger) {
82584
+ nimbusLogger.logInfo(message);
82585
+ }
82586
+ }
80375
82587
  function reportGraphqlQueryParseError(err) {
80376
82588
  const error = normalizeError$2(err);
80377
82589
  const errorCode = GRAPHQL_QUERY_PARSE_ERROR;
@@ -80417,9 +82629,7 @@
80417
82629
  ldsMobileInstrumentation$2.incrementCounter(GRAPHQL_SNAPSHOT_REFRESH_UNDEFINED);
80418
82630
  }
80419
82631
  function reportDraftActionEvent(state, draftCount, message) {
80420
- if (nimbusLogger) {
80421
- nimbusLogger.logInfo(`Draft action event: ${state}, depth: ${draftCount}${message ? `, message: ${message}` : ''}`);
80422
- }
82632
+ logInfo(`Draft action event: ${state}, depth: ${draftCount}${message ? `, message: ${message}` : ''}`);
80423
82633
  switch (state) {
80424
82634
  case 'added':
80425
82635
  ldsMobileInstrumentation$2.incrementCounter(DRAFT_QUEUE_ACTION_ADDED);
@@ -80619,6 +82829,26 @@
80619
82829
  });
80620
82830
  ldsMobileInstrumentation$2.error(normalized, DRAFT_QUEUE_ACTION_UPLOAD_ERROR);
80621
82831
  }
82832
+ /**
82833
+ * Reports a batch-journal crash-recovery failure on the Performance Upload
82834
+ * batching path (B2, currently feature-gated and dormant): a maybe-committed
82835
+ * all-or-none batch's members could not be durably quarantined this session, a
82836
+ * startup reconcile could not surface a prior crash's batch, or a resolved journal
82837
+ * row could not be cleared. Each is otherwise visible only in device logs; this
82838
+ * surfaces it to o11y (greppable log line + reason-tagged counter) so the batching
82839
+ * path can be monitored when it ships.
82840
+ *
82841
+ * PII: carries ONLY the bounded reason code and the queue depth — never a record
82842
+ * id, draft id, tag, or free-text error message (device-log PII policy).
82843
+ */
82844
+ function reportBatchRecoveryFailure(reason, draftCount) {
82845
+ if (nimbusLogger) {
82846
+ nimbusLogger.logInfo(`Batch recovery failed: reason=${reason}, depth=${draftCount}`);
82847
+ }
82848
+ ldsMobileInstrumentation$2.incrementCounter(DRAFT_QUEUE_BATCH_RECOVERY_FAILED, 1, true, {
82849
+ reason,
82850
+ });
82851
+ }
80622
82852
  /**
80623
82853
  * Emits a single greppable Splunk log line (and an o11y counter) every time a draft's
80624
82854
  * Idempotency-Key is rotated — i.e. replaced with a fresh uuid rather than reused on
@@ -80648,9 +82878,7 @@
80648
82878
  });
80649
82879
  }
80650
82880
  function reportDraftQueueState(state, draftCount) {
80651
- if (nimbusLogger) {
80652
- nimbusLogger.logInfo(`Draft state changed: ${state}, depth: ${draftCount}`);
80653
- }
82881
+ logInfo(`Draft state changed: ${state}, depth: ${draftCount}`);
80654
82882
  switch (state) {
80655
82883
  case 'started':
80656
82884
  ldsMobileInstrumentation$2.incrementCounter(DRAFT_QUEUE_STATE_STARTED);
@@ -80763,6 +82991,26 @@
80763
82991
 
80764
82992
  const DEFAULT_FIELD_LAST_MODIFIED_DATE$1 = 'LastModifiedDate';
80765
82993
  const DEFAULT_FIELD_CREATED_DATE$1 = 'CreatedDate';
82994
+ // UI-API Records Batch endpoint. Reuses the same baseUri pattern as the
82995
+ // generated record adapters (see e.g. getUiApiRecordsByRecordId.ts).
82996
+ const BATCH_BASE_URI = '/services/data/v68.0';
82997
+ const BATCH_BASE_PATH = '/ui-api/records/batch';
82998
+ // Non-attributive error codes returned by an allOrNone=true batch. When one
82999
+ // operation fails, UI-API rolls the whole batch back and marks the *innocent*
83000
+ // siblings with one of these codes — they are not themselves the offender:
83001
+ // - ALL_OR_NONE_OPERATION_ROLLED_BACK: the canonical all-or-none rollback
83002
+ // marker applied to every sibling that would otherwise have succeeded.
83003
+ // - PROCESSING_HALTED: applied to operations skipped because processing was
83004
+ // halted (e.g. a dependency/composite-ordering stop) before they ran.
83005
+ // The true offender is any member whose errorCode is neither of these.
83006
+ const PROCESSING_HALTED_ERROR_CODE = 'PROCESSING_HALTED';
83007
+ const ALL_OR_NONE_ROLLED_BACK_ERROR_CODE = 'ALL_OR_NONE_OPERATION_ROLLED_BACK';
83008
+ // Codes that mark a batch member as a rolled-back innocent sibling rather than
83009
+ // the operation that actually caused the batch to fail.
83010
+ const ROLLBACK_SIBLING_ERROR_CODES = new Set([
83011
+ PROCESSING_HALTED_ERROR_CODE,
83012
+ ALL_OR_NONE_ROLLED_BACK_ERROR_CODE,
83013
+ ]);
80766
83014
  class AbstractResourceRequestActionHandler {
80767
83015
  constructor(draftQueue, networkAdapter, getLuvio, recordService) {
80768
83016
  this.draftQueue = draftQueue;
@@ -80925,23 +83173,7 @@
80925
83173
  actionDataChanged = true;
80926
83174
  }
80927
83175
  }
80928
- if (response.status === HttpStatusCode$2.BadRequest &&
80929
- this.isBackdatingError(response.body, action)) {
80930
- updatedAction.timestamp = Date.now();
80931
- updatedAction.data.body.fields = {
80932
- ...updatedAction.data.body.fields,
80933
- LastModifiedDate: new Date(updatedAction.timestamp).toISOString(),
80934
- };
80935
- // The record content changed (LastModifiedDate is bumped), so this is a NEW
80936
- // logical write. Rotate the idempotency key so the server treats it as such
80937
- // rather than deduping it against the stale, pre-backdate request. This is a
80938
- // legitimate rotation — the request body is modified — unlike the generic-400
80939
- // fallback above which must preserve the key. @W-23445154
80940
- if (this.hasIdempotencySupport() &&
80941
- updatedAction.data.headers[HTTP_HEADER_IDEMPOTENCY_KEY] !== undefined) {
80942
- updatedAction.data.headers[HTTP_HEADER_IDEMPOTENCY_KEY] = uuidv4();
80943
- reportIdempotencyKeyRotated(updatedAction.targetId, 'backdating-collision');
80944
- }
83176
+ if (this.applyBackdatingRetryIfNeeded(response, updatedAction)) {
80945
83177
  shouldRetry = true;
80946
83178
  actionDataChanged = true;
80947
83179
  }
@@ -81039,6 +83271,113 @@
81039
83271
  };
81040
83272
  await actionErrored(retryingAction, true, retryDelayInMs, true);
81041
83273
  }
83274
+ /**
83275
+ * If `response` is a LastModifiedDate backdating collision (@W-23445154) for
83276
+ * `action`, mutate the action so it is treated as a NEW logical write — bump
83277
+ * its timestamp + LastModifiedDate, and rotate the idempotency key when one
83278
+ * is present (the body changed, so the server must not dedupe it against the
83279
+ * stale pre-backdate request) — and return true. Otherwise return false and
83280
+ * leave the action untouched.
83281
+ *
83282
+ * Extracted from the single-action handleAction path so the batch upload
83283
+ * path (UiApiActionHandler.classifyBatchFailure) treats a backdating
83284
+ * collision identically instead of diverging (B4).
83285
+ */
83286
+ applyBackdatingRetryIfNeeded(response, action) {
83287
+ if (response.status !== HttpStatusCode$2.BadRequest ||
83288
+ !this.isBackdatingError(response.body, action)) {
83289
+ return false;
83290
+ }
83291
+ action.timestamp = Date.now();
83292
+ action.data.body.fields = {
83293
+ ...action.data.body.fields,
83294
+ LastModifiedDate: new Date(action.timestamp).toISOString(),
83295
+ };
83296
+ if (this.hasIdempotencySupport() &&
83297
+ action.data.headers[HTTP_HEADER_IDEMPOTENCY_KEY] !== undefined) {
83298
+ action.data.headers[HTTP_HEADER_IDEMPOTENCY_KEY] = uuidv4();
83299
+ reportIdempotencyKeyRotated(action.targetId, 'backdating-collision');
83300
+ }
83301
+ return true;
83302
+ }
83303
+ /**
83304
+ * Classifies a failure surfaced by the batch upload path — either a non-ok
83305
+ * batch envelope (whole request failed) or a single offending operation's
83306
+ * error result — into a retry-or-terminal decision, reusing the SAME policy
83307
+ * the single-action handleAction path applies to the same failure shapes so
83308
+ * the two do not diverge (B4). The caller routes the decision: a retry goes
83309
+ * through retryOrCap (so the durable attempt cap and backoff apply), a
83310
+ * terminal result errors the action with no retry.
83311
+ *
83312
+ * Note the idempotency-key state machine in handleAction (key rotation on
83313
+ * recognized idempotency error codes, isIdempotencySupported toggling) is
83314
+ * intentionally NOT shared here: those branches are keyed on the request's
83315
+ * per-action Idempotency-Key, which the batch envelope does not carry.
83316
+ *
83317
+ * commitAmbiguous distinguishes retryable failures that MAY have committed the
83318
+ * all-or-none batch at the origin (a 5xx/408/dropped-connection — or a generic
83319
+ * gateway 400 — returned after the write landed, with the success response lost
83320
+ * in transit) from retryable failures that definitively rolled back or never
83321
+ * reached the origin (a 429 rate-limit, a backdating collision the server
83322
+ * evaluated and rejected). The batch envelope carries no server-visible
83323
+ * idempotency key, so a commit-ambiguous failure cannot be safely re-sent; the
83324
+ * caller returns NETWORK_ERROR and the queue surfaces the members for manual
83325
+ * resolution instead of auto-replaying them (Option A). A definitively
83326
+ * rolled-back failure committed nothing, so a keyless re-batch is replay-safe.
83327
+ */
83328
+ classifyBatchFailure(response, action) {
83329
+ const status = response.status ?? 0;
83330
+ // Transient / infrastructure failures — retry, honoring any server-sent
83331
+ // Retry-After (mirrors handleAction's 408/503 handling). 0 = no response
83332
+ // (connection dropped / suspended in flight); 408 Request Timeout; 429
83333
+ // Too Many Requests; 5xx server errors.
83334
+ if (status === 0 ||
83335
+ status === 408 ||
83336
+ status === 429 ||
83337
+ status >= HttpStatusCode$2.ServerError) {
83338
+ return {
83339
+ shouldRetry: true,
83340
+ retryDelayInMs: getRetryAfterInMs(response.headers),
83341
+ actionDataChanged: false,
83342
+ // 0 (dropped connection), 408 (timeout), and 5xx (gateway/LB/origin
83343
+ // server error) can each be returned AFTER the all-or-none batch
83344
+ // committed at the origin with the 2xx lost — commit-ambiguous, like
83345
+ // handleAction's NoResponse/ServiceUnavailable path. A 429 is a rate
83346
+ // limiter rejecting the request before it is processed, so nothing
83347
+ // committed and a keyless re-batch is replay-safe.
83348
+ commitAmbiguous: status !== 429,
83349
+ };
83350
+ }
83351
+ // LastModifiedDate backdating collision — bump the record + retry, same
83352
+ // as the single-action path. The server evaluated and rejected the write,
83353
+ // so the batch rolled back — not commit-ambiguous.
83354
+ if (this.applyBackdatingRetryIfNeeded(response, action)) {
83355
+ return { shouldRetry: true, actionDataChanged: true, commitAmbiguous: false };
83356
+ }
83357
+ // A 400 with no recognizable server-generated error body is an edge- or
83358
+ // gateway-injected rejection whose commit status is genuinely ambiguous: an
83359
+ // edge proxy or load balancer can return a bare 400 AFTER the origin has
83360
+ // already committed the all-or-none batch. The envelope carries no
83361
+ // server-visible idempotency key, so a keyless re-send could double-apply.
83362
+ // Treat it as commit-ambiguous (like status 0/408/5xx) so the queue does NOT
83363
+ // auto-replay it and surfaces the members for manual resolution instead.
83364
+ if (status === HttpStatusCode$2.BadRequest && !this.isServerGeneratedError(response.body)) {
83365
+ return { shouldRetry: true, actionDataChanged: false, commitAmbiguous: true };
83366
+ }
83367
+ // A real, server-generated client error (validation, permissions, a
83368
+ // deterministic 4xx) — terminal. Retrying it unchanged would only be
83369
+ // rejected again.
83370
+ return { shouldRetry: false, actionDataChanged: false, commitAmbiguous: false };
83371
+ }
83372
+ /**
83373
+ * Reports an upload failure to o11y using the same channel and attempt
83374
+ * numbering as the single-action handleAction catch. Exposed so the batch
83375
+ * upload path surfaces a thrown/deterministic failure to telemetry instead
83376
+ * of swallowing it (B4).
83377
+ */
83378
+ reportUploadFailure(error, action) {
83379
+ reportDraftActionUploadError(error, this.handlerId, this.getUploadRetryCount(action) + 1);
83380
+ }
81042
83381
  async handleActionEnqueued(action) {
81043
83382
  const impactedKeys = await this.recordService.setSideEffectsForActions([action], 'enqueued');
81044
83383
  await this.recordService.reapplyRecordSideEffects(impactedKeys, 'enqueued');
@@ -81501,6 +83840,29 @@
81501
83840
 
81502
83841
  const LDS_ACTION_HANDLER_ID = 'LDS_ACTION_HANDLER';
81503
83842
  const LDS_ACTION_METADATA_API_NAME = 'LDS_ACTION_METADATA_API_NAME';
83843
+ // Request headers/query params that the UI-API records/batch envelope can omit
83844
+ // without changing the write, so their presence must not disqualify an action
83845
+ // from batching (see isActionBatchable, B1). Everything not listed here does
83846
+ // change server behavior and forces single-action dispatch.
83847
+ const BATCH_OMITTABLE_HEADERS = new Set([HTTP_HEADER_IDEMPOTENCY_KEY]);
83848
+ const BATCH_OMITTABLE_QUERY_PARAMS = new Set(['includeFieldsInBody']);
83849
+ // Diagnostic log line for the local-experimental batching path. Mirrors the
83850
+ // helper in PerformanceDraftQueue so handler-side events show up in the same
83851
+ // device-log stream with the same `Batch ` prefix.
83852
+ function batchLog(line) {
83853
+ try {
83854
+ globalThis.__nimbus?.plugins?.JSLoggerPlugin?.logInfo(`Batch ${line}`);
83855
+ }
83856
+ catch {
83857
+ // debug-only
83858
+ }
83859
+ }
83860
+ // Ingestion timestamp that makes the uploaded record stale for the next read. Ingested at
83861
+ // epoch+1 the record is expired under any ttl: the record ttl, a record ttl override, the
83862
+ // default ttl override or a host metadata ttl. (Not 0, which falsy checks treat as missing.)
83863
+ // Expiring it with luvio.storeExpirePossibleStaleRecords or a 0 ttl does not work when a ttl
83864
+ // override is set, since the override replaces the ttl.
83865
+ const STALE_INGESTION_TIMESTAMP = 1;
81504
83866
  class UiApiActionHandler extends AbstractResourceRequestActionHandler {
81505
83867
  constructor(getLuvio, networkAdapter, draftQueue, getRecordAdapter, objectInfoService, isDraftId, recordService, sideEffectService, durableRecordStore) {
81506
83868
  super(draftQueue, networkAdapter, getLuvio, recordService);
@@ -81515,6 +83877,8 @@
81515
83877
  this.durableRecordStore = durableRecordStore;
81516
83878
  this.handlerId = LDS_ACTION_HANDLER_ID;
81517
83879
  this.sideEffectHooks = [];
83880
+ // side effect field values of the create actions being completed, by action id
83881
+ this.injectedFieldsByActionId = new Map();
81518
83882
  recordService.registerRecordHandler(this);
81519
83883
  }
81520
83884
  setSideEffectHooks(hooks) {
@@ -81625,7 +83989,40 @@
81625
83989
  await this.evictKey(completedAction.tag);
81626
83990
  return;
81627
83991
  }
81628
- return super.handleActionCompleted(completedAction, queueOperations);
83992
+ if (method !== 'post') {
83993
+ return super.handleActionCompleted(completedAction, queueOperations);
83994
+ }
83995
+ // super removes the action's side effects before it ingests the response, so what the
83996
+ // create's side effects set has to be captured first
83997
+ const injectedFields = this.getFieldsToInject(completedAction);
83998
+ if (injectedFields !== undefined) {
83999
+ this.injectedFieldsByActionId.set(completedAction.id, injectedFields);
84000
+ }
84001
+ try {
84002
+ await super.handleActionCompleted(completedAction, queueOperations);
84003
+ }
84004
+ finally {
84005
+ this.injectedFieldsByActionId.delete(completedAction.id);
84006
+ }
84007
+ }
84008
+ // The create response only has the fields that were requested, so a field that only a side
84009
+ // effect sets (e.g. ProductConsumed.IsProduct2Serialized) is missing from the cached
84010
+ // server record once the draft's effects are gone. Returns the values of those fields.
84011
+ // Only called for a POST: handleActionCompleted hands every other method straight to super.
84012
+ getFieldsToInject(completedAction) {
84013
+ if (sideEffectRefreshKillSwitch.isOpen({ fallback: false })) {
84014
+ return undefined;
84015
+ }
84016
+ const fields = {};
84017
+ this.recordService.getEffectsForAction(completedAction).forEach((effect) => {
84018
+ if (effect.type === 'record-field-set' && effect.key === completedAction.tag) {
84019
+ fields[effect.fieldName] = { value: effect.value, displayValue: null };
84020
+ }
84021
+ });
84022
+ if (keys$3(fields).length === 0) {
84023
+ return undefined;
84024
+ }
84025
+ return fields;
81629
84026
  }
81630
84027
  async fetchReferenceRecord(referenceFields) {
81631
84028
  const promises = referenceFields.map(async (referenceFieldInfo) => {
@@ -81683,6 +84080,500 @@
81683
84080
  getIdFromResponseBody(responseBody) {
81684
84081
  return responseBody.id;
81685
84082
  }
84083
+ /**
84084
+ * The UI-API records/batch envelope carries only { type, records:[{ apiName?,
84085
+ * fields }] } per operation — it has no place for per-operation headers or
84086
+ * query params (see buildBatchOperations / executeBatch, which send empty
84087
+ * headers and queryParams). An action whose request relies on a header or
84088
+ * query param that changes the *write* would silently lose that semantic if
84089
+ * folded into a batch, so it must be dispatched through single-action
84090
+ * handleAction (which sends the request verbatim) instead (B1).
84091
+ *
84092
+ * Two request members are present on essentially every update/delete draft
84093
+ * and are safe for the batch to omit, so they must NOT disqualify batching
84094
+ * (doing so would disable it wholesale):
84095
+ * - Idempotency-Key header: dropped from the batch envelope by design (the
84096
+ * batch has no per-op key). Its absence weakens replay protection, which
84097
+ * is addressed by journaled batch completion (B2) — it is not a per-op
84098
+ * write-semantic change, so it does not block batching here.
84099
+ * - includeFieldsInBody query param: only shapes the response body, not the
84100
+ * write; updateRecord adds it unconditionally.
84101
+ * Any OTHER header (e.g. If-Unmodified-Since — a conditional update that would
84102
+ * become an unconditional lost-update) or query param (useDefaultRule,
84103
+ * triggerUserEmail, triggerOtherEmail — assignment-rule / email side effects)
84104
+ * does change server behavior and makes the action non-batchable.
84105
+ *
84106
+ * The request BODY is checked too: buildBatchOperations copies ONLY `fields`
84107
+ * into the batch UPDATE/DELETE operation, so any other body member — e.g.
84108
+ * `allowSaveOnDuplicate`, which changes duplicate-rule handling — would be
84109
+ * silently dropped if the action were batched. An action whose body carries
84110
+ * anything beyond `fields` is therefore dispatched single-action (handleAction
84111
+ * sends the body verbatim), preserving those semantics.
84112
+ *
84113
+ * resolveResourceRequest only rewrites basePath/body/urlParams (never headers
84114
+ * or queryParams), and a body option like allowSaveOnDuplicate survives that
84115
+ * rewrite, so the raw action.data is authoritative for this check and we avoid
84116
+ * the cost of resolving here.
84117
+ */
84118
+ isActionBatchable(action) {
84119
+ const request = action.data;
84120
+ if (request.headers !== undefined) {
84121
+ const headerNames = keys$3(request.headers);
84122
+ for (let i = 0; i < headerNames.length; i++) {
84123
+ if (!BATCH_OMITTABLE_HEADERS.has(headerNames[i])) {
84124
+ return false;
84125
+ }
84126
+ }
84127
+ }
84128
+ if (request.queryParams !== undefined) {
84129
+ const queryNames = keys$3(request.queryParams);
84130
+ for (let i = 0; i < queryNames.length; i++) {
84131
+ if (!BATCH_OMITTABLE_QUERY_PARAMS.has(queryNames[i])) {
84132
+ return false;
84133
+ }
84134
+ }
84135
+ }
84136
+ // Only `fields` is carried into the batch op (buildBatchOperations); any
84137
+ // other body member (e.g. allowSaveOnDuplicate) would be dropped, so it
84138
+ // disqualifies the action from batching.
84139
+ const body = request.body;
84140
+ if (body !== undefined && body !== null) {
84141
+ const bodyKeys = keys$3(body);
84142
+ for (let i = 0; i < bodyKeys.length; i++) {
84143
+ if (bodyKeys[i] !== 'fields') {
84144
+ return false;
84145
+ }
84146
+ }
84147
+ }
84148
+ return true;
84149
+ }
84150
+ /**
84151
+ * Sends a single UI-API records/batch request that combines all given actions.
84152
+ * Uses allOrNone=true so any failure rolls back the whole batch on the server,
84153
+ * preserving today's "one bad mutation blocks the queue" UX.
84154
+ *
84155
+ * Per-action result routing pairs each result with its action by index. The
84156
+ * endpoint exposes no per-result correlation key (no client-supplied
84157
+ * referenceId; DELETE/error results carry no id) and does not contractually
84158
+ * guarantee results order matches operations order, so index pairing is
84159
+ * guarded: the result count must equal the action count, and each UPDATE
84160
+ * result's returned record id must match the action's resolved recordId.
84161
+ * - Success (hasErrors === false): each result is paired with its action by
84162
+ * index and forwarded to actionCompleted in order.
84163
+ * - Server-reported failure (hasErrors === true): exactly one result carries
84164
+ * the real errorCode; the innocent siblings carry a non-attributive
84165
+ * rollback code (ALL_OR_NONE_OPERATION_ROLLED_BACK or PROCESSING_HALTED).
84166
+ * The batch rolled back, so a retryable offender parks EVERY member
84167
+ * together (C4/R4-3 — no self-driven prefix/suffix retry) charging a retry
84168
+ * attempt only to the offender, and a deterministic offender is errored
84169
+ * terminally while innocent siblings are left Pending (B5); returns
84170
+ * ACTION_ERRORED (journal cleared, replay-safe).
84171
+ * - Commit-ambiguous transport failure (network throw, empty-body or
84172
+ * misaligned 2xx, result count/id mismatch, or a retryable 5xx/408/dropped-
84173
+ * connection or generic-400 envelope that may have committed with the 2xx
84174
+ * lost): return NETWORK_ERROR WITHOUT retrying. The batch envelope carries
84175
+ * no server-visible idempotency key, so it cannot be safely re-sent; the
84176
+ * queue surfaces the members for manual resolution and retains/clears the
84177
+ * B2 journal instead of auto-replaying them (Option A / R4-4).
84178
+ */
84179
+ async handleBatchActions(actions, actionCompleted, actionErrored) {
84180
+ return this.executeBatch(actions, actionCompleted, actionErrored);
84181
+ }
84182
+ async executeBatch(actions, actionCompleted, actionErrored) {
84183
+ if (actions.length === 0) {
84184
+ return ProcessActionResult.NO_ACTION_TO_PROCESS;
84185
+ }
84186
+ try {
84187
+ const operations = this.buildBatchOperations(actions);
84188
+ batchLog(`sending size=${actions.length}`);
84189
+ const batchRequest = {
84190
+ baseUri: BATCH_BASE_URI,
84191
+ basePath: BATCH_BASE_PATH,
84192
+ method: 'post',
84193
+ body: { allOrNone: true, operations },
84194
+ urlParams: {},
84195
+ queryParams: {},
84196
+ headers: {},
84197
+ priority: 'normal',
84198
+ };
84199
+ // Attribute the batch request to the head action's observability
84200
+ // context. A batch collapses N actions into one request, so there is
84201
+ // no per-member correlation; the head action's context is used as a
84202
+ // representative, mirroring the single-action dispatch path in
84203
+ // handleAction. (If members carried differing contexts, only the
84204
+ // head's is reported.)
84205
+ const dispatchOptions = actions[0].observabilityContext !== undefined
84206
+ ? {
84207
+ requestCorrelator: {
84208
+ observabilityContext: actions[0].observabilityContext,
84209
+ },
84210
+ }
84211
+ : {};
84212
+ const response = await this.networkAdapter(batchRequest, dispatchOptions);
84213
+ if (!response.ok) {
84214
+ // Classify the envelope with the SAME body-aware policy the
84215
+ // single-action path uses (classifyBatchFailure) instead of a
84216
+ // status-only check. Three outcomes, routing EVERY member (not just
84217
+ // the head — C4):
84218
+ // - Commit-AMBIGUOUS (5xx/408/dropped connection, or a generic
84219
+ // gateway 400): may have committed at the origin with the 2xx
84220
+ // lost, and the batch carries no server-visible idempotency key,
84221
+ // so a keyless re-send could double-apply. Return NETWORK_ERROR
84222
+ // WITHOUT retrying; the queue surfaces the members for manual
84223
+ // resolution and retains/clears the journal instead of
84224
+ // auto-replaying them (Option A / R4-4).
84225
+ // - Definitively rolled back but retryable (429 rate-limit,
84226
+ // backdating collision the server evaluated): committed nothing,
84227
+ // so a keyless re-batch is replay-safe — park every member for a
84228
+ // bounded, backed-off retry (capped, honoring Retry-After).
84229
+ // - Deterministic server-generated client error: terminal, so a
84230
+ // rejected batch is not retried forever (C3/B4).
84231
+ const decision = this.classifyBatchFailure(response, actions[0]);
84232
+ batchLog(`http error status=${response.status ?? 0} retry=${decision.shouldRetry}` +
84233
+ ` ambiguous=${decision.commitAmbiguous} size=${actions.length}`);
84234
+ if (decision.shouldRetry) {
84235
+ if (decision.commitAmbiguous) {
84236
+ return ProcessActionResult.NETWORK_ERROR;
84237
+ }
84238
+ await this.retryBatchMembers(actions, response, actionErrored, decision.retryDelayInMs);
84239
+ }
84240
+ else {
84241
+ await this.terminalBatchMembers(actions, response, actionErrored);
84242
+ }
84243
+ return ProcessActionResult.ACTION_ERRORED;
84244
+ }
84245
+ if (response.body === undefined || response.body === null) {
84246
+ // 2xx with no body — a misaligned/empty response. We got a success
84247
+ // status but cannot confirm what committed, so this is
84248
+ // commit-AMBIGUOUS: return NETWORK_ERROR so the queue surfaces the
84249
+ // members for manual resolution and retains/clears the journal,
84250
+ // rather than auto-replaying a keyless batch that may have committed
84251
+ // (Option A / R4-4).
84252
+ batchLog(`empty body ambiguous size=${actions.length}`);
84253
+ return ProcessActionResult.NETWORK_ERROR;
84254
+ }
84255
+ const body = response.body;
84256
+ // Both branches below pair body.results to actions positionally.
84257
+ // The UI-API batch endpoint supplies no per-result correlation key
84258
+ // (no client referenceId, and DELETE/error results carry no id) and
84259
+ // does not contractually guarantee results order matches operations
84260
+ // order, so a short/over-length response would silently mis-pair
84261
+ // completions with the wrong drafts. Refuse to pair positionally
84262
+ // unless the counts match exactly; on mismatch complete nothing. This is
84263
+ // commit-AMBIGUOUS (2xx received, response untrustworthy): return
84264
+ // NETWORK_ERROR so the queue surfaces the members for manual resolution
84265
+ // and retains/clears the journal (Option A / R4-4).
84266
+ if (!isArray$3$1(body.results) || body.results.length !== actions.length) {
84267
+ batchLog(`result count mismatch expected=${actions.length}` +
84268
+ ` got=${isArray$3$1(body.results) ? body.results.length : 'none'}` +
84269
+ ` ambiguous`);
84270
+ return ProcessActionResult.NETWORK_ERROR;
84271
+ }
84272
+ if (body.hasErrors === false) {
84273
+ // Strict success envelope (R4-4): the endpoint claims the batch
84274
+ // succeeded, but we only complete (and remove) a draft when the
84275
+ // member's OWN result confirms it committed — otherwise it is
84276
+ // commit-AMBIGUOUS: return NETWORK_ERROR so the queue surfaces the
84277
+ // members for manual resolution and retains/clears the journal,
84278
+ // rather than silently dropping a write that may never have landed.
84279
+ // (CREATE is never batched; DELETE carries no body, so only its 2xx
84280
+ // status is required — id echo is UPDATE-only.)
84281
+ for (let i = 0; i < actions.length; i++) {
84282
+ const action = actions[i];
84283
+ const method = action.data.method;
84284
+ const result = body.results[i];
84285
+ const childStatus = result?.statusCode;
84286
+ if (childStatus === undefined ||
84287
+ childStatus < HttpStatusCode$2.Ok ||
84288
+ childStatus >= 300) {
84289
+ batchLog(`success envelope unconfirmed child index=${i}` +
84290
+ ` status=${childStatus ?? 'none'} ambiguous`);
84291
+ return ProcessActionResult.NETWORK_ERROR;
84292
+ }
84293
+ if (method === 'patch') {
84294
+ const resolved = this.resolveResourceRequest(action.data);
84295
+ const expectedId = resolved.urlParams['recordId'];
84296
+ const returnedId = !isArray$3$1(result.result)
84297
+ ? result.result.id
84298
+ : undefined;
84299
+ // UPDATE must echo a matching record id; a missing or
84300
+ // mismatched id is commit-AMBIGUOUS.
84301
+ if (returnedId === undefined || returnedId !== expectedId) {
84302
+ // Log the reason code + whether an id came back, NOT the
84303
+ // ids themselves: expectedId/returnedId are record ids,
84304
+ // and the device-log PII policy (metrics.ts) forbids
84305
+ // record ids in device logs (4065667273).
84306
+ batchLog(`success envelope bad update id index=${i}` +
84307
+ ` returned=${returnedId === undefined ? 'none' : 'mismatch'} ambiguous`);
84308
+ return ProcessActionResult.NETWORK_ERROR;
84309
+ }
84310
+ }
84311
+ }
84312
+ batchLog(`completed size=${actions.length}`);
84313
+ for (let i = 0; i < actions.length; i++) {
84314
+ const action = actions[i];
84315
+ const result = body.results[i];
84316
+ const recordBody = result !== undefined && !isArray$3$1(result.result)
84317
+ ? result.result
84318
+ : undefined;
84319
+ const perActionResponse = {
84320
+ status: (result?.statusCode ?? HttpStatusCode$2.Ok),
84321
+ statusText: 'OK',
84322
+ ok: true,
84323
+ headers: {},
84324
+ body: recordBody,
84325
+ };
84326
+ await actionCompleted({
84327
+ ...action,
84328
+ response: perActionResponse,
84329
+ status: DraftActionStatus.Completed,
84330
+ });
84331
+ }
84332
+ return ProcessActionResult.ACTION_SUCCEEDED;
84333
+ }
84334
+ // hasErrors is neither false (clean success, handled above) nor true
84335
+ // (attributable failure, handled below): the envelope is incomplete
84336
+ // or malformed — we can neither confirm a commit nor attribute a
84337
+ // failure, so treat it as commit-AMBIGUOUS (return NETWORK_ERROR, as
84338
+ // above).
84339
+ if (body.hasErrors !== true) {
84340
+ batchLog(`success envelope missing hasErrors flag ambiguous`);
84341
+ return ProcessActionResult.NETWORK_ERROR;
84342
+ }
84343
+ // Locate the action whose result is the real failure. Under
84344
+ // allOrNone=true the server rolls the whole batch back and marks the
84345
+ // innocent siblings with a non-attributive code (B3): the canonical
84346
+ // all-or-none marker ALL_OR_NONE_OPERATION_ROLLED_BACK, or
84347
+ // PROCESSING_HALTED for operations skipped before they ran. The true
84348
+ // offender is the member whose errorCode is neither — matching only
84349
+ // PROCESSING_HALTED would mis-pick an innocent rolled-back sibling as
84350
+ // the offender and leave the real invalid action Pending forever.
84351
+ let offendingIndex = -1;
84352
+ let offendingResult;
84353
+ for (let i = 0; i < body.results.length; i++) {
84354
+ const r = body.results[i];
84355
+ if (r === undefined)
84356
+ continue;
84357
+ if (!isArray$3$1(r.result))
84358
+ continue;
84359
+ const code = r.result[0]?.errorCode;
84360
+ if (code !== undefined && !ROLLBACK_SIBLING_ERROR_CODES.has(code)) {
84361
+ offendingIndex = i;
84362
+ offendingResult = r;
84363
+ break;
84364
+ }
84365
+ }
84366
+ // Unattributed: every failing result carries only a non-attributive
84367
+ // rollback-sibling code with no clear offender. Treat as a transient
84368
+ // server error — retry the whole batch.
84369
+ if (offendingIndex < 0 || offendingResult === undefined) {
84370
+ batchLog(`hasErrors size=${actions.length} unattributed retry=true`);
84371
+ await this.retryBatchMembers(actions, response, actionErrored);
84372
+ return ProcessActionResult.ACTION_ERRORED;
84373
+ }
84374
+ const offendingAction = actions[offendingIndex];
84375
+ const errorBody = offendingResult?.result ?? [];
84376
+ const errorResponse = {
84377
+ status: (offendingResult?.statusCode ??
84378
+ HttpStatusCode$2.BadRequest),
84379
+ statusText: 'Bad Request',
84380
+ ok: false,
84381
+ headers: {},
84382
+ body: errorBody,
84383
+ };
84384
+ const offendingErrorCode = isArray$3$1(offendingResult?.result)
84385
+ ? offendingResult.result[0]?.errorCode ?? 'unknown'
84386
+ : 'unknown';
84387
+ // Classify the offender, reusing the single-action retry/terminal
84388
+ // policy (B4): a transient/ambiguous failure retries through the
84389
+ // durable cap, a deterministic server-generated client error is
84390
+ // terminal so the user can fix or remove it. classifyBatchFailure may
84391
+ // mutate offendingAction (e.g. a backdating bump) and reports
84392
+ // actionDataChanged so the mutation is persisted before the retry.
84393
+ // The batch endpoint returns each member's failure as a UiApiError[]
84394
+ // (the offender loop above keys on r.result[0].errorCode). The shared
84395
+ // classifiers reused by classifyBatchFailure — isBackdatingError /
84396
+ // isServerGeneratedError — and the single-action handleAction path
84397
+ // expect the origin's structured enhancedErrorType envelope, where a
84398
+ // backdating collision surfaces as
84399
+ // { enhancedErrorType: 'RecordError', output: { errors: [...] } }.
84400
+ // Left as a bare array, isBackdatingError never matches, so a batched
84401
+ // LastModifiedDate CollisionDetectedException would be errored
84402
+ // terminally instead of getting the single-action backdating bump +
84403
+ // key-rotate + retry (B4). Wrap the member's error array in that
84404
+ // envelope for CLASSIFICATION ONLY. This is behavior-preserving for
84405
+ // every non-collision offender: isServerGeneratedError is already
84406
+ // true for a UiApiError[] offender, so the terminal decision is
84407
+ // unchanged; only a genuine collision (which also requires the action
84408
+ // to carry a LastModifiedDate field) now recovers. The error surfaced
84409
+ // to the draft (errorResponse) keeps the raw array — unchanged.
84410
+ const classificationResponse = {
84411
+ ...errorResponse,
84412
+ body: {
84413
+ enhancedErrorType: 'RecordError',
84414
+ output: {
84415
+ errors: isArray$3$1(offendingResult?.result) ? offendingResult.result : [],
84416
+ },
84417
+ },
84418
+ };
84419
+ const decision = this.classifyBatchFailure(classificationResponse, offendingAction);
84420
+ batchLog(`failed size=${actions.length} offendingIndex=${offendingIndex}` +
84421
+ ` errorCode=${offendingErrorCode} retry=${decision.shouldRetry}`);
84422
+ if (decision.shouldRetry) {
84423
+ // Transient/ambiguous offender: the whole batch rolled back and
84424
+ // NONE committed. Parking only the offender and leaving the innocent
84425
+ // siblings Pending would let the queue immediately re-collect them
84426
+ // into a fresh, backoff-free batch — and if that batch's new head
84427
+ // draws the same transient response, [A,B,C] retries as [B,C] then
84428
+ // [C], up to 25 + 24 + ... + 1 = 325 operations before the first
84429
+ // backoff expires (R4-3). Park EVERY member together so the whole
84430
+ // batch backs off — but charge a durable retry attempt ONLY to the
84431
+ // offender (via retryOrCap). The innocent rolled-back siblings
84432
+ // produced no error of their own, so they are parked for the same
84433
+ // backoff WITHOUT consuming their retry budget; charging them could
84434
+ // push an innocent later action to its cap for another action's
84435
+ // transient failure (#9, matching the terminal branch's B5
84436
+ // treatment). The offender's own cap still bounds the shared-batch
84437
+ // retry loop. Only the offender carries any classifier mutation (a
84438
+ // backdating bump), so it alone reports actionDataChanged to persist
84439
+ // that mutation before its retry.
84440
+ for (const member of actions) {
84441
+ if (member === offendingAction) {
84442
+ await this.retryOrCap(member, errorResponse, actionErrored, decision.retryDelayInMs, decision.actionDataChanged);
84443
+ }
84444
+ else {
84445
+ await actionErrored(member, true, decision.retryDelayInMs);
84446
+ }
84447
+ }
84448
+ }
84449
+ else {
84450
+ // Deterministic, server-generated offender: terminal. Route ONLY the
84451
+ // offender and leave the innocent rolled-back siblings Pending and
84452
+ // unparked — reporting nothing for them (B5). Charging a sibling a
84453
+ // durable retry attempt for another action's terminal failure could
84454
+ // push an innocent later action to its cap without it ever producing
84455
+ // its own error. The queue re-collects the siblings on the next pass
84456
+ // (bounded: each pass terminally resolves one offender, so there is
84457
+ // no zero-delay storm), and it owns stop state / backoff / retry
84458
+ // budgets — the handler no longer self-drives prefix/suffix retries
84459
+ // (that recursion bypassed stopQueue and could launch a new request
84460
+ // while the original was in flight).
84461
+ await actionErrored({
84462
+ ...offendingAction,
84463
+ error: errorResponse,
84464
+ status: DraftActionStatus.Error,
84465
+ }, false);
84466
+ }
84467
+ return ProcessActionResult.ACTION_ERRORED;
84468
+ }
84469
+ catch (e) {
84470
+ batchLog(`network error ambiguous size=${actions.length}`);
84471
+ const failure = normalizeError$1(e);
84472
+ // A throw here means the request was dispatched but no response was
84473
+ // received — the all-or-none batch may have committed at the origin
84474
+ // with the response lost, and the envelope carries no server-visible
84475
+ // idempotency key. This is commit-AMBIGUOUS: surface the failure to o11y
84476
+ // (the single-action handleAction catch reports every upload error, and
84477
+ // the batch path swallowed them until now — B4; attributed to the head
84478
+ // as a representative, matching the dispatch correlation above), then
84479
+ // return NETWORK_ERROR so the queue surfaces the members for manual
84480
+ // resolution instead of auto-replaying them (Option A).
84481
+ this.reportUploadFailure(failure, actions[0]);
84482
+ return ProcessActionResult.NETWORK_ERROR;
84483
+ }
84484
+ }
84485
+ /**
84486
+ * Retries every given batch member through the durable retry cap
84487
+ * (retryOrCap). Used for whole-batch transient failures (network throw,
84488
+ * misaligned/short/empty response, unattributed rollback, retryable envelope
84489
+ * status) and for the surviving members of a partial failure, so that (a)
84490
+ * every member is parked with backoff before the queue re-arms — not just
84491
+ * the head (C4) — and (b) the durable attempt cap bounds the retries instead
84492
+ * of looping forever (C3). When the cap gate is closed, retryOrCap is a
84493
+ * passthrough that parks each member exactly as before (retry=true).
84494
+ */
84495
+ async retryBatchMembers(members, lastFailure, actionErrored, retryDelayInMs) {
84496
+ for (const member of members) {
84497
+ await this.retryOrCap(member, lastFailure, actionErrored, retryDelayInMs);
84498
+ }
84499
+ }
84500
+ /**
84501
+ * Terminally errors every given batch member (no retry). Used when the batch
84502
+ * envelope is rejected with a deterministic client error (4xx other than
84503
+ * 408/429): retrying an unchanged, server-rejected batch would only be
84504
+ * rejected again, so the drafts are errored for the user to fix or discard —
84505
+ * consistent with the single-action response policy — instead of being
84506
+ * retried forever (C3).
84507
+ */
84508
+ async terminalBatchMembers(members, error, actionErrored) {
84509
+ for (const member of members) {
84510
+ await actionErrored({ ...member, error, status: DraftActionStatus.Error }, false);
84511
+ }
84512
+ }
84513
+ /**
84514
+ * Maps each draft action to a UI-API records/batch operation. Each op has
84515
+ * exactly one record entry; the order of returned ops matches the order of
84516
+ * input actions so per-action result routing works on index alone.
84517
+ *
84518
+ * - method='post' -> CREATE with apiName + fields
84519
+ * - method='patch' -> UPDATE with fields including Id (Id pulled from
84520
+ * urlParams.recordId)
84521
+ * - method='delete' -> DELETE with fields containing only Id
84522
+ *
84523
+ * Each request is re-resolved through resolveResourceRequest first. The
84524
+ * draft-id redirect rewrite that runs when an upstream POST completes only
84525
+ * updates a queued action's basePath/body — NOT its urlParams — so a stored
84526
+ * PATCH/DELETE can still carry a stale draft id in urlParams.recordId at
84527
+ * drain time. resolveResourceRequest re-canonicalizes urlParams.recordId
84528
+ * (and body fields) against the store, and is idempotent when the id is
84529
+ * already canonical, so it is safe to call unconditionally here.
84530
+ */
84531
+ buildBatchOperations(actions) {
84532
+ const operations = [];
84533
+ for (const action of actions) {
84534
+ const request = this.resolveResourceRequest(action.data);
84535
+ const method = request.method;
84536
+ if (method === 'post') {
84537
+ const body = request.body;
84538
+ operations.push({
84539
+ type: 'CREATE',
84540
+ records: [
84541
+ {
84542
+ apiName: body.apiName,
84543
+ fields: { ...body.fields },
84544
+ },
84545
+ ],
84546
+ });
84547
+ }
84548
+ else if (method === 'patch') {
84549
+ const recordId = request.urlParams['recordId'];
84550
+ const body = request.body;
84551
+ operations.push({
84552
+ type: 'UPDATE',
84553
+ records: [
84554
+ {
84555
+ fields: { Id: recordId, ...body.fields },
84556
+ },
84557
+ ],
84558
+ });
84559
+ }
84560
+ else if (method === 'delete') {
84561
+ const recordId = request.urlParams['recordId'];
84562
+ operations.push({
84563
+ type: 'DELETE',
84564
+ records: [
84565
+ {
84566
+ fields: { Id: recordId },
84567
+ },
84568
+ ],
84569
+ });
84570
+ }
84571
+ else {
84572
+ throw Error(`Unsupported method '${method}' in UiApiActionHandler.buildBatchOperations`);
84573
+ }
84574
+ }
84575
+ return operations;
84576
+ }
81686
84577
  async draftActionToSideEffects(action) {
81687
84578
  const method = action.data.method;
81688
84579
  const apiName = action.metadata[LDS_ACTION_METADATA_API_NAME];
@@ -81794,10 +84685,35 @@
81794
84685
  getTypeCacheKeys$1u$1(cacheKeys, this.getLuvio(), record);
81795
84686
  return cacheKeys;
81796
84687
  }
81797
- synchronousIngest(response) {
84688
+ synchronousIngest(response, action) {
81798
84689
  const luvio = this.getLuvio();
84690
+ const injected = this.injectedFieldsByActionId.get(action.id);
84691
+ if (injected === undefined) {
84692
+ const key = keyBuilderFromType$g(luvio, response);
84693
+ luvio.storeIngest(key, ingest$1o$1, response);
84694
+ return;
84695
+ }
84696
+ // never replace what the server sent
84697
+ const fields = { ...response.fields };
84698
+ let injectedAny = false;
84699
+ keys$3(injected).forEach((fieldName) => {
84700
+ if (fields[fieldName] === undefined) {
84701
+ fields[fieldName] = injected[fieldName];
84702
+ injectedAny = true;
84703
+ }
84704
+ });
81799
84705
  const key = keyBuilderFromType$g(luvio, response);
81800
- luvio.storeIngest(key, ingest$1o$1, response);
84706
+ luvio.storeIngest(key, ingest$1o$1, { ...response, fields });
84707
+ if (injectedAny) {
84708
+ // after ingestRecord, which publishes the metadata with a fresh ttl
84709
+ luvio.publishStoreMetadata(key, {
84710
+ ttl: TTL$k,
84711
+ representationName: 'RecordRepresentation',
84712
+ namespace: 'UiApi',
84713
+ version: VERSION$1v$1,
84714
+ ingestionTimestamp: STALE_INGESTION_TIMESTAMP,
84715
+ });
84716
+ }
81801
84717
  }
81802
84718
  mergeRequestBody(targetBody, sourceBody) {
81803
84719
  // IMPORTANT: spread operator isn't deep clone so we have to individually
@@ -81867,6 +84783,10 @@
81867
84783
  await this.sideEffectStore.removeEffects(operations);
81868
84784
  return new Set(operations.map((o) => o.key));
81869
84785
  }
84786
+ // returns the side effects queued for the given action, oldest first
84787
+ getEffectsForAction(action) {
84788
+ return this.sideEffectStore.getEffectsByTag(action.id);
84789
+ }
81870
84790
  // reads a set of records out of the durable store, re-applies current side
81871
84791
  // effects and persists the changed record
81872
84792
  async reapplyRecordSideEffects(recordKeys, lifecycle) {
@@ -82165,6 +85085,12 @@
82165
85085
  const CONTENT_DOCUMENT_DRAFT_ID_KEY = 'CONTENT_DOCUMENT_DRAFT_ID';
82166
85086
  const CONTENT_VERSION_DRAFT_ID_KEY = 'CONTENT_VERSION_DRAFT_ID';
82167
85087
  const CONTENT_DOCUMENT_LINK_DRAFT_ID_KEY = 'CONTENT_DOCUMENT_LINK_DRAFT_ID';
85088
+ /**
85089
+ * Metadata key carrying the LDS binary store URI for the upload's local file.
85090
+ * Set in `buildPendingAction` so the Swift "Pending Images" UI can render
85091
+ * a thumbnail from the local bytes without a JSC round-trip.
85092
+ */
85093
+ const LDS_BINARY_HANDLE_KEY = 'LDS_BINARY_HANDLE';
82168
85094
  const RESPONSE_CONTENT_DOCUMENT_FIELDS = [
82169
85095
  'ContentSize',
82170
85096
  'CreatedDate',
@@ -82416,6 +85342,15 @@
82416
85342
  return Promise.reject(new DraftSynthesisError('Cannot generate local ContentDocumentLink synthetic id', 'CANNOT_GENERATE_ID'));
82417
85343
  });
82418
85344
  pendingAction.metadata[CONTENT_DOCUMENT_LINK_DRAFT_ID_KEY] = contentDocumentLinkId;
85345
+ // Stash the LDS binary store URI so the Swift "Pending Images" section
85346
+ // can render a thumbnail directly from the local file bytes.
85347
+ try {
85348
+ const fileRef = getFileReferenceFromResourceRequest(request);
85349
+ pendingAction.metadata[LDS_BINARY_HANDLE_KEY] = fileRef.handle;
85350
+ }
85351
+ catch {
85352
+ // No file data — leave metadata unset; UI falls back to placeholder.
85353
+ }
82419
85354
  const objectInfo = await this.objectInfoService.getObjectInfo(CONTENT_VERSION_API_NAME);
82420
85355
  if (objectInfo === undefined) {
82421
85356
  throw Error(`Could not generate draft. Object info is missing`);
@@ -83018,7 +85953,18 @@
83018
85953
  return ids.map((id) => recordMap.get(id) || null);
83019
85954
  }
83020
85955
  }
83021
- return new DataLoader(batchRecordQuery);
85956
+ const loader = new DataLoader(batchRecordQuery);
85957
+ const loads = new Map();
85958
+ return Object.assign(loader, {
85959
+ prefetch(id) {
85960
+ const existing = loads.get(id);
85961
+ if (existing)
85962
+ return existing;
85963
+ const load = loader.load(id).then((record) => ({ record }), (error) => ({ error }));
85964
+ loads.set(id, load);
85965
+ return load;
85966
+ },
85967
+ });
83022
85968
  }
83023
85969
 
83024
85970
  function createContext(store, objectInfos, eventEmitter, settings, snapshot, mappedCursors = new Map(), draftFunctions) {
@@ -83052,6 +85998,8 @@
83052
85998
  draftFunctions,
83053
85999
  mappedCursors,
83054
86000
  missingFieldsMap: new Map(),
86001
+ parentPrefetchEnabled: !parentRelationshipPrefetchKillSwitch.isOpen({ fallback: false }),
86002
+ parentResults: new Map(),
83055
86003
  };
83056
86004
  }
83057
86005
 
@@ -86199,6 +89147,207 @@
86199
89147
  return metadataMap;
86200
89148
  }
86201
89149
 
89150
+ function getDirectiveBooleanValue(argument, variables) {
89151
+ if (!argument)
89152
+ return undefined;
89153
+ if (argument.value.kind === Kind$2.BOOLEAN)
89154
+ return argument.value.value;
89155
+ if (argument.value.kind === Kind$2.VARIABLE) {
89156
+ const value = variables[argument.value.name.value];
89157
+ return typeof value === 'boolean' ? value : undefined;
89158
+ }
89159
+ return undefined;
89160
+ }
89161
+ function isSelectionIncluded(selection, variables) {
89162
+ for (const directive of selection.directives || []) {
89163
+ if (directive.name.value !== 'skip' && directive.name.value !== 'include')
89164
+ continue;
89165
+ const argument = (directive.arguments || []).find((argument) => argument.name.value === 'if');
89166
+ const value = getDirectiveBooleanValue(argument, variables);
89167
+ if (value === undefined)
89168
+ return false;
89169
+ if (directive.name.value === 'skip' && value === true)
89170
+ return false;
89171
+ if (directive.name.value === 'include' && value === false)
89172
+ return false;
89173
+ }
89174
+ return true;
89175
+ }
89176
+ function matchesTypeCondition(typeCondition, runtimeType, schema) {
89177
+ if (!typeCondition)
89178
+ return true;
89179
+ const conditionType = schema.getType(typeCondition.name.value);
89180
+ if (!conditionType || conditionType === runtimeType)
89181
+ return conditionType === runtimeType;
89182
+ const kind = conditionType.astNode?.kind;
89183
+ if (kind !== Kind$2.INTERFACE_TYPE_DEFINITION && kind !== Kind$2.UNION_TYPE_DEFINITION)
89184
+ return false;
89185
+ return schema.isSubType(conditionType, runtimeType);
89186
+ }
89187
+ function relationshipId(fieldName, record) {
89188
+ let id;
89189
+ if (fieldName === 'RecordType')
89190
+ id = record.recordTypeId;
89191
+ else if (fieldName.endsWith('__r')) {
89192
+ const relationshipField = record.fields[fieldName.replace('__r', '__c')];
89193
+ id = relationshipField && relationshipField.value;
89194
+ }
89195
+ else {
89196
+ const relationshipField = record.fields[fieldName + 'Id'];
89197
+ id = relationshipField && relationshipField.value;
89198
+ }
89199
+ return typeof id === 'string' && id ? id : null;
89200
+ }
89201
+ function getObjectFields(type) {
89202
+ return isObjectType(type) ? type.getFields() : {};
89203
+ }
89204
+ function getSelectedParentFields(selectionSet, runtimeType, info, visitedFragments) {
89205
+ if (!selectionSet)
89206
+ return [];
89207
+ const selectedParentFields = [];
89208
+ const variables = info.variableValues;
89209
+ for (const selection of selectionSet.selections) {
89210
+ if (!isSelectionIncluded(selection, variables))
89211
+ continue;
89212
+ if (selection.kind === Kind$2.FIELD) {
89213
+ const field = getObjectFields(runtimeType)[selection.name.value];
89214
+ const fieldType = field && getNamedType(field.type);
89215
+ const isParent = fieldType &&
89216
+ ((isObjectType(fieldType) &&
89217
+ fieldType.getInterfaces().some((iface) => iface.name === 'Record')) ||
89218
+ fieldType.name === 'Record');
89219
+ if (isParent &&
89220
+ selection.selectionSet &&
89221
+ !(isObjectType(fieldType) && fieldType.name.endsWith('Connection'))) {
89222
+ selectedParentFields.push({
89223
+ name: selection.name.value,
89224
+ selectionSet: selection.selectionSet,
89225
+ });
89226
+ }
89227
+ }
89228
+ else if (selection.kind === Kind$2.INLINE_FRAGMENT &&
89229
+ matchesTypeCondition(selection.typeCondition, runtimeType, info.schema)) {
89230
+ selectedParentFields.push(...getSelectedParentFields(selection.selectionSet, runtimeType, info, visitedFragments));
89231
+ }
89232
+ else if (selection.kind === Kind$2.FRAGMENT_SPREAD) {
89233
+ const fragment = info.fragments[selection.name.value];
89234
+ if (!fragment ||
89235
+ visitedFragments.has(fragment.name.value) ||
89236
+ !matchesTypeCondition(fragment.typeCondition, runtimeType, info.schema))
89237
+ continue;
89238
+ visitedFragments.add(fragment.name.value);
89239
+ selectedParentFields.push(...getSelectedParentFields(fragment.selectionSet, runtimeType, info, visitedFragments));
89240
+ }
89241
+ }
89242
+ return selectedParentFields;
89243
+ }
89244
+ function getActiveFieldSelectionSets(selectionSet, fieldName, runtimeType, info, visitedFragments) {
89245
+ if (!selectionSet)
89246
+ return [];
89247
+ const fieldSelectionSets = [];
89248
+ const variables = info.variableValues;
89249
+ for (const selection of selectionSet.selections) {
89250
+ if (!isSelectionIncluded(selection, variables))
89251
+ continue;
89252
+ if (selection.kind === Kind$2.FIELD &&
89253
+ selection.name.value === fieldName &&
89254
+ selection.selectionSet)
89255
+ fieldSelectionSets.push(selection.selectionSet);
89256
+ else if (selection.kind === Kind$2.INLINE_FRAGMENT &&
89257
+ matchesTypeCondition(selection.typeCondition, runtimeType, info.schema)) {
89258
+ fieldSelectionSets.push(...getActiveFieldSelectionSets(selection.selectionSet, fieldName, runtimeType, info, visitedFragments));
89259
+ }
89260
+ else if (selection.kind === Kind$2.FRAGMENT_SPREAD) {
89261
+ const fragment = info.fragments[selection.name.value];
89262
+ if (!fragment ||
89263
+ visitedFragments.has(fragment.name.value) ||
89264
+ !matchesTypeCondition(fragment.typeCondition, runtimeType, info.schema))
89265
+ continue;
89266
+ visitedFragments.add(fragment.name.value);
89267
+ fieldSelectionSets.push(...getActiveFieldSelectionSets(fragment.selectionSet, fieldName, runtimeType, info, visitedFragments));
89268
+ }
89269
+ }
89270
+ return fieldSelectionSets;
89271
+ }
89272
+ async function prefetchParentBatch(parents, state) {
89273
+ const { info, context, parentOutcomes, visitedSelections } = state;
89274
+ const nextParents = [];
89275
+ const parentLoads = [];
89276
+ for (const parentWork of parents) {
89277
+ let selectionsByType = visitedSelections.get(parentWork.record.recordRepresentation.id);
89278
+ if (!selectionsByType)
89279
+ visitedSelections.set(parentWork.record.recordRepresentation.id, (selectionsByType = new Map()));
89280
+ let visitedSelectionSets = selectionsByType.get(parentWork.runtimeType);
89281
+ if (!visitedSelectionSets)
89282
+ selectionsByType.set(parentWork.runtimeType, (visitedSelectionSets = new Set()));
89283
+ if (visitedSelectionSets.has(parentWork.selectionSet))
89284
+ continue;
89285
+ visitedSelectionSets.add(parentWork.selectionSet);
89286
+ for (const parentField of getSelectedParentFields(parentWork.selectionSet, parentWork.runtimeType, info, new Set())) {
89287
+ const parentId = relationshipId(parentField.name, parentWork.record.recordRepresentation);
89288
+ if (!parentId)
89289
+ continue;
89290
+ const knownOutcome = parentOutcomes.get(parentId) || context.parentResults.get(parentId);
89291
+ if (knownOutcome && 'error' in knownOutcome)
89292
+ continue;
89293
+ const parentLoad = context.Record.prefetch(parentId);
89294
+ parentLoads.push(parentLoad.then((outcome) => {
89295
+ parentOutcomes.set(parentId, outcome);
89296
+ if ('error' in outcome || outcome.record === null)
89297
+ return;
89298
+ const parentRecord = outcome.record;
89299
+ const declaredParentType = getNamedType(getObjectFields(parentWork.runtimeType)[parentField.name].type);
89300
+ const recordInterface = declaredParentType.name === 'Record' &&
89301
+ declaredParentType.astNode?.kind === Kind$2.INTERFACE_TYPE_DEFINITION
89302
+ ? declaredParentType
89303
+ : undefined;
89304
+ const resolveRecordType = recordInterface?.resolveType;
89305
+ const resolvedParentType = resolveRecordType
89306
+ ? resolveRecordType({
89307
+ recordRepresentation: parentRecord,
89308
+ ingestionTimestamp: parentWork.record.ingestionTimestamp,
89309
+ }, context, info)
89310
+ : declaredParentType;
89311
+ const parentRuntimeType = typeof resolvedParentType === 'string'
89312
+ ? info.schema.getType(resolvedParentType)
89313
+ : resolvedParentType;
89314
+ if (!isObjectType(parentRuntimeType))
89315
+ return;
89316
+ nextParents.push({
89317
+ record: {
89318
+ recordRepresentation: parentRecord,
89319
+ ingestionTimestamp: parentWork.record.ingestionTimestamp,
89320
+ },
89321
+ selectionSet: parentField.selectionSet,
89322
+ runtimeType: parentRuntimeType,
89323
+ });
89324
+ }));
89325
+ }
89326
+ }
89327
+ await Promise.all(parentLoads);
89328
+ if (nextParents.length > 0)
89329
+ await prefetchParentBatch(nextParents, state);
89330
+ }
89331
+ async function prefetchSelectedParents(records, info, context) {
89332
+ const parentOutcomes = new Map();
89333
+ const connectionType = getNamedType(info.returnType);
89334
+ const edgeType = getNamedType(getObjectFields(connectionType).edges?.type);
89335
+ const nodeType = getNamedType(getObjectFields(edgeType).node?.type);
89336
+ if (!isObjectType(connectionType) || !isObjectType(edgeType) || !isObjectType(nodeType)) {
89337
+ return parentOutcomes;
89338
+ }
89339
+ const edgeSelectionSets = info.fieldNodes.flatMap((node) => getActiveFieldSelectionSets(node.selectionSet, 'edges', connectionType, info, new Set()));
89340
+ const nodeSelectionSets = edgeSelectionSets.flatMap((selectionSet) => getActiveFieldSelectionSets(selectionSet, 'node', edgeType, info, new Set()));
89341
+ if (records.length > 0 && nodeSelectionSets.length > 0) {
89342
+ await prefetchParentBatch(records.flatMap((record) => nodeSelectionSets.map((selectionSet) => ({
89343
+ record,
89344
+ selectionSet,
89345
+ runtimeType: nodeType,
89346
+ }))), { info, context, parentOutcomes, visitedSelections: new Map() });
89347
+ }
89348
+ return parentOutcomes;
89349
+ }
89350
+
86202
89351
  /*
86203
89352
  resolves connections...
86204
89353
  */
@@ -86322,6 +89471,11 @@
86322
89471
  earlyEnd,
86323
89472
  };
86324
89473
  });
89474
+ if (context.parentPrefetchEnabled) {
89475
+ const results = await prefetchSelectedParents(records, info, context);
89476
+ for (const [id, outcome] of results)
89477
+ context.parentResults.set(id, outcome);
89478
+ }
86325
89479
  return {
86326
89480
  records,
86327
89481
  hasNextPage,
@@ -86594,7 +89748,8 @@
86594
89748
  .getInterfaces()
86595
89749
  .find((iface) => iface.name === 'Record')) ||
86596
89750
  (recordFieldType && recordFieldType.name === 'Record')) {
86597
- field.resolve = async function relationResolver(obj, _args, { Record, seenRecordIds }) {
89751
+ field.resolve = function relationResolver(obj, _args, context) {
89752
+ const { Record, seenRecordIds, parentPrefetchEnabled } = context;
86598
89753
  const fetchRecordOrNull = async (key) => {
86599
89754
  const recordRepresentation = await Record.load(key);
86600
89755
  return recordRepresentation !== null
@@ -86605,29 +89760,22 @@
86605
89760
  : null;
86606
89761
  };
86607
89762
  const { recordRepresentation: record, ingestionTimestamp } = obj;
86608
- let id = undefined;
86609
- if (field.name === 'RecordType') {
86610
- // RecordTypeId has special handling during ingest and is
86611
- // not in record.fields, so check for it at the UIAPI root property location
86612
- id = record.recordTypeId;
86613
- }
86614
- else if (field.name.endsWith('__r')) {
86615
- // Custom relationships end in `__r` and the corresponding ID field should be `__c`
86616
- let fieldName = field.name.replace('__r', '__c');
86617
- id = record.fields[fieldName] && record.fields[fieldName].value;
86618
- }
86619
- else {
86620
- // Standard relationships are just FieldNameId
86621
- let fieldName = field.name + 'Id';
86622
- id = record.fields[fieldName] && record.fields[fieldName].value;
86623
- }
86624
- if (!id || typeof id !== 'string') {
86625
- // possibly field injection did not inject the necessary Id field
86626
- // for the relationship, or we found a non-string value.
86627
- return null;
89763
+ const id = relationshipId(field.name, record);
89764
+ if (!id) {
89765
+ return parentPrefetchEnabled ? null : Promise.resolve(null);
86628
89766
  }
86629
89767
  seenRecordIds.add(id);
86630
- return fetchRecordOrNull(id);
89768
+ if (!parentPrefetchEnabled)
89769
+ return fetchRecordOrNull(id);
89770
+ const prefetched = context.parentResults.get(id);
89771
+ if (!prefetched)
89772
+ return fetchRecordOrNull(id);
89773
+ if ('error' in prefetched)
89774
+ return Promise.reject(prefetched.error);
89775
+ const recordRepresentation = prefetched.record;
89776
+ return recordRepresentation === null
89777
+ ? null
89778
+ : { recordRepresentation, ingestionTimestamp };
86631
89779
  };
86632
89780
  }
86633
89781
  else if (isObjectType(recordFieldType) &&
@@ -90759,6 +93907,12 @@
90759
93907
  case DraftQueueEventType.ActionUpdated:
90760
93908
  reportDraftActionEvent('updated', draftQueueEvent.draftCount);
90761
93909
  break;
93910
+ case DraftQueueEventType.BatchRecoveryFailed:
93911
+ {
93912
+ const recoveryEvent = draftQueueEvent;
93913
+ reportBatchRecoveryFailure(recoveryEvent.reason, recoveryEvent.draftCount);
93914
+ }
93915
+ break;
90762
93916
  }
90763
93917
  return Promise.resolve();
90764
93918
  });
@@ -90807,14 +93961,38 @@
90807
93961
 
90808
93962
  // so eslint doesn't complain about nimbus
90809
93963
  /* global __nimbus */
90810
- function buildLdsDraftQueue(durableStore) {
93964
+ /**
93965
+ * Builds the regular draft queue.
93966
+ *
93967
+ * One-arg call = legacy plain DurableDraftQueue (unchanged shipped behavior);
93968
+ * the 3-arg call builds a PerformanceDraftQueue (serial, concurrency=1, cross-queue
93969
+ * coordination + optional batching) over the shared store for the gate-ON path.
93970
+ */
93971
+ function buildLdsDraftQueue(durableStore, draftStore, options) {
90811
93972
  if (typeof __nimbus !== 'undefined' &&
90812
93973
  __nimbus.plugins !== undefined &&
90813
93974
  __nimbus.plugins.LdsDraftQueue !== undefined) {
90814
93975
  return new NimbusDraftQueue();
90815
93976
  }
90816
- const useSnapshot = draftQueueStoreSnapshotGate.isOpen({ fallback: true });
90817
- const draftQueue = new DurableDraftQueue(new DurableDraftStore(durableStore, draftQueueInstrumentation, useSnapshot), draftQueueInstrumentation);
93977
+ // Legacy gate-OFF path: no shared store / options → today's plain queue.
93978
+ if (draftStore === undefined && options === undefined) {
93979
+ const useSnapshot = draftQueueStoreSnapshotGate.isOpen({ fallback: true });
93980
+ const draftQueue = new DurableDraftQueue(new DurableDraftStore(durableStore, draftQueueInstrumentation, useSnapshot), draftQueueInstrumentation);
93981
+ return instrumentDraftQueue(draftQueue);
93982
+ }
93983
+ // Performance Upload path: serial queue participating in cross-queue coordination.
93984
+ const store = draftStore ?? new DurableDraftStore(durableStore);
93985
+ const draftQueue = new PerformanceDraftQueue(store, options);
93986
+ return instrumentDraftQueue(draftQueue);
93987
+ }
93988
+ /**
93989
+ * Builds the Performance Upload draft queue (ContentDocument/Version/Link
93990
+ * multipart uploads, concurrency > 1). Only constructed on the gate-ON path, in the
93991
+ * worker realm.
93992
+ */
93993
+ function buildLdsPerformanceDraftQueue(durableStore, draftStore, options) {
93994
+ const store = draftStore ?? new DurableDraftStore(durableStore);
93995
+ const draftQueue = new PerformanceDraftQueue(store, options);
90818
93996
  return instrumentDraftQueue(draftQueue);
90819
93997
  }
90820
93998
 
@@ -95740,7 +98918,10 @@
95740
98918
  if (isSubscribableResult(newResult)) {
95741
98919
  const value = newResult.isOk() ? ok$1(newResult.value.data) : err$1(newResult.error.failure);
95742
98920
  this.subscriptions.forEach((cb) => {
95743
- cb(value);
98921
+ try {
98922
+ cb(value);
98923
+ } catch {
98924
+ }
95744
98925
  });
95745
98926
  }
95746
98927
  return ok$1(void 0);
@@ -96682,7 +99863,10 @@
96682
99863
  if (isSubscribableResult(newResult)) {
96683
99864
  const value = newResult.isOk() ? ok$1(newResult.value.data) : err$1(newResult.error.failure);
96684
99865
  this.subscriptions.forEach((cb) => {
96685
- cb(value);
99866
+ try {
99867
+ cb(value);
99868
+ } catch {
99869
+ }
96686
99870
  });
96687
99871
  }
96688
99872
  return ok$1(void 0);
@@ -96704,6 +99888,79 @@
96704
99888
  }
96705
99889
  };
96706
99890
  }
99891
+ function fetchFromNetwork(getRequest, hooks, contextSeed) {
99892
+ try {
99893
+ const {
99894
+ services,
99895
+ params: [input, init],
99896
+ operationType,
99897
+ requestOptions
99898
+ } = getRequest();
99899
+ const initWithOptions = applyOperationRequestOptions$1(init, operationType, requestOptions);
99900
+ const seed = operationType === void 0 ? contextSeed : { operationType, ...contextSeed };
99901
+ const initWithSeed = seed === void 0 ? initWithOptions : { ...initWithOptions, __contextSeed: seed };
99902
+ const fetchCall = initWithSeed === void 0 ? services.fetch(input) : services.fetch(input, initWithSeed);
99903
+ return convertFetchResponseToData(fetchCall, hooks);
99904
+ } catch (reason) {
99905
+ return resolvedPromiseLike$2(err$1(toError(reason)));
99906
+ }
99907
+ }
99908
+ function convertFetchResponseToData(response, hooks) {
99909
+ return response.then(
99910
+ (response2) => {
99911
+ if (response2.ok) {
99912
+ let resultPromise;
99913
+ if (hooks.isSemanticNullResponse(response2)) {
99914
+ resultPromise = Promise.resolve(ok$1(null));
99915
+ } else if (hooks.isProtocolNoBodyStatus(response2.status) && !hooks.isSemanticNullResponse(response2)) {
99916
+ resultPromise = Promise.resolve(
99917
+ err$1(
99918
+ toError(
99919
+ `Unexpected ${response2.status} response: no-content status was not declared in the API specification. Declare this response in your OAS without a content property.`
99920
+ )
99921
+ )
99922
+ );
99923
+ } else {
99924
+ resultPromise = response2.json().then(
99925
+ (json) => ok$1(json),
99926
+ (reason) => err$1(toError(reason))
99927
+ );
99928
+ }
99929
+ return resultPromise.finally(() => {
99930
+ try {
99931
+ hooks.afterRequestHooks({ statusCode: response2.status });
99932
+ } catch {
99933
+ }
99934
+ });
99935
+ } else {
99936
+ return hooks.coerceError(response2).then((coercedError) => {
99937
+ return err$1(coercedError);
99938
+ }).finally(() => {
99939
+ try {
99940
+ hooks.afterRequestHooks({ statusCode: response2.status });
99941
+ } catch {
99942
+ }
99943
+ });
99944
+ }
99945
+ },
99946
+ (reason) => err$1(toError(reason))
99947
+ );
99948
+ }
99949
+ function completeRefresh(result, getSubscriptions, options = {}) {
99950
+ const { previousResult } = options;
99951
+ if (!options.suppressEqualSuccesses || result.isErr() || !previousResult || previousResult.isErr() || !deepEquals$1(previousResult.value, result.value)) {
99952
+ const subscriptions = getSubscriptions();
99953
+ const callbacks = options.skipRemovedSubscriptions ? [...subscriptions] : subscriptions;
99954
+ callbacks.forEach((callback) => {
99955
+ if (options.skipRemovedSubscriptions && !getSubscriptions().includes(callback)) return;
99956
+ try {
99957
+ callback(result);
99958
+ } catch {
99959
+ }
99960
+ });
99961
+ }
99962
+ return options.reportFailure && result.isErr() ? result : ok$1(void 0);
99963
+ }
96707
99964
  function isAbortableCommand(command) {
96708
99965
  return !!command && typeof command === "object" && "isAbortableCommand" in command && command.isAbortableCommand === true;
96709
99966
  }
@@ -96732,18 +99989,18 @@
96732
99989
  }
96733
99990
  if (prop === "fetchParams") {
96734
99991
  const originalFetchParams = Reflect.get(target, prop, receiver);
96735
- const isInternal = Reflect.get(target, "isInternalExecution", receiver) === true;
99992
+ const suppressAbortSignal = Reflect.get(target, "isInternalExecution", receiver) === true;
96736
99993
  if (typeof originalFetchParams === "function") {
96737
99994
  return function(...args) {
96738
99995
  const originalReturnValue = originalFetchParams.apply(this, args);
96739
- if (!isInternal) {
99996
+ if (!suppressAbortSignal) {
96740
99997
  const [url, init = {}] = originalReturnValue;
96741
99998
  return [url, { signal, ...init }];
96742
99999
  }
96743
100000
  return originalReturnValue;
96744
100001
  };
96745
100002
  } else {
96746
- if (!isInternal && originalFetchParams && Array.isArray(originalFetchParams)) {
100003
+ if (!suppressAbortSignal && originalFetchParams && Array.isArray(originalFetchParams)) {
96747
100004
  const [url, init = {}] = originalFetchParams;
96748
100005
  return [url, { signal, ...init }];
96749
100006
  }
@@ -96770,38 +100027,35 @@
96770
100027
  this.services = services;
96771
100028
  this.additionalNullResponses = [];
96772
100029
  }
96773
- /**
96774
- * The command's operation type. Generated command subclasses override this
96775
- * getter with their concrete operation (see the generator's
96776
- * `generateOperationType`); the base returns `undefined` for commands that
96777
- * don't declare one (e.g. hand-written commands). Transport-layer
96778
- * interceptors use it to tell a read (`query`) apart from a write — see
96779
- * `fetch`, which folds it into the context seed and derives
96780
- * `onestore.retrySafe` from it.
96781
- */
96782
100030
  get operationType() {
96783
100031
  return void 0;
96784
100032
  }
96785
- /** Declared `onestore` options (`handleServerError`, `compression`); generated overrides (`generateRequestOptionsGetter`). */
96786
100033
  get requestOptions() {
96787
100034
  return void 0;
96788
100035
  }
96789
100036
  fetch(contextSeed) {
96790
- try {
96791
- const [input, init] = this.fetchParams;
96792
- const operationType = this.operationType;
96793
- const initWithOptions = applyOperationRequestOptions$1(
96794
- init,
96795
- operationType,
96796
- this.requestOptions
96797
- );
96798
- const seed = operationType === void 0 ? contextSeed : { operationType, ...contextSeed };
96799
- const initWithSeed = seed === void 0 ? initWithOptions : { ...initWithOptions, __contextSeed: seed };
96800
- const fetchCall = initWithSeed === void 0 ? this.services.fetch(input) : this.services.fetch(input, initWithSeed);
96801
- return this.convertFetchResponseToData(fetchCall);
96802
- } catch (reason) {
96803
- return resolvedPromiseLike$2(err$1(toError(reason)));
96804
- }
100037
+ return fetchFromNetwork(
100038
+ () => ({
100039
+ services: this.services,
100040
+ params: this.fetchParams,
100041
+ operationType: this.operationType,
100042
+ requestOptions: this.requestOptions
100043
+ }),
100044
+ {
100045
+ isSemanticNullResponse: (response) => this.isSemanticNullResponse(response),
100046
+ isProtocolNoBodyStatus: (status) => this.isProtocolNoBodyStatus(status),
100047
+ coerceError: (response) => this.coerceError(response),
100048
+ afterRequestHooks: (options) => this.afterRequestHooks(options)
100049
+ },
100050
+ contextSeed
100051
+ );
100052
+ }
100053
+ refresh() {
100054
+ return this.execute().then((newResult) => {
100055
+ if (!isSubscribableResult(newResult)) return ok$1(void 0);
100056
+ const result = newResult.isOk() ? ok$1(newResult.value.data) : err$1(newResult.error.failure);
100057
+ return completeRefresh(result, () => this.subscriptions);
100058
+ });
96805
100059
  }
96806
100060
  isSemanticNullResponse(response) {
96807
100061
  return this.additionalNullResponses.includes(response.status);
@@ -96809,53 +100063,9 @@
96809
100063
  isProtocolNoBodyStatus(status) {
96810
100064
  return status === 204 || status === 205;
96811
100065
  }
96812
- isUndeclaredNoBodyResponse(response) {
96813
- return this.isProtocolNoBodyStatus(response.status) && !this.isSemanticNullResponse(response);
96814
- }
96815
100066
  async coerceError(errorResponse) {
96816
100067
  return toError(errorResponse.statusText);
96817
100068
  }
96818
- convertFetchResponseToData(response) {
96819
- return response.then(
96820
- (response2) => {
96821
- if (response2.ok) {
96822
- let resultPromise;
96823
- if (this.isSemanticNullResponse(response2)) {
96824
- resultPromise = Promise.resolve(ok$1(null));
96825
- } else if (this.isUndeclaredNoBodyResponse(response2)) {
96826
- resultPromise = Promise.resolve(
96827
- err$1(
96828
- toError(
96829
- `Unexpected ${response2.status} response: no-content status was not declared in the API specification. Declare this response in your OAS without a content property.`
96830
- )
96831
- )
96832
- );
96833
- } else {
96834
- resultPromise = response2.json().then(
96835
- (json) => ok$1(json),
96836
- (reason) => err$1(toError(reason))
96837
- );
96838
- }
96839
- return resultPromise.finally(() => {
96840
- try {
96841
- this.afterRequestHooks({ statusCode: response2.status });
96842
- } catch {
96843
- }
96844
- });
96845
- } else {
96846
- return this.coerceError(response2).then((coercedError) => {
96847
- return err$1(coercedError);
96848
- }).finally(() => {
96849
- try {
96850
- this.afterRequestHooks({ statusCode: response2.status });
96851
- } catch {
96852
- }
96853
- });
96854
- }
96855
- },
96856
- (reason) => err$1(toError(reason))
96857
- );
96858
- }
96859
100069
  };
96860
100070
  _FetchNetworkCommand.availableDecorators = {
96861
100071
  abortable: createAbortableDecorator
@@ -97919,7 +101129,7 @@
97919
101129
  },
97920
101130
  };
97921
101131
  }
97922
- // version: 1.466.0-b7b08a8e3c
101132
+ // version: 1.468.0-9ef0fbdaee
97923
101133
 
97924
101134
  /**
97925
101135
  * Copyright (c) 2022, Salesforce, Inc.,
@@ -97945,7 +101155,7 @@
97945
101155
  },
97946
101156
  };
97947
101157
  }
97948
- // version: 1.466.0-b7b08a8e3c
101158
+ // version: 1.468.0-9ef0fbdaee
97949
101159
 
97950
101160
  function findExecutableOperation$1(input) {
97951
101161
  const operations = input.query.definitions.filter(
@@ -98808,6 +102018,53 @@
98808
102018
  }
98809
102019
  };
98810
102020
  }
102021
+ function assertSubscribable(result, report) {
102022
+ if (!isSubscribableResult(result)) {
102023
+ report("Non-subscribable result encountered - please use correct operation type");
102024
+ throw new Error("Internal error in Lightning Data Service adapter occurred");
102025
+ }
102026
+ }
102027
+ function toQueryUpdate(result) {
102028
+ return result.isOk() ? { data: result.value, error: void 0 } : { data: void 0, error: unwrapUserlandError(result.error) };
102029
+ }
102030
+ class SubscribableImperativeBindingsService {
102031
+ bind(getCommand, exposeRefresh = false) {
102032
+ return buildBaseImperativeInvoker(
102033
+ getCommand,
102034
+ (result) => this.transformResult(result, exposeRefresh)
102035
+ );
102036
+ }
102037
+ transformResult(result, exposeRefresh = false) {
102038
+ assertSubscribable(result, (message) => console.error(message));
102039
+ if (result.isErr()) throwUnwrappedUserlandError(result.error.failure);
102040
+ deepFreeze(result.value.data);
102041
+ const api = {
102042
+ data: result.value.data,
102043
+ subscribe: (callback) => result.value.subscribe((update) => {
102044
+ const { data, error } = toQueryUpdate(update);
102045
+ return callback({ data, error });
102046
+ })
102047
+ };
102048
+ if (exposeRefresh) {
102049
+ return {
102050
+ ...api,
102051
+ refresh: () => result.value.refresh().then((refreshed) => {
102052
+ if (refreshed.isOk()) return void 0;
102053
+ throw refreshed.error;
102054
+ })
102055
+ };
102056
+ }
102057
+ return api;
102058
+ }
102059
+ }
102060
+ function buildServiceDescriptor$7() {
102061
+ return {
102062
+ type: "subscribableImperativeBindings",
102063
+ version: "1.0",
102064
+ service: new SubscribableImperativeBindingsService()
102065
+ };
102066
+ }
102067
+
98811
102068
  const supportedCachePolicyTypes = ["no-cache", "only-if-cached"];
98812
102069
  function requestContextIsSupportedCachePolicy(requestContext) {
98813
102070
  return typeof requestContext === "object" && requestContext !== null && "cachePolicy" in requestContext && typeof requestContext.cachePolicy === "object" && requestContext.cachePolicy !== null && "type" in requestContext.cachePolicy && typeof requestContext.cachePolicy.type === "string" && supportedCachePolicyTypes.includes(
@@ -98860,7 +102117,7 @@
98860
102117
  });
98861
102118
  }
98862
102119
  }
98863
- function buildServiceDescriptor$6() {
102120
+ function buildServiceDescriptor$5() {
98864
102121
  return {
98865
102122
  type: "defaultImperativeBindings",
98866
102123
  version: "1.0",
@@ -98880,70 +102137,13 @@
98880
102137
  });
98881
102138
  }
98882
102139
  }
98883
- function buildServiceDescriptor$5() {
102140
+ function buildServiceDescriptor$4() {
98884
102141
  return {
98885
102142
  type: "queryImperativeBindings",
98886
102143
  version: "1.0",
98887
102144
  service: new QueryImperativeBindingsService()
98888
102145
  };
98889
102146
  }
98890
- class SubscribableImperativeBindingsService {
98891
- bind(getCommand, exposeRefresh = false) {
98892
- return buildBaseImperativeInvoker(
98893
- getCommand,
98894
- (result) => this.transformResult(result, exposeRefresh)
98895
- );
98896
- }
98897
- transformResult(result, exposeRefresh = false) {
98898
- if (!isSubscribableResult(result)) {
98899
- console.error(
98900
- "Non-subscribable result encountered - please use correct operation type"
98901
- );
98902
- throw new Error("Internal error in Lightning Data Service adapter occurred");
98903
- }
98904
- if (result.isOk()) {
98905
- deepFreeze(result.value.data);
98906
- const api = {
98907
- data: result.value.data,
98908
- subscribe: (cb) => {
98909
- return result.value.subscribe((result2) => {
98910
- if (result2.isErr()) {
98911
- return cb({
98912
- data: void 0,
98913
- error: unwrapUserlandError(result2.error)
98914
- });
98915
- }
98916
- return cb({ data: result2.value, error: void 0 });
98917
- });
98918
- }
98919
- };
98920
- if (exposeRefresh) {
98921
- return {
98922
- ...api,
98923
- refresh: () => {
98924
- return result.value.refresh().then((res) => {
98925
- if (res.isOk()) {
98926
- return void 0;
98927
- }
98928
- throw res.error;
98929
- });
98930
- }
98931
- };
98932
- } else {
98933
- return api;
98934
- }
98935
- } else {
98936
- throwUnwrappedUserlandError(result.error.failure);
98937
- }
98938
- }
98939
- }
98940
- function buildServiceDescriptor$4() {
98941
- return {
98942
- type: "subscribableImperativeBindings",
98943
- version: "1.0",
98944
- service: new SubscribableImperativeBindingsService()
98945
- };
98946
- }
98947
102147
  class LegacyImperativeBindingsService {
98948
102148
  bind(getCommand) {
98949
102149
  const invoke = async (config, requestContext, callback) => {
@@ -99245,7 +102445,7 @@
99245
102445
  };
99246
102446
  }
99247
102447
  }
99248
- function buildServiceDescriptor$7() {
102448
+ function buildServiceDescriptor$6() {
99249
102449
  return {
99250
102450
  type: "graphQLMutationBindings",
99251
102451
  version: "1.0",
@@ -100393,13 +103593,13 @@
100393
103593
  featureFlagsServiceDescriptor,
100394
103594
  buildServiceDescriptor$b(luvio),
100395
103595
  luvioUiapiRecordsServiceDescriptor,
100396
- buildServiceDescriptor$6(),
100397
103596
  buildServiceDescriptor$5(),
100398
103597
  buildServiceDescriptor$4(),
103598
+ buildServiceDescriptor$7(),
100399
103599
  buildServiceDescriptor$3(),
100400
103600
  buildServiceDescriptor$2$1(),
100401
103601
  buildServiceDescriptor$1$2(),
100402
- buildServiceDescriptor$7(),
103602
+ buildServiceDescriptor$6(),
100403
103603
  buildServiceDescriptor$1$1(),
100404
103604
  buildServiceDescriptor$2(),
100405
103605
  // TODO [W-18753648]: See note above.
@@ -100455,7 +103655,13 @@
100455
103655
  // so eslint doesn't complain about nimbus
100456
103656
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
100457
103657
  /* global __nimbus */
103658
+ const DRAFT_QUEUE_LANE = {
103659
+ serial: 'serial',
103660
+ concurrentBinary: 'concurrentBinary',
103661
+ };
100458
103662
  let lazyDraftQueue;
103663
+ let lazyBinaryDraftQueue;
103664
+ let lazyRoutingDraftQueue;
100459
103665
  let lazyDraftManager;
100460
103666
  let lazyLuvio;
100461
103667
  let lazyInternalLuvio;
@@ -100544,8 +103750,44 @@
100544
103750
  return false;
100545
103751
  },
100546
103752
  });
100547
- // draft queue
100548
- lazyDraftQueue = buildLdsDraftQueue(lazyDurableStore);
103753
+ // Concurrent binary draft queue configuration is supplied by the native
103754
+ // host on globalThis.LDS, injected before the lds bundle loads so the
103755
+ // runtime sees the Performance Upload Queue levers at startup.
103756
+ const concurrentBinaryQueueConfig = (typeof globalThis !== 'undefined' &&
103757
+ globalThis.LDS) ||
103758
+ {};
103759
+ const useConcurrentBinaryQueue = concurrentBinaryQueueConfig.enableConcurrentBinaryQueue === true;
103760
+ const useQueueBatching = concurrentBinaryQueueConfig.enableDraftBatching === true;
103761
+ const usePerformanceDraftQueue = useConcurrentBinaryQueue || useQueueBatching;
103762
+ if (usePerformanceDraftQueue) {
103763
+ const sharedDraftStore = new PerformanceDraftStore(lazyDurableStore);
103764
+ logInfo(`Serial draft queue created with batching=${useQueueBatching}, strictOrdering=true`);
103765
+ lazyDraftQueue = buildLdsDraftQueue(lazyDurableStore, sharedDraftStore, {
103766
+ // No peer queues when there's no binary lane (batching-only).
103767
+ getPeerQueues: () => lazyBinaryDraftQueue !== undefined ? [lazyBinaryDraftQueue] : [],
103768
+ concurrency: 1,
103769
+ strictOrdering: true,
103770
+ queueBatching: useQueueBatching,
103771
+ });
103772
+ // The binary lane lives only in the worker realm. In the WebView realm the serial
103773
+ // queue is a Nimbus proxy to the worker's routing façade, which already routes
103774
+ // binary uploads to the worker's binary lane; a local binary queue there would
103775
+ // take uploads the worker never sees. Only worker-realm queues expose
103776
+ // isHandlerRegistered.
103777
+ if (useConcurrentBinaryQueue &&
103778
+ typeof lazyDraftQueue.isHandlerRegistered ===
103779
+ 'function') {
103780
+ lazyBinaryDraftQueue = buildLdsPerformanceDraftQueue(lazyDurableStore, sharedDraftStore, {
103781
+ getPeerQueues: () => [lazyDraftQueue],
103782
+ concurrency: 4,
103783
+ strictOrdering: false,
103784
+ });
103785
+ logInfo('Concurrent draft queue created with concurrency=4, strictOrdering=false');
103786
+ }
103787
+ }
103788
+ else {
103789
+ lazyDraftQueue = buildLdsDraftQueue(lazyDurableStore);
103790
+ }
100549
103791
  lazySideEffectStore = new SideEffectStore(lazyDurableStore);
100550
103792
  lazySideEffectService = new SideEffectService(lazyDurableRecordStore, lazyObjectInfoService, userId, formatDisplayValue);
100551
103793
  const draftService = new UiApiDraftRecordService(() => lazyLuvio, lazyDurableStore, lazyObjectInfoService, newRecordId, lazySideEffectStore, lazyDurableRecordStore);
@@ -100553,13 +103795,40 @@
100553
103795
  uiApiRecordHandler.setSideEffectHooks(createSfsSideEffectHooks(lazyDurableRecordStore));
100554
103796
  const quickActionHandler = new QuickActionExecutionRepresentationHandler(() => lazyLuvio, draftService, lazyDraftQueue, lazyNetworkAdapter, isGenerated, lazySideEffectService, lazyObjectInfoService, getRecord);
100555
103797
  const updateRecordQuickActionHandler = new UpdateRecordQuickActionExecutionRepresentationHandler(() => lazyLuvio, draftService, lazyDraftQueue, lazyNetworkAdapter, isGenerated, lazySideEffectService);
100556
- const contentDocumentCompositeActionHandler = new ContentDocumentCompositeRepresentationActionHandler(() => lazyLuvio, userId, draftService, lazyObjectInfoService, lazyDraftQueue, lazyNetworkAdapter, isGenerated, NimbusBinaryStore, lazySideEffectService);
103798
+ // Route the CD composite to the concurrent binary queue when gate-ON so
103799
+ // multipart uploads run in parallel and don't block other DML.
103800
+ const contentDocumentTargetQueue = lazyBinaryDraftQueue ?? lazyDraftQueue;
103801
+ logInfo(`ContentDocumentVersion handler routed to ${lazyBinaryDraftQueue !== undefined ? 'concurrent draft queue' : 'serial draft queue'}`);
103802
+ const contentDocumentCompositeActionHandler = new ContentDocumentCompositeRepresentationActionHandler(() => lazyLuvio, userId, draftService, lazyObjectInfoService, contentDocumentTargetQueue, lazyNetworkAdapter, isGenerated, NimbusBinaryStore, lazySideEffectService);
100557
103803
  lazyDraftQueue.addHandler(uiApiRecordHandler);
100558
103804
  lazyDraftQueue.addHandler(quickActionHandler);
100559
103805
  lazyDraftQueue.addHandler(updateRecordQuickActionHandler);
100560
- lazyDraftQueue.addHandler(contentDocumentCompositeActionHandler);
100561
- // draft manager
100562
- lazyDraftManager = new DraftManager(lazyDraftQueue);
103806
+ contentDocumentTargetQueue.addHandler(contentDocumentCompositeActionHandler);
103807
+ // Build the routing façade and manager only when the binary lane exists: flag on and
103808
+ // in the worker realm, over concrete, handler-owning queues (see where it is built).
103809
+ // Feature-detecting isHandlerRegistered rather than sniffing the realm via `window` tests
103810
+ // the exact invariant the queue casts below rely on, and stays correct in non-browser
103811
+ // (e.g. jest) realms where `window` is an unreliable realm signal.
103812
+ const shouldBuildRoutingQueue = lazyBinaryDraftQueue !== undefined;
103813
+ if (shouldBuildRoutingQueue) {
103814
+ // Serial is the primary/fallback lane, so the bridged `draftQueue` routes enqueue
103815
+ // by handler ownership in the worker. Lane labels are stamped onto each action
103816
+ // by getQueueActions so the WebView can display the two queues separately.
103817
+ lazyRoutingDraftQueue = new RoutingDraftQueue({
103818
+ queue: lazyDraftQueue,
103819
+ lane: DRAFT_QUEUE_LANE.serial,
103820
+ }, [
103821
+ {
103822
+ queue: lazyBinaryDraftQueue,
103823
+ lane: DRAFT_QUEUE_LANE.concurrentBinary,
103824
+ },
103825
+ ]);
103826
+ }
103827
+ // The WebView realm's (unused) manager falls back to the base DraftManager: native only
103828
+ // drives the worker-realm manager, and RoutingDraftManager needs the concrete queues.
103829
+ lazyDraftManager = shouldBuildRoutingQueue
103830
+ ? new RoutingDraftManager(lazyDraftQueue, lazyBinaryDraftQueue, DRAFT_QUEUE_LANE)
103831
+ : new DraftManager(lazyDraftQueue);
100563
103832
  const objectInfoCachingEnvironment = enableObjectInfoCaching(durableEnv, lazyObjectInfoService.ensureObjectInfoCached);
100564
103833
  let draftEnv = makeEnvironmentUiApiRecordDraftAware(lazyLuvio, {
100565
103834
  store,
@@ -100634,7 +103903,7 @@
100634
103903
  internalLuvio: lazyInternalLuvio,
100635
103904
  environment: lazyEnvironment,
100636
103905
  draftManager: lazyDraftManager,
100637
- draftQueue: lazyDraftQueue,
103906
+ draftQueue: lazyRoutingDraftQueue ?? lazyDraftQueue,
100638
103907
  createPrimingSession: (config) => {
100639
103908
  return primingSessionFactory({
100640
103909
  store: lazyDurableStore,
@@ -100660,7 +103929,7 @@
100660
103929
  id: '@salesforce/lds-network-adapter',
100661
103930
  instrument: instrument$2,
100662
103931
  });
100663
- // version: 1.466.0-b7b08a8e3c
103932
+ // version: 1.468.0-9ef0fbdaee
100664
103933
 
100665
103934
  const { create: create$2, keys: keys$2 } = Object;
100666
103935
  const { stringify, parse } = JSON;
@@ -108210,7 +111479,7 @@
108210
111479
  cb(graphql_v1_import, graphql_imperative$1, graphql_imperative_legacy_v1_import, graphql_state_manager);
108211
111480
  }
108212
111481
  }
108213
- // version: 1.466.0-ba624febc8
111482
+ // version: 1.468.0-c060a9b9c6
108214
111483
 
108215
111484
  function createFragmentMap(documentNode) {
108216
111485
  const fragments = {};
@@ -137439,7 +140708,7 @@
137439
140708
  configuration: { ...configurationForGraphQLAdapters$1 },
137440
140709
  instrument: instrument$1,
137441
140710
  });
137442
- // version: 1.466.0-ba624febc8
140711
+ // version: 1.468.0-c060a9b9c6
137443
140712
 
137444
140713
  // On core the unstable adapters are re-exported with different names,
137445
140714
  // we want to match them here.
@@ -137591,7 +140860,7 @@
137591
140860
  unstable_graphQL_imperative = createImperativeAdapter(luvio, createInstrumentedAdapter(ldsAdapter, adapterMetadata), adapterMetadata);
137592
140861
  graphQLImperative = ldsAdapter;
137593
140862
  });
137594
- // version: 1.466.0-ba624febc8
140863
+ // version: 1.468.0-c060a9b9c6
137595
140864
 
137596
140865
  var gqlApi = /*#__PURE__*/Object.freeze({
137597
140866
  __proto__: null,
@@ -138443,7 +141712,7 @@
138443
141712
  function register(r) {
138444
141713
  callbacks$1.forEach((callback) => callback(r));
138445
141714
  }
138446
- // version: 1.466.0-b7b08a8e3c
141715
+ // version: 1.468.0-9ef0fbdaee
138447
141716
 
138448
141717
  /**
138449
141718
  * Copyright (c) 2022, Salesforce, Inc.,
@@ -139754,4 +143023,4 @@
139754
143023
  exports.subscribeToAdapter = subscribeToAdapter;
139755
143024
 
139756
143025
  }));
139757
- // version: 1.466.0-b7b08a8e3c
143026
+ // version: 1.468.0-9ef0fbdaee