@keetanetwork/anchor 0.0.107 → 0.0.109

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.
@@ -2,7 +2,7 @@ import { __addDisposableResource, __disposeResources } from "tslib";
2
2
  import { assertNever } from '../utils/never.js';
3
3
  import { asleep } from '../utils/asleep.js';
4
4
  import { Errors } from './common.js';
5
- import { MethodLogger, ManageStatusUpdates, ConvertStringToRequestID } from './internal.js';
5
+ import { CompareQueueEntryOrder, MethodLogger, ManageStatusUpdates, ConvertStringToRequestID } from './internal.js';
6
6
  import { AsyncDisposableStack } from '../utils/defer.js';
7
7
  const keetaAnchorPipeableQueueStatuses = ['completed', 'failed_permanently'];
8
8
  /**
@@ -154,6 +154,12 @@ export class KeetaAnchorQueueStorageDriverMemory {
154
154
  return (queueDuplicate);
155
155
  }
156
156
  })();
157
+ /*
158
+ * Oldest updated first, as the storage driver contract requires;
159
+ * the sort is stable, so ties keep their insertion order. Both
160
+ * branches above return a copy, so sorting in place is safe.
161
+ */
162
+ allEntriesInStatus.sort(CompareQueueEntryOrder);
157
163
  let retval = allEntriesInStatus;
