@trigger.dev/redis-worker 4.5.0-rc.3 → 4.5.0-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3624,12 +3624,12 @@ var require_common = __commonJS({
3624
3624
  if (!debug.enabled) {
3625
3625
  return;
3626
3626
  }
3627
- const self = debug;
3627
+ const self2 = debug;
3628
3628
  const curr = Number(/* @__PURE__ */ new Date());
3629
3629
  const ms = curr - (prevTime || curr);
3630
- self.diff = ms;
3631
- self.prev = prevTime;
3632
- self.curr = curr;
3630
+ self2.diff = ms;
3631
+ self2.prev = prevTime;
3632
+ self2.curr = curr;
3633
3633
  prevTime = curr;
3634
3634
  args[0] = createDebug.coerce(args[0]);
3635
3635
  if (typeof args[0] !== "string") {
@@ -3644,15 +3644,15 @@ var require_common = __commonJS({
3644
3644
  const formatter = createDebug.formatters[format];
3645
3645
  if (typeof formatter === "function") {
3646
3646
  const val = args[index];
3647
- match = formatter.call(self, val);
3647
+ match = formatter.call(self2, val);
3648
3648
  args.splice(index, 1);
3649
3649
  index--;
3650
3650
  }
3651
3651
  return match;
3652
3652
  });
3653
- createDebug.formatArgs.call(self, args);
3654
- const logFn = self.log || createDebug.log;
3655
- logFn.apply(self, args);
3653
+ createDebug.formatArgs.call(self2, args);
3654
+ const logFn = self2.log || createDebug.log;
3655
+ logFn.apply(self2, args);
3656
3656
  }
3657
3657
  debug.namespace = namespace;
3658
3658
  debug.useColors = createDebug.useColors();
@@ -7200,7 +7200,7 @@ var require_cluster = __commonJS({
7200
7200
  if (err) {
7201
7201
  return reject(err);
7202
7202
  }
7203
- const self = this, groupedRecords = (0, util_1.groupSrvRecords)(records), sortedKeys = Object.keys(groupedRecords).sort((a, b) => parseInt(a) - parseInt(b));
7203
+ const self2 = this, groupedRecords = (0, util_1.groupSrvRecords)(records), sortedKeys = Object.keys(groupedRecords).sort((a, b) => parseInt(a) - parseInt(b));
7204
7204
  function tryFirstOne(err2) {
7205
7205
  if (!sortedKeys.length) {
7206
7206
  return reject(err2);
@@ -7209,7 +7209,7 @@ var require_cluster = __commonJS({
7209
7209
  if (!group.records.length) {
7210
7210
  sortedKeys.shift();
7211
7211
  }
7212
- self.dnsLookup(record.name).then((host) => resolve({
7212
+ self2.dnsLookup(record.name).then((host) => resolve({
7213
7213
  host,
7214
7214
  port: record.port
7215
7215
  }), tryFirstOne);
@@ -8416,15 +8416,15 @@ var require_event_handler = __commonJS({
8416
8416
  var utils_1 = require_utils2();
8417
8417
  var DataHandler_1 = require_DataHandler();
8418
8418
  var debug = (0, utils_1.Debug)("connection");
8419
- function connectHandler(self) {
8419
+ function connectHandler(self2) {
8420
8420
  return function() {
8421
- self.setStatus("connect");
8422
- self.resetCommandQueue();
8421
+ self2.setStatus("connect");
8422
+ self2.resetCommandQueue();
8423
8423
  let flushed = false;
8424
- const { connectionEpoch } = self;
8425
- if (self.condition.auth) {
8426
- self.auth(self.condition.auth, function(err) {
8427
- if (connectionEpoch !== self.connectionEpoch) {
8424
+ const { connectionEpoch } = self2;
8425
+ if (self2.condition.auth) {
8426
+ self2.auth(self2.condition.auth, function(err) {
8427
+ if (connectionEpoch !== self2.connectionEpoch) {
8428
8428
  return;
8429
8429
  }
8430
8430
  if (err) {
@@ -8436,36 +8436,36 @@ var require_event_handler = __commonJS({
8436
8436
  console.warn(`[ERROR] The server returned "wrong number of arguments for 'auth' command". You are probably passing both username and password to Redis version 5 or below. You should only pass the 'password' option for Redis version 5 and under.`);
8437
8437
  } else {
8438
8438
  flushed = true;
8439
- self.recoverFromFatalError(err, err);
8439
+ self2.recoverFromFatalError(err, err);
8440
8440
  }
8441
8441
  }
8442
8442
  });
8443
8443
  }
8444
- if (self.condition.select) {
8445
- self.select(self.condition.select).catch((err) => {
8446
- self.silentEmit("error", err);
8444
+ if (self2.condition.select) {
8445
+ self2.select(self2.condition.select).catch((err) => {
8446
+ self2.silentEmit("error", err);
8447
8447
  });
8448
8448
  }
8449
- if (!self.options.enableReadyCheck) {
8450
- exports$1.readyHandler(self)();
8449
+ if (!self2.options.enableReadyCheck) {
8450
+ exports$1.readyHandler(self2)();
8451
8451
  }
8452
- new DataHandler_1.default(self, {
8453
- stringNumbers: self.options.stringNumbers
8452
+ new DataHandler_1.default(self2, {
8453
+ stringNumbers: self2.options.stringNumbers
8454
8454
  });
8455
- if (self.options.enableReadyCheck) {
8456
- self._readyCheck(function(err, info) {
8457
- if (connectionEpoch !== self.connectionEpoch) {
8455
+ if (self2.options.enableReadyCheck) {
8456
+ self2._readyCheck(function(err, info) {
8457
+ if (connectionEpoch !== self2.connectionEpoch) {
8458
8458
  return;
8459
8459
  }
8460
8460
  if (err) {
8461
8461
  if (!flushed) {
8462
- self.recoverFromFatalError(new Error("Ready check failed: " + err.message), err);
8462
+ self2.recoverFromFatalError(new Error("Ready check failed: " + err.message), err);
8463
8463
  }
8464
8464
  } else {
8465
- if (self.connector.check(info)) {
8466
- exports$1.readyHandler(self)();
8465
+ if (self2.connector.check(info)) {
8466
+ exports$1.readyHandler(self2)();
8467
8467
  } else {
8468
- self.disconnect(true);
8468
+ self2.disconnect(true);
8469
8469
  }
8470
8470
  }
8471
8471
  });
@@ -8518,152 +8518,152 @@ var require_event_handler = __commonJS({
8518
8518
  }
8519
8519
  }
8520
8520
  }
8521
- function closeHandler(self) {
8521
+ function closeHandler(self2) {
8522
8522
  return function() {
8523
- const prevStatus = self.status;
8524
- self.setStatus("close");
8525
- if (self.commandQueue.length) {
8526
- abortIncompletePipelines(self.commandQueue);
8523
+ const prevStatus = self2.status;
8524
+ self2.setStatus("close");
8525
+ if (self2.commandQueue.length) {
8526
+ abortIncompletePipelines(self2.commandQueue);
8527
8527
  }
8528
- if (self.offlineQueue.length) {
8529
- abortTransactionFragments(self.offlineQueue);
8528
+ if (self2.offlineQueue.length) {
8529
+ abortTransactionFragments(self2.offlineQueue);
8530
8530
  }
8531
8531
  if (prevStatus === "ready") {
8532
- if (!self.prevCondition) {
8533
- self.prevCondition = self.condition;
8532
+ if (!self2.prevCondition) {
8533
+ self2.prevCondition = self2.condition;
8534
8534
  }
8535
- if (self.commandQueue.length) {
8536
- self.prevCommandQueue = self.commandQueue;
8535
+ if (self2.commandQueue.length) {
8536
+ self2.prevCommandQueue = self2.commandQueue;
8537
8537
  }
8538
8538
  }
8539
- if (self.manuallyClosing) {
8540
- self.manuallyClosing = false;
8539
+ if (self2.manuallyClosing) {
8540
+ self2.manuallyClosing = false;
8541
8541
  debug("skip reconnecting since the connection is manually closed.");
8542
8542
  return close();
8543
8543
  }
8544
- if (typeof self.options.retryStrategy !== "function") {
8544
+ if (typeof self2.options.retryStrategy !== "function") {
8545
8545
  debug("skip reconnecting because `retryStrategy` is not a function");
8546
8546
  return close();
8547
8547
  }
8548
- const retryDelay = self.options.retryStrategy(++self.retryAttempts);
8548
+ const retryDelay = self2.options.retryStrategy(++self2.retryAttempts);
8549
8549
  if (typeof retryDelay !== "number") {
8550
8550
  debug("skip reconnecting because `retryStrategy` doesn't return a number");
8551
8551
  return close();
8552
8552
  }
8553
8553
  debug("reconnect in %sms", retryDelay);
8554
- self.setStatus("reconnecting", retryDelay);
8555
- self.reconnectTimeout = setTimeout(function() {
8556
- self.reconnectTimeout = null;
8557
- self.connect().catch(utils_1.noop);
8554
+ self2.setStatus("reconnecting", retryDelay);
8555
+ self2.reconnectTimeout = setTimeout(function() {
8556
+ self2.reconnectTimeout = null;
8557
+ self2.connect().catch(utils_1.noop);
8558
8558
  }, retryDelay);
8559
- const { maxRetriesPerRequest } = self.options;
8559
+ const { maxRetriesPerRequest } = self2.options;
8560
8560
  if (typeof maxRetriesPerRequest === "number") {
8561
8561
  if (maxRetriesPerRequest < 0) {
8562
8562
  debug("maxRetriesPerRequest is negative, ignoring...");
8563
8563
  } else {
8564
- const remainder = self.retryAttempts % (maxRetriesPerRequest + 1);
8564
+ const remainder = self2.retryAttempts % (maxRetriesPerRequest + 1);
8565
8565
  if (remainder === 0) {
8566
8566
  debug("reach maxRetriesPerRequest limitation, flushing command queue...");
8567
- self.flushQueue(new errors_1.MaxRetriesPerRequestError(maxRetriesPerRequest));
8567
+ self2.flushQueue(new errors_1.MaxRetriesPerRequestError(maxRetriesPerRequest));
8568
8568
  }
8569
8569
  }
8570
8570
  }
8571
8571
  };
8572
8572
  function close() {
8573
- self.setStatus("end");
8574
- self.flushQueue(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG));
8573
+ self2.setStatus("end");
8574
+ self2.flushQueue(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG));
8575
8575
  }
8576
8576
  }
8577
8577
  exports$1.closeHandler = closeHandler;
8578
- function errorHandler(self) {
8578
+ function errorHandler(self2) {
8579
8579
  return function(error) {
8580
8580
  debug("error: %s", error);
8581
- self.silentEmit("error", error);
8581
+ self2.silentEmit("error", error);
8582
8582
  };
8583
8583
  }
8584
8584
  exports$1.errorHandler = errorHandler;
8585
- function readyHandler(self) {
8585
+ function readyHandler(self2) {
8586
8586
  return function() {
8587
- self.setStatus("ready");
8588
- self.retryAttempts = 0;
8589
- if (self.options.monitor) {
8590
- self.call("monitor").then(() => self.setStatus("monitoring"), (error) => self.emit("error", error));
8591
- const { sendCommand } = self;
8592
- self.sendCommand = function(command) {
8587
+ self2.setStatus("ready");
8588
+ self2.retryAttempts = 0;
8589
+ if (self2.options.monitor) {
8590
+ self2.call("monitor").then(() => self2.setStatus("monitoring"), (error) => self2.emit("error", error));
8591
+ const { sendCommand } = self2;
8592
+ self2.sendCommand = function(command) {
8593
8593
  if (Command_1.default.checkFlag("VALID_IN_MONITOR_MODE", command.name)) {
8594
- return sendCommand.call(self, command);
8594
+ return sendCommand.call(self2, command);
8595
8595
  }
8596
8596
  command.reject(new Error("Connection is in monitoring mode, can't process commands."));
8597
8597
  return command.promise;
8598
8598
  };
8599
- self.once("close", function() {
8600
- delete self.sendCommand;
8599
+ self2.once("close", function() {
8600
+ delete self2.sendCommand;
8601
8601
  });
8602
8602
  return;
8603
8603
  }
8604
- const finalSelect = self.prevCondition ? self.prevCondition.select : self.condition.select;
8605
- if (self.options.connectionName) {
8606
- debug("set the connection name [%s]", self.options.connectionName);
8607
- self.client("setname", self.options.connectionName).catch(utils_1.noop);
8604
+ const finalSelect = self2.prevCondition ? self2.prevCondition.select : self2.condition.select;
8605
+ if (self2.options.connectionName) {
8606
+ debug("set the connection name [%s]", self2.options.connectionName);
8607
+ self2.client("setname", self2.options.connectionName).catch(utils_1.noop);
8608
8608
  }
8609
- if (self.options.readOnly) {
8609
+ if (self2.options.readOnly) {
8610
8610
  debug("set the connection to readonly mode");
8611
- self.readonly().catch(utils_1.noop);
8611
+ self2.readonly().catch(utils_1.noop);
8612
8612
  }
8613
- if (self.prevCondition) {
8614
- const condition = self.prevCondition;
8615
- self.prevCondition = null;
8616
- if (condition.subscriber && self.options.autoResubscribe) {
8617
- if (self.condition.select !== finalSelect) {
8613
+ if (self2.prevCondition) {
8614
+ const condition = self2.prevCondition;
8615
+ self2.prevCondition = null;
8616
+ if (condition.subscriber && self2.options.autoResubscribe) {
8617
+ if (self2.condition.select !== finalSelect) {
8618
8618
  debug("connect to db [%d]", finalSelect);
8619
- self.select(finalSelect);
8619
+ self2.select(finalSelect);
8620
8620
  }
8621
8621
  const subscribeChannels = condition.subscriber.channels("subscribe");
8622
8622
  if (subscribeChannels.length) {
8623
8623
  debug("subscribe %d channels", subscribeChannels.length);
8624
- self.subscribe(subscribeChannels);
8624
+ self2.subscribe(subscribeChannels);
8625
8625
  }
8626
8626
  const psubscribeChannels = condition.subscriber.channels("psubscribe");
8627
8627
  if (psubscribeChannels.length) {
8628
8628
  debug("psubscribe %d channels", psubscribeChannels.length);
8629
- self.psubscribe(psubscribeChannels);
8629
+ self2.psubscribe(psubscribeChannels);
8630
8630
  }
8631
8631
  const ssubscribeChannels = condition.subscriber.channels("ssubscribe");
8632
8632
  if (ssubscribeChannels.length) {
8633
8633
  debug("ssubscribe %d channels", ssubscribeChannels.length);
8634
- self.ssubscribe(ssubscribeChannels);
8634
+ self2.ssubscribe(ssubscribeChannels);
8635
8635
  }
8636
8636
  }
8637
8637
  }
8638
- if (self.prevCommandQueue) {
8639
- if (self.options.autoResendUnfulfilledCommands) {
8640
- debug("resend %d unfulfilled commands", self.prevCommandQueue.length);
8641
- while (self.prevCommandQueue.length > 0) {
8642
- const item = self.prevCommandQueue.shift();
8643
- if (item.select !== self.condition.select && item.command.name !== "select") {
8644
- self.select(item.select);
8638
+ if (self2.prevCommandQueue) {
8639
+ if (self2.options.autoResendUnfulfilledCommands) {
8640
+ debug("resend %d unfulfilled commands", self2.prevCommandQueue.length);
8641
+ while (self2.prevCommandQueue.length > 0) {
8642
+ const item = self2.prevCommandQueue.shift();
8643
+ if (item.select !== self2.condition.select && item.command.name !== "select") {
8644
+ self2.select(item.select);
8645
8645
  }
8646
- self.sendCommand(item.command, item.stream);
8646
+ self2.sendCommand(item.command, item.stream);
8647
8647
  }
8648
8648
  } else {
8649
- self.prevCommandQueue = null;
8649
+ self2.prevCommandQueue = null;
8650
8650
  }
8651
8651
  }
8652
- if (self.offlineQueue.length) {
8653
- debug("send %d commands in offline queue", self.offlineQueue.length);
8654
- const offlineQueue = self.offlineQueue;
8655
- self.resetOfflineQueue();
8652
+ if (self2.offlineQueue.length) {
8653
+ debug("send %d commands in offline queue", self2.offlineQueue.length);
8654
+ const offlineQueue = self2.offlineQueue;
8655
+ self2.resetOfflineQueue();
8656
8656
  while (offlineQueue.length > 0) {
8657
8657
  const item = offlineQueue.shift();
8658
- if (item.select !== self.condition.select && item.command.name !== "select") {
8659
- self.select(item.select);
8658
+ if (item.select !== self2.condition.select && item.command.name !== "select") {
8659
+ self2.select(item.select);
8660
8660
  }
8661
- self.sendCommand(item.command, item.stream);
8661
+ self2.sendCommand(item.command, item.stream);
8662
8662
  }
8663
8663
  }
8664
- if (self.condition.select !== finalSelect) {
8664
+ if (self2.condition.select !== finalSelect) {
8665
8665
  debug("connect to db [%d]", finalSelect);
8666
- self.select(finalSelect);
8666
+ self2.select(finalSelect);
8667
8667
  }
8668
8668
  };
8669
8669
  }
@@ -9959,24 +9959,19 @@ var SimpleQueue = class {
9959
9959
  }
9960
9960
  };
9961
9961
 
9962
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js
9963
- var _globalThis = typeof globalThis === "object" ? globalThis : global;
9962
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/version.js
9963
+ var VERSION = "1.9.1";
9964
9964
 
9965
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/version.js
9966
- var VERSION = "1.9.0";
9967
-
9968
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/internal/semver.js
9965
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/internal/semver.js
9969
9966
  var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
9970
9967
  function _makeCompatibilityCheck(ownVersion) {
9971
- var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
9972
- var rejectedVersions = /* @__PURE__ */ new Set();
9973
- var myVersionMatch = ownVersion.match(re);
9968
+ const acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
9969
+ const rejectedVersions = /* @__PURE__ */ new Set();
9970
+ const myVersionMatch = ownVersion.match(re);
9974
9971
  if (!myVersionMatch) {
9975
- return function() {
9976
- return false;
9977
- };
9972
+ return () => false;
9978
9973
  }
9979
- var ownVersionParsed = {
9974
+ const ownVersionParsed = {
9980
9975
  major: +myVersionMatch[1],
9981
9976
  minor: +myVersionMatch[2],
9982
9977
  patch: +myVersionMatch[3],
@@ -10002,11 +9997,11 @@ function _makeCompatibilityCheck(ownVersion) {
10002
9997
  if (rejectedVersions.has(globalVersion)) {
10003
9998
  return false;
10004
9999
  }
10005
- var globalVersionMatch = globalVersion.match(re);
10000
+ const globalVersionMatch = globalVersion.match(re);
10006
10001
  if (!globalVersionMatch) {
10007
10002
  return _reject(globalVersion);
10008
10003
  }
10009
- var globalVersionParsed = {
10004
+ const globalVersionParsed = {
10010
10005
  major: +globalVersionMatch[1],
10011
10006
  minor: +globalVersionMatch[2],
10012
10007
  patch: +globalVersionMatch[3],
@@ -10032,129 +10027,75 @@ function _makeCompatibilityCheck(ownVersion) {
10032
10027
  }
10033
10028
  var isCompatible = _makeCompatibilityCheck(VERSION);
10034
10029
 
10035
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js
10030
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js
10036
10031
  var major = VERSION.split(".")[0];
10037
- var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
10038
- var _global = _globalThis;
10039
- function registerGlobal(type, instance, diag, allowOverride) {
10032
+ var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`);
10033
+ var _global = typeof globalThis === "object" ? globalThis : typeof self === "object" ? self : typeof window === "object" ? window : typeof global === "object" ? global : {};
10034
+ function registerGlobal(type, instance, diag, allowOverride = false) {
10040
10035
  var _a;
10041
- if (allowOverride === void 0) {
10042
- allowOverride = false;
10043
- }
10044
- var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
10036
+ const api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
10045
10037
  version: VERSION
10046
10038
  };
10047
10039
  if (!allowOverride && api[type]) {
10048
- var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
10040
+ const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);
10049
10041
  diag.error(err.stack || err.message);
10050
10042
  return false;
10051
10043
  }
10052
10044
  if (api.version !== VERSION) {
10053
- var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION);
10045
+ const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`);
10054
10046
  diag.error(err.stack || err.message);
10055
10047
  return false;
10056
10048
  }
10057
10049
  api[type] = instance;
10058
- diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + ".");
10050
+ diag.debug(`@opentelemetry/api: Registered a global for ${type} v${VERSION}.`);
10059
10051
  return true;
10060
10052
  }
10061
10053
  function getGlobal(type) {
10062
10054
  var _a, _b;
10063
- var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
10055
+ const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
10064
10056
  if (!globalVersion || !isCompatible(globalVersion)) {
10065
10057
  return;
10066
10058
  }
10067
10059
  return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
10068
10060
  }
10069
10061
  function unregisterGlobal(type, diag) {
10070
- diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + ".");
10071
- var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
10062
+ diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`);
10063
+ const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
10072
10064
  if (api) {
10073
10065
  delete api[type];
10074
10066
  }
10075
10067
  }
10076
10068
 
10077
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js
10078
- var __read = function(o, n) {
10079
- var m = typeof Symbol === "function" && o[Symbol.iterator];
10080
- if (!m) return o;
10081
- var i = m.call(o), r, ar = [], e;
10082
- try {
10083
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
10084
- } catch (error) {
10085
- e = { error };
10086
- } finally {
10087
- try {
10088
- if (r && !r.done && (m = i["return"])) m.call(i);
10089
- } finally {
10090
- if (e) throw e.error;
10091
- }
10069
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js
10070
+ var DiagComponentLogger = class {
10071
+ constructor(props) {
10072
+ this._namespace = props.namespace || "DiagComponentLogger";
10092
10073
  }
10093
- return ar;
10094
- };
10095
- var __spreadArray = function(to, from, pack) {
10096
- if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
10097
- if (ar || !(i in from)) {
10098
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
10099
- ar[i] = from[i];
10100
- }
10074
+ debug(...args) {
10075
+ return logProxy("debug", this._namespace, args);
10076
+ }
10077
+ error(...args) {
10078
+ return logProxy("error", this._namespace, args);
10079
+ }
10080
+ info(...args) {
10081
+ return logProxy("info", this._namespace, args);
10082
+ }
10083
+ warn(...args) {
10084
+ return logProxy("warn", this._namespace, args);
10085
+ }
10086
+ verbose(...args) {
10087
+ return logProxy("verbose", this._namespace, args);
10101
10088
  }
10102
- return to.concat(ar || Array.prototype.slice.call(from));
10103
10089
  };
10104
- var DiagComponentLogger = (
10105
- /** @class */
10106
- function() {
10107
- function DiagComponentLogger2(props) {
10108
- this._namespace = props.namespace || "DiagComponentLogger";
10109
- }
10110
- DiagComponentLogger2.prototype.debug = function() {
10111
- var args = [];
10112
- for (var _i = 0; _i < arguments.length; _i++) {
10113
- args[_i] = arguments[_i];
10114
- }
10115
- return logProxy("debug", this._namespace, args);
10116
- };
10117
- DiagComponentLogger2.prototype.error = function() {
10118
- var args = [];
10119
- for (var _i = 0; _i < arguments.length; _i++) {
10120
- args[_i] = arguments[_i];
10121
- }
10122
- return logProxy("error", this._namespace, args);
10123
- };
10124
- DiagComponentLogger2.prototype.info = function() {
10125
- var args = [];
10126
- for (var _i = 0; _i < arguments.length; _i++) {
10127
- args[_i] = arguments[_i];
10128
- }
10129
- return logProxy("info", this._namespace, args);
10130
- };
10131
- DiagComponentLogger2.prototype.warn = function() {
10132
- var args = [];
10133
- for (var _i = 0; _i < arguments.length; _i++) {
10134
- args[_i] = arguments[_i];
10135
- }
10136
- return logProxy("warn", this._namespace, args);
10137
- };
10138
- DiagComponentLogger2.prototype.verbose = function() {
10139
- var args = [];
10140
- for (var _i = 0; _i < arguments.length; _i++) {
10141
- args[_i] = arguments[_i];
10142
- }
10143
- return logProxy("verbose", this._namespace, args);
10144
- };
10145
- return DiagComponentLogger2;
10146
- }()
10147
- );
10148
10090
  function logProxy(funcName, namespace, args) {
10149
- var logger2 = getGlobal("diag");
10091
+ const logger2 = getGlobal("diag");
10150
10092
  if (!logger2) {
10151
10093
  return;
10152
10094
  }
10153
- args.unshift(namespace);
10154
- return logger2[funcName].apply(logger2, __spreadArray([], __read(args), false));
10095
+ return logger2[funcName](namespace, ...args);
10155
10096
  }
10156
10097
 
10157
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/types.js
10098
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/types.js
10158
10099
  var DiagLogLevel;
10159
10100
  (function(DiagLogLevel2) {
10160
10101
  DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
@@ -10166,7 +10107,7 @@ var DiagLogLevel;
10166
10107
  DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
10167
10108
  })(DiagLogLevel || (DiagLogLevel = {}));
10168
10109
 
10169
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js
10110
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js
10170
10111
  function createLogLevelDiagLogger(maxLevel, logger2) {
10171
10112
  if (maxLevel < DiagLogLevel.NONE) {
10172
10113
  maxLevel = DiagLogLevel.NONE;
@@ -10175,7 +10116,7 @@ function createLogLevelDiagLogger(maxLevel, logger2) {
10175
10116
  }
10176
10117
  logger2 = logger2 || {};
10177
10118
  function _filterFunc(funcName, theLevel) {
10178
- var theFunc = logger2[funcName];
10119
+ const theFunc = logger2[funcName];
10179
10120
  if (typeof theFunc === "function" && maxLevel >= theLevel) {
10180
10121
  return theFunc.bind(logger2);
10181
10122
  }
@@ -10191,278 +10132,181 @@ function createLogLevelDiagLogger(maxLevel, logger2) {
10191
10132
  };
10192
10133
  }
10193
10134
 
10194
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/diag.js
10195
- var __read2 = function(o, n) {
10196
- var m = typeof Symbol === "function" && o[Symbol.iterator];
10197
- if (!m) return o;
10198
- var i = m.call(o), r, ar = [], e;
10199
- try {
10200
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
10201
- } catch (error) {
10202
- e = { error };
10203
- } finally {
10204
- try {
10205
- if (r && !r.done && (m = i["return"])) m.call(i);
10206
- } finally {
10207
- if (e) throw e.error;
10135
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/diag.js
10136
+ var API_NAME = "diag";
10137
+ var DiagAPI = class _DiagAPI {
10138
+ /** Get the singleton instance of the DiagAPI API */
10139
+ static instance() {
10140
+ if (!this._instance) {
10141
+ this._instance = new _DiagAPI();
10208
10142
  }
10143
+ return this._instance;
10209
10144
  }
10210
- return ar;
10211
- };
10212
- var __spreadArray2 = function(to, from, pack) {
10213
- if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
10214
- if (ar || !(i in from)) {
10215
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
10216
- ar[i] = from[i];
10145
+ /**
10146
+ * Private internal constructor
10147
+ * @private
10148
+ */
10149
+ constructor() {
10150
+ function _logProxy(funcName) {
10151
+ return function(...args) {
10152
+ const logger2 = getGlobal("diag");
10153
+ if (!logger2)
10154
+ return;
10155
+ return logger2[funcName](...args);
10156
+ };
10217
10157
  }
10218
- }
10219
- return to.concat(ar || Array.prototype.slice.call(from));
10220
- };
10221
- var API_NAME = "diag";
10222
- var DiagAPI = (
10223
- /** @class */
10224
- function() {
10225
- function DiagAPI2() {
10226
- function _logProxy(funcName) {
10227
- return function() {
10228
- var args = [];
10229
- for (var _i = 0; _i < arguments.length; _i++) {
10230
- args[_i] = arguments[_i];
10231
- }
10232
- var logger2 = getGlobal("diag");
10233
- if (!logger2)
10234
- return;
10235
- return logger2[funcName].apply(logger2, __spreadArray2([], __read2(args), false));
10158
+ const self2 = this;
10159
+ const setLogger = (logger2, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => {
10160
+ var _a, _b, _c;
10161
+ if (logger2 === self2) {
10162
+ const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
10163
+ self2.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
10164
+ return false;
10165
+ }
10166
+ if (typeof optionsOrLogLevel === "number") {
10167
+ optionsOrLogLevel = {
10168
+ logLevel: optionsOrLogLevel
10236
10169
  };
10237
10170
  }
10238
- var self = this;
10239
- var setLogger = function(logger2, optionsOrLogLevel) {
10240
- var _a, _b, _c;
10241
- if (optionsOrLogLevel === void 0) {
10242
- optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
10243
- }
10244
- if (logger2 === self) {
10245
- var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
10246
- self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
10247
- return false;
10248
- }
10249
- if (typeof optionsOrLogLevel === "number") {
10250
- optionsOrLogLevel = {
10251
- logLevel: optionsOrLogLevel
10252
- };
10253
- }
10254
- var oldLogger = getGlobal("diag");
10255
- var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger2);
10256
- if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
10257
- var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
10258
- oldLogger.warn("Current logger will be overwritten from " + stack);
10259
- newLogger.warn("Current logger will overwrite one already registered from " + stack);
10260
- }
10261
- return registerGlobal("diag", newLogger, self, true);
10262
- };
10263
- self.setLogger = setLogger;
10264
- self.disable = function() {
10265
- unregisterGlobal(API_NAME, self);
10266
- };
10267
- self.createComponentLogger = function(options) {
10268
- return new DiagComponentLogger(options);
10269
- };
10270
- self.verbose = _logProxy("verbose");
10271
- self.debug = _logProxy("debug");
10272
- self.info = _logProxy("info");
10273
- self.warn = _logProxy("warn");
10274
- self.error = _logProxy("error");
10275
- }
10276
- DiagAPI2.instance = function() {
10277
- if (!this._instance) {
10278
- this._instance = new DiagAPI2();
10171
+ const oldLogger = getGlobal("diag");
10172
+ const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger2);
10173
+ if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
10174
+ const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
10175
+ oldLogger.warn(`Current logger will be overwritten from ${stack}`);
10176
+ newLogger.warn(`Current logger will overwrite one already registered from ${stack}`);
10279
10177
  }
10280
- return this._instance;
10178
+ return registerGlobal("diag", newLogger, self2, true);
10179
+ };
10180
+ self2.setLogger = setLogger;
10181
+ self2.disable = () => {
10182
+ unregisterGlobal(API_NAME, self2);
10183
+ };
10184
+ self2.createComponentLogger = (options) => {
10185
+ return new DiagComponentLogger(options);
10281
10186
  };
10282
- return DiagAPI2;
10283
- }()
10284
- );
10187
+ self2.verbose = _logProxy("verbose");
10188
+ self2.debug = _logProxy("debug");
10189
+ self2.info = _logProxy("info");
10190
+ self2.warn = _logProxy("warn");
10191
+ self2.error = _logProxy("error");
10192
+ }
10193
+ };
10285
10194
 
10286
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context/context.js
10195
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context/context.js
10287
10196
  function createContextKey(description) {
10288
10197
  return Symbol.for(description);
10289
10198
  }
10290
- var BaseContext = (
10291
- /** @class */
10292
- /* @__PURE__ */ function() {
10293
- function BaseContext2(parentContext) {
10294
- var self = this;
10295
- self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
10296
- self.getValue = function(key) {
10297
- return self._currentContext.get(key);
10298
- };
10299
- self.setValue = function(key, value) {
10300
- var context2 = new BaseContext2(self._currentContext);
10301
- context2._currentContext.set(key, value);
10302
- return context2;
10303
- };
10304
- self.deleteValue = function(key) {
10305
- var context2 = new BaseContext2(self._currentContext);
10306
- context2._currentContext.delete(key);
10307
- return context2;
10308
- };
10309
- }
10310
- return BaseContext2;
10311
- }()
10312
- );
10313
- var ROOT_CONTEXT = new BaseContext();
10314
-
10315
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js
10316
- var __extends = /* @__PURE__ */ function() {
10317
- var extendStatics = function(d, b) {
10318
- extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
10319
- d2.__proto__ = b2;
10320
- } || function(d2, b2) {
10321
- for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
10322
- };
10323
- return extendStatics(d, b);
10324
- };
10325
- return function(d, b) {
10326
- if (typeof b !== "function" && b !== null)
10327
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
10328
- extendStatics(d, b);
10329
- function __() {
10330
- this.constructor = d;
10331
- }
10332
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10333
- };
10334
- }();
10335
- var NoopMeter = (
10336
- /** @class */
10337
- function() {
10338
- function NoopMeter2() {
10339
- }
10340
- NoopMeter2.prototype.createGauge = function(_name, _options) {
10341
- return NOOP_GAUGE_METRIC;
10342
- };
10343
- NoopMeter2.prototype.createHistogram = function(_name, _options) {
10344
- return NOOP_HISTOGRAM_METRIC;
10345
- };
10346
- NoopMeter2.prototype.createCounter = function(_name, _options) {
10347
- return NOOP_COUNTER_METRIC;
10348
- };
10349
- NoopMeter2.prototype.createUpDownCounter = function(_name, _options) {
10350
- return NOOP_UP_DOWN_COUNTER_METRIC;
10351
- };
10352
- NoopMeter2.prototype.createObservableGauge = function(_name, _options) {
10353
- return NOOP_OBSERVABLE_GAUGE_METRIC;
10354
- };
10355
- NoopMeter2.prototype.createObservableCounter = function(_name, _options) {
10356
- return NOOP_OBSERVABLE_COUNTER_METRIC;
10357
- };
10358
- NoopMeter2.prototype.createObservableUpDownCounter = function(_name, _options) {
10359
- return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;
10360
- };
10361
- NoopMeter2.prototype.addBatchObservableCallback = function(_callback, _observables) {
10362
- };
10363
- NoopMeter2.prototype.removeBatchObservableCallback = function(_callback) {
10364
- };
10365
- return NoopMeter2;
10366
- }()
10367
- );
10368
- var NoopMetric = (
10369
- /** @class */
10370
- /* @__PURE__ */ function() {
10371
- function NoopMetric2() {
10372
- }
10373
- return NoopMetric2;
10374
- }()
10375
- );
10376
- var NoopCounterMetric = (
10377
- /** @class */
10378
- function(_super) {
10379
- __extends(NoopCounterMetric2, _super);
10380
- function NoopCounterMetric2() {
10381
- return _super !== null && _super.apply(this, arguments) || this;
10382
- }
10383
- NoopCounterMetric2.prototype.add = function(_value, _attributes) {
10384
- };
10385
- return NoopCounterMetric2;
10386
- }(NoopMetric)
10387
- );
10388
- var NoopUpDownCounterMetric = (
10389
- /** @class */
10390
- function(_super) {
10391
- __extends(NoopUpDownCounterMetric2, _super);
10392
- function NoopUpDownCounterMetric2() {
10393
- return _super !== null && _super.apply(this, arguments) || this;
10394
- }
10395
- NoopUpDownCounterMetric2.prototype.add = function(_value, _attributes) {
10396
- };
10397
- return NoopUpDownCounterMetric2;
10398
- }(NoopMetric)
10399
- );
10400
- var NoopGaugeMetric = (
10401
- /** @class */
10402
- function(_super) {
10403
- __extends(NoopGaugeMetric2, _super);
10404
- function NoopGaugeMetric2() {
10405
- return _super !== null && _super.apply(this, arguments) || this;
10406
- }
10407
- NoopGaugeMetric2.prototype.record = function(_value, _attributes) {
10408
- };
10409
- return NoopGaugeMetric2;
10410
- }(NoopMetric)
10411
- );
10412
- var NoopHistogramMetric = (
10413
- /** @class */
10414
- function(_super) {
10415
- __extends(NoopHistogramMetric2, _super);
10416
- function NoopHistogramMetric2() {
10417
- return _super !== null && _super.apply(this, arguments) || this;
10418
- }
10419
- NoopHistogramMetric2.prototype.record = function(_value, _attributes) {
10420
- };
10421
- return NoopHistogramMetric2;
10422
- }(NoopMetric)
10423
- );
10424
- var NoopObservableMetric = (
10425
- /** @class */
10426
- function() {
10427
- function NoopObservableMetric2() {
10428
- }
10429
- NoopObservableMetric2.prototype.addCallback = function(_callback) {
10199
+ var BaseContext = class _BaseContext {
10200
+ /**
10201
+ * Construct a new context which inherits values from an optional parent context.
10202
+ *
10203
+ * @param parentContext a context from which to inherit values
10204
+ */
10205
+ constructor(parentContext) {
10206
+ const self2 = this;
10207
+ self2._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
10208
+ self2.getValue = (key) => self2._currentContext.get(key);
10209
+ self2.setValue = (key, value) => {
10210
+ const context2 = new _BaseContext(self2._currentContext);
10211
+ context2._currentContext.set(key, value);
10212
+ return context2;
10430
10213
  };
10431
- NoopObservableMetric2.prototype.removeCallback = function(_callback) {
10214
+ self2.deleteValue = (key) => {
10215
+ const context2 = new _BaseContext(self2._currentContext);
10216
+ context2._currentContext.delete(key);
10217
+ return context2;
10432
10218
  };
10433
- return NoopObservableMetric2;
10434
- }()
10435
- );
10436
- var NoopObservableCounterMetric = (
10437
- /** @class */
10438
- function(_super) {
10439
- __extends(NoopObservableCounterMetric2, _super);
10440
- function NoopObservableCounterMetric2() {
10441
- return _super !== null && _super.apply(this, arguments) || this;
10442
- }
10443
- return NoopObservableCounterMetric2;
10444
- }(NoopObservableMetric)
10445
- );
10446
- var NoopObservableGaugeMetric = (
10447
- /** @class */
10448
- function(_super) {
10449
- __extends(NoopObservableGaugeMetric2, _super);
10450
- function NoopObservableGaugeMetric2() {
10451
- return _super !== null && _super.apply(this, arguments) || this;
10452
- }
10453
- return NoopObservableGaugeMetric2;
10454
- }(NoopObservableMetric)
10455
- );
10456
- var NoopObservableUpDownCounterMetric = (
10457
- /** @class */
10458
- function(_super) {
10459
- __extends(NoopObservableUpDownCounterMetric2, _super);
10460
- function NoopObservableUpDownCounterMetric2() {
10461
- return _super !== null && _super.apply(this, arguments) || this;
10462
- }
10463
- return NoopObservableUpDownCounterMetric2;
10464
- }(NoopObservableMetric)
10465
- );
10219
+ }
10220
+ };
10221
+ var ROOT_CONTEXT = new BaseContext();
10222
+
10223
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js
10224
+ var NoopMeter = class {
10225
+ constructor() {
10226
+ }
10227
+ /**
10228
+ * @see {@link Meter.createGauge}
10229
+ */
10230
+ createGauge(_name, _options) {
10231
+ return NOOP_GAUGE_METRIC;
10232
+ }
10233
+ /**
10234
+ * @see {@link Meter.createHistogram}
10235
+ */
10236
+ createHistogram(_name, _options) {
10237
+ return NOOP_HISTOGRAM_METRIC;
10238
+ }
10239
+ /**
10240
+ * @see {@link Meter.createCounter}
10241
+ */
10242
+ createCounter(_name, _options) {
10243
+ return NOOP_COUNTER_METRIC;
10244
+ }
10245
+ /**
10246
+ * @see {@link Meter.createUpDownCounter}
10247
+ */
10248
+ createUpDownCounter(_name, _options) {
10249
+ return NOOP_UP_DOWN_COUNTER_METRIC;
10250
+ }
10251
+ /**
10252
+ * @see {@link Meter.createObservableGauge}
10253
+ */
10254
+ createObservableGauge(_name, _options) {
10255
+ return NOOP_OBSERVABLE_GAUGE_METRIC;
10256
+ }
10257
+ /**
10258
+ * @see {@link Meter.createObservableCounter}
10259
+ */
10260
+ createObservableCounter(_name, _options) {
10261
+ return NOOP_OBSERVABLE_COUNTER_METRIC;
10262
+ }
10263
+ /**
10264
+ * @see {@link Meter.createObservableUpDownCounter}
10265
+ */
10266
+ createObservableUpDownCounter(_name, _options) {
10267
+ return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;
10268
+ }
10269
+ /**
10270
+ * @see {@link Meter.addBatchObservableCallback}
10271
+ */
10272
+ addBatchObservableCallback(_callback, _observables) {
10273
+ }
10274
+ /**
10275
+ * @see {@link Meter.removeBatchObservableCallback}
10276
+ */
10277
+ removeBatchObservableCallback(_callback) {
10278
+ }
10279
+ };
10280
+ var NoopMetric = class {
10281
+ };
10282
+ var NoopCounterMetric = class extends NoopMetric {
10283
+ add(_value, _attributes) {
10284
+ }
10285
+ };
10286
+ var NoopUpDownCounterMetric = class extends NoopMetric {
10287
+ add(_value, _attributes) {
10288
+ }
10289
+ };
10290
+ var NoopGaugeMetric = class extends NoopMetric {
10291
+ record(_value, _attributes) {
10292
+ }
10293
+ };
10294
+ var NoopHistogramMetric = class extends NoopMetric {
10295
+ record(_value, _attributes) {
10296
+ }
10297
+ };
10298
+ var NoopObservableMetric = class {
10299
+ addCallback(_callback) {
10300
+ }
10301
+ removeCallback(_callback) {
10302
+ }
10303
+ };
10304
+ var NoopObservableCounterMetric = class extends NoopObservableMetric {
10305
+ };
10306
+ var NoopObservableGaugeMetric = class extends NoopObservableMetric {
10307
+ };
10308
+ var NoopObservableUpDownCounterMetric = class extends NoopObservableMetric {
10309
+ };
10466
10310
  var NOOP_METER = new NoopMeter();
10467
10311
  var NOOP_COUNTER_METRIC = new NoopCounterMetric();
10468
10312
  var NOOP_GAUGE_METRIC = new NoopGaugeMetric();
@@ -10472,144 +10316,98 @@ var NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();
10472
10316
  var NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();
10473
10317
  var NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric();
10474
10318
 
10475
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/metrics/Metric.js
10319
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics/Metric.js
10476
10320
  var ValueType;
10477
10321
  (function(ValueType2) {
10478
10322
  ValueType2[ValueType2["INT"] = 0] = "INT";
10479
10323
  ValueType2[ValueType2["DOUBLE"] = 1] = "DOUBLE";
10480
10324
  })(ValueType || (ValueType = {}));
10481
10325
 
10482
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js
10483
- var __read3 = function(o, n) {
10484
- var m = typeof Symbol === "function" && o[Symbol.iterator];
10485
- if (!m) return o;
10486
- var i = m.call(o), r, ar = [], e;
10487
- try {
10488
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
10489
- } catch (error) {
10490
- e = { error };
10491
- } finally {
10492
- try {
10493
- if (r && !r.done && (m = i["return"])) m.call(i);
10494
- } finally {
10495
- if (e) throw e.error;
10496
- }
10326
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js
10327
+ var NoopContextManager = class {
10328
+ active() {
10329
+ return ROOT_CONTEXT;
10497
10330
  }
10498
- return ar;
10499
- };
10500
- var __spreadArray3 = function(to, from, pack) {
10501
- if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
10502
- if (ar || !(i in from)) {
10503
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
10504
- ar[i] = from[i];
10505
- }
10331
+ with(_context, fn, thisArg, ...args) {
10332
+ return fn.call(thisArg, ...args);
10506
10333
  }
10507
- return to.concat(ar || Array.prototype.slice.call(from));
10508
- };
10509
- var NoopContextManager = (
10510
- /** @class */
10511
- function() {
10512
- function NoopContextManager2() {
10513
- }
10514
- NoopContextManager2.prototype.active = function() {
10515
- return ROOT_CONTEXT;
10516
- };
10517
- NoopContextManager2.prototype.with = function(_context, fn, thisArg) {
10518
- var args = [];
10519
- for (var _i = 3; _i < arguments.length; _i++) {
10520
- args[_i - 3] = arguments[_i];
10521
- }
10522
- return fn.call.apply(fn, __spreadArray3([thisArg], __read3(args), false));
10523
- };
10524
- NoopContextManager2.prototype.bind = function(_context, target) {
10525
- return target;
10526
- };
10527
- NoopContextManager2.prototype.enable = function() {
10528
- return this;
10529
- };
10530
- NoopContextManager2.prototype.disable = function() {
10531
- return this;
10532
- };
10533
- return NoopContextManager2;
10534
- }()
10535
- );
10536
-
10537
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/context.js
10538
- var __read4 = function(o, n) {
10539
- var m = typeof Symbol === "function" && o[Symbol.iterator];
10540
- if (!m) return o;
10541
- var i = m.call(o), r, ar = [], e;
10542
- try {
10543
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
10544
- } catch (error) {
10545
- e = { error };
10546
- } finally {
10547
- try {
10548
- if (r && !r.done && (m = i["return"])) m.call(i);
10549
- } finally {
10550
- if (e) throw e.error;
10551
- }
10334
+ bind(_context, target) {
10335
+ return target;
10552
10336
  }
10553
- return ar;
10554
- };
10555
- var __spreadArray4 = function(to, from, pack) {
10556
- if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
10557
- if (ar || !(i in from)) {
10558
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
10559
- ar[i] = from[i];
10560
- }
10337
+ enable() {
10338
+ return this;
10339
+ }
10340
+ disable() {
10341
+ return this;
10561
10342
  }
10562
- return to.concat(ar || Array.prototype.slice.call(from));
10563
10343
  };
10344
+
10345
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/context.js
10564
10346
  var API_NAME2 = "context";
10565
10347
  var NOOP_CONTEXT_MANAGER = new NoopContextManager();
10566
- var ContextAPI = (
10567
- /** @class */
10568
- function() {
10569
- function ContextAPI2() {
10348
+ var ContextAPI = class _ContextAPI {
10349
+ /** Empty private constructor prevents end users from constructing a new instance of the API */
10350
+ constructor() {
10351
+ }
10352
+ /** Get the singleton instance of the Context API */
10353
+ static getInstance() {
10354
+ if (!this._instance) {
10355
+ this._instance = new _ContextAPI();
10570
10356
  }
10571
- ContextAPI2.getInstance = function() {
10572
- if (!this._instance) {
10573
- this._instance = new ContextAPI2();
10574
- }
10575
- return this._instance;
10576
- };
10577
- ContextAPI2.prototype.setGlobalContextManager = function(contextManager) {
10578
- return registerGlobal(API_NAME2, contextManager, DiagAPI.instance());
10579
- };
10580
- ContextAPI2.prototype.active = function() {
10581
- return this._getContextManager().active();
10582
- };
10583
- ContextAPI2.prototype.with = function(context2, fn, thisArg) {
10584
- var _a;
10585
- var args = [];
10586
- for (var _i = 3; _i < arguments.length; _i++) {
10587
- args[_i - 3] = arguments[_i];
10588
- }
10589
- return (_a = this._getContextManager()).with.apply(_a, __spreadArray4([context2, fn, thisArg], __read4(args), false));
10590
- };
10591
- ContextAPI2.prototype.bind = function(context2, target) {
10592
- return this._getContextManager().bind(context2, target);
10593
- };
10594
- ContextAPI2.prototype._getContextManager = function() {
10595
- return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER;
10596
- };
10597
- ContextAPI2.prototype.disable = function() {
10598
- this._getContextManager().disable();
10599
- unregisterGlobal(API_NAME2, DiagAPI.instance());
10600
- };
10601
- return ContextAPI2;
10602
- }()
10603
- );
10357
+ return this._instance;
10358
+ }
10359
+ /**
10360
+ * Set the current context manager.
10361
+ *
10362
+ * @returns true if the context manager was successfully registered, else false
10363
+ */
10364
+ setGlobalContextManager(contextManager) {
10365
+ return registerGlobal(API_NAME2, contextManager, DiagAPI.instance());
10366
+ }
10367
+ /**
10368
+ * Get the currently active context
10369
+ */
10370
+ active() {
10371
+ return this._getContextManager().active();
10372
+ }
10373
+ /**
10374
+ * Execute a function with an active context
10375
+ *
10376
+ * @param context context to be active during function execution
10377
+ * @param fn function to execute in a context
10378
+ * @param thisArg optional receiver to be used for calling fn
10379
+ * @param args optional arguments forwarded to fn
10380
+ */
10381
+ with(context2, fn, thisArg, ...args) {
10382
+ return this._getContextManager().with(context2, fn, thisArg, ...args);
10383
+ }
10384
+ /**
10385
+ * Bind a context to a target function or event emitter
10386
+ *
10387
+ * @param context context to bind to the event emitter or function. Defaults to the currently active context
10388
+ * @param target function or event emitter to bind
10389
+ */
10390
+ bind(context2, target) {
10391
+ return this._getContextManager().bind(context2, target);
10392
+ }
10393
+ _getContextManager() {
10394
+ return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER;
10395
+ }
10396
+ /** Disable and remove the global context manager */
10397
+ disable() {
10398
+ this._getContextManager().disable();
10399
+ unregisterGlobal(API_NAME2, DiagAPI.instance());
10400
+ }
10401
+ };
10604
10402
 
10605
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js
10403
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js
10606
10404
  var TraceFlags;
10607
10405
  (function(TraceFlags2) {
10608
10406
  TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE";
10609
10407
  TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED";
10610
10408
  })(TraceFlags || (TraceFlags = {}));
10611
10409
 
10612
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js
10410
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js
10613
10411
  var INVALID_SPANID = "0000000000000000";
10614
10412
  var INVALID_TRACEID = "00000000000000000000000000000000";
10615
10413
  var INVALID_SPAN_CONTEXT = {
@@ -10618,52 +10416,54 @@ var INVALID_SPAN_CONTEXT = {
10618
10416
  traceFlags: TraceFlags.NONE
10619
10417
  };
10620
10418
 
10621
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js
10622
- var NonRecordingSpan = (
10623
- /** @class */
10624
- function() {
10625
- function NonRecordingSpan2(_spanContext) {
10626
- if (_spanContext === void 0) {
10627
- _spanContext = INVALID_SPAN_CONTEXT;
10628
- }
10629
- this._spanContext = _spanContext;
10630
- }
10631
- NonRecordingSpan2.prototype.spanContext = function() {
10632
- return this._spanContext;
10633
- };
10634
- NonRecordingSpan2.prototype.setAttribute = function(_key, _value) {
10635
- return this;
10636
- };
10637
- NonRecordingSpan2.prototype.setAttributes = function(_attributes) {
10638
- return this;
10639
- };
10640
- NonRecordingSpan2.prototype.addEvent = function(_name, _attributes) {
10641
- return this;
10642
- };
10643
- NonRecordingSpan2.prototype.addLink = function(_link) {
10644
- return this;
10645
- };
10646
- NonRecordingSpan2.prototype.addLinks = function(_links) {
10647
- return this;
10648
- };
10649
- NonRecordingSpan2.prototype.setStatus = function(_status) {
10650
- return this;
10651
- };
10652
- NonRecordingSpan2.prototype.updateName = function(_name) {
10653
- return this;
10654
- };
10655
- NonRecordingSpan2.prototype.end = function(_endTime) {
10656
- };
10657
- NonRecordingSpan2.prototype.isRecording = function() {
10658
- return false;
10659
- };
10660
- NonRecordingSpan2.prototype.recordException = function(_exception, _time) {
10661
- };
10662
- return NonRecordingSpan2;
10663
- }()
10664
- );
10419
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js
10420
+ var NonRecordingSpan = class {
10421
+ constructor(spanContext = INVALID_SPAN_CONTEXT) {
10422
+ this._spanContext = spanContext;
10423
+ }
10424
+ // Returns a SpanContext.
10425
+ spanContext() {
10426
+ return this._spanContext;
10427
+ }
10428
+ // By default does nothing
10429
+ setAttribute(_key, _value) {
10430
+ return this;
10431
+ }
10432
+ // By default does nothing
10433
+ setAttributes(_attributes) {
10434
+ return this;
10435
+ }
10436
+ // By default does nothing
10437
+ addEvent(_name, _attributes) {
10438
+ return this;
10439
+ }
10440
+ addLink(_link) {
10441
+ return this;
10442
+ }
10443
+ addLinks(_links) {
10444
+ return this;
10445
+ }
10446
+ // By default does nothing
10447
+ setStatus(_status) {
10448
+ return this;
10449
+ }
10450
+ // By default does nothing
10451
+ updateName(_name) {
10452
+ return this;
10453
+ }
10454
+ // By default does nothing
10455
+ end(_endTime) {
10456
+ }
10457
+ // isRecording always returns false for NonRecordingSpan.
10458
+ isRecording() {
10459
+ return false;
10460
+ }
10461
+ // By default does nothing
10462
+ recordException(_exception, _time) {
10463
+ }
10464
+ };
10665
10465
 
10666
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js
10466
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js
10667
10467
  var SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN");
10668
10468
  function getSpan(context2) {
10669
10469
  return context2.getValue(SPAN_KEY) || void 0;
@@ -10685,14 +10485,126 @@ function getSpanContext(context2) {
10685
10485
  return (_a = getSpan(context2)) === null || _a === void 0 ? void 0 : _a.spanContext();
10686
10486
  }
10687
10487
 
10688
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js
10689
- var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
10690
- var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
10488
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js
10489
+ var isHex = new Uint8Array([
10490
+ 0,
10491
+ 0,
10492
+ 0,
10493
+ 0,
10494
+ 0,
10495
+ 0,
10496
+ 0,
10497
+ 0,
10498
+ 0,
10499
+ 0,
10500
+ 0,
10501
+ 0,
10502
+ 0,
10503
+ 0,
10504
+ 0,
10505
+ 0,
10506
+ 0,
10507
+ 0,
10508
+ 0,
10509
+ 0,
10510
+ 0,
10511
+ 0,
10512
+ 0,
10513
+ 0,
10514
+ 0,
10515
+ 0,
10516
+ 0,
10517
+ 0,
10518
+ 0,
10519
+ 0,
10520
+ 0,
10521
+ 0,
10522
+ 0,
10523
+ 0,
10524
+ 0,
10525
+ 0,
10526
+ 0,
10527
+ 0,
10528
+ 0,
10529
+ 0,
10530
+ 0,
10531
+ 0,
10532
+ 0,
10533
+ 0,
10534
+ 0,
10535
+ 0,
10536
+ 0,
10537
+ 0,
10538
+ 1,
10539
+ 1,
10540
+ 1,
10541
+ 1,
10542
+ 1,
10543
+ 1,
10544
+ 1,
10545
+ 1,
10546
+ 1,
10547
+ 1,
10548
+ 0,
10549
+ 0,
10550
+ 0,
10551
+ 0,
10552
+ 0,
10553
+ 0,
10554
+ 0,
10555
+ 1,
10556
+ 1,
10557
+ 1,
10558
+ 1,
10559
+ 1,
10560
+ 1,
10561
+ 0,
10562
+ 0,
10563
+ 0,
10564
+ 0,
10565
+ 0,
10566
+ 0,
10567
+ 0,
10568
+ 0,
10569
+ 0,
10570
+ 0,
10571
+ 0,
10572
+ 0,
10573
+ 0,
10574
+ 0,
10575
+ 0,
10576
+ 0,
10577
+ 0,
10578
+ 0,
10579
+ 0,
10580
+ 0,
10581
+ 0,
10582
+ 0,
10583
+ 0,
10584
+ 0,
10585
+ 0,
10586
+ 0,
10587
+ 1,
10588
+ 1,
10589
+ 1,
10590
+ 1,
10591
+ 1,
10592
+ 1
10593
+ ]);
10594
+ function isValidHex(id, length) {
10595
+ if (typeof id !== "string" || id.length !== length)
10596
+ return false;
10597
+ let r = 0;
10598
+ for (let i = 0; i < id.length; i += 4) {
10599
+ r += (isHex[id.charCodeAt(i)] | 0) + (isHex[id.charCodeAt(i + 1)] | 0) + (isHex[id.charCodeAt(i + 2)] | 0) + (isHex[id.charCodeAt(i + 3)] | 0);
10600
+ }
10601
+ return r === length;
10602
+ }
10691
10603
  function isValidTraceId(traceId) {
10692
- return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;
10604
+ return isValidHex(traceId, 32) && traceId !== INVALID_TRACEID;
10693
10605
  }
10694
10606
  function isValidSpanId(spanId) {
10695
- return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;
10607
+ return isValidHex(spanId, 16) && spanId !== INVALID_SPANID;
10696
10608
  }
10697
10609
  function isSpanContextValid(spanContext) {
10698
10610
  return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
@@ -10701,129 +10613,115 @@ function wrapSpanContext(spanContext) {
10701
10613
  return new NonRecordingSpan(spanContext);
10702
10614
  }
10703
10615
 
10704
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js
10616
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js
10705
10617
  var contextApi = ContextAPI.getInstance();
10706
- var NoopTracer = (
10707
- /** @class */
10708
- function() {
10709
- function NoopTracer2() {
10710
- }
10711
- NoopTracer2.prototype.startSpan = function(name, options, context2) {
10712
- if (context2 === void 0) {
10713
- context2 = contextApi.active();
10714
- }
10715
- var root = Boolean(options === null || options === void 0 ? void 0 : options.root);
10716
- if (root) {
10717
- return new NonRecordingSpan();
10718
- }
10719
- var parentFromContext = context2 && getSpanContext(context2);
10720
- if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) {
10721
- return new NonRecordingSpan(parentFromContext);
10722
- } else {
10723
- return new NonRecordingSpan();
10724
- }
10725
- };
10726
- NoopTracer2.prototype.startActiveSpan = function(name, arg2, arg3, arg4) {
10727
- var opts;
10728
- var ctx;
10729
- var fn;
10730
- if (arguments.length < 2) {
10731
- return;
10732
- } else if (arguments.length === 2) {
10733
- fn = arg2;
10734
- } else if (arguments.length === 3) {
10735
- opts = arg2;
10736
- fn = arg3;
10737
- } else {
10738
- opts = arg2;
10739
- ctx = arg3;
10740
- fn = arg4;
10741
- }
10742
- var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
10743
- var span = this.startSpan(name, opts, parentContext);
10744
- var contextWithSpanSet = setSpan(parentContext, span);
10745
- return contextApi.with(contextWithSpanSet, fn, void 0, span);
10746
- };
10747
- return NoopTracer2;
10748
- }()
10749
- );
10618
+ var NoopTracer = class {
10619
+ // startSpan starts a noop span.
10620
+ startSpan(name, options, context2 = contextApi.active()) {
10621
+ const root = Boolean(options === null || options === void 0 ? void 0 : options.root);
10622
+ if (root) {
10623
+ return new NonRecordingSpan();
10624
+ }
10625
+ const parentFromContext = context2 && getSpanContext(context2);
10626
+ if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) {
10627
+ return new NonRecordingSpan(parentFromContext);
10628
+ } else {
10629
+ return new NonRecordingSpan();
10630
+ }
10631
+ }
10632
+ startActiveSpan(name, arg2, arg3, arg4) {
10633
+ let opts;
10634
+ let ctx;
10635
+ let fn;
10636
+ if (arguments.length < 2) {
10637
+ return;
10638
+ } else if (arguments.length === 2) {
10639
+ fn = arg2;
10640
+ } else if (arguments.length === 3) {
10641
+ opts = arg2;
10642
+ fn = arg3;
10643
+ } else {
10644
+ opts = arg2;
10645
+ ctx = arg3;
10646
+ fn = arg4;
10647
+ }
10648
+ const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
10649
+ const span = this.startSpan(name, opts, parentContext);
10650
+ const contextWithSpanSet = setSpan(parentContext, span);
10651
+ return contextApi.with(contextWithSpanSet, fn, void 0, span);
10652
+ }
10653
+ };
10750
10654
  function isSpanContext(spanContext) {
10751
- return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number";
10655
+ return spanContext !== null && typeof spanContext === "object" && "spanId" in spanContext && typeof spanContext["spanId"] === "string" && "traceId" in spanContext && typeof spanContext["traceId"] === "string" && "traceFlags" in spanContext && typeof spanContext["traceFlags"] === "number";
10752
10656
  }
10753
10657
 
10754
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js
10658
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js
10755
10659
  var NOOP_TRACER = new NoopTracer();
10756
- var ProxyTracer = (
10757
- /** @class */
10758
- function() {
10759
- function ProxyTracer2(_provider, name, version, options) {
10760
- this._provider = _provider;
10761
- this.name = name;
10762
- this.version = version;
10763
- this.options = options;
10764
- }
10765
- ProxyTracer2.prototype.startSpan = function(name, options, context2) {
10766
- return this._getTracer().startSpan(name, options, context2);
10767
- };
10768
- ProxyTracer2.prototype.startActiveSpan = function(_name, _options, _context, _fn) {
10769
- var tracer = this._getTracer();
10770
- return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
10771
- };
10772
- ProxyTracer2.prototype._getTracer = function() {
10773
- if (this._delegate) {
10774
- return this._delegate;
10775
- }
10776
- var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
10777
- if (!tracer) {
10778
- return NOOP_TRACER;
10779
- }
10780
- this._delegate = tracer;
10660
+ var ProxyTracer = class {
10661
+ constructor(provider, name, version, options) {
10662
+ this._provider = provider;
10663
+ this.name = name;
10664
+ this.version = version;
10665
+ this.options = options;
10666
+ }
10667
+ startSpan(name, options, context2) {
10668
+ return this._getTracer().startSpan(name, options, context2);
10669
+ }
10670
+ startActiveSpan(_name, _options, _context, _fn) {
10671
+ const tracer = this._getTracer();
10672
+ return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
10673
+ }
10674
+ /**
10675
+ * Try to get a tracer from the proxy tracer provider.
10676
+ * If the proxy tracer provider has no delegate, return a noop tracer.
10677
+ */
10678
+ _getTracer() {
10679
+ if (this._delegate) {
10781
10680
  return this._delegate;
10782
- };
10783
- return ProxyTracer2;
10784
- }()
10785
- );
10786
-
10787
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js
10788
- var NoopTracerProvider = (
10789
- /** @class */
10790
- function() {
10791
- function NoopTracerProvider2() {
10792
- }
10793
- NoopTracerProvider2.prototype.getTracer = function(_name, _version, _options) {
10794
- return new NoopTracer();
10795
- };
10796
- return NoopTracerProvider2;
10797
- }()
10798
- );
10799
-
10800
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js
10801
- var NOOP_TRACER_PROVIDER = new NoopTracerProvider();
10802
- var ProxyTracerProvider = (
10803
- /** @class */
10804
- function() {
10805
- function ProxyTracerProvider2() {
10806
10681
  }
10807
- ProxyTracerProvider2.prototype.getTracer = function(name, version, options) {
10808
- var _a;
10809
- return (_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options);
10810
- };
10811
- ProxyTracerProvider2.prototype.getDelegate = function() {
10812
- var _a;
10813
- return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;
10814
- };
10815
- ProxyTracerProvider2.prototype.setDelegate = function(delegate) {
10816
- this._delegate = delegate;
10817
- };
10818
- ProxyTracerProvider2.prototype.getDelegateTracer = function(name, version, options) {
10819
- var _a;
10820
- return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);
10821
- };
10822
- return ProxyTracerProvider2;
10823
- }()
10824
- );
10682
+ const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
10683
+ if (!tracer) {
10684
+ return NOOP_TRACER;
10685
+ }
10686
+ this._delegate = tracer;
10687
+ return this._delegate;
10688
+ }
10689
+ };
10690
+
10691
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js
10692
+ var NoopTracerProvider = class {
10693
+ getTracer(_name, _version, _options) {
10694
+ return new NoopTracer();
10695
+ }
10696
+ };
10697
+
10698
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js
10699
+ var NOOP_TRACER_PROVIDER = new NoopTracerProvider();
10700
+ var ProxyTracerProvider = class {
10701
+ /**
10702
+ * Get a {@link ProxyTracer}
10703
+ */
10704
+ getTracer(name, version, options) {
10705
+ var _a;
10706
+ return (_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options);
10707
+ }
10708
+ getDelegate() {
10709
+ var _a;
10710
+ return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;
10711
+ }
10712
+ /**
10713
+ * Set the delegate tracer provider
10714
+ */
10715
+ setDelegate(delegate) {
10716
+ this._delegate = delegate;
10717
+ }
10718
+ getDelegateTracer(name, version, options) {
10719
+ var _a;
10720
+ return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);
10721
+ }
10722
+ };
10825
10723
 
10826
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js
10724
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js
10827
10725
  var SpanKind;
10828
10726
  (function(SpanKind2) {
10829
10727
  SpanKind2[SpanKind2["INTERNAL"] = 0] = "INTERNAL";
@@ -10833,7 +10731,7 @@ var SpanKind;
10833
10731
  SpanKind2[SpanKind2["CONSUMER"] = 4] = "CONSUMER";
10834
10732
  })(SpanKind || (SpanKind = {}));
10835
10733
 
10836
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js
10734
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/status.js
10837
10735
  var SpanStatusCode;
10838
10736
  (function(SpanStatusCode2) {
10839
10737
  SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
@@ -10841,99 +10739,112 @@ var SpanStatusCode;
10841
10739
  SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
10842
10740
  })(SpanStatusCode || (SpanStatusCode = {}));
10843
10741
 
10844
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js
10742
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context-api.js
10845
10743
  var context = ContextAPI.getInstance();
10846
10744
 
10847
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js
10848
- var NoopMeterProvider = (
10849
- /** @class */
10850
- function() {
10851
- function NoopMeterProvider2() {
10852
- }
10853
- NoopMeterProvider2.prototype.getMeter = function(_name, _version, _options) {
10854
- return NOOP_METER;
10855
- };
10856
- return NoopMeterProvider2;
10857
- }()
10858
- );
10745
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js
10746
+ var NoopMeterProvider = class {
10747
+ getMeter(_name, _version, _options) {
10748
+ return NOOP_METER;
10749
+ }
10750
+ };
10859
10751
  var NOOP_METER_PROVIDER = new NoopMeterProvider();
10860
10752
 
10861
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/metrics.js
10753
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/metrics.js
10862
10754
  var API_NAME3 = "metrics";
10863
- var MetricsAPI = (
10864
- /** @class */
10865
- function() {
10866
- function MetricsAPI2() {
10755
+ var MetricsAPI = class _MetricsAPI {
10756
+ /** Empty private constructor prevents end users from constructing a new instance of the API */
10757
+ constructor() {
10758
+ }
10759
+ /** Get the singleton instance of the Metrics API */
10760
+ static getInstance() {
10761
+ if (!this._instance) {
10762
+ this._instance = new _MetricsAPI();
10867
10763
  }
10868
- MetricsAPI2.getInstance = function() {
10869
- if (!this._instance) {
10870
- this._instance = new MetricsAPI2();
10871
- }
10872
- return this._instance;
10873
- };
10874
- MetricsAPI2.prototype.setGlobalMeterProvider = function(provider) {
10875
- return registerGlobal(API_NAME3, provider, DiagAPI.instance());
10876
- };
10877
- MetricsAPI2.prototype.getMeterProvider = function() {
10878
- return getGlobal(API_NAME3) || NOOP_METER_PROVIDER;
10879
- };
10880
- MetricsAPI2.prototype.getMeter = function(name, version, options) {
10881
- return this.getMeterProvider().getMeter(name, version, options);
10882
- };
10883
- MetricsAPI2.prototype.disable = function() {
10884
- unregisterGlobal(API_NAME3, DiagAPI.instance());
10885
- };
10886
- return MetricsAPI2;
10887
- }()
10888
- );
10764
+ return this._instance;
10765
+ }
10766
+ /**
10767
+ * Set the current global meter provider.
10768
+ * Returns true if the meter provider was successfully registered, else false.
10769
+ */
10770
+ setGlobalMeterProvider(provider) {
10771
+ return registerGlobal(API_NAME3, provider, DiagAPI.instance());
10772
+ }
10773
+ /**
10774
+ * Returns the global meter provider.
10775
+ */
10776
+ getMeterProvider() {
10777
+ return getGlobal(API_NAME3) || NOOP_METER_PROVIDER;
10778
+ }
10779
+ /**
10780
+ * Returns a meter from the global meter provider.
10781
+ */
10782
+ getMeter(name, version, options) {
10783
+ return this.getMeterProvider().getMeter(name, version, options);
10784
+ }
10785
+ /** Remove the global meter provider */
10786
+ disable() {
10787
+ unregisterGlobal(API_NAME3, DiagAPI.instance());
10788
+ }
10789
+ };
10889
10790
 
10890
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/metrics-api.js
10791
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics-api.js
10891
10792
  var metrics = MetricsAPI.getInstance();
10892
10793
 
10893
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/trace.js
10794
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/trace.js
10894
10795
  var API_NAME4 = "trace";
10895
- var TraceAPI = (
10896
- /** @class */
10897
- function() {
10898
- function TraceAPI2() {
10899
- this._proxyTracerProvider = new ProxyTracerProvider();
10900
- this.wrapSpanContext = wrapSpanContext;
10901
- this.isSpanContextValid = isSpanContextValid;
10902
- this.deleteSpan = deleteSpan;
10903
- this.getSpan = getSpan;
10904
- this.getActiveSpan = getActiveSpan;
10905
- this.getSpanContext = getSpanContext;
10906
- this.setSpan = setSpan;
10907
- this.setSpanContext = setSpanContext;
10908
- }
10909
- TraceAPI2.getInstance = function() {
10910
- if (!this._instance) {
10911
- this._instance = new TraceAPI2();
10912
- }
10913
- return this._instance;
10914
- };
10915
- TraceAPI2.prototype.setGlobalTracerProvider = function(provider) {
10916
- var success = registerGlobal(API_NAME4, this._proxyTracerProvider, DiagAPI.instance());
10917
- if (success) {
10918
- this._proxyTracerProvider.setDelegate(provider);
10919
- }
10920
- return success;
10921
- };
10922
- TraceAPI2.prototype.getTracerProvider = function() {
10923
- return getGlobal(API_NAME4) || this._proxyTracerProvider;
10924
- };
10925
- TraceAPI2.prototype.getTracer = function(name, version) {
10926
- return this.getTracerProvider().getTracer(name, version);
10927
- };
10928
- TraceAPI2.prototype.disable = function() {
10929
- unregisterGlobal(API_NAME4, DiagAPI.instance());
10930
- this._proxyTracerProvider = new ProxyTracerProvider();
10931
- };
10932
- return TraceAPI2;
10933
- }()
10934
- );
10796
+ var TraceAPI = class _TraceAPI {
10797
+ /** Empty private constructor prevents end users from constructing a new instance of the API */
10798
+ constructor() {
10799
+ this._proxyTracerProvider = new ProxyTracerProvider();
10800
+ this.wrapSpanContext = wrapSpanContext;
10801
+ this.isSpanContextValid = isSpanContextValid;
10802
+ this.deleteSpan = deleteSpan;
10803
+ this.getSpan = getSpan;
10804
+ this.getActiveSpan = getActiveSpan;
10805
+ this.getSpanContext = getSpanContext;
10806
+ this.setSpan = setSpan;
10807
+ this.setSpanContext = setSpanContext;
10808
+ }
10809
+ /** Get the singleton instance of the Trace API */
10810
+ static getInstance() {
10811
+ if (!this._instance) {
10812
+ this._instance = new _TraceAPI();
10813
+ }
10814
+ return this._instance;
10815
+ }
10816
+ /**
10817
+ * Set the current global tracer.
10818
+ *
10819
+ * @returns true if the tracer provider was successfully registered, else false
10820
+ */
10821
+ setGlobalTracerProvider(provider) {
10822
+ const success = registerGlobal(API_NAME4, this._proxyTracerProvider, DiagAPI.instance());
10823
+ if (success) {
10824
+ this._proxyTracerProvider.setDelegate(provider);
10825
+ }
10826
+ return success;
10827
+ }
10828
+ /**
10829
+ * Returns the global tracer provider.
10830
+ */
10831
+ getTracerProvider() {
10832
+ return getGlobal(API_NAME4) || this._proxyTracerProvider;
10833
+ }
10834
+ /**
10835
+ * Returns a tracer from the global tracer provider.
10836
+ */
10837
+ getTracer(name, version) {
10838
+ return this.getTracerProvider().getTracer(name, version);
10839
+ }
10840
+ /** Remove the global tracer provider */
10841
+ disable() {
10842
+ unregisterGlobal(API_NAME4, DiagAPI.instance());
10843
+ this._proxyTracerProvider = new ProxyTracerProvider();
10844
+ }
10845
+ };
10935
10846
 
10936
- // ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js
10847
+ // ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace-api.js
10937
10848
  var trace = TraceAPI.getInstance();
10938
10849
  function getTracer(name) {
10939
10850
  return trace.getTracer(name);
@@ -16382,6 +16293,7 @@ var stringToDate = zod.z.string().transform((v, ctx) => {
16382
16293
  }
16383
16294
  return d;
16384
16295
  });
16296
+ var stringToBool = zod.z.union([zod.z.literal("true"), zod.z.literal("false")]).transform((v) => v === "true");
16385
16297
  var stringToError = zod.z.string().transform((v, ctx) => {
16386
16298
  try {
16387
16299
  return BufferEntryError.parse(JSON.parse(v));
@@ -16398,6 +16310,27 @@ var BufferEntrySchema = zod.z.object({
16398
16310
  status: BufferEntryStatus,
16399
16311
  attempts: stringToInt,
16400
16312
  createdAt: stringToDate,
16313
+ // Microsecond epoch of accept time, kept as a hash field for dwell
16314
+ // metrics. Not a queue sort key (the queue is a FIFO LIST). Defaulted
16315
+ // so an entry written by an accept Lua predating this field — or one
16316
+ // surviving across the deploy that introduced it — still parses instead
16317
+ // of being silently dropped on pop.
16318
+ createdAtMicros: stringToInt.default("0"),
16319
+ // Drainer-ack flag: `true` once the drainer has materialised this run
16320
+ // into PG. The hash persists for a short grace TTL after ack so direct
16321
+ // reads (retrieve, trace, etc.) still resolve while PG replica lag
16322
+ // settles. Absent on pre-ack entries.
16323
+ materialised: stringToBool.default("false"),
16324
+ // Denormalised pointer to the Redis idempotency lookup key (set when
16325
+ // the run was accepted with an idempotency key, empty otherwise). The
16326
+ // ack Lua reads this to DEL the lookup atomically with marking the
16327
+ // entry materialised.
16328
+ idempotencyLookupKey: zod.z.string().optional().default(""),
16329
+ // Optimistic-lock counter for the snapshot's `metadata` field.
16330
+ // Incremented atomically by the CAS metadata Lua. Matches the
16331
+ // semantic of `TaskRun.metadataVersion` on the PG side (which the
16332
+ // UpdateMetadataService uses for the same retry-on-conflict pattern).
16333
+ metadataVersion: stringToInt.default("0"),
16401
16334
  lastError: stringToError.optional()
16402
16335
  });
16403
16336
  function serialiseSnapshot(snapshot) {
@@ -16408,21 +16341,42 @@ function deserialiseSnapshot(serialised) {
16408
16341
  }
16409
16342
 
16410
16343
  // src/mollifier/buffer.ts
16344
+ var DEFAULT_ACK_GRACE_TTL_SECONDS = 30;
16345
+ var DEFAULT_RECONNECT_STEP_MS = 50;
16346
+ var DEFAULT_RECONNECT_MAX_MS = 1e3;
16347
+ var DEFAULT_MAX_RETRIES_PER_REQUEST = 20;
16348
+ var DRAINING_SET_KEY = "mollifier:draining";
16349
+ function mollifierReconnectDelayMs(times, random = Math.random, stepMs = DEFAULT_RECONNECT_STEP_MS, maxMs = DEFAULT_RECONNECT_MAX_MS) {
16350
+ const base = Math.min(times * stepMs, maxMs);
16351
+ const half = Math.floor(base / 2);
16352
+ return half + Math.round(random() * (base - half));
16353
+ }
16354
+ function encodeKeyPart(value) {
16355
+ return Buffer.from(value, "utf8").toString("base64url");
16356
+ }
16357
+ function idempotencyLookupKeyFor(input) {
16358
+ return `mollifier:idempotency:${encodeKeyPart(input.envId)}:${encodeKeyPart(input.taskIdentifier)}:${encodeKeyPart(input.idempotencyKey)}`;
16359
+ }
16360
+ var PENDING_PREFIX = "pending:";
16361
+ function makeIdempotencyClaimKey(input) {
16362
+ return `mollifier:claim:${encodeKeyPart(input.envId)}:${encodeKeyPart(input.taskIdentifier)}:${encodeKeyPart(input.idempotencyKey)}`;
16363
+ }
16411
16364
  var MollifierBuffer = class {
16412
16365
  redis;
16413
- entryTtlSeconds;
16414
16366
  logger;
16367
+ ackGraceTtlSeconds;
16415
16368
  constructor(options) {
16416
- this.entryTtlSeconds = options.entryTtlSeconds;
16417
16369
  this.logger = options.logger ?? new logger$1.Logger("MollifierBuffer", "debug");
16370
+ this.ackGraceTtlSeconds = options.ackGraceTtlSeconds ?? DEFAULT_ACK_GRACE_TTL_SECONDS;
16371
+ const reconnectStepMs = options.reconnectStepMs ?? DEFAULT_RECONNECT_STEP_MS;
16372
+ const reconnectMaxMs = options.reconnectMaxMs ?? DEFAULT_RECONNECT_MAX_MS;
16418
16373
  this.redis = createRedisClient(
16419
16374
  {
16420
16375
  ...options.redisOptions,
16421
16376
  retryStrategy(times) {
16422
- const delay = Math.min(times * 50, 1e3);
16423
- return delay;
16377
+ return mollifierReconnectDelayMs(times, Math.random, reconnectStepMs, reconnectMaxMs);
16424
16378
  },
16425
- maxRetriesPerRequest: 20
16379
+ maxRetriesPerRequest: options.maxRetriesPerRequest ?? DEFAULT_MAX_RETRIES_PER_REQUEST
16426
16380
  },
16427
16381
  {
16428
16382
  onError: (error) => {
@@ -16432,14 +16386,26 @@ var MollifierBuffer = class {
16432
16386
  );
16433
16387
  this.#registerCommands();
16434
16388
  }
16435
- // Returns true if the entry was newly written; false if a duplicate runId
16436
- // was already buffered (idempotent no-op). Callers can use the boolean to
16437
- // record a duplicate-accept metric without affecting buffer state.
16389
+ // Three outcomes:
16390
+ // - { kind: "accepted" } entry was newly written.
16391
+ // - { kind: "duplicate_run_id" } runId was already buffered (idempotent
16392
+ // no-op, same semantic as the previous boolean-false return).
16393
+ // - { kind: "duplicate_idempotency", existingRunId } — the (env, task,
16394
+ // idempotencyKey) tuple was already bound to another buffered run.
16395
+ // The Lua's atomic SETNX is the race-winner; the second caller gets
16396
+ // the winner's runId so it can return that as the trigger response.
16438
16397
  async accept(input) {
16439
16398
  const entryKey = `mollifier:entries:${input.runId}`;
16440
16399
  const queueKey = `mollifier:queue:${input.envId}`;
16441
16400
  const orgsKey = "mollifier:orgs";
16442
- const createdAt = (/* @__PURE__ */ new Date()).toISOString();
16401
+ const nowMs = Date.now();
16402
+ const createdAt = new Date(nowMs).toISOString();
16403
+ const createdAtMicros = nowMs * 1e3;
16404
+ const idempotencyLookupKey = input.idempotencyKey && input.taskIdentifier ? idempotencyLookupKeyFor({
16405
+ envId: input.envId,
16406
+ taskIdentifier: input.taskIdentifier,
16407
+ idempotencyKey: input.idempotencyKey
16408
+ }) : "";
16443
16409
  const result = await this.redis.acceptMollifierEntry(
16444
16410
  entryKey,
16445
16411
  queueKey,
@@ -16449,10 +16415,16 @@ var MollifierBuffer = class {
16449
16415
  input.orgId,
16450
16416
  input.payload,
16451
16417
  createdAt,
16452
- String(this.entryTtlSeconds),
16453
- "mollifier:org-envs:"
16418
+ String(createdAtMicros),
16419
+ "mollifier:org-envs:",
16420
+ idempotencyLookupKey,
16421
+ "mollifier:entries:"
16454
16422
  );
16455
- return result === 1;
16423
+ if (typeof result === "string" && result.length > 0) {
16424
+ return { kind: "duplicate_idempotency", existingRunId: result };
16425
+ }
16426
+ if (result === 1) return { kind: "accepted" };
16427
+ return { kind: "duplicate_run_id" };
16456
16428
  }
16457
16429
  async pop(envId) {
16458
16430
  const queueKey = `mollifier:queue:${envId}`;
@@ -16461,6 +16433,7 @@ var MollifierBuffer = class {
16461
16433
  const encoded = await this.redis.popAndMarkDraining(
16462
16434
  queueKey,
16463
16435
  orgsKey,
16436
+ DRAINING_SET_KEY,
16464
16437
  entryPrefix,
16465
16438
  envId,
16466
16439
  "mollifier:org-envs:"
@@ -16506,28 +16479,277 @@ var MollifierBuffer = class {
16506
16479
  async listEnvsForOrg(orgId) {
16507
16480
  return this.redis.smembers(`mollifier:org-envs:${orgId}`);
16508
16481
  }
16482
+ // Read-only enumeration of currently-queued entries for a single env.
16483
+ // Used by the stale-sweep to compute per-entry dwell time, so order is
16484
+ // immaterial — LRANGE returns them newest-first (LPUSH head) but the
16485
+ // caller scans the whole window. Non-destructive: the drainer still
16486
+ // RPOPs these entries in FIFO order.
16487
+ //
16488
+ // The entry HGETALLs are issued in a single pipelined batch (one
16489
+ // network round-trip instead of N) — at the stale-sweep's default
16490
+ // maxCount=1000 the serial implementation cost ~1000 RTTs per env,
16491
+ // which dominated sweep wall-time at any meaningful backlog.
16492
+ //
16493
+ // A missing entry (empty hash) is skipped: the drainer's RPOP+DEL of
16494
+ // the entry hash can race our LRANGE→HGETALL window, so a runId on
16495
+ // the queue with no backing hash is an expected concurrency outcome,
16496
+ // not an error.
16497
+ async listEntriesForEnv(envId, maxCount) {
16498
+ if (maxCount <= 0) return [];
16499
+ const runIds = await this.redis.lrange(
16500
+ `mollifier:queue:${envId}`,
16501
+ 0,
16502
+ maxCount - 1
16503
+ );
16504
+ if (runIds.length === 0) return [];
16505
+ const pipeline = this.redis.pipeline();
16506
+ for (const runId of runIds) {
16507
+ pipeline.hgetall(`mollifier:entries:${runId}`);
16508
+ }
16509
+ const results = await pipeline.exec();
16510
+ if (!results) return [];
16511
+ const entries = [];
16512
+ for (let i = 0; i < results.length; i++) {
16513
+ const [err, raw] = results[i];
16514
+ if (err) {
16515
+ this.logger.error("MollifierBuffer.listEntriesForEnv: hgetall failed", {
16516
+ runId: runIds[i],
16517
+ err: err.message
16518
+ });
16519
+ continue;
16520
+ }
16521
+ if (!raw || Object.keys(raw).length === 0) continue;
16522
+ const parsed = BufferEntrySchema.safeParse(raw);
16523
+ if (!parsed.success) {
16524
+ this.logger.error("MollifierBuffer.listEntriesForEnv: invalid entry shape", {
16525
+ runId: runIds[i],
16526
+ errors: parsed.error.flatten()
16527
+ });
16528
+ continue;
16529
+ }
16530
+ entries.push(parsed.data);
16531
+ }
16532
+ return entries;
16533
+ }
16534
+ // Atomic snapshot mutation. Used by customer-mutation API endpoints
16535
+ // (tags, metadata-put, reschedule, cancel) when the run is still in
16536
+ // the buffer. Three outcomes:
16537
+ // - "applied_to_snapshot": entry was QUEUED + not materialised; the
16538
+ // drainer will read the patched payload on its next pop.
16539
+ // - "not_found": no entry hash exists for this runId — including a
16540
+ // FAILED entry, whose hash the drainer-terminal `fail` path DELs.
16541
+ // - "busy": entry is DRAINING or materialised. The API
16542
+ // wait-and-bounces through PG.
16543
+ // - "limit_exceeded": an `append_tags` patch carrying `maxTags` would
16544
+ // push the deduped tag count over the cap; nothing is written.
16545
+ async mutateSnapshot(runId, patch) {
16546
+ const result = await this.redis.mutateMollifierSnapshot(
16547
+ `mollifier:entries:${runId}`,
16548
+ JSON.stringify(patch)
16549
+ );
16550
+ if (result === "applied_to_snapshot" || result === "not_found" || result === "busy" || result === "limit_exceeded") {
16551
+ return result;
16552
+ }
16553
+ throw new Error(`MollifierBuffer.mutateSnapshot: unexpected Lua return value: ${result}`);
16554
+ }
16555
+ // Optimistic compare-and-swap on the snapshot's metadata. Caller reads
16556
+ // the current metadataVersion via getEntry, applies operations in JS via
16557
+ // `applyMetadataOperations`, then calls this with the new metadata + the
16558
+ // expected version. Lua refuses if the version has moved (caller retries
16559
+ // up to N times). Mirrors the PG-side `UpdateMetadataService` retry
16560
+ // loop so concurrent increment/append operations don't lose deltas.
16561
+ async casSetMetadata(input) {
16562
+ const entryKey = `mollifier:entries:${input.runId}`;
16563
+ const raw = await this.redis.casSetMollifierMetadata(
16564
+ entryKey,
16565
+ String(input.expectedVersion),
16566
+ input.newMetadata,
16567
+ input.newMetadataType
16568
+ );
16569
+ if (raw === "not_found") return { kind: "not_found" };
16570
+ if (raw === "busy") return { kind: "busy" };
16571
+ if (raw.startsWith("conflict:")) {
16572
+ return { kind: "version_conflict", currentVersion: Number(raw.slice("conflict:".length)) };
16573
+ }
16574
+ if (raw.startsWith("applied:")) {
16575
+ return { kind: "applied", newVersion: Number(raw.slice("applied:".length)) };
16576
+ }
16577
+ throw new Error(`MollifierBuffer.casSetMetadata: unexpected Lua return: ${raw}`);
16578
+ }
16579
+ // Atomic pre-gate claim on a (env, task, idempotencyKey) tuple. One
16580
+ // call across both PG and buffer paths serialises through this claim;
16581
+ // closes the race the buffer-side SETNX leaves open during the
16582
+ // gate-transition burst window.
16583
+ //
16584
+ // The caller supplies an opaque `token` (UUID) on claim. The same token
16585
+ // MUST be passed to `publishClaim` / `releaseClaim`, which compare-and-
16586
+ // act so a late release from a previous claimant whose TTL expired
16587
+ // cannot erase a new owner's claim.
16588
+ //
16589
+ // - "claimed": we now own the claim, the caller proceeds with the
16590
+ // trigger pipeline and must `publishClaim` on success or
16591
+ // `releaseClaim` on failure.
16592
+ // - "pending": another trigger owns the claim and hasn't published
16593
+ // yet; the caller should poll.
16594
+ // - "resolved": the claim already holds a runId; the caller can
16595
+ // return that runId as a cached hit.
16596
+ async claimIdempotency(input) {
16597
+ const claimKey = makeIdempotencyClaimKey(input);
16598
+ const raw = await this.redis.claimMollifierIdempotency(
16599
+ claimKey,
16600
+ `${PENDING_PREFIX}${input.token}`,
16601
+ PENDING_PREFIX,
16602
+ String(input.ttlSeconds)
16603
+ );
16604
+ if (raw === "claimed") return { kind: "claimed" };
16605
+ if (raw === "pending") return { kind: "pending" };
16606
+ if (raw.startsWith("resolved:")) {
16607
+ return { kind: "resolved", runId: raw.slice("resolved:".length) };
16608
+ }
16609
+ throw new Error(`MollifierBuffer.claimIdempotency: unexpected return: ${raw}`);
16610
+ }
16611
+ // Publish the winning runId to the claim so subsequent claimants /
16612
+ // waiters see "resolved". TTL bounded by the customer's
16613
+ // `idempotencyKeyExpiresAt` minus now; caller computes.
16614
+ //
16615
+ // Compare-and-set on the caller's token: if the current value isn't
16616
+ // our pending marker (TTL expired and another claimant moved in, or
16617
+ // someone else already published), the publish is a no-op. The caller
16618
+ // can treat any such case as "we lost the claim" and re-read.
16619
+ // Returns true if we published; false if the claim slot was no longer
16620
+ // ours.
16621
+ async publishClaim(input) {
16622
+ const claimKey = makeIdempotencyClaimKey(input);
16623
+ const result = await this.redis.publishMollifierClaim(
16624
+ claimKey,
16625
+ `${PENDING_PREFIX}${input.token}`,
16626
+ input.runId,
16627
+ String(input.ttlSeconds)
16628
+ );
16629
+ return result === 1;
16630
+ }
16631
+ // Release the claim on pipeline error so waiters can re-claim and
16632
+ // retry. Idempotent.
16633
+ //
16634
+ // Compare-and-delete on the caller's token: only deletes if the
16635
+ // current value is exactly our pending marker. A late release from a
16636
+ // claimant whose TTL expired is a no-op, so a new owner's claim is
16637
+ // never wiped by a slow predecessor.
16638
+ async releaseClaim(input) {
16639
+ const claimKey = makeIdempotencyClaimKey(input);
16640
+ await this.redis.releaseMollifierClaim(
16641
+ claimKey,
16642
+ `${PENDING_PREFIX}${input.token}`
16643
+ );
16644
+ }
16645
+ // Read the current claim value, used by the wait/poll loop on losers
16646
+ // to detect "pending" → "resolved" transitions and timeouts.
16647
+ async readClaim(input) {
16648
+ const claimKey = makeIdempotencyClaimKey(input);
16649
+ const value = await this.redis.get(claimKey);
16650
+ if (value === null) return null;
16651
+ if (value.startsWith(PENDING_PREFIX)) return { kind: "pending" };
16652
+ return { kind: "resolved", runId: value };
16653
+ }
16654
+ // Resolve a buffered run by (env, task, idempotencyKey) tuple. Used by
16655
+ // `IdempotencyKeyConcern.handleTriggerRequest` after the PG check
16656
+ // misses — same key may belong to a buffered run waiting to drain. The
16657
+ // lookup self-heals: if the lookup points at an entry hash that's gone,
16658
+ // we clear the lookup and report a miss. The clear is a compare-and-
16659
+ // delete (only if the key still holds the stale runId we observed) so a
16660
+ // fresh accept that rebinds the key between our GET and DEL isn't wiped.
16661
+ async lookupIdempotency(input) {
16662
+ const lookupKey = idempotencyLookupKeyFor(input);
16663
+ const runId = await this.redis.get(lookupKey);
16664
+ if (!runId) return null;
16665
+ const entry = await this.getEntry(runId);
16666
+ if (!entry) {
16667
+ await this.redis.delMollifierKeyIfEquals(lookupKey, runId);
16668
+ return null;
16669
+ }
16670
+ return runId;
16671
+ }
16672
+ // Clear the idempotency binding from a buffered run. Used by
16673
+ // `ResetIdempotencyKeyService` alongside the existing PG-side
16674
+ // `updateMany`. Returns the runId that was cleared, or null if no
16675
+ // buffered run held this key.
16676
+ async resetIdempotency(input) {
16677
+ const lookupKey = idempotencyLookupKeyFor(input);
16678
+ const claimKey = makeIdempotencyClaimKey(input);
16679
+ const clearedRunId = await this.redis.resetMollifierIdempotency(
16680
+ lookupKey,
16681
+ "mollifier:entries:",
16682
+ claimKey
16683
+ );
16684
+ return { clearedRunId: clearedRunId.length > 0 ? clearedRunId : null };
16685
+ }
16686
+ // Marks the entry as materialised (PG row written) and resets its TTL to
16687
+ // the grace window. Entry hash persists past ack as a read-fallback
16688
+ // safety net for the brief PG replica-lag window between drainer-side
16689
+ // write and reader-side visibility. Also clears the associated
16690
+ // idempotency lookup if one was set on accept.
16509
16691
  async ack(runId) {
16510
- await this.redis.del(`mollifier:entries:${runId}`);
16692
+ await this.redis.ackMollifierEntry(
16693
+ `mollifier:entries:${runId}`,
16694
+ DRAINING_SET_KEY,
16695
+ String(this.ackGraceTtlSeconds),
16696
+ runId
16697
+ );
16511
16698
  }
16512
16699
  async requeue(runId) {
16513
16700
  await this.redis.requeueMollifierEntry(
16514
16701
  `mollifier:entries:${runId}`,
16515
16702
  "mollifier:orgs",
16703
+ DRAINING_SET_KEY,
16516
16704
  "mollifier:queue:",
16517
16705
  runId,
16518
16706
  "mollifier:org-envs:"
16519
16707
  );
16520
16708
  }
16521
- // Returns true if the entry transitioned to FAILED; false if the entry no
16522
- // longer exists (TTL expired between pop and fail). Caller can use the
16523
- // boolean to skip downstream FAILED handling for ghost entries.
16709
+ // Returns true if a live entry was torn down; false if the entry no
16710
+ // longer existed (a concurrent ack or manual cleanup removed it between
16711
+ // pop and fail there is no accept-time TTL). Note FAILED is not an
16712
+ // observable state: the Lua marks the hash FAILED then DELs it in the
16713
+ // same atomic script, so a subsequent getEntry returns null. Caller can
16714
+ // use the boolean to skip downstream FAILED handling for ghost entries.
16524
16715
  async fail(runId, error) {
16525
16716
  const result = await this.redis.failMollifierEntry(
16526
16717
  `mollifier:entries:${runId}`,
16527
- JSON.stringify(error)
16718
+ DRAINING_SET_KEY,
16719
+ JSON.stringify(error),
16720
+ runId
16528
16721
  );
16529
16722
  return result === 1;
16530
16723
  }
16724
+ // Observability-only: number of entries currently in DRAINING state
16725
+ // (popped, not yet acked/failed/requeued). The gauge in the webapp
16726
+ // drainer worker polls this on a short interval and emits it as
16727
+ // `mollifier.draining.current` for ops dashboards and post-crash
16728
+ // forensics. Cheap (single ZCARD).
16729
+ async getDrainingCount() {
16730
+ return this.redis.zcard(DRAINING_SET_KEY);
16731
+ }
16732
+ // Observability-only: list runIds that have been DRAINING longer than
16733
+ // `olderThanMs` (i.e. popped before `now - olderThanMs`). Bounded by
16734
+ // `limit` to keep the result set tractable when something has gone
16735
+ // very wrong. ZRANGEBYSCORE is O(log N + K). Score is the pop wall-clock
16736
+ // in milliseconds as written by the popAndMarkDraining Lua.
16737
+ async listStaleDraining(olderThanMs, limit) {
16738
+ const maxScore = Date.now() - Math.max(0, olderThanMs);
16739
+ return this.redis.zrangebyscore(
16740
+ DRAINING_SET_KEY,
16741
+ "-inf",
16742
+ String(maxScore),
16743
+ "LIMIT",
16744
+ 0,
16745
+ Math.max(0, limit)
16746
+ );
16747
+ }
16748
+ // Returns Redis-side TTL on the entry hash. Returns -1 for entries
16749
+ // with no TTL — the steady state under the current design, where
16750
+ // entries persist until drainer ack/fail. The ack grace TTL (30s
16751
+ // post-materialise) is the only context where this returns a
16752
+ // positive value; tests around the grace TTL still rely on it.
16531
16753
  async getEntryTtlSeconds(runId) {
16532
16754
  return this.redis.ttl(`mollifier:entries:${runId}`);
16533
16755
  }
@@ -16558,8 +16780,10 @@ var MollifierBuffer = class {
16558
16780
  local orgId = ARGV[3]
16559
16781
  local payload = ARGV[4]
16560
16782
  local createdAt = ARGV[5]
16561
- local ttlSeconds = tonumber(ARGV[6])
16783
+ local createdAtMicros = ARGV[6]
16562
16784
  local orgEnvsPrefix = ARGV[7]
16785
+ local idempotencyLookupKey = ARGV[8] or ''
16786
+ local entryPrefix = ARGV[9]
16563
16787
 
16564
16788
  -- Idempotent: refuse if an entry for this runId already exists in any
16565
16789
  -- state. Caller-side dedup is also enforced via API idempotency keys,
@@ -16568,6 +16792,27 @@ var MollifierBuffer = class {
16568
16792
  return 0
16569
16793
  end
16570
16794
 
16795
+ -- Idempotency-key dedup. If the caller passed a lookup key
16796
+ -- and it's already bound to another buffered run, return the
16797
+ -- winner's runId so the loser's API response can echo it as a
16798
+ -- cached hit. Otherwise SET the lookup (no TTL \u2014 lifecycle is
16799
+ -- paired with the entry hash; drainer ack/fail clear it
16800
+ -- explicitly).
16801
+ if idempotencyLookupKey ~= '' then
16802
+ local existing = redis.call('GET', idempotencyLookupKey)
16803
+ if existing then
16804
+ -- Self-heal: only honour the binding if its entry hash still
16805
+ -- exists. If the entry was evicted (maxmemory) but the lookup
16806
+ -- survived, the binding is stale \u2014 fall through and rebind to
16807
+ -- this run rather than returning a dead runId that would block
16808
+ -- the key indefinitely. Mirrors lookupIdempotency's self-heal.
16809
+ if redis.call('EXISTS', entryPrefix .. existing) == 1 then
16810
+ return existing
16811
+ end
16812
+ end
16813
+ redis.call('SET', idempotencyLookupKey, runId)
16814
+ end
16815
+
16571
16816
  redis.call('HSET', entryKey,
16572
16817
  'runId', runId,
16573
16818
  'envId', envId,
@@ -16575,8 +16820,20 @@ var MollifierBuffer = class {
16575
16820
  'payload', payload,
16576
16821
  'status', 'QUEUED',
16577
16822
  'attempts', '0',
16578
- 'createdAt', createdAt)
16579
- redis.call('EXPIRE', entryKey, ttlSeconds)
16823
+ 'createdAt', createdAt,
16824
+ 'createdAtMicros', createdAtMicros,
16825
+ 'idempotencyLookupKey', idempotencyLookupKey,
16826
+ 'metadataVersion', '0')
16827
+ -- No EXPIRE on the entry hash. Buffer entries persist until the
16828
+ -- drainer ACKs (post-materialise grace) or FAILs them \u2014 the
16829
+ -- drainer is the only recovery mechanism, so silent TTL-based
16830
+ -- eviction would lose runs with no customer-visible signal.
16831
+ -- Memory pressure from an offline drainer is the alertable
16832
+ -- failure mode instead; see _ops/mollifier-ops.md.
16833
+ -- LIST queue: LPUSH at the head, drainer RPOPs from the tail, so
16834
+ -- insertion order == drain order (FIFO). createdAtMicros is kept
16835
+ -- as a hash field for dwell metrics only \u2014 it is no longer a sort
16836
+ -- key now that the buffer has no list/pagination surface.
16580
16837
  redis.call('LPUSH', queueKey, runId)
16581
16838
  -- Org-level membership: maintained atomically with the per-env
16582
16839
  -- queue so the drainer can walk orgs \u2192 envs-for-org and
@@ -16588,10 +16845,11 @@ var MollifierBuffer = class {
16588
16845
  `
16589
16846
  });
16590
16847
  this.redis.defineCommand("requeueMollifierEntry", {
16591
- numberOfKeys: 2,
16848
+ numberOfKeys: 3,
16592
16849
  lua: `
16593
16850
  local entryKey = KEYS[1]
16594
16851
  local orgsKey = KEYS[2]
16852
+ local drainingSetKey = KEYS[3]
16595
16853
  local queuePrefix = ARGV[1]
16596
16854
  local runId = ARGV[2]
16597
16855
  local orgEnvsPrefix = ARGV[3]
@@ -16606,7 +16864,12 @@ var MollifierBuffer = class {
16606
16864
  local nextAttempts = tonumber(currentAttempts or '0') + 1
16607
16865
 
16608
16866
  redis.call('HSET', entryKey, 'status', 'QUEUED', 'attempts', tostring(nextAttempts))
16609
- redis.call('LPUSH', queuePrefix .. envId, runId)
16867
+ -- Requeue RPUSHes to the tail (the RPOP end) so a transiently
16868
+ -- failed entry pops next rather than going to the back of the
16869
+ -- line behind a fresh backlog. createdAt is immutable across
16870
+ -- retries; the drainer's maxAttempts caps the
16871
+ -- retry loop so a poisoned entry doesn't head-of-line forever.
16872
+ redis.call('RPUSH', queuePrefix .. envId, runId)
16610
16873
  -- Re-track the org/env: pop may have SREM'd them when the queue
16611
16874
  -- last emptied. SADDs are idempotent if the values are still
16612
16875
  -- present.
@@ -16614,18 +16877,31 @@ var MollifierBuffer = class {
16614
16877
  redis.call('SADD', orgsKey, orgId)
16615
16878
  redis.call('SADD', orgEnvsPrefix .. orgId, envId)
16616
16879
  end
16880
+ -- Observability-only: leaving DRAINING state, so drop the
16881
+ -- entry from the draining-tracker set. ZREM on absent member
16882
+ -- is a no-op.
16883
+ redis.call('ZREM', drainingSetKey, runId)
16617
16884
  return 1
16618
16885
  `
16619
16886
  });
16620
16887
  this.redis.defineCommand("popAndMarkDraining", {
16621
- numberOfKeys: 2,
16888
+ numberOfKeys: 3,
16622
16889
  lua: `
16623
16890
  local queueKey = KEYS[1]
16624
16891
  local orgsKey = KEYS[2]
16892
+ local drainingSetKey = KEYS[3]
16625
16893
  local entryPrefix = ARGV[1]
16626
16894
  local envId = ARGV[2]
16627
16895
  local orgEnvsPrefix = ARGV[3]
16628
16896
 
16897
+ -- Wall-clock millis used as the ZADD score on the draining-tracker
16898
+ -- set. Computed once per script invocation so all observers see
16899
+ -- the same pop instant. redis.call('TIME') is deterministic per
16900
+ -- script execution (Lua sees it as a single read), satisfying the
16901
+ -- write-determinism contract on replicas/AOF replay.
16902
+ local timeArr = redis.call('TIME')
16903
+ local nowMs = tonumber(timeArr[1]) * 1000 + math.floor(tonumber(timeArr[2]) / 1000)
16904
+
16629
16905
  -- Helper: prune org-level membership when an env's queue empties.
16630
16906
  -- Called only from the success branch where we know orgId from the
16631
16907
  -- popped entry. The no-runId branch below can't reach this because
@@ -16640,11 +16916,13 @@ var MollifierBuffer = class {
16640
16916
  end
16641
16917
  end
16642
16918
 
16643
- -- Loop to skip orphan queue references \u2014 runIds whose entry hash has
16644
- -- expired (TTL hit). HSET on a missing key would CREATE a partial
16645
- -- hash without a TTL, leaking memory. The loop is bounded by queue
16646
- -- length; entire Lua script remains atomic.
16919
+ -- Loop to skip orphan queue references \u2014 runIds whose entry hash is
16920
+ -- gone (e.g. Redis maxmemory eviction, since QUEUED entries carry
16921
+ -- no TTL of their own). HSET on a missing key would CREATE a
16922
+ -- partial hash without a TTL, leaking memory. The loop is bounded
16923
+ -- by queue length; entire Lua script remains atomic.
16647
16924
  while true do
16925
+ -- RPOP returns the tail member (oldest, FIFO), or false when empty.
16648
16926
  local runId = redis.call('RPOP', queueKey)
16649
16927
  if not runId then
16650
16928
  -- Queue is empty AND we have no entry to read orgId from, so
@@ -16656,40 +16934,334 @@ var MollifierBuffer = class {
16656
16934
  local entryKey = entryPrefix .. runId
16657
16935
  if redis.call('EXISTS', entryKey) == 1 then
16658
16936
  redis.call('HSET', entryKey, 'status', 'DRAINING')
16937
+ -- Observability-only: track the runId in the draining set
16938
+ -- with the pop wall-clock as score. Acked/failed/requeued
16939
+ -- in the corresponding Lua scripts. The set is NOT
16940
+ -- load-bearing for correctness \u2014 the per-entry hash carries
16941
+ -- status \u2014 so a missed ZREM on a partial Lua execution is
16942
+ -- recoverable via the stale-sweep + entry hash, not a
16943
+ -- correctness bug.
16944
+ redis.call('ZADD', drainingSetKey, nowMs, runId)
16659
16945
  local raw = redis.call('HGETALL', entryKey)
16660
16946
  local result = {}
16661
16947
  for i = 1, #raw, 2 do
16662
16948
  result[raw[i]] = raw[i + 1]
16663
16949
  end
16664
16950
  -- Prune org-level membership if this pop drained the queue.
16665
- -- Atomic with the RPOP above \u2014 a concurrent accept AFTER this
16666
- -- script will SADD both back along with its LPUSH.
16951
+ -- Atomic with the RPOP above \u2014 a concurrent accept AFTER
16952
+ -- this script will SADD both back along with its LPUSH.
16667
16953
  if redis.call('LLEN', queueKey) == 0 then
16668
16954
  pruneOrgMembership(result['orgId'])
16669
16955
  end
16670
16956
  return cjson.encode(result)
16671
16957
  end
16672
- -- Orphan queue reference: entry TTL expired while runId was queued.
16673
- -- Discard the reference and loop to the next.
16958
+ -- Orphan queue reference: entry hash gone (evicted) while runId
16959
+ -- was queued. Discard the reference and loop to the next.
16674
16960
  end
16675
16961
  `
16676
16962
  });
16677
- this.redis.defineCommand("failMollifierEntry", {
16963
+ this.redis.defineCommand("casSetMollifierMetadata", {
16964
+ numberOfKeys: 1,
16965
+ lua: `
16966
+ local entryKey = KEYS[1]
16967
+ local expectedVersion = tonumber(ARGV[1])
16968
+ local newMetadata = ARGV[2]
16969
+ local newMetadataType = ARGV[3]
16970
+
16971
+ if redis.call('EXISTS', entryKey) == 0 then
16972
+ return 'not_found'
16973
+ end
16974
+
16975
+ local status = redis.call('HGET', entryKey, 'status')
16976
+ local materialised = redis.call('HGET', entryKey, 'materialised')
16977
+ if status ~= 'QUEUED' or materialised == 'true' then
16978
+ return 'busy'
16979
+ end
16980
+
16981
+ local currentVersionStr = redis.call('HGET', entryKey, 'metadataVersion') or '0'
16982
+ local currentVersion = tonumber(currentVersionStr) or 0
16983
+ if currentVersion ~= expectedVersion then
16984
+ return 'conflict:' .. tostring(currentVersion)
16985
+ end
16986
+
16987
+ -- Write the new metadata onto the snapshot's payload JSON. We
16988
+ -- keep the rest of the payload intact \u2014 only metadata/metadataType
16989
+ -- change. metadataVersion is denormalised on the hash for cheap
16990
+ -- CAS reads; it's intentionally NOT stored inside the payload
16991
+ -- itself (PG-side metadataVersion is a column, not a JSON field).
16992
+ local payloadJson = redis.call('HGET', entryKey, 'payload')
16993
+ local ok, payload = pcall(cjson.decode, payloadJson)
16994
+ if not ok then return 'busy' end
16995
+ payload.metadata = newMetadata
16996
+ payload.metadataType = newMetadataType
16997
+
16998
+ local newVersion = currentVersion + 1
16999
+ redis.call('HSET', entryKey,
17000
+ 'payload', cjson.encode(payload),
17001
+ 'metadataVersion', tostring(newVersion))
17002
+ return 'applied:' .. tostring(newVersion)
17003
+ `
17004
+ });
17005
+ this.redis.defineCommand("claimMollifierIdempotency", {
17006
+ numberOfKeys: 1,
17007
+ lua: `
17008
+ local claimKey = KEYS[1]
17009
+ local pendingMarker = ARGV[1] -- "pending:<caller-token>"
17010
+ local pendingPrefix = ARGV[2] -- "pending:"
17011
+ local ttl = tonumber(ARGV[3])
17012
+
17013
+ -- SETNX-with-TTL: atomic; only one caller can win.
17014
+ local won = redis.call('SET', claimKey, pendingMarker, 'NX', 'EX', ttl)
17015
+ if won then
17016
+ return 'claimed'
17017
+ end
17018
+
17019
+ local existing = redis.call('GET', claimKey)
17020
+ if not existing then
17021
+ -- The slot expired in the race window between the SET NX
17022
+ -- failing and this GET. It's free now \u2014 claim it so we don't
17023
+ -- string.sub a nil and error out.
17024
+ redis.call('SET', claimKey, pendingMarker, 'EX', ttl)
17025
+ return 'claimed'
17026
+ end
17027
+ -- Any "pending:*" value is a live claim \u2014 the caller-supplied
17028
+ -- token differentiates ownership but is opaque to losers.
17029
+ if string.sub(existing, 1, string.len(pendingPrefix)) == pendingPrefix then
17030
+ return 'pending'
17031
+ end
17032
+ return 'resolved:' .. existing
17033
+ `
17034
+ });
17035
+ this.redis.defineCommand("publishMollifierClaim", {
17036
+ numberOfKeys: 1,
17037
+ lua: `
17038
+ local claimKey = KEYS[1]
17039
+ local ownerMarker = ARGV[1] -- "pending:<our-token>"
17040
+ local runId = ARGV[2]
17041
+ local ttl = tonumber(ARGV[3])
17042
+
17043
+ local existing = redis.call('GET', claimKey)
17044
+ if existing == ownerMarker then
17045
+ redis.call('SET', claimKey, runId, 'EX', ttl)
17046
+ return 1
17047
+ end
17048
+ return 0
17049
+ `
17050
+ });
17051
+ this.redis.defineCommand("releaseMollifierClaim", {
17052
+ numberOfKeys: 1,
17053
+ lua: `
17054
+ local claimKey = KEYS[1]
17055
+ local ownerMarker = ARGV[1] -- "pending:<our-token>"
17056
+
17057
+ local existing = redis.call('GET', claimKey)
17058
+ if existing == ownerMarker then
17059
+ redis.call('DEL', claimKey)
17060
+ return 1
17061
+ end
17062
+ return 0
17063
+ `
17064
+ });
17065
+ this.redis.defineCommand("resetMollifierIdempotency", {
17066
+ numberOfKeys: 1,
17067
+ lua: `
17068
+ local lookupKey = KEYS[1]
17069
+ local entryPrefix = ARGV[1]
17070
+ local claimKey = ARGV[2]
17071
+
17072
+ -- Reset reopens the key across BOTH the buffer lookup and the
17073
+ -- cross-store pre-gate claim pointer. Without clearing the claim,
17074
+ -- a resolved/pending claim would keep deduping new triggers for
17075
+ -- the rest of its TTL even though the binding was reset. DEL is
17076
+ -- unconditional \u2014 the claim is gone regardless of whether a
17077
+ -- buffered run currently holds the lookup.
17078
+ redis.call('DEL', claimKey)
17079
+
17080
+ local runId = redis.call('GET', lookupKey)
17081
+ if not runId then
17082
+ return ''
17083
+ end
17084
+
17085
+ local entryKey = entryPrefix .. runId
17086
+ if redis.call('EXISTS', entryKey) == 0 then
17087
+ -- Stale lookup. Lazy cleanup.
17088
+ redis.call('DEL', lookupKey)
17089
+ return ''
17090
+ end
17091
+
17092
+ -- Clear the idempotency fields on the snapshot payload so the
17093
+ -- drainer's eventual engine.trigger call inserts a PG row
17094
+ -- without the key set.
17095
+ local payloadJson = redis.call('HGET', entryKey, 'payload')
17096
+ if payloadJson then
17097
+ local ok, payload = pcall(cjson.decode, payloadJson)
17098
+ if ok then
17099
+ payload.idempotencyKey = cjson.null
17100
+ payload.idempotencyKeyExpiresAt = cjson.null
17101
+ redis.call('HSET', entryKey, 'payload', cjson.encode(payload))
17102
+ end
17103
+ end
17104
+ -- Clear the denormalised lookup pointer on the hash so a later
17105
+ -- ack doesn't try to DEL a key that's already gone.
17106
+ redis.call('HSET', entryKey, 'idempotencyLookupKey', '')
17107
+ redis.call('DEL', lookupKey)
17108
+ return runId
17109
+ `
17110
+ });
17111
+ this.redis.defineCommand("mutateMollifierSnapshot", {
16678
17112
  numberOfKeys: 1,
16679
17113
  lua: `
16680
17114
  local entryKey = KEYS[1]
17115
+ local patchJson = ARGV[1]
17116
+
17117
+ if redis.call('EXISTS', entryKey) == 0 then
17118
+ return 'not_found'
17119
+ end
17120
+
17121
+ local status = redis.call('HGET', entryKey, 'status')
17122
+ local materialised = redis.call('HGET', entryKey, 'materialised')
17123
+ if status ~= 'QUEUED' or materialised == 'true' then
17124
+ return 'busy'
17125
+ end
17126
+
17127
+ local payloadJson = redis.call('HGET', entryKey, 'payload')
17128
+ local ok, payload = pcall(cjson.decode, payloadJson)
17129
+ if not ok then return 'busy' end
17130
+
17131
+ local patch = cjson.decode(patchJson)
17132
+
17133
+ if patch.type == 'append_tags' then
17134
+ -- cjson decode of an absent or empty-array field gives nil or
17135
+ -- an empty table; we rebuild as a dense array. Existing tags
17136
+ -- are preserved; new tags are appended only if not present.
17137
+ local existing = payload.tags or {}
17138
+ local seen = {}
17139
+ local merged = {}
17140
+ for _, t in ipairs(existing) do
17141
+ if not seen[t] then
17142
+ seen[t] = true
17143
+ table.insert(merged, t)
17144
+ end
17145
+ end
17146
+ for _, t in ipairs(patch.tags or {}) do
17147
+ if not seen[t] then
17148
+ seen[t] = true
17149
+ table.insert(merged, t)
17150
+ end
17151
+ end
17152
+ -- Cap the deduped count when the caller supplies a limit, so a
17153
+ -- buffered run can't exceed MAX_TAGS_PER_RUN via the tags API.
17154
+ -- Reject the whole patch (write nothing) rather than truncating.
17155
+ if patch.maxTags ~= nil and #merged > patch.maxTags then
17156
+ return 'limit_exceeded'
17157
+ end
17158
+ payload.tags = merged
17159
+ elseif patch.type == 'set_metadata' then
17160
+ payload.metadata = patch.metadata
17161
+ payload.metadataType = patch.metadataType
17162
+ -- Bump the denormalised metadataVersion so an in-flight
17163
+ -- casSetMetadata (optimistic CAS keyed on this counter) sees
17164
+ -- the concurrent write as a version conflict and retries,
17165
+ -- instead of clobbering it under a now-stale expectedVersion.
17166
+ local currentVersion = tonumber(redis.call('HGET', entryKey, 'metadataVersion') or '0') or 0
17167
+ redis.call('HSET', entryKey, 'metadataVersion', tostring(currentVersion + 1))
17168
+ elseif patch.type == 'set_delay' then
17169
+ payload.delayUntil = patch.delayUntil
17170
+ elseif patch.type == 'mark_cancelled' then
17171
+ payload.cancelledAt = patch.cancelledAt
17172
+ payload.cancelReason = patch.cancelReason
17173
+ else
17174
+ return 'busy'
17175
+ end
17176
+
17177
+ redis.call('HSET', entryKey, 'payload', cjson.encode(payload))
17178
+ return 'applied_to_snapshot'
17179
+ `
17180
+ });
17181
+ this.redis.defineCommand("ackMollifierEntry", {
17182
+ numberOfKeys: 2,
17183
+ lua: `
17184
+ local entryKey = KEYS[1]
17185
+ local drainingSetKey = KEYS[2]
17186
+ local graceTtlSeconds = tonumber(ARGV[1])
17187
+ local runId = ARGV[2]
17188
+
17189
+ -- Always ZREM from the draining-tracker \u2014 even if the entry hash
17190
+ -- has been concurrently torn down, the runId might still be in
17191
+ -- the set (e.g. fail() ran first and cleared the hash but a
17192
+ -- delayed ack races in). Idempotent: ZREM on absent is a no-op.
17193
+ redis.call('ZREM', drainingSetKey, runId)
17194
+
17195
+ -- Guard: never create a partial entry. If the hash is gone between
17196
+ -- pop and ack (concurrent fail or eviction \u2014 QUEUED entries carry
17197
+ -- no TTL), the run is gone, nothing to mark materialised.
17198
+ if redis.call('EXISTS', entryKey) == 0 then
17199
+ return 0
17200
+ end
17201
+
17202
+ -- If the entry was accepted with an idempotency key, the lookup
17203
+ -- string was stored on the hash at accept time. Clear it now \u2014
17204
+ -- PG becomes canonical for the key post-materialisation.
17205
+ local lookupKey = redis.call('HGET', entryKey, 'idempotencyLookupKey')
17206
+ if lookupKey and lookupKey ~= '' then
17207
+ redis.call('DEL', lookupKey)
17208
+ end
17209
+
17210
+ redis.call('HSET', entryKey, 'materialised', 'true')
17211
+ redis.call('EXPIRE', entryKey, graceTtlSeconds)
17212
+ return 1
17213
+ `
17214
+ });
17215
+ this.redis.defineCommand("failMollifierEntry", {
17216
+ numberOfKeys: 2,
17217
+ lua: `
17218
+ local entryKey = KEYS[1]
17219
+ local drainingSetKey = KEYS[2]
16681
17220
  local errorPayload = ARGV[1]
17221
+ local runId = ARGV[2]
17222
+
17223
+ -- Always ZREM from the draining-tracker (idempotent on absent).
17224
+ -- Mirrors ack: the runId may be in the set even if the entry hash
17225
+ -- has been raced away.
17226
+ redis.call('ZREM', drainingSetKey, runId)
16682
17227
 
16683
- -- Guard: never create a partial entry. If the hash expired between
16684
- -- pop and fail, the run is gone \u2014 nothing to mark FAILED.
17228
+ -- Guard: nothing to mark FAILED if the hash is gone (concurrent
17229
+ -- ack/manual cleanup). Returning 0 lets the caller distinguish
17230
+ -- "marked failed" from "no-op".
16685
17231
  if redis.call('EXISTS', entryKey) == 0 then
16686
17232
  return 0
16687
17233
  end
16688
17234
 
16689
17235
  redis.call('HSET', entryKey, 'status', 'FAILED', 'lastError', errorPayload)
17236
+
17237
+ -- Terminal-failure contract: the drainer's onTerminalFailure
17238
+ -- callback (see MollifierDrainer.processEntry) has been
17239
+ -- invoked before this fail() and has either written a
17240
+ -- SYSTEM_FAILURE PG row (for both non-retryable AND
17241
+ -- max-attempts-exhausted retryable errors) or chosen to fall
17242
+ -- through (genuinely bad snapshot the engine can't materialise
17243
+ -- a row from). Either way the buffer entry is no longer
17244
+ -- load-bearing here. Clear the idempotency lookup -- PG's
17245
+ -- unique constraint is the canonical dedup mechanism
17246
+ -- post-materialise -- and drop the entry hash so failed runs
17247
+ -- don't accrete forever now that there's no accept-time TTL.
17248
+ local lookupKey = redis.call('HGET', entryKey, 'idempotencyLookupKey')
17249
+ if lookupKey and lookupKey ~= '' then
17250
+ redis.call('DEL', lookupKey)
17251
+ end
17252
+ redis.call('DEL', entryKey)
16690
17253
  return 1
16691
17254
  `
16692
17255
  });
17256
+ this.redis.defineCommand("delMollifierKeyIfEquals", {
17257
+ numberOfKeys: 1,
17258
+ lua: `
17259
+ if redis.call('GET', KEYS[1]) == ARGV[1] then
17260
+ return redis.call('DEL', KEYS[1])
17261
+ end
17262
+ return 0
17263
+ `
17264
+ });
16693
17265
  this.redis.defineCommand("mollifierEvaluateTrip", {
16694
17266
  numberOfKeys: 2,
16695
17267
  lua: `
@@ -16717,12 +17289,16 @@ var MollifierBuffer = class {
16717
17289
  var MollifierDrainer = class {
16718
17290
  buffer;
16719
17291
  handler;
17292
+ onTerminalFailure;
16720
17293
  maxAttempts;
16721
17294
  isRetryable;
16722
17295
  pollIntervalMs;
16723
17296
  maxOrgsPerTick;
17297
+ drainBatchSize;
17298
+ concurrency;
17299
+ maxBackoffMs;
17300
+ backoffFloorMs;
16724
17301
  logger;
16725
- limit;
16726
17302
  // Rotation state. `orgCursor` advances through the active-orgs list.
16727
17303
  // Each org has its own internal cursor in `perOrgEnvCursors` for
16728
17304
  // cycling through that org's envs. Both reset on `start()`.
@@ -16734,12 +17310,16 @@ var MollifierDrainer = class {
16734
17310
  constructor(options) {
16735
17311
  this.buffer = options.buffer;
16736
17312
  this.handler = options.handler;
17313
+ this.onTerminalFailure = options.onTerminalFailure;
16737
17314
  this.maxAttempts = options.maxAttempts;
16738
17315
  this.isRetryable = options.isRetryable;
16739
17316
  this.pollIntervalMs = options.pollIntervalMs ?? 100;
16740
17317
  this.maxOrgsPerTick = options.maxOrgsPerTick ?? 500;
17318
+ this.drainBatchSize = Math.max(1, options.drainBatchSize ?? 1);
17319
+ this.concurrency = Math.max(1, options.concurrency);
17320
+ this.maxBackoffMs = options.maxBackoffMs ?? 5e3;
17321
+ this.backoffFloorMs = Math.max(1, options.backoffFloorMs ?? 100);
16741
17322
  this.logger = options.logger ?? new logger$1.Logger("MollifierDrainer", "debug");
16742
- this.limit = pLimit(options.concurrency);
16743
17323
  }
16744
17324
  async runOnce() {
16745
17325
  const orgs = await this.buffer.listOrgs();
@@ -16756,15 +17336,64 @@ var MollifierDrainer = class {
16756
17336
  const envId = this.pickEnvForOrg(orgId, envsForOrg);
16757
17337
  targets.push(envId);
16758
17338
  }
16759
- const inflight = [];
16760
- for (const envId of targets) {
16761
- inflight.push(this.limit(() => this.processOneFromEnv(envId)));
16762
- }
16763
- const results = await Promise.all(inflight);
16764
- return {
16765
- drained: results.filter((r) => r === "drained").length,
16766
- failed: results.filter((r) => r === "failed").length
17339
+ if (targets.length === 0) return { drained: 0, failed: 0 };
17340
+ const remaining = /* @__PURE__ */ new Map();
17341
+ const skip = /* @__PURE__ */ new Set();
17342
+ for (const envId of targets) remaining.set(envId, this.drainBatchSize);
17343
+ let cursor = 0;
17344
+ const pickNextEnv = () => {
17345
+ for (let i = 0; i < targets.length; i++) {
17346
+ const idx = (cursor + i) % targets.length;
17347
+ const envId = targets[idx];
17348
+ if (skip.has(envId)) continue;
17349
+ const r = remaining.get(envId) ?? 0;
17350
+ if (r > 0) {
17351
+ remaining.set(envId, r - 1);
17352
+ cursor = (idx + 1) % targets.length;
17353
+ return envId;
17354
+ }
17355
+ }
17356
+ return null;
17357
+ };
17358
+ let drained = 0;
17359
+ let failed = 0;
17360
+ const worker = async () => {
17361
+ while (true) {
17362
+ const envId = pickNextEnv();
17363
+ if (envId === null) return;
17364
+ let entry;
17365
+ try {
17366
+ entry = await this.buffer.pop(envId);
17367
+ } catch (err) {
17368
+ this.logger.error("MollifierDrainer.pop failed", { envId, err });
17369
+ if (!skip.has(envId)) {
17370
+ skip.add(envId);
17371
+ failed += 1;
17372
+ }
17373
+ continue;
17374
+ }
17375
+ if (!entry) {
17376
+ skip.add(envId);
17377
+ continue;
17378
+ }
17379
+ try {
17380
+ const outcome = await this.processEntry(entry);
17381
+ if (outcome === "drained") drained += 1;
17382
+ else failed += 1;
17383
+ } catch (err) {
17384
+ this.logger.error("MollifierDrainer.processEntry failed", {
17385
+ envId,
17386
+ runId: entry.runId,
17387
+ err
17388
+ });
17389
+ failed += 1;
17390
+ }
17391
+ }
16767
17392
  };
17393
+ const totalBudget = targets.length * this.drainBatchSize;
17394
+ const workerCount = Math.min(this.concurrency, totalBudget);
17395
+ await Promise.all(Array.from({ length: workerCount }, () => worker()));
17396
+ return { drained, failed };
16768
17397
  }
16769
17398
  start() {
16770
17399
  if (this.isRunning) return;
@@ -16838,8 +17467,8 @@ var MollifierDrainer = class {
16838
17467
  // brief blip while preventing a tight retry loop during a long Redis
16839
17468
  // outage. 1 → 200ms, 2 → 400ms, 3 → 800ms, 4 → 1.6s, 5 → 3.2s, 6+ → 5s.
16840
17469
  backoffMs(consecutiveErrors) {
16841
- const base = Math.max(this.pollIntervalMs, 100);
16842
- const capped = Math.min(base * 2 ** (consecutiveErrors - 1), 5e3);
17470
+ const base = Math.max(this.pollIntervalMs, this.backoffFloorMs);
17471
+ const capped = Math.min(base * 2 ** (consecutiveErrors - 1), this.maxBackoffMs);
16843
17472
  return capped;
16844
17473
  }
16845
17474
  delay(ms) {
@@ -16870,31 +17499,6 @@ var MollifierDrainer = class {
16870
17499
  this.perOrgEnvCursors.set(orgId, (cursor + 1) % sorted.length);
16871
17500
  return sorted[idx];
16872
17501
  }
16873
- // A failure for one env (e.g. a Redis hiccup mid-batch in `pop`, or in
16874
- // `requeue`/`fail` during error recovery inside `processEntry`) must not
16875
- // poison the rest of the batch — `Promise.all` would otherwise reject and
16876
- // bubble all the way to `loop()`. Catch both stages here so the failed env
16877
- // is just counted as "failed" for this tick and we move on.
16878
- async processOneFromEnv(envId) {
16879
- let entry;
16880
- try {
16881
- entry = await this.buffer.pop(envId);
16882
- } catch (err) {
16883
- this.logger.error("MollifierDrainer.pop failed", { envId, err });
16884
- return "failed";
16885
- }
16886
- if (!entry) return "empty";
16887
- try {
16888
- return await this.processEntry(entry);
16889
- } catch (err) {
16890
- this.logger.error("MollifierDrainer.processEntry failed", {
16891
- envId,
16892
- runId: entry.runId,
16893
- err
16894
- });
16895
- return "failed";
16896
- }
16897
- }
16898
17502
  async processEntry(entry) {
16899
17503
  try {
16900
17504
  const payload = deserialiseSnapshot(entry.payload);
@@ -16918,13 +17522,46 @@ var MollifierDrainer = class {
16918
17522
  });
16919
17523
  return "failed";
16920
17524
  }
17525
+ const cause = this.isRetryable(err) ? "max-attempts-exhausted" : "non-retryable";
16921
17526
  const code = err instanceof Error ? err.name : "Unknown";
16922
17527
  const message = err instanceof Error ? err.message : String(err);
17528
+ if (this.onTerminalFailure) {
17529
+ try {
17530
+ await this.onTerminalFailure({
17531
+ runId: entry.runId,
17532
+ envId: entry.envId,
17533
+ orgId: entry.orgId,
17534
+ payload: deserialiseSnapshot(entry.payload),
17535
+ attempts: nextAttempts,
17536
+ createdAt: entry.createdAt,
17537
+ error: { code, message },
17538
+ cause
17539
+ });
17540
+ } catch (writeErr) {
17541
+ if (this.isRetryable(writeErr)) {
17542
+ await this.buffer.requeue(entry.runId);
17543
+ this.logger.warn(
17544
+ "MollifierDrainer: terminal-failure callback retryable; requeued",
17545
+ {
17546
+ runId: entry.runId,
17547
+ attempts: nextAttempts,
17548
+ writeErr
17549
+ }
17550
+ );
17551
+ return "failed";
17552
+ }
17553
+ this.logger.error("MollifierDrainer: terminal-failure callback failed", {
17554
+ runId: entry.runId,
17555
+ writeErr
17556
+ });
17557
+ }
17558
+ }
16923
17559
  await this.buffer.fail(entry.runId, { code, message });
16924
17560
  this.logger.error("MollifierDrainer: terminal failure", {
16925
17561
  runId: entry.runId,
16926
17562
  code,
16927
- message
17563
+ message,
17564
+ cause
16928
17565
  });
16929
17566
  return "failed";
16930
17567
  }
@@ -16965,7 +17602,9 @@ exports.WorkerQueueManager = WorkerQueueManager;
16965
17602
  exports.createDefaultRetryStrategy = createDefaultRetryStrategy;
16966
17603
  exports.defaultRetryOptions = defaultRetryOptions;
16967
17604
  exports.deserialiseSnapshot = deserialiseSnapshot;
17605
+ exports.idempotencyLookupKeyFor = idempotencyLookupKeyFor;
16968
17606
  exports.isAbortError = isAbortError;
17607
+ exports.makeIdempotencyClaimKey = makeIdempotencyClaimKey;
16969
17608
  exports.noopTelemetry = noopTelemetry;
16970
17609
  exports.serialiseSnapshot = serialiseSnapshot;
16971
17610
  //# sourceMappingURL=index.cjs.map