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