158
164
  if (filter?.limit !== undefined) {
159
165
  retval = allEntriesInStatus.slice(0, filter.limit);
@@ -322,6 +328,13 @@ export class KeetaAnchorQueueRunner {
322
328
  * prepared to handle that situation as well.
323
329
  */
324
330
  processTimeout = 300_000; /* 5 minutes */
331
+ /**
332
+ * The number of completed entries fetched per maintenance pass
333
+ * when moving entries to the next stage. A full page means more
334
+ * entries may be waiting behind it, so unmoved entries are sent
335
+ * to the back of the line.
336
+ */
337
+ pipeMoveFetchLimit = 100;
325
338
  /**
326
339
  * When piping a batch of jobs to another runner, this is the number
327
340
  * of jobs to include in each batch (max).
@@ -511,7 +524,8 @@ export class KeetaAnchorQueueRunner {
511
524
  oldStatus: '@internal',
512
525
  by: this.workerID
513
526
  });
514
- }
527
+ },
528
+ pipeMoveFetchLimit: this.pipeMoveFetchLimit
515
529
  });
516
530
  }
517
531
  decodeEntry(entry) {
@@ -694,6 +708,7 @@ export class KeetaAnchorQueueRunner {
694
708
  }
695
709
  const processJobOk = Symbol('processJobOk');
696
710
  const processJobTimeout = Symbol('processJobTimeout');
711
+ const processJobContended = Symbol('processJobContended');
697
712
  const processJob = async (index, entry, startingStatus, processor) => {
698
713
  if (timeout !== undefined) {
699
714
  const elapsed = Date.now() - startTime;
@@ -753,7 +768,7 @@ export class KeetaAnchorQueueRunner {
753
768
  catch (error) {
754
769
  if (Errors.IncorrectStateAssertedError.isInstance(error)) {
755
770
  logger?.debug(`Skipping request with id ${String(entry.id)} because it is no longer in the expected state "${startingStatus}"`, error);
756
- return (processJobOk);
771
+ return (processJobContended);
757
772
  }
758
773
  logger?.error(`Failed to process request with id ${String(entry.id)}, setting state to "${setEntryStatus.status}":`, error);
759
774
  setEntryStatus.status = 'failed_temporarily';
@@ -772,20 +787,44 @@ export class KeetaAnchorQueueRunner {
772
787
  await this.queue.setStatus(entry.id, setEntryStatus.status, { oldStatus: 'processing', by: by, output: this.encodeResponse(setEntryStatus.output), error: setEntryStatus.error });
773
788
  return (processJobOk);
774
789
  };
790
+ /**
791
+ * Process up to `batchSize` entries in the given status.
792
+ *
793
+ * Returns 'empty' when no entries are left in that status,
794
+ * 'timeout' when the run timeout was reached, and 'more' when
795
+ * the batch is used up and entries may remain.
796
+ */
797
+ const processStatus = async (status, processor) => {
798
+ /*
799
+ * Losing an entry to another worker does not use up a
800
+ * batch slot, but the retries are bounded so a run always
801
+ * ends
802
+ */
803
+ let contended = 0;
804
+ let processed = 0;
805
+ while (processed < batchSize) {
806
+ const entry = await this.nextEntryToProcess(status, processed + contended);
807
+ if (entry === undefined) {
808
+ return ('empty');
809
+ }
810
+ const result = await processJob(processed, entry, status, processor);
811
+ if (result === processJobTimeout) {
812
+ return ('timeout');
813
+ }
814
+ if (result === processJobContended && contended < batchSize) {
815
+ contended++;
816
+ continue;
817
+ }
818
+ processed++;
819
+ }
820
+ return ('more');
821
+ };
775
822
  /*
776
823
  * Process pending jobs first
777
824
  */
778
- for (let index = 0; index < batchSize; index++) {
779
- const entries = await this.queue.query({ status: 'pending', limit: 1 });
780
- const entry = entries[0];
781
- if (entry === undefined) {
782
- retval = false;
783
- break;
784
- }
785
- const result = await processJob(index, entry, 'pending', this.processor.bind(this));
786
- if (result === processJobTimeout) {
787
- break;
788
- }
825
+ const pendingResult = await processStatus('pending', this.processor.bind(this));
826
+ if (pendingResult === 'empty') {
827
+ retval = false;
789
828
  }
790
829
  /*
791
830
  * Next process any pipes to other runners
@@ -821,24 +860,12 @@ export class KeetaAnchorQueueRunner {
821
860
  status: 'stuck',
822
861
  processor: this.processorStuck?.bind(this)
823
862
  }];
824
- let timeoutReached = false;
825
863
  for (const condition of conditions) {
826
864
  if (condition.processor === undefined) {
827
865
  continue;
828
866
  }
829
- for (let index = 0; index < batchSize; index++) {
830
- const entries = await this.queue.query({ status: condition.status, limit: 1 });
831
- const entry = entries[0];
832
- if (entry === undefined) {
833
- break;
834
- }
835
- const result = await processJob(index, entry, condition.status, condition.processor);
836
- if (result === processJobTimeout) {
837
- timeoutReached = true;
838
- break;
839
- }
840
- }
841
- if (timeoutReached) {
867
+ const conditionResult = await processStatus(condition.status, condition.processor);
868
+ if (conditionResult === 'timeout') {
842
869
  break;
843
870
  }
844
871
  }
@@ -854,6 +881,30 @@ export class KeetaAnchorQueueRunner {
854
881
  await result_2;
855
882
  }
856
883
  }
884
+ /**
885
+ * Pick the next entry in the given status for this worker to try.
886
+ *
887
+ * query() returns the oldest entries first, so if every worker
888
+ * took the first one they would all race for the same entry and
889
+ * all but one would lose it. Instead each worker looks at the
890
+ * oldest `workers.count` entries and takes the one at its worker
891
+ * ID plus `attempt`, so concurrent workers start on different
892
+ * entries. Adding the attempt number rotates the slot within a
893
+ * run, so every worker reaches the oldest entry within
894
+ * `workers.count` attempts even when some worker IDs are not
895
+ * running. With a single worker this is simply the oldest entry.
896
+ *
897
+ * @param status The status to pick an entry from
898
+ * @param attempt How many entries this run has already tried in
899
+ * that status
900
+ */
901
+ async nextEntryToProcess(status, attempt) {
902
+ const candidates = await this.queue.query({ status: status, limit: Math.max(1, this.workers.count) });
903
+ if (candidates.length === 0) {
904
+ return (undefined);
905
+ }
906
+ return (candidates[(this.workers.id + attempt) % candidates.length]);
907
+ }
857
908
  async markStuckRequestsAsStuck() {
858
909
  const stuckThreshold = this.processTimeout * this.stuckMultiplier;
859
910
  const logger = this.methodLogger('markStuckRequestsAsStuck');
@@ -904,7 +955,8 @@ export class KeetaAnchorQueueRunner {
904
955
  if (pipes.length === 0) {
905
956
  return;
906
957
  }
907
- const allRequests = await this.queue.query({ status: statusTarget, limit: 100 });
958
+ const fetchLimit = this.pipeMoveFetchLimit;
959
+ const allRequests = await this.queue.query({ status: statusTarget, limit: fetchLimit });
908
960
  let requests = allRequests;
909
961
  const RequestSentToPipes = new Map();
910
962
  function IncrRequestSentToPipes(requestID) {
@@ -1071,16 +1123,55 @@ export class KeetaAnchorQueueRunner {
1071
1123
  }
1072
1124
  }
1073
1125
  }
1126
+ const unmovedRequests = [];
1074
1127
  const TotalPipes = pipes.length;
1075
1128
  for (const request of allRequests) {
1076
1129
  const sentCount = RequestSentToPipes.get(request.id) ?? 0;
1077
1130
  if (sentCount !== TotalPipes) {
1078
1131
  logger?.debug(`${statusTarget} request with id ${String(request.id)} was only moved to ${sentCount} out of ${TotalPipes} pipes -- not marking as moved`);
1132
+ unmovedRequests.push(request);
1079
1133
  continue;
1080
1134
  }
1081
1135
  logger?.debug(`Marking ${statusTarget} request with id ${String(request.id)} as moved`);
1082
1136
  await this.queue.setStatus(request.id, 'moved', { oldStatus: statusTarget, by: this.workerID });
1083
1137
  }
1138
+ /*
1139
+ * If we fetched a full page, there may be more entries behind
1140
+ * the ones we could not move. Since query() returns the oldest
1141
+ * updated entries first, the same entries would be fetched again
1142
+ * on the next pass and block everything behind them, so touch
1143
+ * each one we could not move to send it to the back of the line.
1144
+ *
1145
+ * Touching resets "updated", which completed-entry retention
1146
+ * also reads; that is safe only because retention is skipped
1147
+ * for any queue with pipes (see deleteExpiredCompleted). The
1148
+ * original worker is kept so the entry still records who
1149
+ * processed it.
1150
+ */
1151
+ if (allRequests.length >= fetchLimit) {
1152
+ await this.sendToBackOfLine(unmovedRequests, statusTarget);
1153
+ }
1154
+ }
1155
+ /**
1156
+ * Send entries to the back of the line by setting each to the
1157
+ * status it already has, which bumps "updated" and keeps the
1158
+ * worker that processed it. Another worker may have changed an
1159
+ * entry since it was fetched, so a failure is logged and skipped.
1160
+ */
1161
+ async sendToBackOfLine(requests, status) {
1162
+ const logger = this.methodLogger('sendToBackOfLine');
1163
+ for (const request of requests) {
1164
+ let worker = undefined;
1165
+ if (request.worker !== null) {
1166
+ worker = request.worker;
1167
+ }
1168
+ try {
1169
+ await this.queue.setStatus(request.id, status, { oldStatus: status, by: worker });
1170
+ }
1171
+ catch (error) {
1172
+ logger?.debug(`Failed to move ${status} request with id ${String(request.id)} to the back of the line:`, error);
1173
+ }
1174
+ }
1084
1175
  }
1085
1176
  async maintain() {
1086
1177
  const logger = this.methodLogger('maintain');