@nightx.co/pulsar 0.0.0-stage → 1.0.15

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.
Files changed (162) hide show
  1. package/README.md +14 -2
  2. package/dist/chunk-3sg08kqp.js +10 -0
  3. package/dist/chunk-3sg08kqp.js.map +9 -0
  4. package/dist/chunk-a9kye38b.js +54 -0
  5. package/dist/chunk-a9kye38b.js.map +12 -0
  6. package/dist/chunk-cpn1qh4e.js +10 -0
  7. package/dist/chunk-cpn1qh4e.js.map +12 -0
  8. package/dist/chunk-rrj8rm04.js +10 -0
  9. package/dist/chunk-rrj8rm04.js.map +11 -0
  10. package/dist/cluster/Nebula.d.ts +30 -0
  11. package/dist/cluster/Nebula.d.ts.map +1 -0
  12. package/dist/helpers/computeConfigDelta.d.ts +18 -0
  13. package/dist/helpers/computeConfigDelta.d.ts.map +1 -0
  14. package/dist/helpers/defineQueue.d.ts +13 -0
  15. package/dist/helpers/defineQueue.d.ts.map +1 -0
  16. package/dist/helpers/generateShaHash.d.ts +2 -0
  17. package/dist/helpers/generateShaHash.d.ts.map +1 -0
  18. package/dist/index.d.ts +6 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +8 -0
  21. package/dist/index.js.map +50 -0
  22. package/dist/integrations/PulsarEventsIntegrations.d.ts +7 -0
  23. package/dist/integrations/PulsarEventsIntegrations.d.ts.map +1 -0
  24. package/dist/integrations/PulsarLoggerIntegrations.d.ts +12 -0
  25. package/dist/integrations/PulsarLoggerIntegrations.d.ts.map +1 -0
  26. package/dist/integrations/index.d.ts +4 -0
  27. package/dist/integrations/index.d.ts.map +1 -0
  28. package/dist/integrations/index.js +8 -0
  29. package/dist/integrations/index.js.map +11 -0
  30. package/dist/modules/Queue.module.d.ts +45 -0
  31. package/dist/modules/Queue.module.d.ts.map +1 -0
  32. package/dist/modules/Scheduler.module.d.ts +42 -0
  33. package/dist/modules/Scheduler.module.d.ts.map +1 -0
  34. package/dist/modules/Tick.module.d.ts +35 -0
  35. package/dist/modules/Tick.module.d.ts.map +1 -0
  36. package/dist/modules/TickController.module.d.ts +36 -0
  37. package/dist/modules/TickController.module.d.ts.map +1 -0
  38. package/dist/monitoring/PulsarMonitoringStreamProducer.d.ts +2 -0
  39. package/dist/monitoring/PulsarMonitoringStreamProducer.d.ts.map +1 -0
  40. package/dist/monitoring/index.d.ts +2 -0
  41. package/dist/monitoring/index.d.ts.map +1 -0
  42. package/dist/monitoring/server/PulsarMonitoringStream.d.ts +2 -0
  43. package/dist/monitoring/server/PulsarMonitoringStream.d.ts.map +1 -0
  44. package/dist/network/NetworkInterface.d.ts +13 -0
  45. package/dist/network/NetworkInterface.d.ts.map +1 -0
  46. package/dist/network/UnifiedTransportManager.d.ts +21 -0
  47. package/dist/network/UnifiedTransportManager.d.ts.map +1 -0
  48. package/dist/network/abstract/BaseNetworkDriver.d.ts +17 -0
  49. package/dist/network/abstract/BaseNetworkDriver.d.ts.map +1 -0
  50. package/dist/network/auth/Authenticator.d.ts +2 -0
  51. package/dist/network/auth/Authenticator.d.ts.map +1 -0
  52. package/dist/network/drivers/HttpNetworkDriver.d.ts +31 -0
  53. package/dist/network/drivers/HttpNetworkDriver.d.ts.map +1 -0
  54. package/dist/network/drivers/WebSocketNetworkDriver.d.ts +23 -0
  55. package/dist/network/drivers/WebSocketNetworkDriver.d.ts.map +1 -0
  56. package/dist/network/helpers/httpQueueOperations.d.ts +2 -0
  57. package/dist/network/helpers/httpQueueOperations.d.ts.map +1 -0
  58. package/dist/network/interfaces/network.types.d.ts +13 -0
  59. package/dist/network/interfaces/network.types.d.ts.map +1 -0
  60. package/dist/run/Queues.d.ts +2 -0
  61. package/dist/run/Queues.d.ts.map +1 -0
  62. package/dist/run/index.d.ts +2 -0
  63. package/dist/run/index.d.ts.map +1 -0
  64. package/dist/run/index2.d.ts +2 -0
  65. package/dist/run/index2.d.ts.map +1 -0
  66. package/dist/runtimes/IsolateRuntime.d.ts +17 -0
  67. package/dist/runtimes/IsolateRuntime.d.ts.map +1 -0
  68. package/dist/runtimes/PersistentRuntime.d.ts +22 -0
  69. package/dist/runtimes/PersistentRuntime.d.ts.map +1 -0
  70. package/dist/runtimes/ServerlessRuntime.d.ts +15 -0
  71. package/dist/runtimes/ServerlessRuntime.d.ts.map +1 -0
  72. package/dist/runtimes/runtimeTypes.d.ts +15 -0
  73. package/dist/runtimes/runtimeTypes.d.ts.map +1 -0
  74. package/dist/server/PulsarRequestHandler.d.ts +41 -0
  75. package/dist/server/PulsarRequestHandler.d.ts.map +1 -0
  76. package/dist/server/helpers/acquireRedisLock.d.ts +14 -0
  77. package/dist/server/helpers/acquireRedisLock.d.ts.map +1 -0
  78. package/dist/server/helpers/checkFencingValidity.d.ts +14 -0
  79. package/dist/server/helpers/checkFencingValidity.d.ts.map +1 -0
  80. package/dist/server/helpers/performIsolateRestart.d.ts +20 -0
  81. package/dist/server/helpers/performIsolateRestart.d.ts.map +1 -0
  82. package/dist/server/index.d.ts +2 -0
  83. package/dist/server/index.d.ts.map +1 -0
  84. package/dist/server/index.js +8 -0
  85. package/dist/server/index.js.map +13 -0
  86. package/dist/server/parser/parseRequest.d.ts +10 -0
  87. package/dist/server/parser/parseRequest.d.ts.map +1 -0
  88. package/dist/server/utility/extract-headers.d.ts +14 -0
  89. package/dist/server/utility/extract-headers.d.ts.map +1 -0
  90. package/dist/service/ConfigurationStore.d.ts +23 -0
  91. package/dist/service/ConfigurationStore.d.ts.map +1 -0
  92. package/dist/service/Isolate.service.d.ts +12 -0
  93. package/dist/service/Isolate.service.d.ts.map +1 -0
  94. package/dist/service/Pulsar.service.d.ts +41 -0
  95. package/dist/service/Pulsar.service.d.ts.map +1 -0
  96. package/dist/service/PulsarBaseService.d.ts +49 -0
  97. package/dist/service/PulsarBaseService.d.ts.map +1 -0
  98. package/dist/service/PulsarEventBus.d.ts +36 -0
  99. package/dist/service/PulsarEventBus.d.ts.map +1 -0
  100. package/dist/service/SwarmBudgetTracker.d.ts +14 -0
  101. package/dist/service/SwarmBudgetTracker.d.ts.map +1 -0
  102. package/dist/service/consumers/PulsarWorker.d.ts +10 -0
  103. package/dist/service/consumers/PulsarWorker.d.ts.map +1 -0
  104. package/dist/shared/PulsarRuntimeCore.d.ts +55 -0
  105. package/dist/shared/PulsarRuntimeCore.d.ts.map +1 -0
  106. package/dist/static/TimingProfile.d.ts +9 -0
  107. package/dist/static/TimingProfile.d.ts.map +1 -0
  108. package/dist/static/static.d.ts +3 -0
  109. package/dist/static/static.d.ts.map +1 -0
  110. package/dist/storage/PulsarStorage.d.ts +42 -0
  111. package/dist/storage/PulsarStorage.d.ts.map +1 -0
  112. package/dist/storage/drivers/PostgresDriver.d.ts +20 -0
  113. package/dist/storage/drivers/PostgresDriver.d.ts.map +1 -0
  114. package/dist/storage/drivers/RedisDriver.d.ts +20 -0
  115. package/dist/storage/drivers/RedisDriver.d.ts.map +1 -0
  116. package/dist/storage/drivers/types.d.ts +27 -0
  117. package/dist/storage/drivers/types.d.ts.map +1 -0
  118. package/dist/storage/index.d.ts +4 -0
  119. package/dist/storage/index.d.ts.map +1 -0
  120. package/dist/storage/index.js +403 -0
  121. package/dist/storage/index.js.map +21 -0
  122. package/dist/storage/repositories/PostgresEngineOperationRepository.d.ts +39 -0
  123. package/dist/storage/repositories/PostgresEngineOperationRepository.d.ts.map +1 -0
  124. package/dist/storage/repositories/PostgresQueueRepository.d.ts +26 -0
  125. package/dist/storage/repositories/PostgresQueueRepository.d.ts.map +1 -0
  126. package/dist/storage/repositories/QueueRepository.d.ts +20 -0
  127. package/dist/storage/repositories/QueueRepository.d.ts.map +1 -0
  128. package/dist/storage/repositories/RedisQueueRepository.d.ts +28 -0
  129. package/dist/storage/repositories/RedisQueueRepository.d.ts.map +1 -0
  130. package/dist/subsys/DeferredTickEvaluator.d.ts +23 -0
  131. package/dist/subsys/DeferredTickEvaluator.d.ts.map +1 -0
  132. package/dist/subsys/EventBus.d.ts +13 -0
  133. package/dist/subsys/EventBus.d.ts.map +1 -0
  134. package/dist/subsys/ExecutionProfileSwitcher.d.ts +10 -0
  135. package/dist/subsys/ExecutionProfileSwitcher.d.ts.map +1 -0
  136. package/dist/subsys/LoggerService.d.ts +15 -0
  137. package/dist/subsys/LoggerService.d.ts.map +1 -0
  138. package/dist/subsys/PulsarClock.d.ts +32 -0
  139. package/dist/subsys/PulsarClock.d.ts.map +1 -0
  140. package/dist/subsys/RuntimeCacheStorage.d.ts +18 -0
  141. package/dist/subsys/RuntimeCacheStorage.d.ts.map +1 -0
  142. package/dist/subsys/RuntimeEventBridge.d.ts +16 -0
  143. package/dist/subsys/RuntimeEventBridge.d.ts.map +1 -0
  144. package/dist/types/base.types.d.ts +65 -0
  145. package/dist/types/base.types.d.ts.map +1 -0
  146. package/dist/types/config.types.d.ts +56 -0
  147. package/dist/types/config.types.d.ts.map +1 -0
  148. package/dist/types/consumer.types.d.ts +36 -0
  149. package/dist/types/consumer.types.d.ts.map +1 -0
  150. package/dist/types/engine.types.d.ts +139 -0
  151. package/dist/types/engine.types.d.ts.map +1 -0
  152. package/dist/types/eventTriggerStrategry.types.d.ts +34 -0
  153. package/dist/types/eventTriggerStrategry.types.d.ts.map +1 -0
  154. package/dist/types/integrations.types.d.ts +16 -0
  155. package/dist/types/integrations.types.d.ts.map +1 -0
  156. package/dist/types/nebula.types.d.ts +65 -0
  157. package/dist/types/nebula.types.d.ts.map +1 -0
  158. package/dist/types/queue.types.d.ts +106 -0
  159. package/dist/types/queue.types.d.ts.map +1 -0
  160. package/dist/types/runtime.types.d.ts +89 -0
  161. package/dist/types/runtime.types.d.ts.map +1 -0
  162. package/package.json +71 -5
@@ -0,0 +1,50 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["..\\..\\..\\node_modules\\.bun\\eventemitter3@5.0.4\\node_modules\\eventemitter3\\index.js", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\utils\\utf8.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\ExtData.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\DecodeError.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\utils\\int.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\timestamp.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\ExtensionCodec.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\utils\\typedArrays.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\Encoder.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\encode.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\utils\\prettyByte.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\CachedKeyDecoder.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\Decoder.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\decode.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\utils\\stream.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\decodeAsync.cjs", "..\\..\\..\\node_modules\\.bun\\@msgpack+msgpack@3.1.3\\node_modules\\@msgpack\\msgpack\\dist.cjs\\index.cjs", "..\\src\\helpers\\defineQueue.ts", "..\\src\\service\\Isolate.service.ts", "..\\src\\service\\Pulsar.service.ts", "..\\src\\service\\PulsarEventBus.ts", "..\\src\\subsys\\PulsarClock.ts", "..\\src\\service\\SwarmBudgetTracker.ts", "..\\src\\static\\TimingProfile.ts", "..\\src\\modules\\Scheduler.module.ts", "..\\src\\subsys\\ExecutionProfileSwitcher.ts", "..\\src\\modules\\Tick.module.ts", "..\\src\\modules\\TickController.module.ts", "..\\src\\shared\\PulsarRuntimeCore.ts", "..\\src\\subsys\\RuntimeEventBridge.ts", "..\\src\\subsys\\DeferredTickEvaluator.ts", "..\\src\\runtimes\\PersistentRuntime.ts", "..\\src\\runtimes\\ServerlessRuntime.ts", "..\\src\\runtimes\\IsolateRuntime.ts", "..\\src\\network\\NetworkInterface.ts", "..\\..\\..\\node_modules\\.bun\\eventemitter3@5.0.4\\node_modules\\eventemitter3\\index.mjs", "..\\src\\network\\drivers\\HttpNetworkDriver.ts", "..\\src\\network\\abstract\\BaseNetworkDriver.ts", "..\\src\\network\\drivers\\WebSocketNetworkDriver.ts", "..\\src\\network\\UnifiedTransportManager.ts", "..\\src\\service\\PulsarBaseService.ts"],
4
+ "sourcesContent": [
5
+ "'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n",
6
+ "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.utf8Count = utf8Count;\nexports.utf8EncodeJs = utf8EncodeJs;\nexports.utf8EncodeTE = utf8EncodeTE;\nexports.utf8Encode = utf8Encode;\nexports.utf8DecodeJs = utf8DecodeJs;\nexports.utf8DecodeTD = utf8DecodeTD;\nexports.utf8Decode = utf8Decode;\nfunction utf8Count(str) {\n const strLength = str.length;\n let byteLength = 0;\n let pos = 0;\n while (pos < strLength) {\n let value = str.charCodeAt(pos++);\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n byteLength++;\n continue;\n }\n else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n byteLength += 2;\n }\n else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n const extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n byteLength += 3;\n }\n else {\n // 4-byte\n byteLength += 4;\n }\n }\n }\n return byteLength;\n}\nfunction utf8EncodeJs(str, output, outputOffset) {\n const strLength = str.length;\n let offset = outputOffset;\n let pos = 0;\n while (pos < strLength) {\n let value = str.charCodeAt(pos++);\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n output[offset++] = value;\n continue;\n }\n else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n output[offset++] = ((value >> 6) & 0x1f) | 0xc0;\n }\n else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n const extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n output[offset++] = ((value >> 12) & 0x0f) | 0xe0;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n }\n else {\n // 4-byte\n output[offset++] = ((value >> 18) & 0x07) | 0xf0;\n output[offset++] = ((value >> 12) & 0x3f) | 0x80;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n }\n }\n output[offset++] = (value & 0x3f) | 0x80;\n }\n}\n// TextEncoder and TextDecoder are standardized in whatwg encoding:\n// https://encoding.spec.whatwg.org/\n// and available in all the modern browsers:\n// https://caniuse.com/textencoder\n// They are available in Node.js since v12 LTS as well:\n// https://nodejs.org/api/globals.html#textencoder\nconst sharedTextEncoder = new TextEncoder();\n// This threshold should be determined by benchmarking, which might vary in engines and input data.\n// Run `npx ts-node benchmark/encode-string.ts` for details.\nconst TEXT_ENCODER_THRESHOLD = 50;\nfunction utf8EncodeTE(str, output, outputOffset) {\n sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));\n}\nfunction utf8Encode(str, output, outputOffset) {\n if (str.length > TEXT_ENCODER_THRESHOLD) {\n utf8EncodeTE(str, output, outputOffset);\n }\n else {\n utf8EncodeJs(str, output, outputOffset);\n }\n}\nconst CHUNK_SIZE = 4096;\nfunction utf8DecodeJs(bytes, inputOffset, byteLength) {\n let offset = inputOffset;\n const end = offset + byteLength;\n const units = [];\n let result = \"\";\n while (offset < end) {\n const byte1 = bytes[offset++];\n if ((byte1 & 0x80) === 0) {\n // 1 byte\n units.push(byte1);\n }\n else if ((byte1 & 0xe0) === 0xc0) {\n // 2 bytes\n const byte2 = bytes[offset++] & 0x3f;\n units.push(((byte1 & 0x1f) << 6) | byte2);\n }\n else if ((byte1 & 0xf0) === 0xe0) {\n // 3 bytes\n const byte2 = bytes[offset++] & 0x3f;\n const byte3 = bytes[offset++] & 0x3f;\n units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);\n }\n else if ((byte1 & 0xf8) === 0xf0) {\n // 4 bytes\n const byte2 = bytes[offset++] & 0x3f;\n const byte3 = bytes[offset++] & 0x3f;\n const byte4 = bytes[offset++] & 0x3f;\n let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;\n if (unit > 0xffff) {\n unit -= 0x10000;\n units.push(((unit >>> 10) & 0x3ff) | 0xd800);\n unit = 0xdc00 | (unit & 0x3ff);\n }\n units.push(unit);\n }\n else {\n units.push(byte1);\n }\n if (units.length >= CHUNK_SIZE) {\n result += String.fromCharCode(...units);\n units.length = 0;\n }\n }\n if (units.length > 0) {\n result += String.fromCharCode(...units);\n }\n return result;\n}\nconst sharedTextDecoder = new TextDecoder();\n// This threshold should be determined by benchmarking, which might vary in engines and input data.\n// Run `npx ts-node benchmark/decode-string.ts` for details.\nconst TEXT_DECODER_THRESHOLD = 200;\nfunction utf8DecodeTD(bytes, inputOffset, byteLength) {\n const stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);\n return sharedTextDecoder.decode(stringBytes);\n}\nfunction utf8Decode(bytes, inputOffset, byteLength) {\n if (byteLength > TEXT_DECODER_THRESHOLD) {\n return utf8DecodeTD(bytes, inputOffset, byteLength);\n }\n else {\n return utf8DecodeJs(bytes, inputOffset, byteLength);\n }\n}\n//# sourceMappingURL=utf8.cjs.map",
7
+ "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ExtData = void 0;\n/**\n * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.\n */\nclass ExtData {\n type;\n data;\n constructor(type, data) {\n this.type = type;\n this.data = data;\n }\n}\nexports.ExtData = ExtData;\n//# sourceMappingURL=ExtData.cjs.map",
8
+ "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DecodeError = void 0;\nclass DecodeError extends Error {\n constructor(message) {\n super(message);\n // fix the prototype chain in a cross-platform way\n const proto = Object.create(DecodeError.prototype);\n Object.setPrototypeOf(this, proto);\n Object.defineProperty(this, \"name\", {\n configurable: true,\n enumerable: false,\n value: DecodeError.name,\n });\n }\n}\nexports.DecodeError = DecodeError;\n//# sourceMappingURL=DecodeError.cjs.map",
9
+ "\"use strict\";\n// Integer Utility\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UINT32_MAX = void 0;\nexports.setUint64 = setUint64;\nexports.setInt64 = setInt64;\nexports.getInt64 = getInt64;\nexports.getUint64 = getUint64;\nexports.UINT32_MAX = 4294967295;\n// DataView extension to handle int64 / uint64,\n// where the actual range is 53-bits integer (a.k.a. safe integer)\nfunction setUint64(view, offset, value) {\n const high = value / 4294967296;\n const low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\nfunction setInt64(view, offset, value) {\n const high = Math.floor(value / 4294967296);\n const low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\nfunction getInt64(view, offset) {\n const high = view.getInt32(offset);\n const low = view.getUint32(offset + 4);\n return high * 4294967296 + low;\n}\nfunction getUint64(view, offset) {\n const high = view.getUint32(offset);\n const low = view.getUint32(offset + 4);\n return high * 4294967296 + low;\n}\n//# sourceMappingURL=int.cjs.map",
10
+ "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.timestampExtension = exports.EXT_TIMESTAMP = void 0;\nexports.encodeTimeSpecToTimestamp = encodeTimeSpecToTimestamp;\nexports.encodeDateToTimeSpec = encodeDateToTimeSpec;\nexports.encodeTimestampExtension = encodeTimestampExtension;\nexports.decodeTimestampToTimeSpec = decodeTimestampToTimeSpec;\nexports.decodeTimestampExtension = decodeTimestampExtension;\n// https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type\nconst DecodeError_ts_1 = require(\"./DecodeError.cjs\");;\nconst int_ts_1 = require(\"./utils/int.cjs\");;\nexports.EXT_TIMESTAMP = -1;\nconst TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int\nconst TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int\nfunction encodeTimeSpecToTimestamp({ sec, nsec }) {\n if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {\n // Here sec >= 0 && nsec >= 0\n if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {\n // timestamp 32 = { sec32 (unsigned) }\n const rv = new Uint8Array(4);\n const view = new DataView(rv.buffer);\n view.setUint32(0, sec);\n return rv;\n }\n else {\n // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }\n const secHigh = sec / 0x100000000;\n const secLow = sec & 0xffffffff;\n const rv = new Uint8Array(8);\n const view = new DataView(rv.buffer);\n // nsec30 | secHigh2\n view.setUint32(0, (nsec << 2) | (secHigh & 0x3));\n // secLow32\n view.setUint32(4, secLow);\n return rv;\n }\n }\n else {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n const rv = new Uint8Array(12);\n const view = new DataView(rv.buffer);\n view.setUint32(0, nsec);\n (0, int_ts_1.setInt64)(view, 4, sec);\n return rv;\n }\n}\nfunction encodeDateToTimeSpec(date) {\n const msec = date.getTime();\n const sec = Math.floor(msec / 1e3);\n const nsec = (msec - sec * 1e3) * 1e6;\n // Normalizes { sec, nsec } to ensure nsec is unsigned.\n const nsecInSec = Math.floor(nsec / 1e9);\n return {\n sec: sec + nsecInSec,\n nsec: nsec - nsecInSec * 1e9,\n };\n}\nfunction encodeTimestampExtension(object) {\n if (object instanceof Date) {\n const timeSpec = encodeDateToTimeSpec(object);\n return encodeTimeSpecToTimestamp(timeSpec);\n }\n else {\n return null;\n }\n}\nfunction decodeTimestampToTimeSpec(data) {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n // data may be 32, 64, or 96 bits\n switch (data.byteLength) {\n case 4: {\n // timestamp 32 = { sec32 }\n const sec = view.getUint32(0);\n const nsec = 0;\n return { sec, nsec };\n }\n case 8: {\n // timestamp 64 = { nsec30, sec34 }\n const nsec30AndSecHigh2 = view.getUint32(0);\n const secLow32 = view.getUint32(4);\n const sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;\n const nsec = nsec30AndSecHigh2 >>> 2;\n return { sec, nsec };\n }\n case 12: {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n const sec = (0, int_ts_1.getInt64)(view, 4);\n const nsec = view.getUint32(0);\n return { sec, nsec };\n }\n default:\n throw new DecodeError_ts_1.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);\n }\n}\nfunction decodeTimestampExtension(data) {\n const timeSpec = decodeTimestampToTimeSpec(data);\n return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);\n}\nexports.timestampExtension = {\n type: exports.EXT_TIMESTAMP,\n encode: encodeTimestampExtension,\n decode: decodeTimestampExtension,\n};\n//# sourceMappingURL=timestamp.cjs.map",
11
+ "\"use strict\";\n// ExtensionCodec to handle MessagePack extensions\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ExtensionCodec = void 0;\nconst ExtData_ts_1 = require(\"./ExtData.cjs\");;\nconst timestamp_ts_1 = require(\"./timestamp.cjs\");;\nclass ExtensionCodec {\n static defaultCodec = new ExtensionCodec();\n // ensures ExtensionCodecType<X> matches ExtensionCodec<X>\n // this will make type errors a lot more clear\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __brand;\n // built-in extensions\n builtInEncoders = [];\n builtInDecoders = [];\n // custom extensions\n encoders = [];\n decoders = [];\n constructor() {\n this.register(timestamp_ts_1.timestampExtension);\n }\n register({ type, encode, decode, }) {\n if (type >= 0) {\n // custom extensions\n this.encoders[type] = encode;\n this.decoders[type] = decode;\n }\n else {\n // built-in extensions\n const index = -1 - type;\n this.builtInEncoders[index] = encode;\n this.builtInDecoders[index] = decode;\n }\n }\n tryToEncode(object, context) {\n // built-in extensions\n for (let i = 0; i < this.builtInEncoders.length; i++) {\n const encodeExt = this.builtInEncoders[i];\n if (encodeExt != null) {\n const data = encodeExt(object, context);\n if (data != null) {\n const type = -1 - i;\n return new ExtData_ts_1.ExtData(type, data);\n }\n }\n }\n // custom extensions\n for (let i = 0; i < this.encoders.length; i++) {\n const encodeExt = this.encoders[i];\n if (encodeExt != null) {\n const data = encodeExt(object, context);\n if (data != null) {\n const type = i;\n return new ExtData_ts_1.ExtData(type, data);\n }\n }\n }\n if (object instanceof ExtData_ts_1.ExtData) {\n // to keep ExtData as is\n return object;\n }\n return null;\n }\n decode(data, type, context) {\n const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];\n if (decodeExt) {\n return decodeExt(data, type, context);\n }\n else {\n // decode() does not fail, returns ExtData instead.\n return new ExtData_ts_1.ExtData(type, data);\n }\n }\n}\nexports.ExtensionCodec = ExtensionCodec;\n//# sourceMappingURL=ExtensionCodec.cjs.map",
12
+ "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ensureUint8Array = ensureUint8Array;\nfunction isArrayBufferLike(buffer) {\n return (buffer instanceof ArrayBuffer || (typeof SharedArrayBuffer !== \"undefined\" && buffer instanceof SharedArrayBuffer));\n}\nfunction ensureUint8Array(buffer) {\n if (buffer instanceof Uint8Array) {\n return buffer;\n }\n else if (ArrayBuffer.isView(buffer)) {\n return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n }\n else if (isArrayBufferLike(buffer)) {\n return new Uint8Array(buffer);\n }\n else {\n // ArrayLike<number>\n return Uint8Array.from(buffer);\n }\n}\n//# sourceMappingURL=typedArrays.cjs.map",
13
+ "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Encoder = exports.DEFAULT_INITIAL_BUFFER_SIZE = exports.DEFAULT_MAX_DEPTH = void 0;\nconst utf8_ts_1 = require(\"./utils/utf8.cjs\");;\nconst ExtensionCodec_ts_1 = require(\"./ExtensionCodec.cjs\");;\nconst int_ts_1 = require(\"./utils/int.cjs\");;\nconst typedArrays_ts_1 = require(\"./utils/typedArrays.cjs\");;\nexports.DEFAULT_MAX_DEPTH = 100;\nexports.DEFAULT_INITIAL_BUFFER_SIZE = 2048;\nclass Encoder {\n extensionCodec;\n context;\n useBigInt64;\n maxDepth;\n initialBufferSize;\n sortKeys;\n forceFloat32;\n ignoreUndefined;\n forceIntegerToFloat;\n pos;\n view;\n bytes;\n entered = false;\n constructor(options) {\n this.extensionCodec = options?.extensionCodec ?? ExtensionCodec_ts_1.ExtensionCodec.defaultCodec;\n this.context = options?.context; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined\n this.useBigInt64 = options?.useBigInt64 ?? false;\n this.maxDepth = options?.maxDepth ?? exports.DEFAULT_MAX_DEPTH;\n this.initialBufferSize = options?.initialBufferSize ?? exports.DEFAULT_INITIAL_BUFFER_SIZE;\n this.sortKeys = options?.sortKeys ?? false;\n this.forceFloat32 = options?.forceFloat32 ?? false;\n this.ignoreUndefined = options?.ignoreUndefined ?? false;\n this.forceIntegerToFloat = options?.forceIntegerToFloat ?? false;\n this.pos = 0;\n this.view = new DataView(new ArrayBuffer(this.initialBufferSize));\n this.bytes = new Uint8Array(this.view.buffer);\n }\n clone() {\n // Because of slightly special argument `context`,\n // type assertion is needed.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return new Encoder({\n extensionCodec: this.extensionCodec,\n context: this.context,\n useBigInt64: this.useBigInt64,\n maxDepth: this.maxDepth,\n initialBufferSize: this.initialBufferSize,\n sortKeys: this.sortKeys,\n forceFloat32: this.forceFloat32,\n ignoreUndefined: this.ignoreUndefined,\n forceIntegerToFloat: this.forceIntegerToFloat,\n });\n }\n reinitializeState() {\n this.pos = 0;\n }\n /**\n * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.\n *\n * @returns Encodes the object and returns a shared reference the encoder's internal buffer.\n */\n encodeSharedRef(object) {\n if (this.entered) {\n const instance = this.clone();\n return instance.encodeSharedRef(object);\n }\n try {\n this.entered = true;\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.subarray(0, this.pos);\n }\n finally {\n this.entered = false;\n }\n }\n /**\n * @returns Encodes the object and returns a copy of the encoder's internal buffer.\n */\n encode(object) {\n if (this.entered) {\n const instance = this.clone();\n return instance.encode(object);\n }\n try {\n this.entered = true;\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.slice(0, this.pos);\n }\n finally {\n this.entered = false;\n }\n }\n doEncode(object, depth) {\n if (depth > this.maxDepth) {\n throw new Error(`Too deep objects in depth ${depth}`);\n }\n if (object == null) {\n this.encodeNil();\n }\n else if (typeof object === \"boolean\") {\n this.encodeBoolean(object);\n }\n else if (typeof object === \"number\") {\n if (!this.forceIntegerToFloat) {\n this.encodeNumber(object);\n }\n else {\n this.encodeNumberAsFloat(object);\n }\n }\n else if (typeof object === \"string\") {\n this.encodeString(object);\n }\n else if (this.useBigInt64 && typeof object === \"bigint\") {\n this.encodeBigInt64(object);\n }\n else {\n this.encodeObject(object, depth);\n }\n }\n ensureBufferSizeToWrite(sizeToWrite) {\n const requiredSize = this.pos + sizeToWrite;\n if (this.view.byteLength < requiredSize) {\n this.resizeBuffer(requiredSize * 2);\n }\n }\n resizeBuffer(newSize) {\n const newBuffer = new ArrayBuffer(newSize);\n const newBytes = new Uint8Array(newBuffer);\n const newView = new DataView(newBuffer);\n newBytes.set(this.bytes);\n this.view = newView;\n this.bytes = newBytes;\n }\n encodeNil() {\n this.writeU8(0xc0);\n }\n encodeBoolean(object) {\n if (object === false) {\n this.writeU8(0xc2);\n }\n else {\n this.writeU8(0xc3);\n }\n }\n encodeNumber(object) {\n if (!this.forceIntegerToFloat && Number.isSafeInteger(object)) {\n if (object >= 0) {\n if (object < 0x80) {\n // positive fixint\n this.writeU8(object);\n }\n else if (object < 0x100) {\n // uint 8\n this.writeU8(0xcc);\n this.writeU8(object);\n }\n else if (object < 0x10000) {\n // uint 16\n this.writeU8(0xcd);\n this.writeU16(object);\n }\n else if (object < 0x100000000) {\n // uint 32\n this.writeU8(0xce);\n this.writeU32(object);\n }\n else if (!this.useBigInt64) {\n // uint 64\n this.writeU8(0xcf);\n this.writeU64(object);\n }\n else {\n this.encodeNumberAsFloat(object);\n }\n }\n else {\n if (object >= -0x20) {\n // negative fixint\n this.writeU8(0xe0 | (object + 0x20));\n }\n else if (object >= -0x80) {\n // int 8\n this.writeU8(0xd0);\n this.writeI8(object);\n }\n else if (object >= -0x8000) {\n // int 16\n this.writeU8(0xd1);\n this.writeI16(object);\n }\n else if (object >= -0x80000000) {\n // int 32\n this.writeU8(0xd2);\n this.writeI32(object);\n }\n else if (!this.useBigInt64) {\n // int 64\n this.writeU8(0xd3);\n this.writeI64(object);\n }\n else {\n this.encodeNumberAsFloat(object);\n }\n }\n }\n else {\n this.encodeNumberAsFloat(object);\n }\n }\n encodeNumberAsFloat(object) {\n if (this.forceFloat32) {\n // float 32\n this.writeU8(0xca);\n this.writeF32(object);\n }\n else {\n // float 64\n this.writeU8(0xcb);\n this.writeF64(object);\n }\n }\n encodeBigInt64(object) {\n if (object >= BigInt(0)) {\n // uint 64\n this.writeU8(0xcf);\n this.writeBigUint64(object);\n }\n else {\n // int 64\n this.writeU8(0xd3);\n this.writeBigInt64(object);\n }\n }\n writeStringHeader(byteLength) {\n if (byteLength < 32) {\n // fixstr\n this.writeU8(0xa0 + byteLength);\n }\n else if (byteLength < 0x100) {\n // str 8\n this.writeU8(0xd9);\n this.writeU8(byteLength);\n }\n else if (byteLength < 0x10000) {\n // str 16\n this.writeU8(0xda);\n this.writeU16(byteLength);\n }\n else if (byteLength < 0x100000000) {\n // str 32\n this.writeU8(0xdb);\n this.writeU32(byteLength);\n }\n else {\n throw new Error(`Too long string: ${byteLength} bytes in UTF-8`);\n }\n }\n encodeString(object) {\n const maxHeaderSize = 1 + 4;\n const byteLength = (0, utf8_ts_1.utf8Count)(object);\n this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n this.writeStringHeader(byteLength);\n (0, utf8_ts_1.utf8Encode)(object, this.bytes, this.pos);\n this.pos += byteLength;\n }\n encodeObject(object, depth) {\n // try to encode objects with custom codec first of non-primitives\n const ext = this.extensionCodec.tryToEncode(object, this.context);\n if (ext != null) {\n this.encodeExtension(ext);\n }\n else if (Array.isArray(object)) {\n this.encodeArray(object, depth);\n }\n else if (ArrayBuffer.isView(object)) {\n this.encodeBinary(object);\n }\n else if (typeof object === \"object\") {\n this.encodeMap(object, depth);\n }\n else {\n // symbol, function and other special object come here unless extensionCodec handles them.\n throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`);\n }\n }\n encodeBinary(object) {\n const size = object.byteLength;\n if (size < 0x100) {\n // bin 8\n this.writeU8(0xc4);\n this.writeU8(size);\n }\n else if (size < 0x10000) {\n // bin 16\n this.writeU8(0xc5);\n this.writeU16(size);\n }\n else if (size < 0x100000000) {\n // bin 32\n this.writeU8(0xc6);\n this.writeU32(size);\n }\n else {\n throw new Error(`Too large binary: ${size}`);\n }\n const bytes = (0, typedArrays_ts_1.ensureUint8Array)(object);\n this.writeU8a(bytes);\n }\n encodeArray(object, depth) {\n const size = object.length;\n if (size < 16) {\n // fixarray\n this.writeU8(0x90 + size);\n }\n else if (size < 0x10000) {\n // array 16\n this.writeU8(0xdc);\n this.writeU16(size);\n }\n else if (size < 0x100000000) {\n // array 32\n this.writeU8(0xdd);\n this.writeU32(size);\n }\n else {\n throw new Error(`Too large array: ${size}`);\n }\n for (const item of object) {\n this.doEncode(item, depth + 1);\n }\n }\n countWithoutUndefined(object, keys) {\n let count = 0;\n for (const key of keys) {\n if (object[key] !== undefined) {\n count++;\n }\n }\n return count;\n }\n encodeMap(object, depth) {\n const keys = Object.keys(object);\n if (this.sortKeys) {\n keys.sort();\n }\n const size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;\n if (size < 16) {\n // fixmap\n this.writeU8(0x80 + size);\n }\n else if (size < 0x10000) {\n // map 16\n this.writeU8(0xde);\n this.writeU16(size);\n }\n else if (size < 0x100000000) {\n // map 32\n this.writeU8(0xdf);\n this.writeU32(size);\n }\n else {\n throw new Error(`Too large map object: ${size}`);\n }\n for (const key of keys) {\n const value = object[key];\n if (!(this.ignoreUndefined && value === undefined)) {\n this.encodeString(key);\n this.doEncode(value, depth + 1);\n }\n }\n }\n encodeExtension(ext) {\n if (typeof ext.data === \"function\") {\n const data = ext.data(this.pos + 6);\n const size = data.length;\n if (size >= 0x100000000) {\n throw new Error(`Too large extension object: ${size}`);\n }\n this.writeU8(0xc9);\n this.writeU32(size);\n this.writeI8(ext.type);\n this.writeU8a(data);\n return;\n }\n const size = ext.data.length;\n if (size === 1) {\n // fixext 1\n this.writeU8(0xd4);\n }\n else if (size === 2) {\n // fixext 2\n this.writeU8(0xd5);\n }\n else if (size === 4) {\n // fixext 4\n this.writeU8(0xd6);\n }\n else if (size === 8) {\n // fixext 8\n this.writeU8(0xd7);\n }\n else if (size === 16) {\n // fixext 16\n this.writeU8(0xd8);\n }\n else if (size < 0x100) {\n // ext 8\n this.writeU8(0xc7);\n this.writeU8(size);\n }\n else if (size < 0x10000) {\n // ext 16\n this.writeU8(0xc8);\n this.writeU16(size);\n }\n else if (size < 0x100000000) {\n // ext 32\n this.writeU8(0xc9);\n this.writeU32(size);\n }\n else {\n throw new Error(`Too large extension object: ${size}`);\n }\n this.writeI8(ext.type);\n this.writeU8a(ext.data);\n }\n writeU8(value) {\n this.ensureBufferSizeToWrite(1);\n this.view.setUint8(this.pos, value);\n this.pos++;\n }\n writeU8a(values) {\n const size = values.length;\n this.ensureBufferSizeToWrite(size);\n this.bytes.set(values, this.pos);\n this.pos += size;\n }\n writeI8(value) {\n this.ensureBufferSizeToWrite(1);\n this.view.setInt8(this.pos, value);\n this.pos++;\n }\n writeU16(value) {\n this.ensureBufferSizeToWrite(2);\n this.view.setUint16(this.pos, value);\n this.pos += 2;\n }\n writeI16(value) {\n this.ensureBufferSizeToWrite(2);\n this.view.setInt16(this.pos, value);\n this.pos += 2;\n }\n writeU32(value) {\n this.ensureBufferSizeToWrite(4);\n this.view.setUint32(this.pos, value);\n this.pos += 4;\n }\n writeI32(value) {\n this.ensureBufferSizeToWrite(4);\n this.view.setInt32(this.pos, value);\n this.pos += 4;\n }\n writeF32(value) {\n this.ensureBufferSizeToWrite(4);\n this.view.setFloat32(this.pos, value);\n this.pos += 4;\n }\n writeF64(value) {\n this.ensureBufferSizeToWrite(8);\n this.view.setFloat64(this.pos, value);\n this.pos += 8;\n }\n writeU64(value) {\n this.ensureBufferSizeToWrite(8);\n (0, int_ts_1.setUint64)(this.view, this.pos, value);\n this.pos += 8;\n }\n writeI64(value) {\n this.ensureBufferSizeToWrite(8);\n (0, int_ts_1.setInt64)(this.view, this.pos, value);\n this.pos += 8;\n }\n writeBigUint64(value) {\n this.ensureBufferSizeToWrite(8);\n this.view.setBigUint64(this.pos, value);\n this.pos += 8;\n }\n writeBigInt64(value) {\n this.ensureBufferSizeToWrite(8);\n this.view.setBigInt64(this.pos, value);\n this.pos += 8;\n }\n}\nexports.Encoder = Encoder;\n//# sourceMappingURL=Encoder.cjs.map",
14
+ "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.encode = encode;\nconst Encoder_ts_1 = require(\"./Encoder.cjs\");;\n/**\n * It encodes `value` in the MessagePack format and\n * returns a byte buffer.\n *\n * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.\n */\nfunction encode(value, options) {\n const encoder = new Encoder_ts_1.Encoder(options);\n return encoder.encodeSharedRef(value);\n}\n//# sourceMappingURL=encode.cjs.map",
15
+ "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.prettyByte = prettyByte;\nfunction prettyByte(byte) {\n return `${byte < 0 ? \"-\" : \"\"}0x${Math.abs(byte).toString(16).padStart(2, \"0\")}`;\n}\n//# sourceMappingURL=prettyByte.cjs.map",
16
+ "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CachedKeyDecoder = void 0;\nconst utf8_ts_1 = require(\"./utils/utf8.cjs\");;\nconst DEFAULT_MAX_KEY_LENGTH = 16;\nconst DEFAULT_MAX_LENGTH_PER_KEY = 16;\nclass CachedKeyDecoder {\n hit = 0;\n miss = 0;\n caches;\n maxKeyLength;\n maxLengthPerKey;\n constructor(maxKeyLength = DEFAULT_MAX_KEY_LENGTH, maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY) {\n this.maxKeyLength = maxKeyLength;\n this.maxLengthPerKey = maxLengthPerKey;\n // avoid `new Array(N)`, which makes a sparse array,\n // because a sparse array is typically slower than a non-sparse array.\n this.caches = [];\n for (let i = 0; i < this.maxKeyLength; i++) {\n this.caches.push([]);\n }\n }\n canBeCached(byteLength) {\n return byteLength > 0 && byteLength <= this.maxKeyLength;\n }\n find(bytes, inputOffset, byteLength) {\n const records = this.caches[byteLength - 1];\n FIND_CHUNK: for (const record of records) {\n const recordBytes = record.bytes;\n for (let j = 0; j < byteLength; j++) {\n if (recordBytes[j] !== bytes[inputOffset + j]) {\n continue FIND_CHUNK;\n }\n }\n return record.str;\n }\n return null;\n }\n store(bytes, value) {\n const records = this.caches[bytes.length - 1];\n const record = { bytes, str: value };\n if (records.length >= this.maxLengthPerKey) {\n // `records` are full!\n // Set `record` to an arbitrary position.\n records[(Math.random() * records.length) | 0] = record;\n }\n else {\n records.push(record);\n }\n }\n decode(bytes, inputOffset, byteLength) {\n const cachedValue = this.find(bytes, inputOffset, byteLength);\n if (cachedValue != null) {\n this.hit++;\n return cachedValue;\n }\n this.miss++;\n const str = (0, utf8_ts_1.utf8DecodeJs)(bytes, inputOffset, byteLength);\n // Ensure to copy a slice of bytes because the bytes may be a NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.\n const slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);\n this.store(slicedCopyOfBytes, str);\n return str;\n }\n}\nexports.CachedKeyDecoder = CachedKeyDecoder;\n//# sourceMappingURL=CachedKeyDecoder.cjs.map",
17
+ "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Decoder = void 0;\nconst prettyByte_ts_1 = require(\"./utils/prettyByte.cjs\");;\nconst ExtensionCodec_ts_1 = require(\"./ExtensionCodec.cjs\");;\nconst int_ts_1 = require(\"./utils/int.cjs\");;\nconst utf8_ts_1 = require(\"./utils/utf8.cjs\");;\nconst typedArrays_ts_1 = require(\"./utils/typedArrays.cjs\");;\nconst CachedKeyDecoder_ts_1 = require(\"./CachedKeyDecoder.cjs\");;\nconst DecodeError_ts_1 = require(\"./DecodeError.cjs\");;\nconst STATE_ARRAY = \"array\";\nconst STATE_MAP_KEY = \"map_key\";\nconst STATE_MAP_VALUE = \"map_value\";\nconst mapKeyConverter = (key) => {\n if (typeof key === \"string\" || typeof key === \"number\") {\n return key;\n }\n throw new DecodeError_ts_1.DecodeError(\"The type of key must be string or number but \" + typeof key);\n};\nclass StackPool {\n stack = [];\n stackHeadPosition = -1;\n get length() {\n return this.stackHeadPosition + 1;\n }\n top() {\n return this.stack[this.stackHeadPosition];\n }\n pushArrayState(size) {\n const state = this.getUninitializedStateFromPool();\n state.type = STATE_ARRAY;\n state.position = 0;\n state.size = size;\n state.array = new Array(size);\n }\n pushMapState(size) {\n const state = this.getUninitializedStateFromPool();\n state.type = STATE_MAP_KEY;\n state.readCount = 0;\n state.size = size;\n state.map = {};\n }\n getUninitializedStateFromPool() {\n this.stackHeadPosition++;\n if (this.stackHeadPosition === this.stack.length) {\n const partialState = {\n type: undefined,\n size: 0,\n array: undefined,\n position: 0,\n readCount: 0,\n map: undefined,\n key: null,\n };\n this.stack.push(partialState);\n }\n return this.stack[this.stackHeadPosition];\n }\n release(state) {\n const topStackState = this.stack[this.stackHeadPosition];\n if (topStackState !== state) {\n throw new Error(\"Invalid stack state. Released state is not on top of the stack.\");\n }\n if (state.type === STATE_ARRAY) {\n const partialState = state;\n partialState.size = 0;\n partialState.array = undefined;\n partialState.position = 0;\n partialState.type = undefined;\n }\n if (state.type === STATE_MAP_KEY || state.type === STATE_MAP_VALUE) {\n const partialState = state;\n partialState.size = 0;\n partialState.map = undefined;\n partialState.readCount = 0;\n partialState.type = undefined;\n }\n this.stackHeadPosition--;\n }\n reset() {\n this.stack.length = 0;\n this.stackHeadPosition = -1;\n }\n}\nconst HEAD_BYTE_REQUIRED = -1;\nconst EMPTY_VIEW = new DataView(new ArrayBuffer(0));\nconst EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);\ntry {\n // IE11: The spec says it should throw RangeError,\n // IE11: but in IE11 it throws TypeError.\n EMPTY_VIEW.getInt8(0);\n}\ncatch (e) {\n if (!(e instanceof RangeError)) {\n throw new Error(\"This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access\");\n }\n}\nconst MORE_DATA = new RangeError(\"Insufficient data\");\nconst sharedCachedKeyDecoder = new CachedKeyDecoder_ts_1.CachedKeyDecoder();\nclass Decoder {\n extensionCodec;\n context;\n useBigInt64;\n rawStrings;\n maxStrLength;\n maxBinLength;\n maxArrayLength;\n maxMapLength;\n maxExtLength;\n keyDecoder;\n mapKeyConverter;\n totalPos = 0;\n pos = 0;\n view = EMPTY_VIEW;\n bytes = EMPTY_BYTES;\n headByte = HEAD_BYTE_REQUIRED;\n stack = new StackPool();\n entered = false;\n constructor(options) {\n this.extensionCodec = options?.extensionCodec ?? ExtensionCodec_ts_1.ExtensionCodec.defaultCodec;\n this.context = options?.context; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined\n this.useBigInt64 = options?.useBigInt64 ?? false;\n this.rawStrings = options?.rawStrings ?? false;\n this.maxStrLength = options?.maxStrLength ?? int_ts_1.UINT32_MAX;\n this.maxBinLength = options?.maxBinLength ?? int_ts_1.UINT32_MAX;\n this.maxArrayLength = options?.maxArrayLength ?? int_ts_1.UINT32_MAX;\n this.maxMapLength = options?.maxMapLength ?? int_ts_1.UINT32_MAX;\n this.maxExtLength = options?.maxExtLength ?? int_ts_1.UINT32_MAX;\n this.keyDecoder = options?.keyDecoder !== undefined ? options.keyDecoder : sharedCachedKeyDecoder;\n this.mapKeyConverter = options?.mapKeyConverter ?? mapKeyConverter;\n }\n clone() {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return new Decoder({\n extensionCodec: this.extensionCodec,\n context: this.context,\n useBigInt64: this.useBigInt64,\n rawStrings: this.rawStrings,\n maxStrLength: this.maxStrLength,\n maxBinLength: this.maxBinLength,\n maxArrayLength: this.maxArrayLength,\n maxMapLength: this.maxMapLength,\n maxExtLength: this.maxExtLength,\n keyDecoder: this.keyDecoder,\n });\n }\n reinitializeState() {\n this.totalPos = 0;\n this.headByte = HEAD_BYTE_REQUIRED;\n this.stack.reset();\n // view, bytes, and pos will be re-initialized in setBuffer()\n }\n setBuffer(buffer) {\n const bytes = (0, typedArrays_ts_1.ensureUint8Array)(buffer);\n this.bytes = bytes;\n this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n this.pos = 0;\n }\n appendBuffer(buffer) {\n if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {\n this.setBuffer(buffer);\n }\n else {\n const remainingData = this.bytes.subarray(this.pos);\n const newData = (0, typedArrays_ts_1.ensureUint8Array)(buffer);\n // concat remainingData + newData\n const newBuffer = new Uint8Array(remainingData.length + newData.length);\n newBuffer.set(remainingData);\n newBuffer.set(newData, remainingData.length);\n this.setBuffer(newBuffer);\n }\n }\n hasRemaining(size) {\n return this.view.byteLength - this.pos >= size;\n }\n createExtraByteError(posToShow) {\n const { view, pos } = this;\n return new RangeError(`Extra ${view.byteLength - pos} of ${view.byteLength} byte(s) found at buffer[${posToShow}]`);\n }\n /**\n * @throws {@link DecodeError}\n * @throws {@link RangeError}\n */\n decode(buffer) {\n if (this.entered) {\n const instance = this.clone();\n return instance.decode(buffer);\n }\n try {\n this.entered = true;\n this.reinitializeState();\n this.setBuffer(buffer);\n const object = this.doDecodeSync();\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.pos);\n }\n return object;\n }\n finally {\n this.entered = false;\n }\n }\n *decodeMulti(buffer) {\n if (this.entered) {\n const instance = this.clone();\n yield* instance.decodeMulti(buffer);\n return;\n }\n try {\n this.entered = true;\n this.reinitializeState();\n this.setBuffer(buffer);\n while (this.hasRemaining(1)) {\n yield this.doDecodeSync();\n }\n }\n finally {\n this.entered = false;\n }\n }\n async decodeAsync(stream) {\n if (this.entered) {\n const instance = this.clone();\n return instance.decodeAsync(stream);\n }\n try {\n this.entered = true;\n let decoded = false;\n let object;\n for await (const buffer of stream) {\n if (decoded) {\n this.entered = false;\n throw this.createExtraByteError(this.totalPos);\n }\n this.appendBuffer(buffer);\n try {\n object = this.doDecodeSync();\n decoded = true;\n }\n catch (e) {\n if (!(e instanceof RangeError)) {\n throw e; // rethrow\n }\n // fallthrough\n }\n this.totalPos += this.pos;\n }\n if (decoded) {\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.totalPos);\n }\n return object;\n }\n const { headByte, pos, totalPos } = this;\n throw new RangeError(`Insufficient data in parsing ${(0, prettyByte_ts_1.prettyByte)(headByte)} at ${totalPos} (${pos} in the current buffer)`);\n }\n finally {\n this.entered = false;\n }\n }\n decodeArrayStream(stream) {\n return this.decodeMultiAsync(stream, true);\n }\n decodeStream(stream) {\n return this.decodeMultiAsync(stream, false);\n }\n async *decodeMultiAsync(stream, isArray) {\n if (this.entered) {\n const instance = this.clone();\n yield* instance.decodeMultiAsync(stream, isArray);\n return;\n }\n try {\n this.entered = true;\n let isArrayHeaderRequired = isArray;\n let arrayItemsLeft = -1;\n for await (const buffer of stream) {\n if (isArray && arrayItemsLeft === 0) {\n throw this.createExtraByteError(this.totalPos);\n }\n this.appendBuffer(buffer);\n if (isArrayHeaderRequired) {\n arrayItemsLeft = this.readArraySize();\n isArrayHeaderRequired = false;\n this.complete();\n }\n try {\n while (true) {\n yield this.doDecodeSync();\n if (--arrayItemsLeft === 0) {\n break;\n }\n }\n }\n catch (e) {\n if (!(e instanceof RangeError)) {\n throw e; // rethrow\n }\n // fallthrough\n }\n this.totalPos += this.pos;\n }\n }\n finally {\n this.entered = false;\n }\n }\n doDecodeSync() {\n DECODE: while (true) {\n const headByte = this.readHeadByte();\n let object;\n if (headByte >= 0xe0) {\n // negative fixint (111x xxxx) 0xe0 - 0xff\n object = headByte - 0x100;\n }\n else if (headByte < 0xc0) {\n if (headByte < 0x80) {\n // positive fixint (0xxx xxxx) 0x00 - 0x7f\n object = headByte;\n }\n else if (headByte < 0x90) {\n // fixmap (1000 xxxx) 0x80 - 0x8f\n const size = headByte - 0x80;\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = {};\n }\n }\n else if (headByte < 0xa0) {\n // fixarray (1001 xxxx) 0x90 - 0x9f\n const size = headByte - 0x90;\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = [];\n }\n }\n else {\n // fixstr (101x xxxx) 0xa0 - 0xbf\n const byteLength = headByte - 0xa0;\n object = this.decodeString(byteLength, 0);\n }\n }\n else if (headByte === 0xc0) {\n // nil\n object = null;\n }\n else if (headByte === 0xc2) {\n // false\n object = false;\n }\n else if (headByte === 0xc3) {\n // true\n object = true;\n }\n else if (headByte === 0xca) {\n // float 32\n object = this.readF32();\n }\n else if (headByte === 0xcb) {\n // float 64\n object = this.readF64();\n }\n else if (headByte === 0xcc) {\n // uint 8\n object = this.readU8();\n }\n else if (headByte === 0xcd) {\n // uint 16\n object = this.readU16();\n }\n else if (headByte === 0xce) {\n // uint 32\n object = this.readU32();\n }\n else if (headByte === 0xcf) {\n // uint 64\n if (this.useBigInt64) {\n object = this.readU64AsBigInt();\n }\n else {\n object = this.readU64();\n }\n }\n else if (headByte === 0xd0) {\n // int 8\n object = this.readI8();\n }\n else if (headByte === 0xd1) {\n // int 16\n object = this.readI16();\n }\n else if (headByte === 0xd2) {\n // int 32\n object = this.readI32();\n }\n else if (headByte === 0xd3) {\n // int 64\n if (this.useBigInt64) {\n object = this.readI64AsBigInt();\n }\n else {\n object = this.readI64();\n }\n }\n else if (headByte === 0xd9) {\n // str 8\n const byteLength = this.lookU8();\n object = this.decodeString(byteLength, 1);\n }\n else if (headByte === 0xda) {\n // str 16\n const byteLength = this.lookU16();\n object = this.decodeString(byteLength, 2);\n }\n else if (headByte === 0xdb) {\n // str 32\n const byteLength = this.lookU32();\n object = this.decodeString(byteLength, 4);\n }\n else if (headByte === 0xdc) {\n // array 16\n const size = this.readU16();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = [];\n }\n }\n else if (headByte === 0xdd) {\n // array 32\n const size = this.readU32();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = [];\n }\n }\n else if (headByte === 0xde) {\n // map 16\n const size = this.readU16();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = {};\n }\n }\n else if (headByte === 0xdf) {\n // map 32\n const size = this.readU32();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = {};\n }\n }\n else if (headByte === 0xc4) {\n // bin 8\n const size = this.lookU8();\n object = this.decodeBinary(size, 1);\n }\n else if (headByte === 0xc5) {\n // bin 16\n const size = this.lookU16();\n object = this.decodeBinary(size, 2);\n }\n else if (headByte === 0xc6) {\n // bin 32\n const size = this.lookU32();\n object = this.decodeBinary(size, 4);\n }\n else if (headByte === 0xd4) {\n // fixext 1\n object = this.decodeExtension(1, 0);\n }\n else if (headByte === 0xd5) {\n // fixext 2\n object = this.decodeExtension(2, 0);\n }\n else if (headByte === 0xd6) {\n // fixext 4\n object = this.decodeExtension(4, 0);\n }\n else if (headByte === 0xd7) {\n // fixext 8\n object = this.decodeExtension(8, 0);\n }\n else if (headByte === 0xd8) {\n // fixext 16\n object = this.decodeExtension(16, 0);\n }\n else if (headByte === 0xc7) {\n // ext 8\n const size = this.lookU8();\n object = this.decodeExtension(size, 1);\n }\n else if (headByte === 0xc8) {\n // ext 16\n const size = this.lookU16();\n object = this.decodeExtension(size, 2);\n }\n else if (headByte === 0xc9) {\n // ext 32\n const size = this.lookU32();\n object = this.decodeExtension(size, 4);\n }\n else {\n throw new DecodeError_ts_1.DecodeError(`Unrecognized type byte: ${(0, prettyByte_ts_1.prettyByte)(headByte)}`);\n }\n this.complete();\n const stack = this.stack;\n while (stack.length > 0) {\n // arrays and maps\n const state = stack.top();\n if (state.type === STATE_ARRAY) {\n state.array[state.position] = object;\n state.position++;\n if (state.position === state.size) {\n object = state.array;\n stack.release(state);\n }\n else {\n continue DECODE;\n }\n }\n else if (state.type === STATE_MAP_KEY) {\n if (object === \"__proto__\") {\n throw new DecodeError_ts_1.DecodeError(\"The key __proto__ is not allowed\");\n }\n state.key = this.mapKeyConverter(object);\n state.type = STATE_MAP_VALUE;\n continue DECODE;\n }\n else {\n // it must be `state.type === State.MAP_VALUE` here\n state.map[state.key] = object;\n state.readCount++;\n if (state.readCount === state.size) {\n object = state.map;\n stack.release(state);\n }\n else {\n state.key = null;\n state.type = STATE_MAP_KEY;\n continue DECODE;\n }\n }\n }\n return object;\n }\n }\n readHeadByte() {\n if (this.headByte === HEAD_BYTE_REQUIRED) {\n this.headByte = this.readU8();\n // console.log(\"headByte\", prettyByte(this.headByte));\n }\n return this.headByte;\n }\n complete() {\n this.headByte = HEAD_BYTE_REQUIRED;\n }\n readArraySize() {\n const headByte = this.readHeadByte();\n switch (headByte) {\n case 0xdc:\n return this.readU16();\n case 0xdd:\n return this.readU32();\n default: {\n if (headByte < 0xa0) {\n return headByte - 0x90;\n }\n else {\n throw new DecodeError_ts_1.DecodeError(`Unrecognized array type byte: ${(0, prettyByte_ts_1.prettyByte)(headByte)}`);\n }\n }\n }\n }\n pushMapState(size) {\n if (size > this.maxMapLength) {\n throw new DecodeError_ts_1.DecodeError(`Max length exceeded: map length (${size}) > maxMapLengthLength (${this.maxMapLength})`);\n }\n this.stack.pushMapState(size);\n }\n pushArrayState(size) {\n if (size > this.maxArrayLength) {\n throw new DecodeError_ts_1.DecodeError(`Max length exceeded: array length (${size}) > maxArrayLength (${this.maxArrayLength})`);\n }\n this.stack.pushArrayState(size);\n }\n decodeString(byteLength, headerOffset) {\n if (!this.rawStrings || this.stateIsMapKey()) {\n return this.decodeUtf8String(byteLength, headerOffset);\n }\n return this.decodeBinary(byteLength, headerOffset);\n }\n /**\n * @throws {@link RangeError}\n */\n decodeUtf8String(byteLength, headerOffset) {\n if (byteLength > this.maxStrLength) {\n throw new DecodeError_ts_1.DecodeError(`Max length exceeded: UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`);\n }\n if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {\n throw MORE_DATA;\n }\n const offset = this.pos + headerOffset;\n let object;\n if (this.stateIsMapKey() && this.keyDecoder?.canBeCached(byteLength)) {\n object = this.keyDecoder.decode(this.bytes, offset, byteLength);\n }\n else {\n object = (0, utf8_ts_1.utf8Decode)(this.bytes, offset, byteLength);\n }\n this.pos += headerOffset + byteLength;\n return object;\n }\n stateIsMapKey() {\n if (this.stack.length > 0) {\n const state = this.stack.top();\n return state.type === STATE_MAP_KEY;\n }\n return false;\n }\n /**\n * @throws {@link RangeError}\n */\n decodeBinary(byteLength, headOffset) {\n if (byteLength > this.maxBinLength) {\n throw new DecodeError_ts_1.DecodeError(`Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`);\n }\n if (!this.hasRemaining(byteLength + headOffset)) {\n throw MORE_DATA;\n }\n const offset = this.pos + headOffset;\n const object = this.bytes.subarray(offset, offset + byteLength);\n this.pos += headOffset + byteLength;\n return object;\n }\n decodeExtension(size, headOffset) {\n if (size > this.maxExtLength) {\n throw new DecodeError_ts_1.DecodeError(`Max length exceeded: ext length (${size}) > maxExtLength (${this.maxExtLength})`);\n }\n const extType = this.view.getInt8(this.pos + headOffset);\n const data = this.decodeBinary(size, headOffset + 1 /* extType */);\n return this.extensionCodec.decode(data, extType, this.context);\n }\n lookU8() {\n return this.view.getUint8(this.pos);\n }\n lookU16() {\n return this.view.getUint16(this.pos);\n }\n lookU32() {\n return this.view.getUint32(this.pos);\n }\n readU8() {\n const value = this.view.getUint8(this.pos);\n this.pos++;\n return value;\n }\n readI8() {\n const value = this.view.getInt8(this.pos);\n this.pos++;\n return value;\n }\n readU16() {\n const value = this.view.getUint16(this.pos);\n this.pos += 2;\n return value;\n }\n readI16() {\n const value = this.view.getInt16(this.pos);\n this.pos += 2;\n return value;\n }\n readU32() {\n const value = this.view.getUint32(this.pos);\n this.pos += 4;\n return value;\n }\n readI32() {\n const value = this.view.getInt32(this.pos);\n this.pos += 4;\n return value;\n }\n readU64() {\n const value = (0, int_ts_1.getUint64)(this.view, this.pos);\n this.pos += 8;\n return value;\n }\n readI64() {\n const value = (0, int_ts_1.getInt64)(this.view, this.pos);\n this.pos += 8;\n return value;\n }\n readU64AsBigInt() {\n const value = this.view.getBigUint64(this.pos);\n this.pos += 8;\n return value;\n }\n readI64AsBigInt() {\n const value = this.view.getBigInt64(this.pos);\n this.pos += 8;\n return value;\n }\n readF32() {\n const value = this.view.getFloat32(this.pos);\n this.pos += 4;\n return value;\n }\n readF64() {\n const value = this.view.getFloat64(this.pos);\n this.pos += 8;\n return value;\n }\n}\nexports.Decoder = Decoder;\n//# sourceMappingURL=Decoder.cjs.map",
18
+ "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.decode = decode;\nexports.decodeMulti = decodeMulti;\nconst Decoder_ts_1 = require(\"./Decoder.cjs\");;\n/**\n * It decodes a single MessagePack object in a buffer.\n *\n * This is a synchronous decoding function.\n * See other variants for asynchronous decoding: {@link decodeAsync}, {@link decodeMultiStream}, or {@link decodeArrayStream}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nfunction decode(buffer, options) {\n const decoder = new Decoder_ts_1.Decoder(options);\n return decoder.decode(buffer);\n}\n/**\n * It decodes multiple MessagePack objects in a buffer.\n * This is corresponding to {@link decodeMultiStream}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nfunction decodeMulti(buffer, options) {\n const decoder = new Decoder_ts_1.Decoder(options);\n return decoder.decodeMulti(buffer);\n}\n//# sourceMappingURL=decode.cjs.map",
19
+ "\"use strict\";\n// utility for whatwg streams\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isAsyncIterable = isAsyncIterable;\nexports.asyncIterableFromStream = asyncIterableFromStream;\nexports.ensureAsyncIterable = ensureAsyncIterable;\nfunction isAsyncIterable(object) {\n return object[Symbol.asyncIterator] != null;\n}\nasync function* asyncIterableFromStream(stream) {\n const reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n yield value;\n }\n }\n finally {\n reader.releaseLock();\n }\n}\nfunction ensureAsyncIterable(streamLike) {\n if (isAsyncIterable(streamLike)) {\n return streamLike;\n }\n else {\n return asyncIterableFromStream(streamLike);\n }\n}\n//# sourceMappingURL=stream.cjs.map",
20
+ "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.decodeAsync = decodeAsync;\nexports.decodeArrayStream = decodeArrayStream;\nexports.decodeMultiStream = decodeMultiStream;\nconst Decoder_ts_1 = require(\"./Decoder.cjs\");;\nconst stream_ts_1 = require(\"./utils/stream.cjs\");;\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nasync function decodeAsync(streamLike, options) {\n const stream = (0, stream_ts_1.ensureAsyncIterable)(streamLike);\n const decoder = new Decoder_ts_1.Decoder(options);\n return decoder.decodeAsync(stream);\n}\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nfunction decodeArrayStream(streamLike, options) {\n const stream = (0, stream_ts_1.ensureAsyncIterable)(streamLike);\n const decoder = new Decoder_ts_1.Decoder(options);\n return decoder.decodeArrayStream(stream);\n}\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nfunction decodeMultiStream(streamLike, options) {\n const stream = (0, stream_ts_1.ensureAsyncIterable)(streamLike);\n const decoder = new Decoder_ts_1.Decoder(options);\n return decoder.decodeStream(stream);\n}\n//# sourceMappingURL=decodeAsync.cjs.map",
21
+ "\"use strict\";\n// Main Functions:\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.decodeTimestampExtension = exports.encodeTimestampExtension = exports.decodeTimestampToTimeSpec = exports.encodeTimeSpecToTimestamp = exports.encodeDateToTimeSpec = exports.EXT_TIMESTAMP = exports.ExtData = exports.ExtensionCodec = exports.Encoder = exports.DecodeError = exports.Decoder = exports.decodeMultiStream = exports.decodeArrayStream = exports.decodeAsync = exports.decodeMulti = exports.decode = exports.encode = void 0;\nconst encode_ts_1 = require(\"./encode.cjs\");;\nObject.defineProperty(exports, \"encode\", { enumerable: true, get: function () { return encode_ts_1.encode; } });\nconst decode_ts_1 = require(\"./decode.cjs\");;\nObject.defineProperty(exports, \"decode\", { enumerable: true, get: function () { return decode_ts_1.decode; } });\nObject.defineProperty(exports, \"decodeMulti\", { enumerable: true, get: function () { return decode_ts_1.decodeMulti; } });\nconst decodeAsync_ts_1 = require(\"./decodeAsync.cjs\");;\nObject.defineProperty(exports, \"decodeAsync\", { enumerable: true, get: function () { return decodeAsync_ts_1.decodeAsync; } });\nObject.defineProperty(exports, \"decodeArrayStream\", { enumerable: true, get: function () { return decodeAsync_ts_1.decodeArrayStream; } });\nObject.defineProperty(exports, \"decodeMultiStream\", { enumerable: true, get: function () { return decodeAsync_ts_1.decodeMultiStream; } });\nconst Decoder_ts_1 = require(\"./Decoder.cjs\");;\nObject.defineProperty(exports, \"Decoder\", { enumerable: true, get: function () { return Decoder_ts_1.Decoder; } });\nconst DecodeError_ts_1 = require(\"./DecodeError.cjs\");;\nObject.defineProperty(exports, \"DecodeError\", { enumerable: true, get: function () { return DecodeError_ts_1.DecodeError; } });\nconst Encoder_ts_1 = require(\"./Encoder.cjs\");;\nObject.defineProperty(exports, \"Encoder\", { enumerable: true, get: function () { return Encoder_ts_1.Encoder; } });\n// Utilities for Extension Types:\nconst ExtensionCodec_ts_1 = require(\"./ExtensionCodec.cjs\");;\nObject.defineProperty(exports, \"ExtensionCodec\", { enumerable: true, get: function () { return ExtensionCodec_ts_1.ExtensionCodec; } });\nconst ExtData_ts_1 = require(\"./ExtData.cjs\");;\nObject.defineProperty(exports, \"ExtData\", { enumerable: true, get: function () { return ExtData_ts_1.ExtData; } });\nconst timestamp_ts_1 = require(\"./timestamp.cjs\");;\nObject.defineProperty(exports, \"EXT_TIMESTAMP\", { enumerable: true, get: function () { return timestamp_ts_1.EXT_TIMESTAMP; } });\nObject.defineProperty(exports, \"encodeDateToTimeSpec\", { enumerable: true, get: function () { return timestamp_ts_1.encodeDateToTimeSpec; } });\nObject.defineProperty(exports, \"encodeTimeSpecToTimestamp\", { enumerable: true, get: function () { return timestamp_ts_1.encodeTimeSpecToTimestamp; } });\nObject.defineProperty(exports, \"decodeTimestampToTimeSpec\", { enumerable: true, get: function () { return timestamp_ts_1.decodeTimestampToTimeSpec; } });\nObject.defineProperty(exports, \"encodeTimestampExtension\", { enumerable: true, get: function () { return timestamp_ts_1.encodeTimestampExtension; } });\nObject.defineProperty(exports, \"decodeTimestampExtension\", { enumerable: true, get: function () { return timestamp_ts_1.decodeTimestampExtension; } });\n//# sourceMappingURL=index.cjs.map",
22
+ "import type { EngineConsumerConfig } from \"../types/consumer.types.ts\";\r\nimport type { EngineQueuesConfig } from \"../types/queue.types.ts\";\r\n\r\nexport type QueueModule = EngineQueuesConfig & {\r\n consumer : EngineConsumerConfig;\r\n}\r\n\r\ntype DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never;\r\ntype EngineConsumerConfigWithoutQueue = DistributiveOmit<EngineConsumerConfig, \"queue\">;\r\n\r\ntype CreateQueueConfig = EngineQueuesConfig & { consumer : EngineConsumerConfigWithoutQueue};\r\n\r\nexport function createQueue(config : CreateQueueConfig) : QueueModule {\r\n return {\r\n ...config,\r\n consumer: {\r\n ...config.consumer,\r\n queue : config.queue\r\n }\r\n }\r\n}",
23
+ "export class IsolateInstance {\r\n constructor(private MAX_ISOLATE_LIFESPAN_MS : number) {\r\n this.set(\"isolate_id\", crypto.randomUUID());\r\n this.set(\"isolate_start_time\", Date.now());\r\n this.set(\"isolate_max_life_span_ms\", this.MAX_ISOLATE_LIFESPAN_MS);\r\n }\r\n\r\n public isSameIsolate(id : string) : boolean {\r\n return id === this.get<string>(\"isolate_id\");\r\n }\r\n\r\n get id () : string {\r\n return this.get<string>(\"isolate_id\") ?? crypto.randomUUID();\r\n }\r\n\r\n get remainingTime() : number {\r\n const startTime = this.get<number>(\"isolate_start_time\");\r\n const maxSpan = this.get<number>(\"isolate_max_life_span_ms\") ?? this.MAX_ISOLATE_LIFESPAN_MS;\r\n\r\n if (typeof startTime !== \"number\") {\r\n return maxSpan;\r\n }\r\n\r\n const elapsed = Date.now() - startTime;\r\n return Math.max(0, maxSpan - elapsed);\r\n }\r\n\r\n get uptime() : number {\r\n const startTime = this.get<number>(\"isolate_start_time\");\r\n return typeof startTime === \"number\" ? Date.now() - startTime : 0;\r\n }\r\n\r\n get maxTime() : number {\r\n return this.get<number>(\"isolate_max_life_span_ms\") ?? this.MAX_ISOLATE_LIFESPAN_MS;\r\n }\r\n\r\n set<T = unknown>(key: string, value: T) : void {\r\n (globalThis as Record<string, unknown>)[key] = value;\r\n }\r\n\r\n get<T = unknown>(key: string) : T | undefined {\r\n return (globalThis as Record<string, unknown>)[key] as T;\r\n }\r\n}",
24
+ "import sha256 from \"js-sha256\";\r\nimport { PulsarCore } from \"./PulsarBaseService.ts\";\r\nimport { config } from \"./ConfigurationStore.ts\";\r\n\r\nimport type { ConfigForRuntime, PulsarRuntimeType } from \"../types/runtime.types.ts\";\r\nimport type { TimingProfile, TimingProfileType } from \"../static/TimingProfile.ts\";\r\n\r\nimport type { EngineQueuesConfig } from \"../types/queue.types.ts\";\r\nimport type { IRuntimeExecutionContext } from \"../runtimes/runtimeTypes.ts\";\r\n\r\nexport type SpawnerAlgorithm = \"ROUND_ROBIN\" | \"LEAST_CONNECTIONS\" | \"CBS\";\r\n\r\n/**\r\n * Main orchestrator engine for Pulsar responsible for managing queue execution loops,\r\n * dynamic scheduling, non-blocking worker dispatching, telemetry collection,\r\n*/\r\nexport class Pulsar<R extends PulsarRuntimeType = PulsarRuntimeType> extends PulsarCore {\r\n\r\n private isolateId : string;\r\n private currentExecutionId : string;\r\n private lockKey : string;\r\n\r\n // Tracks the in flight shutdown() chain kicked off by an emitted event\r\n // so the HTTP handler can await it before the response returns.\r\n private shutdownPromise : Promise<void> | null = null;\r\n\r\n private eventCleanUps : Array<() => void> = [];\r\n\r\n private activeQueues = new Set<EngineQueuesConfig>();\r\n\r\n constructor (private baseConfig : ConfigForRuntime<R> & { runtime : R }) {\r\n super(baseConfig);\r\n\r\n this.registerEvents();\r\n\r\n if(!this.isV8Isolate) this.isolateId = crypto.randomUUID();\r\n else this.isolateId = this.V8Isolate.id;\r\n\r\n if(this.isV8Isolate) {\r\n this.currentExecutionId = this.V8Isolate.get('current_execution_id')!;\r\n this.lockKey = this.V8Isolate.get('lock_key')!;\r\n }\r\n else { \r\n this.currentExecutionId = this.generateCurrentExecutionIdFromConfig();\r\n this.lockKey = 'lock-template-static-defination-for-non-v8';\r\n }\r\n\r\n this.tickController.initializeState();\r\n }\r\n\r\n public async start() {\r\n await this.unifiedTransportManager.bootAll();\r\n await config.reconcileConfiguration(this.storage.ops);\r\n\r\n this.tickController.initializeState();\r\n this.configureQueueProfiles();\r\n await this.runtimeStrategy.onStart(this.executionContext);\r\n }\r\n\r\n public async triggerQueue(queue : string) {\r\n const targetQueue = this.queues.find(q => q.queue === queue);\r\n if(!targetQueue) throw new Error(\"[Pulsar] Target queue is missing.\");\r\n\r\n this.logger.log(`[Pulsar] : Event-driven trigger for (${queue})`);\r\n\r\n await this.validateConfiguration();\r\n\r\n await this.runTick(targetQueue);\r\n }\r\n\r\n public async validateConfiguration() {\r\n const status = await config.reconcileConfiguration(this.storage.ops);\r\n return { status : 200, message : status }\r\n }\r\n\r\n private configureQueueProfiles() {\r\n for (const config of this.queues) {\r\n const profile = (config as any).profile as TimingProfileType | TimingProfile || 'REALTIME';\r\n this.scheduler.registerQueueProfile(config.queue, profile);\r\n }\r\n }\r\n\r\n private async runTick(queueConfig : EngineQueuesConfig) {\r\n this.activeQueues.add(queueConfig);\r\n return await this.tickController.runTick(queueConfig);\r\n }\r\n\r\n public async shutdown () {\r\n this.shutdownPromise ??= this.doShutdown();\r\n return this.shutdownPromise;\r\n }\r\n\r\n private async doShutdown() {\r\n this.logger.log(`Engine Shutdown ⚠️.`);\r\n\r\n this.removeRegisteredEvents();\r\n\r\n if(this.unifiedTransportManager) {\r\n await this.unifiedTransportManager.shutdownAll();\r\n }\r\n\r\n const continuationScheduled = await this.runtimeStrategy.handleCycleCompletion(this.executionContext);\r\n\r\n // deadRun decides whether a continuation is being scheduled for THIS\r\n // lock's queue(s). If yes, the lock must stay held under this instanceId\r\n // until the continuation lands and renews it — releasing now would open\r\n // a window for an unrelated request to win the lock first.\r\n\r\n if (!continuationScheduled) {\r\n await this.releaseExecutionLock(this.lockKey, this.currentExecutionId);\r\n }\r\n\r\n await this.storage.ops.pingHealthCheck();\r\n await this.storage.disconnect();\r\n }\r\n\r\n public async scheduleRestart(queue : string) {\r\n if(queue) {\r\n const targetQueue = this.queues.find(q => q.queue == queue);\r\n if(targetQueue) {\r\n this.activeQueues.add(targetQueue);\r\n }\r\n }\r\n\r\n const activeQueues = Array.from(this.activeQueues.values());\r\n\r\n await this.releaseExecutionLock(this.lockKey, this.isolateId);\r\n await this.storage.ops.addRestart(activeQueues);\r\n //await this.tickController.restartTick(activeQueues);\r\n\r\n await this.runtimeStrategy.handleRestart(this.executionContext);\r\n\r\n await this.storage.ops.updateRestartOwnership(queue, 'handled_by_engine');\r\n }\r\n\r\n public async restartForSameIsolate(headers : Record<string, string>) {\r\n let delaySeconds = 30;\r\n \r\n if(this.isV8Isolate) {\r\n const isolate = this.V8Isolate;\r\n const timeRemaining = isolate.remainingTime;\r\n delaySeconds = timeRemaining + 5;\r\n }\r\n\r\n this.logger.log(`Estimated Restart in (${delaySeconds})S`);\r\n\r\n await this.queueService.triggerUrl({\r\n url: config.get('engine.selfURL'),\r\n headers,\r\n delaySeconds\r\n });\r\n }\r\n\r\n private get executionContext () : IRuntimeExecutionContext {\r\n return {\r\n lockKey: this.lockKey,\r\n currentExecutionId: this.currentExecutionId,\r\n isolateId: this.isolateId,\r\n\r\n getActiveQueues: () => Array.from(this.activeQueues.values()),\r\n runTick: (queueConfig) => this.runTick(queueConfig),\r\n endTick: (queueName) => this.tickController.endTick(queueName)\r\n }\r\n }\r\n\r\n public setCurrentExecutionId(id : string) {\r\n this.currentExecutionId = id;\r\n }\r\n\r\n private generateCurrentExecutionIdFromConfig() {\r\n const queuesWithPooler = this.baseConfig.queues.map(q => `${q.queue}:${q.pooler}`).join(',');\r\n return sha256(queuesWithPooler);\r\n }\r\n \r\n private registerEvents() {\r\n const shouldShutdownOnCycleComplete = this.runtimeStrategy.shouldShutdownOnCycleComplete;\r\n\r\n this.eventCleanUps.push(\r\n this.events.on(\"tick:cycle-completed\", async () => {\r\n if (shouldShutdownOnCycleComplete) {\r\n await this.shutdown();\r\n }\r\n else {\r\n this.logger.log(\"[Pulsar Persistent] : Cycle completed. Resetting state for next execution round.\");\r\n this.tickController.initializeState();\r\n }\r\n })\r\n )\r\n\r\n this.eventCleanUps.push(\r\n this.events.on(\"tick:force-run\", async ({ queue, reason }) => {\r\n this.logger.log(`[Tick] : Force executing tick for queue [${queue.queue}] Trigger Reason : ${reason}`);\r\n await this.runTick(queue);\r\n })\r\n )\r\n\r\n this.eventCleanUps.push(\r\n this.events.on(\"tick:end\", ({ queue, reason }) => {\r\n this.logger.log(`[Tick] : Force stoping tick for queue [${queue}] (Trigger Reason : ${reason})`);\r\n this.tickController.endTick(queue);\r\n })\r\n )\r\n\r\n this.eventCleanUps.push(\r\n this.events.on(\"tick:time-exceeded\", async () => {\r\n if (shouldShutdownOnCycleComplete) {\r\n await this.shutdown();\r\n }\r\n })\r\n )\r\n\r\n this.eventCleanUps.push(\r\n this.events.on('engine:health-check-requested', async () => {\r\n this.logger.log(`Pulsar : Health checking ping at (${new Date().toISOString()})`);\r\n await this.storage.ops.pingHealthCheck();\r\n })\r\n )\r\n }\r\n\r\n private removeRegisteredEvents () {\r\n this.eventCleanUps.forEach((cleanup) => cleanup());\r\n this.eventCleanUps = [];\r\n }\r\n \r\n public async awaitPendingShutdown() {\r\n await this.events.drain();\r\n if (this.shutdownPromise) await this.shutdownPromise;\r\n }\r\n\r\n public async deleteScheduledRestart(queue : string | '__GLOBAL__') {\r\n await this.storage.ops.deleteRestart(queue);\r\n }\r\n\r\n public async acquireExecutionLock(lockKey : string, ownerId : string, ttlMs : number) {\r\n return await this.storage.repository.acquireQueueLock(lockKey, ownerId, ttlMs);\r\n }\r\n\r\n public async releaseExecutionLock(lockKey : string, ownerId : string) {\r\n return await this.storage.repository.releaseQueueLock(lockKey, ownerId);\r\n }\r\n}",
25
+ "import type { EngineQueuesConfig } from \"../types/queue.types\";\r\n\r\ntype PulsarEventMap = {\r\n \"tick:time-exceeded\" : { queue : string; elapsedMs : number };\r\n \"tick:cycle-completed\" : { queue : string; cycles : number };\r\n \"tick:force-run\" : { queue : EngineQueuesConfig; reason? : string };\r\n \"tick:end\" : { queue : string; reason? : string };\r\n \"engine:shutdown-requested\" : { reason : string };\r\n \"engine:health-check-requested\" : { timestamp : number };\r\n}\r\n\r\nexport class PulsarEventBus {\r\n private target = new EventTarget();\r\n private pending = new Set<Promise<unknown>>();\r\n\r\n\r\n private track(p : Promise<unknown>) {\r\n const tracked = p\r\n .catch(err => console.error('[EventBus] : handler failed - ', err))\r\n .finally(() => this.pending.delete(tracked));\r\n \r\n this.pending.add(tracked);\r\n }\r\n\r\n public emit<K extends keyof PulsarEventMap>(event : K, payload : PulsarEventMap[K]) : void {\r\n this.target.dispatchEvent(new CustomEvent(event, { detail: payload }));\r\n }\r\n\r\n public on<K extends keyof PulsarEventMap>(event : K, handler : (payload : PulsarEventMap[K]) => Promise<void> | void) : () => void {\r\n const listener = (e : Event) => {\r\n const result = handler((e as CustomEvent<PulsarEventMap[K]>).detail);\r\n if (result instanceof Promise) this.track(result);\r\n }\r\n\r\n this.target.addEventListener(event, listener as EventListener);\r\n return () => this.target.removeEventListener(event, listener as EventListener);\r\n }\r\n\r\n public once<K extends keyof PulsarEventMap>(event : K, handler: (payload : PulsarEventMap[K]) => Promise<void> | void) : void {\r\n const listener = (e: Event) => handler((e as CustomEvent<PulsarEventMap[K]>).detail);\r\n this.target.addEventListener(event, listener as EventListener, { once: true });\r\n }\r\n\r\n public async drain() {\r\n while (this.pending.size > 0) {\r\n await Promise.allSettled([...this.pending]);\r\n }\r\n }\r\n}",
26
+ "export interface ClockOptions {\r\n /** Maximum allowed runtime in milliseconds for the entire engine execution (e.g., 25000 for 25s) */\r\n maxExecutionBudgetMs?: number;\r\n /** Safety margin in milliseconds reserved for graceful cleanup/shutdown */\r\n safetyBufferMs?: number;\r\n /** Maximum number of execution spans to retain in memory */\r\n maxTrackHistory?: number;\r\n\r\n enabled?: boolean;\r\n}\r\n\r\nexport class PulsarClock {\r\n private tracks: { id: string; duration: number; contextId : string }[] = [];\r\n private startTime: number;\r\n private maxExecutionBudgetMs: number;\r\n private safetyBufferMs: number;\r\n private maxTrackHistory: number;\r\n private enabled: boolean;\r\n\r\n public cpuExecutionMicroseconds = 0;\r\n\r\n constructor(options: ClockOptions = {}) {\r\n this.startTime = performance.now();\r\n this.maxExecutionBudgetMs = options.maxExecutionBudgetMs ?? 25000;\r\n this.safetyBufferMs = options.safetyBufferMs ?? 2000;\r\n this.maxTrackHistory = options.maxTrackHistory ?? 100;\r\n this.enabled = options.enabled ?? false;\r\n }\r\n\r\n public async trackExecutionTime<T>({ contextId } : { contextId: string }, fn: () => Promise<T>): Promise<T> {\r\n const start = performance.now();\r\n try {\r\n return await fn();\r\n }\r\n finally {\r\n if(this.enabled == true) {\r\n const end = performance.now();\r\n const duration = end - start;\r\n\r\n this.tracks.push({ id: crypto.randomUUID(), duration, contextId });\r\n\r\n if (this.tracks.length > this.maxTrackHistory) {\r\n this.tracks.shift();\r\n }\r\n }\r\n }\r\n }\r\n \r\n public getElapsedTotalTime() : number {\r\n return performance.now() - this.startTime;\r\n }\r\n\r\n public getTimeRemaining() : number {\r\n const elapsed = this.getElapsedTotalTime();\r\n const remaining = this.maxExecutionBudgetMs - elapsed - this.safetyBufferMs;\r\n return Math.max(0, remaining);\r\n }\r\n\r\n public getAverageTickDuration(lastN = 5): number {\r\n if (this.tracks.length === 0) return 0;\r\n const recent = this.tracks.slice(-lastN);\r\n const total = recent.reduce((sum, t) => sum + t.duration, 0);\r\n return total / recent.length;\r\n }\r\n\r\n /**\r\n * Determines if executing another tick is safe.\r\n * Uses recent average tick duration to estimate whether another tick will exceed the deadline.\r\n */\r\n public isSafeToContinue() : boolean {\r\n if(!this.enabled) return true;\r\n\r\n const remaining = this.getTimeRemaining();\r\n\r\n if (remaining <= 0) return false;\r\n\r\n const estimatedNextTick = this.getAverageTickDuration(5);\r\n if (estimatedNextTick > 0 && remaining < estimatedNextTick) {\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n public clear(contextId : string) {\r\n this.tracks = this.tracks.filter(track => track.contextId !== contextId);\r\n }\r\n}",
27
+ "export class SwarmManager {\r\n constructor(\r\n private maxGlobalJobsPerTick: number,\r\n private maxGlobalConcurrency: number\r\n ) {}\r\n\r\n /**\r\n * Getter for configured maximum global worker concurrency.\r\n */\r\n public getMaxGlobalConcurrency(): number {\r\n return this.maxGlobalConcurrency;\r\n }\r\n\r\n /**\r\n * Getter for configured maximum global jobs per 1s tick window.\r\n */\r\n public getMaxGlobalJobsPerTick(): number {\r\n return this.maxGlobalJobsPerTick;\r\n }\r\n}",
28
+ "export type TimingProfileType = 'REALTIME' | 'STANDARD' | 'RELAXED' | 'ULTRA_EFFICIENT' | 'BALANCED' | 'CUSTOM';\r\n\r\nexport interface TimingProfile {\r\n activePollMs: number; // How fast to poll when jobs are active & slots are free (e.g. 10ms - 50ms)\r\n backoffPollMs: number; // How fast to re-check when slots are full (e.g. 100ms - 500ms)\r\n idlePollMs?: number; // Idle fallback poll (if DB triggers/notifiers are missed)\r\n maxTimerMs: number; // Max setTimeout duration allowed before re-evaluating metrics\r\n}\r\n\r\nexport const TIMING_PROFILES: Record<Exclude<TimingProfileType, 'CUSTOM'>, TimingProfile> = {\r\n // Ultra-fast for high-throughput, latency-critical queues (e.g. 10,000+ fast jobs)\r\n REALTIME: {\r\n activePollMs: 1000, // 10\r\n backoffPollMs: 1000,\r\n idlePollMs: 1000,\r\n maxTimerMs: 5_000,// 30s\r\n },\r\n // Balanced for standard background job workloads\r\n STANDARD: {\r\n activePollMs: 100,\r\n backoffPollMs: 500,\r\n idlePollMs: 10000,\r\n maxTimerMs: 60000,\r\n },\r\n // Balanced for standard background job workloads\r\n BALANCED : {\r\n activePollMs: 10000,\r\n backoffPollMs: 500,\r\n idlePollMs: 10000,\r\n maxTimerMs: 60000,\r\n },\r\n // Low-cost for non-urgent tasks (e.g., reports, cleanup)\r\n RELAXED: {\r\n activePollMs: 1000,\r\n backoffPollMs: 20000,\r\n idlePollMs: 30000,\r\n maxTimerMs: 60000,\r\n },\r\n\r\n ULTRA_EFFICIENT: {\r\n activePollMs: 5000,\r\n backoffPollMs: 100000,\r\n idlePollMs: 120000,\r\n maxTimerMs: 240000,\r\n },\r\n}",
29
+ "import { config } from \"../service/ConfigurationStore.ts\";\r\nimport { TIMING_PROFILES, type TimingProfile, type TimingProfileType } from \"../static/TimingProfile.ts\";\r\n\r\nexport interface ScheduleRequest {\r\n queue : string;\r\n readyJobs : number;\r\n delayedJobs : number;\r\n availableSlots : number;\r\n nextVisibleAt? : number | null;\r\n}\r\n\r\ninterface ScheduleMetrics {\r\n queue : string;\r\n readyJobs : number;\r\n delayedJobs : number;\r\n availableSlots : number;\r\n nextVisibleAt? : number | null;\r\n}\r\n\r\ninterface ScheduleOptions {\r\n metrics : ScheduleMetrics;\r\n /** Standard wakeup handler for ready/backoff/idle ticks */\r\n onNext: () => void | Promise<void>;\r\n /** Specialized handler when scheduling near-term delayed jobs */\r\n onUpcomingDelayedNext?: (upcomingTimeMs : number) => void | Promise<void>;\r\n /** Async hook for long delays exceeding maxTimerMs (e.g. persistent state / external triggers) */\r\n onFutureSchedule?: (nextVisibleAt : number) => Promise<void>;\r\n}\r\n\r\nconst MAX_SAFE_TIMEOUT_MS = 2_147_483_647;\r\n\r\nexport class Scheduler {\r\n private timers = new Map<string, ReturnType<typeof setTimeout>>();\r\n private profiles = new Map<string, TimingProfile>();\r\n\r\n constructor() {}\r\n\r\n /**\r\n * Register a timing profile for a queue\r\n */\r\n public registerQueueProfile(queue : string, profileInput : TimingProfileType | TimingProfile) {\r\n if (typeof profileInput === 'string') {\r\n const preset = profileInput !== 'CUSTOM' ? TIMING_PROFILES[profileInput] : undefined;\r\n this.profiles.set(queue, preset ?? TIMING_PROFILES.STANDARD);\r\n }\r\n else {\r\n this.profiles.set(queue, profileInput);\r\n }\r\n }\r\n\r\n public getProfile(queue : string) : TimingProfile {\r\n const liveQueueConfig = config.get('queues')?.find(q => q.queue === queue);\r\n const liveProfile = liveQueueConfig?.profile;\r\n\r\n if (liveProfile) {\r\n if (typeof liveProfile === 'string') {\r\n return liveProfile !== 'CUSTOM' ? TIMING_PROFILES[liveProfile] : TIMING_PROFILES.STANDARD;\r\n }\r\n if (typeof liveProfile === 'object') {\r\n return liveProfile as TimingProfile;\r\n }\r\n }\r\n\r\n return this.profiles.get(queue) ?? TIMING_PROFILES.STANDARD;\r\n }\r\n\r\n /**\r\n * Cancel pending schedules for a queue\r\n */\r\n public cancel(queue : string) {\r\n const pending = this.timers.get(queue);\r\n if (pending) {\r\n clearTimeout(pending as ReturnType<typeof setTimeout>);\r\n //clearImmediate(pending as any);\r\n }\r\n this.timers.delete(queue);\r\n }\r\n\r\n public scheduleNext(options : ScheduleOptions): void {\r\n const { metrics, onNext, onUpcomingDelayedNext, onFutureSchedule } = options;\r\n const { queue, readyJobs, delayedJobs, availableSlots, nextVisibleAt } = metrics;\r\n\r\n this.cancel(queue);\r\n const profile = this.getProfile(queue);\r\n\r\n // 1. Ready jobs + open slots -> Ultra-fast profile-based active tick\r\n if (readyJobs > 0 && availableSlots > 0) {\r\n this.setTimer(queue, onNext, profile.activePollMs);\r\n return;\r\n }\r\n\r\n // 2. Ready jobs but slots full -> Backoff poll to check slot freeing\r\n if (readyJobs > 0 && availableSlots === 0) {\r\n this.setTimer(queue, onNext, profile.backoffPollMs);\r\n return;\r\n }\r\n\r\n // 3. Delayed jobs present -> Calculate exact delta safely without blocking threads\r\n if (delayedJobs > 0 && nextVisibleAt) {\r\n const deltaMs = Math.max(0, nextVisibleAt - Date.now());\r\n\r\n if (deltaMs <= profile.maxTimerMs) {\r\n if(onUpcomingDelayedNext) {\r\n onUpcomingDelayedNext(deltaMs);\r\n }\r\n \r\n this.setTimer(queue, onNext, deltaMs);\r\n return;\r\n }\r\n\r\n // Long delay handing over to external Redis/Trigger safety nets\r\n if (onFutureSchedule) {\r\n onFutureSchedule(nextVisibleAt).catch((err) =>\r\n console.error(`Scheduler error setting long delay for ${queue}:`, err)\r\n )\r\n }\r\n return;\r\n }\r\n\r\n // 4. Idle fallback (optional trigger fallback)\r\n if (profile.idlePollMs) {\r\n this.setTimer(queue, onNext, profile.idlePollMs);\r\n }\r\n }\r\n\r\n private setTimer(queue : string, callback : () => void, delayMs : number) {\r\n const safeDelay = Math.min(Math.max(0, delayMs), MAX_SAFE_TIMEOUT_MS);\r\n\r\n const wrappedCallback = () => {\r\n this.timers.delete(queue);\r\n callback();\r\n }\r\n\r\n if (safeDelay === 0) {\r\n const immediate = setTimeout(wrappedCallback);\r\n this.timers.set(queue, immediate);\r\n return;\r\n }\r\n\r\n const timer = setTimeout(wrappedCallback, safeDelay);\r\n this.timers.set(queue, timer);\r\n }\r\n}",
30
+ "import type { EngineQueuesConfig } from \"../types/queue.types\";\r\nimport type { ILogger } from \"./LoggerService\";\r\nimport { TIMING_PROFILES, type TimingProfile } from \"../static/TimingProfile\";\r\nimport { config } from \"../service/ConfigurationStore\";\r\n\r\nexport class ExecutionProfileSwitcher {\r\n private transitionItems = new Set<string>();\r\n\r\n constructor(private logger : ILogger) {}\r\n\r\n transitionToIdleMode({ queue, stateTransitionPolicy } : EngineQueuesConfig) {\r\n if(this.transitionItems.has(queue)) return;\r\n this.transitionItems.add(queue);\r\n\r\n this.logger.log(`[ENGINE_STATE] Transitioning engine execution profile to IDLE. Queue config: (${queue})`);\r\n\r\n if(stateTransitionPolicy?.enabled) {\r\n const rawProfile = stateTransitionPolicy.idleTimingProfile;\r\n\r\n if (rawProfile) {\r\n const idleProfile : TimingProfile = typeof rawProfile === \"object\"\r\n ? {\r\n activePollMs: rawProfile.activePollMs,\r\n backoffPollMs: rawProfile.backoffPollMs,\r\n idlePollMs: rawProfile.idlePollMs,\r\n } as TimingProfile\r\n : TIMING_PROFILES[rawProfile as keyof typeof TIMING_PROFILES];\r\n\r\n config.modifyQueue(queue, 'profile', idleProfile);\r\n }\r\n }\r\n }\r\n\r\n transitionToActiveMode({ queue, profile, stateTransitionPolicy } : EngineQueuesConfig) {\r\n this.transitionItems.delete(queue);\r\n\r\n if(stateTransitionPolicy?.enabled) {\r\n config.modifyQueue(queue, 'profile', profile);\r\n }\r\n\r\n this.logger.log(`[ENGINE_STATE] Transitioning engine execution profile to ACTIVE. Queue config: (${queue})`);\r\n }\r\n}",
31
+ "import type { QueueService } from \"./Queue.module.ts\";\r\nimport type { SwarmManager } from '../service/SwarmBudgetTracker.ts';\r\n\r\nimport type { PulsarUnifiedStorage } from '../storage/PulsarStorage.ts';\r\nimport type { EngineQueuesConfig, QueueMessage } from \"../types/queue.types.ts\";\r\nimport { ExecutionProfileSwitcher } from \"../subsys/ExecutionProfileSwitcher.ts\";\r\nimport { LoggerService, type ILogger } from \"../subsys/LoggerService.ts\";\r\nimport type { UnifiedTransportManager } from \"../network/UnifiedTransportManager.ts\";\r\nimport type { PulsarEventBus } from \"../service/PulsarEventBus.ts\";\r\n//import { PulsarMonitoringStreamProducer } from \"../../monitoring/PulsarMonitoringStreamProducer.ts\";\r\n\r\nexport interface IBatchCandidate {\r\n workerId : string;\r\n batch : QueueMessage[];\r\n}\r\n\r\ntype GetBatchCandidate = {\r\n queueConfig : EngineQueuesConfig;\r\n maxGlobalSlotsAllowed: number;\r\n}\r\n\r\ninterface ISpwanWorkers {\r\n grantedWorkerIds : string[];\r\n candidateBatches : IBatchCandidate[];\r\n queueConfig : EngineQueuesConfig;\r\n}\r\n\r\ninterface ITick {\r\n storage : PulsarUnifiedStorage;\r\n queue : QueueService;\r\n events : PulsarEventBus;\r\n swarmManager : SwarmManager;\r\n unifiedTransportManager : UnifiedTransportManager\r\n}\r\n\r\nexport class TickService {\r\n private storage : PulsarUnifiedStorage;\r\n private queue : QueueService;\r\n private executionProfileSwitcher : ExecutionProfileSwitcher;\r\n //private streamProducer : PulsarMonitoringStreamProducer;\r\n private unifiedTransportManager : UnifiedTransportManager;\r\n\r\n private swarmManager: SwarmManager;\r\n\r\n private PROCESS_ID : string;\r\n private globalSequence = 0;\r\n\r\n private consecutiveEmptyTicks = 0;\r\n\r\n private logger : ILogger;\r\n private events : PulsarEventBus;\r\n\r\n constructor ({ queue, storage, swarmManager, unifiedTransportManager, events } : ITick){\r\n this.storage = storage;\r\n this.queue = queue;\r\n this.swarmManager = swarmManager;\r\n this.unifiedTransportManager = unifiedTransportManager;\r\n \r\n this.logger = new LoggerService();\r\n this.executionProfileSwitcher = new ExecutionProfileSwitcher(this.logger);\r\n\r\n this.PROCESS_ID = crypto.randomUUID().slice(0, 12);\r\n this.globalSequence = 0;\r\n //this.streamProducer = new PulsarMonitoringStreamProducer();\r\n\r\n this.events = events;\r\n }\r\n\r\n public async run(queueConfig : EngineQueuesConfig, maxGlobalSlotsAllowed : number) {\r\n const { concurrency, queue } = queueConfig;\r\n\r\n const maxGlobalConcurrency = this.swarmManager.getMaxGlobalConcurrency();\r\n const { batches : candidateBatches, window } = await this.getCandidatesBatch({\r\n queueConfig,\r\n maxGlobalSlotsAllowed,\r\n })\r\n\r\n const isStateTransitionPolicyActive = queueConfig.stateTransitionPolicy?.enabled == true;\r\n\r\n if(!candidateBatches || candidateBatches.length === 0) {\r\n if(isStateTransitionPolicyActive) {\r\n this.consecutiveEmptyTicks++;\r\n\r\n if (this.consecutiveEmptyTicks >= (queueConfig.stateTransitionPolicy?.idleThresholdTicks ?? 10)) {\r\n this.executionProfileSwitcher.transitionToIdleMode(queueConfig);\r\n }\r\n }\r\n\r\n this.logger.warn(`[Tick] : [${queue}] - Empty Tick Executred)`);\r\n return;\r\n }\r\n\r\n if (isStateTransitionPolicyActive && this.consecutiveEmptyTicks > 0) {\r\n this.consecutiveEmptyTicks = 0;\r\n this.executionProfileSwitcher.transitionToActiveMode(queueConfig);\r\n }\r\n\r\n const grantedWorkerIds = await this.storage.repository.registerWorker(\r\n queue,\r\n candidateBatches,\r\n concurrency,\r\n maxGlobalConcurrency\r\n )\r\n\r\n const grantedSet = new Set(grantedWorkerIds);\r\n\r\n const ungrantedBatches = candidateBatches.filter(b => !grantedSet.has(b.workerId));\r\n if (ungrantedBatches.length > 0) {\r\n const ungrantedJobCount = ungrantedBatches.reduce((sum, b) => sum + b.batch.length, 0);\r\n \r\n await this.storage.repository.refundGlobalJobBudget(ungrantedJobCount, window);\r\n }\r\n\r\n if (grantedWorkerIds.length === 0) return;\r\n\r\n this.logger.log(`[Tick] : [${queue}] - Tick Executred. Total Jobs (${candidateBatches.reduce((sum, x) => sum + x.batch.length, 0)})`); \r\n\r\n await this.spwanWorkers({ candidateBatches, grantedWorkerIds, queueConfig });\r\n }\r\n\r\n private async spwanWorkers({ grantedWorkerIds, candidateBatches, queueConfig : { queue } } : ISpwanWorkers) {\r\n if (!grantedWorkerIds?.length) return;\r\n const grantedSet = new Set(grantedWorkerIds);\r\n\r\n const activeBatches = candidateBatches.filter(b => grantedSet.has(b.workerId));\r\n\r\n await Promise.allSettled(activeBatches.map(({ batch, workerId }) => {\r\n \r\n // this.streamProducer.stream.base(`worker-dispatched`, { worker_id : workerId });\r\n // batch.forEach(job => {\r\n // this.streamProducer.stream.base(`job-added`, { msg_id : job.msg_id, status : 'pending', created_at : job.enqueued_at });\r\n // })\r\n\r\n return this.unifiedTransportManager.dispatchToNetwork(queue, { batch : batch, worker_id : workerId });\r\n }))\r\n }\r\n\r\n private async getCandidatesBatch({ queueConfig, maxGlobalSlotsAllowed } : GetBatchCandidate) : Promise<{ batches : IBatchCandidate[], window : string}> {\r\n const { concurrency, maxJobsPerTick, queue, sleep, n } = queueConfig;\r\n\r\n const activeWorkersCount = await this.storage.repository.getActiveWorkersCount(queue);\r\n\r\n const localAvailableSlots = Math.max(0, concurrency - activeWorkersCount);\r\n if (localAvailableSlots === 0) return { batches : [], window : '' };\r\n\r\n const effectiveSlots = Math.min(localAvailableSlots, maxGlobalSlotsAllowed);\r\n if (effectiveSlots === 0) return { batches : [], window : '' };\r\n\r\n const capacityMax = effectiveSlots * n;\r\n const localMaxJobs = (maxJobsPerTick !== undefined && maxJobsPerTick > 0) ? maxJobsPerTick : Infinity;\r\n\r\n const desiredToFetch = Math.min(capacityMax, localMaxJobs);\r\n if (desiredToFetch <= 0) return { batches : [], window : '' };\r\n \r\n const globalMaxJobsPerTick = this.swarmManager.getMaxGlobalJobsPerTick();\r\n\r\n const { granted : maxToFetch, window } = await this.storage.repository.claimGlobalJobBudget(\r\n desiredToFetch, \r\n globalMaxJobsPerTick\r\n );\r\n\r\n if (maxToFetch <= 0) return { batches : [], window : window };\r\n\r\n const jobs = await this.queue.read(queue, sleep ?? 1, maxToFetch);\r\n const jobsCount = jobs.length;\r\n\r\n if (jobsCount === 0) {\r\n await this.storage.repository.refundGlobalJobBudget(maxToFetch, window);\r\n return { batches : [], window : window };\r\n }\r\n\r\n if (jobsCount < maxToFetch) {\r\n const unusedBudget = maxToFetch - jobs.length;\r\n await this.storage.repository.refundGlobalJobBudget(unusedBudget, window);\r\n }\r\n\r\n const candidateBatchesCount = Math.ceil(jobsCount / n);\r\n const candidateBatches: IBatchCandidate[] = new Array(candidateBatchesCount);\r\n\r\n const timestamp = Date.now();\r\n\r\n let batchIdx = 0;\r\n\r\n for (let i = 0; i < jobsCount; i += n) {\r\n candidateBatches[batchIdx++] = {\r\n workerId: `w_${this.PROCESS_ID}_${timestamp}_${this.globalSequence++}`,\r\n batch: jobs.slice(i, i + n)\r\n }\r\n }\r\n\r\n return { batches : candidateBatches, window};\r\n }\r\n}",
32
+ "import type { Scheduler } from \"./Scheduler.module.ts\";\r\nimport type { TickService } from \"./Tick.module.ts\";\r\nimport type { PulsarClock } from \"../subsys/PulsarClock.ts\";\r\nimport type { PulsarUnifiedStorage } from \"../storage/PulsarStorage.ts\";\r\nimport type { PulsarEventBus } from \"../service/PulsarEventBus.ts\";\r\nimport type { EngineQueuesConfig } from \"../types/queue.types.ts\";\r\nimport type { PulsarRuntimeCore } from \"../shared/PulsarRuntimeCore.ts\";\r\nimport { config } from \"../service/ConfigurationStore.ts\";\r\nimport { LoggerService, type ILogger } from \"../subsys/LoggerService.ts\";\r\n\r\ninterface ITickController {\r\n clock : PulsarClock;\r\n tickService : TickService;\r\n scheduler : Scheduler;\r\n storage : PulsarUnifiedStorage;\r\n runtimeStrategy : PulsarRuntimeCore;\r\n events : PulsarEventBus;\r\n}\r\n\r\n\r\nexport class TickController {\r\n private clock: PulsarClock;\r\n\r\n private tickService: TickService;\r\n private scheduler: Scheduler;\r\n private storage: PulsarUnifiedStorage;\r\n \r\n private events : PulsarEventBus;\r\n private runtimeStrategy: PulsarRuntimeCore;\r\n \r\n private tickState = new Map<string, { count: number; max : number; registred : boolean, stopped: boolean }>();\r\n private activeTicks = new Set<string>();\r\n\r\n private lastHealthCheckAt : number = 0;\r\n\r\n private logger : ILogger;\r\n\r\n constructor({ scheduler, storage, tickService, clock, events, runtimeStrategy }: ITickController) {\r\n this.logger = new LoggerService();\r\n this.clock = clock;\r\n\r\n this.tickService = tickService;\r\n this.scheduler = scheduler;\r\n this.storage = storage;\r\n this.events = events;\r\n\r\n this.runtimeStrategy = runtimeStrategy;\r\n\r\n this.initializeState();\r\n }\r\n\r\n public initializeState() {\r\n this.tickState.clear();\r\n this.activeTicks.clear();\r\n }\r\n\r\n public async runTick(queueConfig : EngineQueuesConfig) {\r\n await this.runtimeStrategy.executeTick(queueConfig, async () => {\r\n const { queue } = queueConfig;\r\n \r\n this.initializeTickState(queueConfig);\r\n \r\n if (this.activeTicks.has(queue) || this.tickState.get(queue)?.stopped) {\r\n return;\r\n }\r\n\r\n this.activeTicks.add(queue);\r\n this.scheduler.cancel(queue); // cancel any pending wakeup timer for this queue running now\r\n\r\n try {\r\n let globalAvailableSlots : number = Infinity;\r\n\r\n const maxGlobalConcurrency = config.get('swarmConfig')?.maxGlobalConcurrency;\r\n\r\n if(maxGlobalConcurrency !== undefined) {\r\n const totalActiveWorkers = await this.storage.repository.getGlobalActiveWorkersCount();\r\n globalAvailableSlots = Math.max(0, maxGlobalConcurrency - totalActiveWorkers);\r\n }\r\n\r\n if (globalAvailableSlots > 0 && !this.tickState.get(queue)?.stopped) {\r\n await this.tickService.run(queueConfig, globalAvailableSlots);\r\n }\r\n }\r\n catch (error) {\r\n this.logger.error(`Orchestrator error on ${queue}:`, error);\r\n }\r\n finally {\r\n this.activeTicks.delete(queue);\r\n this.updateTickCounter(queue);\r\n }\r\n \r\n if (this.tickState.get(queue)?.stopped == true) return;\r\n\r\n await this.runtimeStrategy.scheduleTick(queueConfig, () => this.runTick(queueConfig))\r\n })\r\n }\r\n\r\n public endTick(queue: string) {\r\n const state = this.tickState.get(queue);\r\n\r\n if (state) {\r\n if(state.stopped == true) return;\r\n\r\n this.tickState.set(queue, { ...state, stopped: true });\r\n this.scheduler.cancel(queue);\r\n this.clock.clear(queue);\r\n\r\n const allStopped = config.raw.queues.every((q) => {\r\n const s = this.tickState.get(q.queue);\r\n return s ? s.stopped : true;\r\n });\r\n\r\n if(allStopped) {\r\n this.events.emit(\"tick:cycle-completed\", {\r\n queue : queue,\r\n cycles : this.tickState.get(queue)?.count ?? 1\r\n })\r\n }\r\n }\r\n }\r\n\r\n private initializeTickState(q : EngineQueuesConfig) {\r\n const existing = this.tickState.get(q.queue);\r\n\r\n if (!existing) {\r\n this.tickState.set(q.queue, { count: 0, max: q.cycleTickLimit ?? 10, registred : true, stopped: false });\r\n }\r\n }\r\n\r\n private updateTickCounter(queue: string) {\r\n const state = this.tickState.get(queue) ?? { count: 0, stopped: false, max : 10, registred : false };\r\n const newCount = state.count + 1;\r\n const maxAllowed = state.max;\r\n\r\n const isMaxReached = newCount >= maxAllowed;\r\n\r\n if ((state.stopped || isMaxReached) && !state.stopped) {\r\n this.tickState.set(queue, { count: newCount, stopped : state.stopped, max: maxAllowed, registred: state.registred });\r\n this.endTick(queue);\r\n }\r\n else {\r\n this.tickState.set(queue, { count: newCount, stopped: state.stopped, max: maxAllowed, registred: state.registred });\r\n }\r\n\r\n this.triggerPeriodicHealthCheck();\r\n }\r\n\r\n private triggerPeriodicHealthCheck() {\r\n const now = Date.now();\r\n const shouldShutdownOnCycleComplete = this.runtimeStrategy.shouldShutdownOnCycleComplete;\r\n const healthCheckIntervalSec = (config.get('engine.healthCheckIntervalSec') ?? 15) * 1000;\r\n\r\n if (now - this.lastHealthCheckAt >= healthCheckIntervalSec && !shouldShutdownOnCycleComplete) {\r\n this.lastHealthCheckAt = now;\r\n this.events.emit('engine:health-check-requested', { timestamp: now });\r\n }\r\n }\r\n}",
33
+ "import type { QueueService } from \"../modules/Queue.module.ts\";\r\nimport type { PulsarClock } from \"../subsys/PulsarClock.ts\";\r\nimport type { IPulsarRuntime, IRuntimeExecutionContext } from \"../runtimes/runtimeTypes.ts\";\r\nimport type { EngineQueuesConfig } from \"../types/queue.types.ts\";\r\nimport type { IsolateInstance } from \"../service/Isolate.service.ts\";\r\nimport type { PulsarUnifiedStorage } from \"../storage/PulsarStorage.ts\";\r\nimport type { PulsarEventBus } from \"../service/PulsarEventBus.ts\";\r\nimport type { Scheduler } from \"../modules/Scheduler.module.ts\";\r\nimport type { SelfInvokingEngine } from \"../types/engine.types.ts\";\r\nimport { LoggerService, type ILogger } from \"../subsys/LoggerService.ts\";\r\nimport { config } from \"../service/ConfigurationStore.ts\";\r\n\r\nexport interface RuntimeDependencies {\r\n queueService : QueueService;\r\n clock : PulsarClock;\r\n storage : PulsarUnifiedStorage\r\n queues : EngineQueuesConfig[];\r\n events : PulsarEventBus;\r\n isolate : IsolateInstance;\r\n scheduler : Scheduler;\r\n}\r\n\r\ninterface ISelfInvocationState {\r\n idpInvoked : boolean;\r\n continuationScheduledForCurrentLock : boolean;\r\n}\r\n\r\ninterface ExecuteSelfInvocation {\r\n queue : string;\r\n pooler : string;\r\n delaySec : number;\r\n continuationOwnerId : string;\r\n isIdpLock : boolean;\r\n isEdpLock : boolean;\r\n targetEdpQueue : string | null;\r\n}\r\n\r\nexport abstract class PulsarRuntimeCore implements IPulsarRuntime {\r\n abstract readonly type : \"PERSISTENT\" | \"SERVERLESS_VM\" | \"V8_ISOLATE\";\r\n abstract readonly shouldShutdownOnCycleComplete : boolean;\r\n \r\n /** Minimum runtime required to make booting up the engine worth it (in seconds) */\r\n abstract readonly minBootRequirementSec : number;\r\n\r\n protected queueService : QueueService;\r\n protected clock : PulsarClock;\r\n protected queues : EngineQueuesConfig[];\r\n protected storage : PulsarUnifiedStorage;\r\n protected isolate : IsolateInstance;\r\n protected events : PulsarEventBus;\r\n protected scheduler : Scheduler;\r\n protected logger : ILogger;\r\n\r\n constructor(deps : RuntimeDependencies) {\r\n this.queueService = deps.queueService;\r\n this.clock = deps.clock;\r\n this.queues = deps.queues;\r\n this.isolate = deps.isolate;\r\n this.storage = deps.storage;\r\n this.events = deps.events;\r\n this.scheduler = deps.scheduler;\r\n this.logger = new LoggerService();\r\n }\r\n\r\n abstract onStart(ctx : IRuntimeExecutionContext) : Promise<void>;\r\n abstract handleCycleCompletion(ctx : IRuntimeExecutionContext) : Promise<boolean>;\r\n abstract handleRestart(ctx : IRuntimeExecutionContext) : Promise<void>;\r\n\r\n public abstract executeTick(queueConfig: EngineQueuesConfig, tickRunner: () => Promise<void>) : Promise<void>;\r\n abstract scheduleTick(queueConfig: EngineQueuesConfig, tickRunner: () => Promise<void>) : Promise<void>;\r\n\r\n protected async executeQueuesTick(runTick : IRuntimeExecutionContext[\"runTick\"]) {\r\n const tickConcurrency = config.get('engine.tickConcurrency'); // \"sequential\" | \"parallel\"\r\n \r\n this.logger.log(`[Tick Controller] : Execution tick mode has been selected with concurrency ${tickConcurrency}`);\r\n\r\n if(tickConcurrency == \"sequential\") {\r\n for(const q of this.queues) {\r\n if(q.pooler == \"interval-driven-pooler\") {\r\n await runTick(q);\r\n }\r\n }\r\n }\r\n else {\r\n const results = await Promise.allSettled(\r\n this.queues.filter(q => q.pooler === \"interval-driven-pooler\")\r\n .map((q) => runTick(q))\r\n )\r\n\r\n for (const res of results) {\r\n if (res.status === \"rejected\") {\r\n this.logger.error(\"[Tick] : Error >>\", res.reason);\r\n }\r\n }\r\n }\r\n }\r\n\r\n protected async triggerSelfInvocation(args : ExecuteSelfInvocation) : Promise<ISelfInvocationState> {\r\n const { queue, pooler, delaySec, continuationOwnerId, isIdpLock, isEdpLock, targetEdpQueue } = args;\r\n\r\n const url = config.get('engine.selfURL');\r\n\r\n const engine = config.raw.engine as SelfInvokingEngine;\r\n const selfInvocationMethod = engine.selfInvocationMethod;\r\n\r\n const state : ISelfInvocationState = {\r\n idpInvoked: false,\r\n continuationScheduledForCurrentLock: false\r\n }\r\n\r\n if (pooler === \"interval-driven-pooler\") {\r\n state.idpInvoked = true;\r\n if (isIdpLock) state.continuationScheduledForCurrentLock = true;\r\n this.logger.log(`(IDP) : Invoking Self in ${delaySec} seconds...`);\r\n }\r\n else if (pooler === \"event-driven-pooler\") {\r\n if (isEdpLock && queue === targetEdpQueue) {\r\n state.continuationScheduledForCurrentLock = true;\r\n }\r\n this.logger.log(`(EDP) : Invoking Self in ${delaySec} seconds...`);\r\n }\r\n\r\n const headers : Record<string, string> = {\r\n 'content-type': 'application/json',\r\n 'x-last-execution-id': continuationOwnerId,\r\n 'x-last-execution-at': new Date().toISOString(),\r\n 'x-execution-owner': 'engine',\r\n 'x-restart': 'false',\r\n 'x-pooler': pooler,\r\n 'x-target-queue': queue\r\n }\r\n\r\n if(selfInvocationMethod == \"auto_using_pgnet\") {\r\n await this.queueService.triggerUrl({ url, headers, delaySeconds: delaySec })\r\n }\r\n\r\n else if (typeof selfInvocationMethod === \"object\" && selfInvocationMethod !== null && selfInvocationMethod.method === \"manual\") {\r\n await selfInvocationMethod.handler(url);\r\n }\r\n\r\n return state;\r\n }\r\n}",
34
+ "import type { PulsarUnifiedStorage } from \"../storage/PulsarStorage\";\r\nimport { PulsarEventBus } from \"../service/PulsarEventBus\";\r\nimport type { IRuntimeExecutionContext } from \"../runtimes/runtimeTypes\";\r\nimport type { ILogger } from \"./LoggerService\";\r\nimport type { EngineQueuesConfig } from \"../types/queue.types\";\r\nimport { config } from \"../service/ConfigurationStore\";\r\n\r\nexport class RuntimeEventBridge {\r\n private readonly pgNotifyChannel = 'channel_pulsar_event_driven_queue' as const;\r\n\r\n private events : PulsarEventBus;\r\n\r\n constructor (\r\n protected readonly storage : PulsarUnifiedStorage,\r\n protected readonly logger : ILogger,\r\n protected readonly runtimeExecutionId : string\r\n ) {\r\n this.events = new PulsarEventBus();\r\n }\r\n\r\n public async registerPgNotifyHandler(ctx : IRuntimeExecutionContext) {\r\n await this.storage.ops.subscribeToDatabaseEvents<{ queue_name : string, fencing_token : string, notified_at : string }>(this.pgNotifyChannel, async (event) => {\r\n this.logger.log(`[Persistent Runtime] : Recived PgNotification Event - ${new Date().toISOString()}`);\r\n \r\n const targetQueue = config.get('queues').find(q => q.queue === event.queue_name);\r\n if(!targetQueue) {\r\n this.logger.error(`[Persistent Runtime] : Received notification for unregistered or unmanaged queue: '${event.queue_name}' on channel: ${this.pgNotifyChannel}`);\r\n return;\r\n }\r\n\r\n const canTrigger = await this.handleTriggerValidity(targetQueue.queue, event.fencing_token);\r\n\r\n if(canTrigger) {\r\n await ctx.runTick(targetQueue);\r\n }\r\n }, () => {\r\n this.logger.log(`[Persistent Runtime] : Successfully established PostgreSQL notification listener on channel : ${this.pgNotifyChannel}`);\r\n })\r\n }\r\n\r\n public async registerPollingHandler(ctx : IRuntimeExecutionContext) {\r\n setInterval(async () => {\r\n const entries = await this.storage.ops.getPollingQueueEntries('q_3');\r\n\r\n for(const entry of entries) {\r\n const queueName = entry.payload.queue_name;\r\n const fencingToken = entry.payload.fencing_token;\r\n\r\n const queue = await this.handleTriggerValidity(queueName, fencingToken);\r\n\r\n if(queue) {\r\n await ctx.runTick(queue);\r\n await this.storage.ops.deletePollingQueueEntry(entry.id);\r\n }\r\n }\r\n }, config.get(\"engine.poolingIntervalMS\"));\r\n }\r\n\r\n public async httpEventDrivenQueueTrigger(queueName : string, fencingToken : string, ctx : IRuntimeExecutionContext) {\r\n const targetQueue = config.get('queues').find(q => q.queue === queueName);\r\n\r\n if(!targetQueue) {\r\n this.logger.error(`[Persistent Runtime] : Received notification for unregistered or unmanaged queue : '${queueName}' on channel : ${this.pgNotifyChannel}`);\r\n return;\r\n }\r\n\r\n const canTrigger = await this.handleTriggerValidity(queueName, fencingToken);\r\n\r\n if(canTrigger) {\r\n await ctx.runTick(targetQueue);\r\n }\r\n }\r\n \r\n private async handleTriggerValidity(queue : string, fencingToken : number | string) : Promise<EngineQueuesConfig | null> {\r\n const targetQueue = config.get('queues').find(q => q.queue === queue);\r\n if(!targetQueue) {\r\n this.logger.error(`[Persistent Runtime] : pool entry for unregistered or unmanaged queue: '${queue}'`);\r\n return null;\r\n }\r\n \r\n const isValidToken = await this.storage.ops.checkFencingTokenValidity(queue, fencingToken);\r\n \r\n if(!isValidToken) {\r\n const errorMsg = `[EventDrivenPoller]-[ExecutionTrigger]-[${queue}] : Engine execution rejected : Invalid fencing token.`;\r\n this.logger.error(errorMsg);\r\n return null;\r\n }\r\n\r\n const lockKey = `lock:edp:${queue}`;\r\n const lockTTL = 120_000;\r\n\r\n //console.log(`lock acquire method : ${lockKey}:${this.runtimeExecutionId}:${lockTTL}`);\r\n\r\n const lockAcquired = await this.storage.repository.acquireQueueLock(\r\n lockKey,\r\n this.runtimeExecutionId,\r\n lockTTL\r\n )\r\n\r\n if (lockAcquired) {\r\n await this.storage.repository.clearDispatchPending(lockKey);\r\n }\r\n else {\r\n this.logger.log(`[Persistent Runtime] : Engine busy for queue ${queue}, skipping trigger.`);\r\n return null;\r\n }\r\n\r\n return targetQueue;\r\n }\r\n}",
35
+ "import type { PulsarEventBus } from \"../service/PulsarEventBus\";\r\nimport type { PulsarClock } from \"./PulsarClock\";\r\nimport type { Scheduler } from \"../modules/Scheduler.module\";\r\nimport type { ILogger } from \"./LoggerService\";\r\nimport { config } from \"../service/ConfigurationStore\";\r\nimport type { EngineQueuesConfig } from \"@package/src/types/queue.types\";\r\n\r\nexport class DeferredTickEvaluator {\r\n constructor (\r\n private minBootRequirementSec : number,\r\n private scheduler : Scheduler,\r\n private events : PulsarEventBus,\r\n private clock : PulsarClock,\r\n private logger : ILogger\r\n ) {}\r\n\r\n private timers = new Map<string, ReturnType<typeof setTimeout>>();\r\n private watchdogTimer : ReturnType<typeof setInterval> | null = null;\r\n private isShutdownTriggered = false;\r\n\r\n public evaluateUpcomingDelayedNext(upcomingTimeMs : number, queue : string) {\r\n const isolate = config.raw.isolate;\r\n if (!isolate) throw new Error(\"Isolate is not configured for V8_Isolate_Runtime!\");\r\n\r\n const selfInvocationIntervalSec = config.get(\"engine.selfInvocationIntervalSec\") ?? 1;\r\n const MIN_EXECUTION_TIME_SEC = this.minBootRequirementSec;\r\n const REQUIRED_BUDGET_MS = (selfInvocationIntervalSec + MIN_EXECUTION_TIME_SEC) * 1000;\r\n\r\n const deltaRemainingTimeMs = isolate.remainingTime - upcomingTimeMs;\r\n\r\n if (deltaRemainingTimeMs < REQUIRED_BUDGET_MS) {\r\n this.logger.log(\r\n `[Isolate Runtime] Sleep duration of ${upcomingTimeMs}ms exceeds safe isolate budget. ` +\r\n `Canceling timer sleep and initiating shutdown.`\r\n );\r\n\r\n this.scheduler.cancel(queue);\r\n this.triggerGracefulShutdown(queue);\r\n return;\r\n }\r\n\r\n this.startDelayedSleepWatchdog(queue, REQUIRED_BUDGET_MS);\r\n }\r\n \r\n private startDelayedSleepWatchdog(queue : string, requiredBudgetMs: number) {\r\n this.stopRuntimeWatchdog();\r\n this.isShutdownTriggered = false;\r\n\r\n this.watchdogTimer = setInterval(() => {\r\n const isolate = config.raw.isolate;\r\n if (!isolate || this.isShutdownTriggered) return;\r\n\r\n if (isolate.remainingTime <= requiredBudgetMs) {\r\n this.logger.log(\r\n `[Isolate Watchdog] Remaining isolate budget (${isolate.remainingTime}ms) expired during delayed sleep. ` +\r\n `Canceling wakeup and executing graceful shutdown.`\r\n );\r\n\r\n this.scheduler.cancel(queue);\r\n this.triggerGracefulShutdown(queue);\r\n }\r\n }, 1000)\r\n }\r\n\r\n private triggerGracefulShutdown(queue : string) {\r\n if (this.isShutdownTriggered) return;\r\n this.isShutdownTriggered = true;\r\n\r\n this.stopRuntimeWatchdog();\r\n\r\n this.events.emit(\"tick:time-exceeded\", {\r\n queue,\r\n elapsedMs: this.clock.getElapsedTotalTime(),\r\n });\r\n\r\n this.events.emit(\"tick:cycle-completed\", { queue, cycles: 1 });\r\n }\r\n\r\n public stopRuntimeWatchdog() {\r\n if (this.watchdogTimer) {\r\n clearInterval(this.watchdogTimer);\r\n this.watchdogTimer = null;\r\n }\r\n }\r\n\r\n public clearTimer(queue : string) {\r\n const pending = this.timers.get(queue);\r\n if(pending) {\r\n clearTimeout(pending as ReturnType<typeof setTimeout>);\r\n }\r\n\r\n this.timers.delete(queue);\r\n }\r\n\r\n public forceExecuteTickLater(queue : EngineQueuesConfig, targetTimestamp : number) {\r\n const MAX_TIMEOUT = 2147483647; // ~24.8 days in ms\r\n\r\n const reason = `Extended time limit reached ${targetTimestamp}ms elapsed, overriding standard caps !`;\r\n\r\n const forceRunTick = () => this.events.emit(\"tick:force-run\", { queue, reason });\r\n\r\n const delay = targetTimestamp - Date.now();\r\n\r\n if (delay > MAX_TIMEOUT) {\r\n this.timers.set(\r\n queue.queue,\r\n setTimeout(() => {\r\n this.forceExecuteTickLater(queue, targetTimestamp);\r\n }, MAX_TIMEOUT)\r\n )\r\n }\r\n\r\n this.timers.set(\r\n queue.queue,\r\n setTimeout(() => {\r\n forceRunTick();\r\n }, Math.max(0, delay))\r\n )\r\n }\r\n}\r\n",
36
+ "import { PulsarRuntime } from \"../types/runtime.types.ts\";\r\nimport { PulsarRuntimeCore, type RuntimeDependencies } from \"../shared/PulsarRuntimeCore.ts\";\r\nimport { RuntimeEventBridge } from \"../subsys/RuntimeEventBridge.ts\";\r\nimport { DeferredTickEvaluator } from \"../subsys/DeferredTickEvaluator.ts\";\r\nimport { EventTriggerStrategy } from \"../types/eventTriggerStrategry.types.ts\";\r\nimport { createRuntimeCacheStorage } from \"../subsys/RuntimeCacheStorage.ts\";\r\nimport { config } from \"../service/ConfigurationStore.ts\";\r\n\r\nimport type { EngineQueuesConfig } from \"../types/queue.types.ts\";\r\nimport type { IRuntimeExecutionContext } from \"./runtimeTypes.ts\";\r\nimport type { RuntimeCacheStorage } from \"../subsys/RuntimeCacheStorage.ts\";\r\n\r\nexport class PersistentRuntime extends PulsarRuntimeCore {\r\n public readonly type = \"PERSISTENT\";\r\n public readonly shouldShutdownOnCycleComplete = false;\r\n public override minBootRequirementSec = 1;\r\n private readonly runtimeExecutionId : string;\r\n\r\n private deferredTickEvaluator : DeferredTickEvaluator;\r\n private runtimeEventBridge : RuntimeEventBridge;\r\n\r\n /** Runtime Storage */\r\n protected rs : RuntimeCacheStorage;\r\n\r\n constructor(deps : RuntimeDependencies) {\r\n super(deps);\r\n\r\n this.deferredTickEvaluator = new DeferredTickEvaluator(\r\n this.minBootRequirementSec,\r\n this.scheduler,\r\n this.events,\r\n this.clock,\r\n this.logger\r\n )\r\n \r\n this.runtimeExecutionId = crypto.randomUUID();\r\n\r\n this.runtimeEventBridge = new RuntimeEventBridge(this.storage, this.logger, this.runtimeExecutionId);\r\n this.rs = createRuntimeCacheStorage();\r\n this.rs.kv.set(\"runtime_execution_id\", this.runtimeExecutionId);\r\n }\r\n\r\n override async onStart(ctx : IRuntimeExecutionContext) {\r\n this.logger.log(`Initialized Persistent Runtime.`);\r\n\r\n const bridge = this.runtimeEventBridge;\r\n\r\n if(config.raw.runtime == PulsarRuntime['PERSISTENT']) {\r\n const eventTriggerStrategy= config.raw.eventTriggerStrategy;\r\n\r\n switch (eventTriggerStrategy) {\r\n case EventTriggerStrategy['POSTGRES_NOTIFY']:\r\n await bridge.registerPgNotifyHandler(ctx);\r\n break;\r\n \r\n case EventTriggerStrategy['POLLING']:\r\n await bridge.registerPollingHandler(ctx);\r\n break;\r\n\r\n case EventTriggerStrategy['WEBHOOK']:\r\n this.logger.log(`[Persistent Runtime] : Event Driven Queue triggers will heppen via webhook endpoint.`);\r\n break;\r\n }\r\n\r\n }\r\n \r\n this.rs.kv.set(\"active_runtime_ctx\", ctx);\r\n await this.executeQueuesTick(ctx.runTick);\r\n }\r\n\r\n override async executeTick(queueConfig : EngineQueuesConfig, tickRunner : () => Promise<void>) {\r\n this.deferredTickEvaluator.clearTimer(queueConfig.queue);\r\n \r\n const { isValid, reason } = this.validateTickRun(queueConfig);\r\n\r\n if (!isValid) {\r\n this.logger.warn(`[Tick] : [${queueConfig.queue}] - Rejected, invalid tick run: ${reason}. Please Reconnect Worker ASAP.`);\r\n }\r\n\r\n // unfinished, status : pending\r\n if(queueConfig.interventionPolicy == \"tick\") {\r\n const shouldStop = await this.storage.repository.getStopSignal(queueConfig.queue);\r\n \r\n if(shouldStop) {\r\n this.events.emit(\"tick:cycle-completed\", { queue : queueConfig.queue, cycles : 1 });\r\n return;\r\n }\r\n }\r\n\r\n await tickRunner();\r\n }\r\n\r\n private validateTickRun({ queue } : EngineQueuesConfig) : { isValid : boolean, reason : string } {\r\n const targetConsumer = config.raw.queues.find(q => q.queue === queue);\r\n \r\n if (!targetConsumer) {\r\n return { \r\n isValid: false, \r\n reason: `Queue configuration could not be found for '${queue}'.` \r\n }\r\n }\r\n\r\n if (targetConsumer.consumer.type === \"socket\") {\r\n const connectionList = this.rs.lists.get(queue);\r\n\r\n if (!connectionList) {\r\n this.events.emit('tick:end', { queue, reason : \"Socket consumer connection list does not exist\" });\r\n\r\n return { \r\n isValid: false, \r\n reason: `Socket consumer connection list does not exist for queue '${queue}'.` \r\n }\r\n }\r\n\r\n const workers = Array.from(connectionList.values());\r\n if (workers.length == 0) {\r\n this.events.emit('tick:end', { queue, reason : `Socket consumer has (${workers.length}) active connections.` });\r\n\r\n return { \r\n isValid: false, \r\n reason: `Socket consumer for queue '${queue}' has (${workers.length}) active connections.` \r\n }\r\n }\r\n }\r\n\r\n return { isValid: true, reason: \"Tick run validation passed successfully.\" };\r\n }\r\n\r\n override async scheduleTick(queueConfig : EngineQueuesConfig, tickRunner : () => Promise<void>) : Promise<void> {\r\n const { queue, concurrency, pooler } = queueConfig;\r\n\r\n const metrics = await this.queueService.getSingleQueueMetrics(queue);\r\n\r\n if(!metrics) return;\r\n\r\n if(metrics?.total == 0) {\r\n if(pooler == \"event-driven-pooler\") {\r\n this.logger.log(`[Tick] : [${queue}] - Tick Process Ended. Cycle Limit Reached`);\r\n this.events.emit(\"tick:cycle-completed\", { queue, cycles: 1 });\r\n return;\r\n }\r\n }\r\n\r\n const activeWorkers = await this.storage.repository.getActiveWorkersCount(queue);\r\n const availableSlots = Math.max(0, concurrency - activeWorkers);\r\n\r\n this.deferredTickEvaluator.clearTimer(queue);\r\n\r\n this.scheduler.scheduleNext({\r\n metrics : { queue, availableSlots, ...metrics },\r\n onNext : tickRunner,\r\n onUpcomingDelayedNext : (upcomingTimeMs : number) => {\r\n this.logger.log(`[Scheduler] : Next tick scheduled in ${(upcomingTimeMs / 1000).toFixed(2)}s`);\r\n },\r\n onFutureSchedule : async (nextVisibleAtMs) => {\r\n const delayMs = nextVisibleAtMs - Date.now();\r\n this.logger.log(`[Scheduler] : Deffered tick execution in ${(Math.max(0, delayMs) / 1000).toFixed(2)}s`);\r\n this.deferredTickEvaluator.forceExecuteTickLater(queueConfig, nextVisibleAtMs);\r\n }\r\n })\r\n }\r\n\r\n override async handleCycleCompletion() {\r\n return false;\r\n }\r\n\r\n override async handleRestart() {\r\n this.logger.log(\"[Persistent Runtime] : Restart triggered. Handled by process manager (PM2/systemd).\");\r\n }\r\n}",
37
+ "import { config } from \"../service/ConfigurationStore.ts\";\r\nimport { PulsarRuntimeCore, type RuntimeDependencies } from \"../shared/PulsarRuntimeCore.ts\";\r\nimport type { EngineQueuesConfig } from \"../types/queue.types.ts\";\r\nimport type { IRuntimeExecutionContext } from \"./runtimeTypes.ts\";\r\n\r\nexport class ServerlessRuntime extends PulsarRuntimeCore {\r\n public readonly type = \"SERVERLESS_VM\";\r\n\r\n public override readonly shouldShutdownOnCycleComplete = true;\r\n public override minBootRequirementSec = 1;\r\n\r\n constructor(deps : RuntimeDependencies) {\r\n super(deps);\r\n \r\n this.logger.log(`Initialized Serverless VM Runtime.`);\r\n }\r\n\r\n public override async onStart(ctx : IRuntimeExecutionContext) {\r\n await this.executeQueuesTick(ctx.runTick);\r\n }\r\n\r\n public override async executeTick(_queueConfig: EngineQueuesConfig, tickRunner: () => Promise<void>) {\r\n await tickRunner();\r\n }\r\n\r\n override async scheduleTick(_queueConfig: EngineQueuesConfig, tickRunner: () => Promise<void>): Promise<void> {\r\n await tickRunner();\r\n }\r\n\r\n override async handleCycleCompletion(ctx : IRuntimeExecutionContext) {\r\n let idpInvoked = false;\r\n let continuationScheduledForCurrentLock = false;\r\n const continuationOwnerId = ctx.currentExecutionId;\r\n\r\n const currentLockKey = ctx.lockKey;\r\n\r\n const isEdpLock = currentLockKey?.startsWith(\"pulsar:lock:edp:\");\r\n const isIdpLock = currentLockKey === \"pulsar:lock:idp\";\r\n const targetEdpQueue = isEdpLock ? currentLockKey?.replace(\"pulsar:lock:edp:\", \"\") : null;\r\n\r\n for (const { queue, pooler } of ctx.getActiveQueues()) {\r\n try {\r\n if(pooler == \"interval-driven-pooler\" && idpInvoked) continue;\r\n if (isEdpLock && queue !== targetEdpQueue) continue;\r\n \r\n const metrics = await this.queueService.getSingleQueueMetrics(queue);\r\n\r\n if (!metrics || metrics.total === 0) {\r\n console.log(`[Pulsar] Failed to fetch metrics for ${queue}. Halting queue.`);\r\n ctx.endTick(queue);\r\n continue;\r\n }\r\n\r\n const totalJobs = metrics.total;\r\n const shouldInvoke = await this.storage.repository.evaluateDeadRun(\r\n queue,\r\n pooler,\r\n totalJobs,\r\n continuationOwnerId,\r\n 15000\r\n )\r\n\r\n if (!shouldInvoke) {\r\n console.log(`[Pulsar] Should not invoke for ${queue}. Skipping.`);\r\n continue;\r\n }\r\n\r\n const selfInvocationIntervalSec = config.get(\"engine.selfInvocationIntervalSec\") ?? 1;\r\n\r\n const stateUpdate = await this.triggerSelfInvocation({\r\n queue,\r\n pooler,\r\n delaySec : selfInvocationIntervalSec,\r\n continuationOwnerId,\r\n isIdpLock,\r\n isEdpLock,\r\n targetEdpQueue\r\n })\r\n\r\n if (stateUpdate.idpInvoked) idpInvoked = true;\r\n\r\n if (stateUpdate.continuationScheduledForCurrentLock) {\r\n continuationScheduledForCurrentLock = true;\r\n }\r\n }\r\n catch (error) {\r\n console.log(`[deadRun] Error checking queue ${queue}:`, error);\r\n }\r\n }\r\n \r\n return continuationScheduledForCurrentLock;\r\n }\r\n\r\n public override async handleRestart(_ctx: IRuntimeExecutionContext) {};\r\n}",
38
+ "import { PulsarRuntimeCore, type RuntimeDependencies } from \"../shared/PulsarRuntimeCore.ts\";\r\nimport { PulsarRuntime } from \"../types/runtime.types.ts\";\r\n\r\nimport type { EngineQueuesConfig } from \"../types/queue.types.ts\";\r\nimport type { IRuntimeExecutionContext } from \"./runtimeTypes.ts\";\r\nimport { config } from \"../service/ConfigurationStore.ts\";\r\nimport { DeferredTickEvaluator } from \"../subsys/DeferredTickEvaluator.ts\";\r\n\r\nexport class IsolateRuntime extends PulsarRuntimeCore {\r\n public readonly type = \"V8_ISOLATE\";\r\n public readonly shouldShutdownOnCycleComplete = true;\r\n public override minBootRequirementSec = 5;\r\n\r\n private deferredTickEvaluator : DeferredTickEvaluator;\r\n\r\n constructor(private deps : RuntimeDependencies) {\r\n super(deps);\r\n\r\n this.logger.log(`[EngineRuntime] : Initialized V8 Isolate Runtime.`);\r\n\r\n this.deferredTickEvaluator = new DeferredTickEvaluator(\r\n this.minBootRequirementSec,\r\n this.scheduler,\r\n this.events,\r\n this.clock,\r\n this.logger\r\n )\r\n }\r\n\r\n public override async onStart(ctx : IRuntimeExecutionContext) {\r\n await this.executeQueuesTick(ctx.runTick);\r\n }\r\n\r\n public override async executeTick(queueConfig : EngineQueuesConfig, tickRunner : () => Promise<void>) {\r\n const { queue } = queueConfig;\r\n\r\n this.deferredTickEvaluator.stopRuntimeWatchdog();\r\n\r\n const isSafeToContinue = this.deps.clock.isSafeToContinue();\r\n const events = this.deps.events;\r\n\r\n if (!isSafeToContinue) {\r\n this.logger.log(`[EngineRuntime] : Ending All Ticks due to time limit.`);\r\n \r\n events.emit(\"tick:time-exceeded\", {\r\n queue,\r\n elapsedMs : this.deps.clock.getElapsedTotalTime()\r\n });\r\n\r\n events.emit(\"tick:cycle-completed\", { queue, cycles : 1 });\r\n \r\n return;\r\n }\r\n\r\n // unfinished, status : pending\r\n if(queueConfig.interventionPolicy == \"tick\" || (queueConfig.interventionPolicy == \"inherit\" && config.get('engine.interventionPolicy') == \"tick\")) {\r\n const shouldStop = await this.storage.repository.getStopSignal(queueConfig.queue);\r\n \r\n if(shouldStop) {\r\n events.emit(\"tick:cycle-completed\", { queue, cycles : 1 });\r\n return;\r\n }\r\n }\r\n\r\n await this.deps.clock.trackExecutionTime({ contextId: queue }, tickRunner);\r\n }\r\n\r\n public override async scheduleTick(queueConfig : EngineQueuesConfig, tickRunner : () => Promise<void>) {\r\n const { queue, concurrency, pooler } = queueConfig;\r\n\r\n const metrics = await this.queueService.getSingleQueueMetrics(queue);\r\n\r\n if(!metrics) return;\r\n\r\n if(metrics?.total == 0) {\r\n if(pooler == \"event-driven-pooler\") {\r\n this.logger.log(`[Tick] : [${queue}] - Tick Process Ended. Cycle Limit Reached`);\r\n this.events.emit(\"tick:cycle-completed\", { queue, cycles: 1 });\r\n return;\r\n }\r\n }\r\n\r\n const activeWorkers = await this.storage.repository.getActiveWorkersCount(queue);\r\n const availableSlots = Math.max(0, concurrency - activeWorkers);\r\n \r\n const wrappedTickRunner = async () => {\r\n this.deferredTickEvaluator.stopRuntimeWatchdog();\r\n await tickRunner();\r\n }\r\n\r\n this.scheduler.scheduleNext({\r\n metrics : { queue, availableSlots, ...metrics },\r\n onNext : wrappedTickRunner,\r\n onUpcomingDelayedNext: (upcomingTimeMs : number) => {\r\n this.logger.log(`[Scheduler] : Next tick scheduled in ${(upcomingTimeMs / 1000).toFixed(2)}s`);\r\n return this.deferredTickEvaluator.evaluateUpcomingDelayedNext(upcomingTimeMs, queue)\r\n },\r\n onFutureSchedule : async (nextVisibleAt) => {\r\n this.logger.log(`[Scheduler] : scheduled tick execution request`, nextVisibleAt);\r\n //await this.storage.repository.setFutureSchedule(queue, String(nextVisibleAt));\r\n },\r\n })\r\n \r\n return;\r\n }\r\n\r\n public override async handleCycleCompletion(ctx : IRuntimeExecutionContext) {\r\n let idpInvoked = false;\r\n let continuationScheduledForCurrentLock = false;\r\n const continuationOwnerId = ctx.currentExecutionId;\r\n\r\n const currentLockKey = ctx.lockKey;\r\n\r\n const isEdpLock = currentLockKey?.startsWith(\"pulsar:lock:edp:\");\r\n const isIdpLock = currentLockKey === \"pulsar:lock:idp\";\r\n const targetEdpQueue = isEdpLock ? currentLockKey?.replace(\"pulsar:lock:edp:\", \"\") : null;\r\n \r\n for (const { queue, pooler } of ctx.getActiveQueues()) {\r\n try {\r\n if(pooler == \"interval-driven-pooler\" && idpInvoked) continue;\r\n if (isEdpLock && queue !== targetEdpQueue) continue;\r\n \r\n const metrics = await this.queueService.getSingleQueueMetrics(queue);\r\n\r\n if(!metrics) continue;\r\n\r\n if (metrics.total === 0) {\r\n this.logger.log(`[Engine] : Queue ${queue} is empty (total: 0) using ${pooler} pooler. Halting tick.`)\r\n\r\n if(pooler == \"event-driven-pooler\") {\r\n ctx.endTick(queue);\r\n continue;\r\n }\r\n else {\r\n ctx.endTick(queue);\r\n }\r\n }\r\n\r\n const totalJobs = metrics.total;\r\n const shouldInvoke = await this.storage.repository.evaluateDeadRun(\r\n queue,\r\n pooler,\r\n totalJobs,\r\n continuationOwnerId,\r\n 15000\r\n )\r\n\r\n if (!shouldInvoke) {\r\n this.logger.log(`[Engine] : Should not invoke for ${queue}. Skipping.`);\r\n continue;\r\n }\r\n\r\n const selfInvocationIntervalSec : number = config.get(\"engine.selfInvocationIntervalSec\") ?? 1;\r\n const isV8Isolate = config.get('runtime') == PulsarRuntime.V8_ISOLATE;\r\n\r\n let delaySec = selfInvocationIntervalSec;\r\n\r\n if(isV8Isolate && config.raw.isolate) {\r\n const isolate = config.raw.isolate;\r\n const remainingTimeSec = (isolate.remainingTime / 1000);\r\n\r\n const MIN_EXECUTION_TIME_SEC = this.minBootRequirementSec;\r\n\r\n const REQUIRED_BUDGET_SEC = selfInvocationIntervalSec + MIN_EXECUTION_TIME_SEC;\r\n\r\n if (remainingTimeSec < REQUIRED_BUDGET_SEC) {\r\n this.logger.log(\r\n `[EngineRuntime] : Isolate remaining time (${remainingTimeSec.toFixed(3)}s) is insufficient ` +\r\n `for self-invocation (${selfInvocationIntervalSec}s delay + ${MIN_EXECUTION_TIME_SEC}s min work). Triggering restart.`\r\n );\r\n\r\n await this.handleRestart(ctx);\r\n return true;\r\n }\r\n const maxAvailableDelay = Math.max(1, remainingTimeSec - MIN_EXECUTION_TIME_SEC);\r\n delaySec = Math.min(selfInvocationIntervalSec, maxAvailableDelay);\r\n }\r\n \r\n const stateUpdate = await this.triggerSelfInvocation({\r\n queue,\r\n pooler,\r\n delaySec,\r\n continuationOwnerId,\r\n isIdpLock,\r\n isEdpLock,\r\n targetEdpQueue\r\n })\r\n\r\n if (stateUpdate.idpInvoked) idpInvoked = true;\r\n\r\n if (stateUpdate.continuationScheduledForCurrentLock) {\r\n continuationScheduledForCurrentLock = true;\r\n }\r\n }\r\n catch (error) {\r\n this.logger.log(`[deadRun] : Error checking queue ${queue}:`, error);\r\n }\r\n }\r\n \r\n return continuationScheduledForCurrentLock;\r\n }\r\n\r\n public override async handleRestart(ctx : IRuntimeExecutionContext) {\r\n let idpInvoked = false;\r\n const continuationOwnerId = ctx.currentExecutionId;\r\n const selfRestartIntervalSec = config.get(\"engine.selfRestartIntervalSec\");\r\n\r\n const activeQueues = ctx.getActiveQueues();\r\n\r\n for (const { queue, pooler } of activeQueues) {\r\n \r\n if(pooler == \"interval-driven-pooler\" && idpInvoked) continue;\r\n\r\n const headers : Record<string, string> = {\r\n 'content-type': 'application/json',\r\n 'x-last-execution-id' : continuationOwnerId,\r\n 'x-last-execution-at' : new Date().toISOString(),\r\n 'x-execution-owner' : 'engine',\r\n 'x-restart' : 'true',\r\n 'x-pooler' : pooler,\r\n 'x-target-queue' : queue\r\n };\r\n\r\n this.logger.log(`(${pooler}) : invoking engine via restartTick (${selfRestartIntervalSec})`);\r\n\r\n if(pooler == \"interval-driven-pooler\") idpInvoked = true;\r\n\r\n const lockKey = ctx.lockKey;\r\n\r\n await this.storage.repository.releaseQueueLock(lockKey, ctx.isolateId);\r\n await this.storage.ops.addRestart(activeQueues);\r\n\r\n await this.queueService.triggerUrl({\r\n url: config.get('engine.selfURL'),\r\n headers,\r\n delaySeconds: selfRestartIntervalSec\r\n });\r\n\r\n await this.storage.ops.updateRestartOwnership(queue, 'handled_by_engine');\r\n }\r\n }\r\n}",
39
+ "import { serve } from \"crossws/server\";\r\nimport EventEmitter from \"eventemitter3\";\r\nimport { LoggerService } from \"../subsys/LoggerService\";\r\n\r\nimport type { Server, ServerHandler } from \"srvx\";\r\nimport type { NetworkConfig } from \"./interfaces/network.types\";\r\nimport type { ILogger } from \"../subsys/LoggerService\";\r\nimport { createRuntimeCacheStorage, type RuntimeCacheStorage } from \"../subsys/RuntimeCacheStorage\";\r\n\r\nexport class NetworkInterface extends EventEmitter {\r\n private serverInstance : Server<ServerHandler> = null as any;\r\n private logger : ILogger;\r\n private store : RuntimeCacheStorage;\r\n\r\n public onFetch?: (request : Request) => Promise<Response> | Response;\r\n\r\n constructor(private readonly config : NetworkConfig) {\r\n super();\r\n this.logger = new LoggerService();\r\n this.store = createRuntimeCacheStorage();\r\n }\r\n\r\n public async start() {\r\n const self = this;\r\n\r\n this.logger.log(`[Network] : Initializing server on port ${this.config.port} in [${this.config.mode}] mode`);\r\n\r\n const openWebSocket = this.config.mode === \"hybrid\" || this.config.mode === \"websocket\";\r\n\r\n if (openWebSocket) {\r\n this.logger.log(`[Network] : WebSocket server handlers attached on port ${this.config.port}`);\r\n }\r\n\r\n this.serverInstance = serve({\r\n port : this.config.port,\r\n ...(openWebSocket ? {\r\n websocket: {\r\n open(peer) { \r\n self.emit(\"open\", peer); \r\n },\r\n message(peer, message) { \r\n self.emit(\"message\", peer, message); \r\n },\r\n close(peer, event) { \r\n self.emit(\"close\", peer, event); \r\n },\r\n },\r\n } : {}),\r\n fetch(request) {\r\n if (self.onFetch) {\r\n return self.onFetch(request);\r\n }\r\n self.logger.warn(`[Network] : Unhandled route accessed: ${request.method} ${request.url}`);\r\n return new Response(null, { status: 404 });\r\n },\r\n gracefulShutdown: false,\r\n maxRequestBodySize: undefined,\r\n })\r\n\r\n this.store.kv.set('self_url', this.serverInstance.url);\r\n\r\n await this.serverInstance.ready();\r\n this.logger.log(`[Server] Successfully started and listening on port ${this.config.port}`);\r\n }\r\n\r\n public async close() {\r\n try {\r\n await this.serverInstance?.close(true);\r\n }\r\n catch (err) {\r\n this.logger.error(`[Network] : Error closing server:`, err);\r\n }\r\n }\r\n}",
40
+ "import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n",
41
+ "import msgpack from '@msgpack/msgpack';\r\nimport { RuntimeEventBridge } from '../../subsys/RuntimeEventBridge';\r\nimport { BaseNetworkDriver } from \"../abstract/BaseNetworkDriver\";\r\nimport { createRuntimeCacheStorage } from \"../../subsys/RuntimeCacheStorage\";\r\nimport { parseRequest } from \"../../server/parser/parseRequest\";\r\nimport { extractHeaders, type ResponseHeaders } from '../../server/utility/extract-headers';\r\nimport { config } from \"../../service/ConfigurationStore\";\r\n\r\nimport { PulsarRuntime } from \"../../types/runtime.types\";\r\nimport type { PulsarUnifiedStorage } from \"../../storage/PulsarStorage\";\r\nimport type { NetworkConfig } from \"../interfaces/network.types\";\r\nimport type { NetworkInterface } from \"../NetworkInterface\";\r\nimport type { QueueService } from \"../../modules/Queue.module\";\r\nimport type { EngineConsumerConfig } from \"../../types/consumer.types\";\r\nimport type { RuntimeCacheStorage } from \"../../subsys/RuntimeCacheStorage\";\r\nimport type { IRuntimeExecutionContext } from '../../runtimes/runtimeTypes';\r\n\r\ntype StandardArgs = {\r\n headers : ResponseHeaders;\r\n body : any;\r\n}\r\n\r\ntype StandardResponse = {\r\n status : number;\r\n message : string;\r\n}\r\n\r\nexport class HttpNetworkDriver extends BaseNetworkDriver {\r\n public override readonly interface = \"HTTP\";\r\n\r\n private consumersMap : Map<string, EngineConsumerConfig>;\r\n private triggerHandler?: (queue : string, data : any) => void;\r\n\r\n private runtimeEventBridge : RuntimeEventBridge;\r\n private store : RuntimeCacheStorage;\r\n\r\n\r\n constructor(\r\n readonly networkConfig : NetworkConfig,\r\n private readonly networkInterface : NetworkInterface,\r\n private storage : PulsarUnifiedStorage,\r\n private queueService : QueueService\r\n ) {\r\n super(networkConfig);\r\n this.store = createRuntimeCacheStorage();\r\n\r\n const runtimeExecutionId = this.rs.kv.get<string>(\"runtime_execution_id\");\r\n\r\n this.runtimeEventBridge = new RuntimeEventBridge(this.storage, this.logger, runtimeExecutionId!);\r\n\r\n const consumers = config.get('queues');\r\n const map : Map<string, EngineConsumerConfig> = new Map();\r\n consumers.forEach(({ consumer, queue }) => map.set(queue, consumer));\r\n \r\n this.consumersMap = map;\r\n\r\n if (this.networkInterface) {\r\n this.networkInterface.onFetch = (req : Request) => this.handleFetch(req);\r\n }\r\n }\r\n\r\n public override async start() {}\r\n\r\n public override async broadcast(queue : string, payload : any) {\r\n const consumer = this.consumersMap.get(queue);\r\n if (!consumer) {\r\n throw new Error(`No consumer registered for queue: \"${queue}\"`);\r\n }\r\n\r\n if (consumer.type !== \"http\") return;\r\n\r\n const { worker_id, batch } = payload;\r\n\r\n const binaryPayload = msgpack.encode(payload);\r\n\r\n const selfUrl = config.get('runtime') == PulsarRuntime.PERSISTENT ? this.store.kv.get('self_url') as string : config.get('engine.selfURL');\r\n\r\n try {\r\n await fetch(`${consumer.url}/dispatch`, {\r\n method: \"POST\",\r\n headers: {\r\n 'content-type': 'application/x-msgpack',\r\n ...consumer.headers,\r\n 'x-worker-id': worker_id,\r\n 'x-batch-size': batch.length.toString(),\r\n 'x-pulsar-callback-url': selfUrl,\r\n 'x-queue': queue,\r\n \"x-execution-signature\": crypto.randomUUID(),\r\n \"x-instance-id\" : config.get(\"instanceId\"),\r\n \"x-api-key\" : config.get(\"apiKey\"),\r\n \"x-dispatched-at\" : new Date().toISOString()\r\n },\r\n body: binaryPayload\r\n })\r\n }\r\n catch (error) {\r\n this.logger.error('Error dispatching jobs to http consumer,', error);\r\n }\r\n }\r\n\r\n public onTrigger(handler: (queue : string, data : any) => void) {\r\n this.triggerHandler = handler;\r\n }\r\n\r\n public override async stop() {}\r\n\r\n private async handleFetch(req : Request) {\r\n const { url: rawUrl, method, body, headers : rawHeaders } = await parseRequest(req);\r\n const headers = extractHeaders(rawHeaders);\r\n\r\n const url = new URL(rawUrl);\r\n const args = { headers, body };\r\n\r\n if (url.pathname.endsWith(\"/ack\") && method === \"POST\") {\r\n const response = await this.handleAck(args);\r\n return new Response(response.message, { status: response.status });\r\n }\r\n\r\n if (url.pathname.endsWith(\"/nack\") && method === \"POST\") {\r\n const response = await this.handleNack(args);\r\n return new Response(response.message, { status: response.status });\r\n }\r\n\r\n if (url.pathname.endsWith(\"/retry\") && method === \"POST\") {\r\n const response = await this.handleRetry(args);\r\n return new Response(response.message, { status: response.status });\r\n }\r\n\r\n if (url.pathname.endsWith(\"/deregister\") && method === \"POST\") {\r\n const response = await this.handleDeregister(args);\r\n return new Response(response.message, { status: response.status });\r\n }\r\n\r\n const executionOwner = headers.executionOwner;\r\n const poolerMode = headers.poolerMode;\r\n\r\n if(executionOwner == 'trigger') {\r\n if(poolerMode == 'event-driven-pooler') {\r\n const queueName = headers.targetQueue as string;\r\n const fencingToken = headers.fencingToken ?? '0';\r\n\r\n const activeCtx = this.store.kv.get<IRuntimeExecutionContext>('active_runtime_ctx');\r\n\r\n if(!activeCtx) {\r\n this.logger.warn('active runtime context was not found');\r\n return new Response('UNKNOWN ROUTE', { status: 200 });\r\n }\r\n\r\n else await this.runtimeEventBridge.httpEventDrivenQueueTrigger(queueName, fencingToken, activeCtx);\r\n }\r\n }\r\n\r\n return new Response('UNKNOWN ROUTE', { status: 200 });\r\n }\r\n\r\n private async performBatchAction(queue : string, workerId : string, messageIds : number[], action : \"ACK\" | \"NACK\" | \"RETRY\" | \"DEREGISTER\") {\r\n try {\r\n switch (action) {\r\n case \"ACK\":\r\n await this.queueService.ackBatch(queue, messageIds);\r\n break;\r\n case \"NACK\":\r\n await this.queueService.ackBatch(queue, messageIds);\r\n break;\r\n case \"RETRY\":\r\n await this.queueService.retryBatch(queue, messageIds);\r\n break;\r\n case \"DEREGISTER\":\r\n await this.storage.repository.deregisterWorker(workerId, queue);\r\n break;\r\n }\r\n }\r\n catch (error) {\r\n this.logger.error(`Error performing batch action [${action}] for queue [${queue}]:`, error);\r\n throw error;\r\n }\r\n }\r\n\r\n private parseBody(body : ArrayBufferLike | Uint8Array) : any {\r\n try {\r\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {\r\n return msgpack.decode(body);\r\n }\r\n\r\n return body;\r\n }\r\n catch (err : any) {\r\n throw new Error(`Failed to parse request body : ${err?.message}`);\r\n }\r\n }\r\n\r\n private extractContext(args : StandardArgs) {\r\n const headers = args.headers;\r\n const body = this.parseBody(args.body);\r\n const queue = headers.targetQueue;\r\n const workerId = headers.workerId ?? '';\r\n\r\n if (!queue) {\r\n throw new Error(\"[HttpNetworkDriver] Queue not found in headers\");\r\n }\r\n\r\n return { headers, body, queue, workerId };\r\n }\r\n\r\n private async getMessageIds(args : StandardArgs) : Promise<{ queue : string; messageIds : number[]; workerId : string }> {\r\n const { queue, body, workerId } = this.extractContext(args);\r\n\r\n const rawMsgIds = (Array.isArray(body?.msg_ids) ? body.msg_ids : []) as number[];\r\n const messageIds : number[] = rawMsgIds\r\n .map((id) => Number.parseInt(String(id), 10))\r\n .filter((id) => Number.isInteger(id) && id >= 0);\r\n\r\n return { queue, messageIds, workerId };\r\n }\r\n\r\n private async handleAck(args : StandardArgs) : Promise<StandardResponse> {\r\n const { messageIds, queue, workerId } = await this.getMessageIds(args);\r\n await this.performBatchAction(queue, workerId, messageIds, \"ACK\");\r\n return { message: \"Jobs Acknowledged\", status: 200 };\r\n }\r\n\r\n private async handleNack(args : StandardArgs) : Promise<StandardResponse> {\r\n const { messageIds, queue, workerId } = await this.getMessageIds(args);\r\n await this.performBatchAction(queue, workerId, messageIds, \"NACK\");\r\n return { message: \"Jobs Not Acknowledged\", status: 200 };\r\n }\r\n\r\n private async handleRetry(args : StandardArgs) : Promise<StandardResponse> {\r\n const { queue, workerId, messageIds } = await this.getMessageIds(args);\r\n await this.performBatchAction(queue, workerId, messageIds, \"RETRY\");\r\n return { message: \"Jobs Retry Applied\", status: 200 };\r\n }\r\n\r\n private async handleDeregister(args : StandardArgs) : Promise<StandardResponse> {\r\n const { queue, workerId } = this.extractContext(args);\r\n\r\n if (!workerId) {\r\n throw new Error(\"[HttpNetworkDriver] Worker ID not found in headers\");\r\n }\r\n\r\n await this.performBatchAction(queue, workerId, [], \"DEREGISTER\");\r\n return { message: \"Worker Deregistered\", status: 200 };\r\n }\r\n}",
42
+ "import { LoggerService, type ILogger } from \"../../subsys/LoggerService\";\r\nimport { createRuntimeCacheStorage, type RuntimeCacheStorage } from \"../../subsys/RuntimeCacheStorage\";\r\nimport type { NetworkConfig } from \"../interfaces/network.types\";\r\n\r\nexport abstract class BaseNetworkDriver {\r\n protected isRunning : boolean = false;\r\n protected logger : ILogger;\r\n\r\n public abstract interface : \"WEBSOCKET\" | \"HTTP\";\r\n\r\n /** Runtime Storage */\r\n protected rs : RuntimeCacheStorage;\r\n\r\n constructor(protected readonly config : NetworkConfig) {\r\n this.logger = new LoggerService();\r\n this.rs = createRuntimeCacheStorage();\r\n }\r\n\r\n public abstract start() : Promise<void>;\r\n public abstract stop() : Promise<void>;\r\n public abstract broadcast(queue : string, payload : any) : Promise<void>;\r\n public abstract onTrigger(handler: (queue: string, data: any) => void) : void;\r\n}",
43
+ "import msgpack from '@msgpack/msgpack';\r\nimport type { Peer, Message } from \"crossws\";\r\nimport { BaseNetworkDriver } from \"../abstract/BaseNetworkDriver\";\r\n\r\nimport type { NetworkConfig } from \"../interfaces/network.types\";\r\nimport type { NetworkInterface } from \"../NetworkInterface\";\r\n\r\nexport class WebSocketNetworkDriver extends BaseNetworkDriver {\r\n public override readonly interface = \"WEBSOCKET\";\r\n\r\n private queuePeers = new Map<string, Set<Peer>>();\r\n private triggerHandler?: (queue : string, data : any) => void;\r\n\r\n private boundOpen = (peer : Peer) => this.onConnectionOpen(peer);\r\n private boundMessage = (peer : Peer, message : Message) => this.onMessage(peer, message);\r\n private boundClose = (peer : Peer) => this.onConnectionClose(peer);\r\n\r\n constructor(config : NetworkConfig, private networkInterface : NetworkInterface) {\r\n super(config);\r\n\r\n this.networkInterface.on(\"open\", this.boundOpen);\r\n this.networkInterface.on(\"message\", this.boundMessage);\r\n this.networkInterface.on(\"close\", this.boundClose);\r\n }\r\n\r\n public override async start() {}\r\n\r\n public override async broadcast(queue : string, payload : any) {\r\n const peers = this.queuePeers.get(queue);\r\n if (!peers || peers.size === 0) {\r\n this.logger.warn(`[Network] : No active workers listening on queue: ${queue}`);\r\n return;\r\n }\r\n\r\n const binaryPayload = msgpack.encode(payload);\r\n\r\n for (const peer of peers) {\r\n try {\r\n peer.send(binaryPayload);\r\n }\r\n catch (err) {\r\n this.logger.error(`[Network] : Failed to send message to peer ${peer.id}:`, err);\r\n }\r\n }\r\n }\r\n\r\n public onTrigger(handler: (queue : string, data : any) => void) {\r\n this.triggerHandler = handler;\r\n }\r\n\r\n public override async stop() {\r\n this.networkInterface.off(\"open\", this.boundOpen);\r\n this.networkInterface.off(\"message\", this.boundMessage);\r\n this.networkInterface.off(\"close\", this.boundClose);\r\n\r\n for (const peers of this.queuePeers.values()) {\r\n for (const peer of peers) {\r\n try { peer.close(1001, \"server shutting down\"); } catch {}\r\n }\r\n }\r\n\r\n this.queuePeers.clear();\r\n }\r\n\r\n private onConnectionOpen(peer : Peer) {\r\n this.logger.log(\"[Network] : Worker connected:\", peer.id);\r\n }\r\n\r\n private onMessage(peer : Peer, message : Message) {\r\n const data = JSON.parse(message.toString());\r\n\r\n data.type === \"REGISTER\" ?\r\n this.handleWorkerRegistration(peer, data) :\r\n this.handleWorkerMessage(data);\r\n }\r\n\r\n private handleWorkerRegistration(peer : Peer, data : { type : string, queue : string }) {\r\n let peersSet = this.queuePeers.get(data.queue);\r\n\r\n if (!peersSet) {\r\n peersSet = new Set<Peer>();\r\n this.queuePeers.set(data.queue, peersSet);\r\n }\r\n\r\n if (peersSet.has(peer)) {\r\n this.logger.log(`[Network] : Worker ${peer.id} is already registered to queue: ${data.queue}`);\r\n return;\r\n }\r\n\r\n peer.subscribe(data.queue);\r\n peersSet.add(peer);\r\n\r\n this.rs.lists.add(data.queue, peer.id);\r\n\r\n this.logger.log(`[Network] : Worker ${peer.id} registered to queue: ${data.queue}`);\r\n }\r\n\r\n private handleWorkerMessage(data : any) {\r\n if (this.triggerHandler) {\r\n const queue = data.queue;\r\n const payload = data.data !== undefined ? data?.data : data;\r\n if (queue) {\r\n this.triggerHandler(queue, payload);\r\n }\r\n }\r\n }\r\n\r\n private onConnectionClose(peer : Peer) {\r\n this.logger.log(\"[Network] : [WebSocketNetworkDriver] - Worker disconnected:\", peer.id);\r\n\r\n for (const [queue, peers] of this.queuePeers.entries()) {\r\n if (peers.has(peer)) {\r\n peers.delete(peer);\r\n this.rs.lists.remove(queue, peer.id);\r\n if (peers.size === 0) {\r\n this.queuePeers.delete(queue);\r\n }\r\n }\r\n }\r\n }\r\n}",
44
+ "import type { NetworkConfig } from \"./interfaces/network.types\";\r\nimport type { PulsarUnifiedStorage } from \"../storage/PulsarStorage\";\r\nimport type { QueueService } from \"../modules/Queue.module\";\r\n\r\nimport { NetworkInterface } from \"./NetworkInterface\";\r\nimport { BaseNetworkDriver } from \"./abstract/BaseNetworkDriver\";\r\nimport { HttpNetworkDriver } from \"./drivers/HttpNetworkDriver\";\r\nimport { WebSocketNetworkDriver } from \"./drivers/WebSocketNetworkDriver\";\r\nimport { config } from \"../service/ConfigurationStore\";\r\nimport { LoggerService, type ILogger } from \"../subsys/LoggerService\";\r\n\r\nexport class UnifiedTransportManager {\r\n\r\n private drivers : BaseNetworkDriver[] = [];\r\n public readonly topology : NetworkConfig['mode'];\r\n private networkInterface?: NetworkInterface;\r\n private readonly isServerMode : boolean;\r\n private readonly logger : ILogger;\r\n\r\n constructor(private readonly config : NetworkConfig, private storage : PulsarUnifiedStorage, private queueServuce : QueueService) {\r\n this.topology = config.mode;\r\n this.isServerMode = config.isServer;\r\n\r\n this.logger = new LoggerService();\r\n\r\n if (this.isServerMode) this.initializeTopology();\r\n else this.initializeClientTopology();\r\n }\r\n\r\n private initializeTopology() {\r\n this.networkInterface = new NetworkInterface(this.config);\r\n\r\n if (this.config.mode === \"websocket\" || this.config.mode === \"hybrid\") {\r\n this.drivers.push(new WebSocketNetworkDriver(this.config, this.networkInterface));\r\n }\r\n\r\n if (this.config.mode === \"http\" || this.config.mode === \"hybrid\") {\r\n this.drivers.push(new HttpNetworkDriver(this.config, this.networkInterface, this.storage, this.queueServuce));\r\n }\r\n }\r\n\r\n private initializeClientTopology() {\r\n this.drivers.push(new HttpNetworkDriver(this.config, undefined as any, this.storage, this.queueServuce));\r\n }\r\n\r\n public async bootAll() {\r\n if (!this.isServerMode || !this.networkInterface) return;\r\n\r\n await this.networkInterface.start();\r\n\r\n for (const driver of this.drivers) {\r\n await driver.start();\r\n }\r\n }\r\n\r\n public async shutdownAll() {\r\n if (!this.isServerMode) return;\r\n \r\n for (const driver of this.drivers) {\r\n await driver.stop();\r\n }\r\n \r\n await this.networkInterface?.close();\r\n }\r\n\r\n public onTrigger(onTrigger: (queue : string, data : any) => void) {\r\n for (const driver of this.drivers) {\r\n driver.onTrigger(onTrigger);\r\n }\r\n }\r\n\r\n public async dispatchToNetwork(queue : string, payload : any) {\r\n const targetQueue = config.get('queues').find(q => q.queue === queue)!;\r\n\r\n const interfaceMap : Record<string, string> = {\r\n http: \"HTTP\",\r\n socket: \"WEBSOCKET\"\r\n }\r\n\r\n const consumerType = targetQueue.consumer.type;\r\n const targetInterface = interfaceMap[consumerType];\r\n\r\n if (!targetInterface) {\r\n throw new Error(`[DispatchToNetwork] : Unsupported consumer type \"${consumerType}\" for queue: \"${queue}\"`);\r\n }\r\n\r\n for (const driver of this.drivers) {\r\n if (driver.interface === targetInterface) {\r\n await driver.broadcast(queue, payload);\r\n }\r\n }\r\n\r\n const matched = this.drivers.filter(d => d.interface === targetInterface);\r\n\r\n if (matched.length === 0) {\r\n this.logger.error(`[DispatchToNetwork] : No \"${targetInterface}\" driver available for queue \"${queue}\" (mode: ${this.topology}, server: ${this.isServerMode})`); \r\n throw new Error(`[DispatchToNetwork] : No \"${targetInterface}\" driver available for queue \"${queue}\" (mode: ${this.topology}, server: ${this.isServerMode})`);\r\n }\r\n }\r\n}",
45
+ "import { PulsarUnifiedStorage } from '../storage/PulsarStorage.ts';\r\nimport { PulsarEventBus } from './PulsarEventBus.ts';\r\nimport { PulsarClock } from '../subsys/PulsarClock.ts';\r\nimport { QueueService } from '../modules/Queue.module.ts';\r\n\r\nimport { SwarmManager } from './SwarmBudgetTracker.ts';\r\nimport { Scheduler } from \"../modules/Scheduler.module.ts\";\r\nimport { TickService } from '../modules/Tick.module.ts';\r\nimport { TickController } from '../modules/TickController.module.ts';\r\nimport { PulsarRuntime } from '../types/runtime.types.ts';\r\n\r\nimport { PersistentRuntime } from '../runtimes/PersistentRuntime.ts';\r\nimport { ServerlessRuntime } from '../runtimes/ServerlessRuntime.ts';\r\nimport { IsolateRuntime } from '../runtimes/IsolateRuntime.ts';\r\n\r\nimport type { EngineQueuesConfig } from '../types/queue.types.ts';\r\nimport type { EngineConsumerConfig } from '../types/consumer.types.ts';\r\nimport type { IsolateInstance } from './Isolate.service.ts';\r\nimport type { EngineConfig } from '../types/base.types.ts';\r\nimport type { IIntegration, IntegrationConstructor, IntegrationMap } from '../types/integrations.types.ts';\r\nimport type { PulsarRuntimeCore, RuntimeDependencies } from '../shared/PulsarRuntimeCore.ts';\r\n\r\nimport { config } from './ConfigurationStore.ts';\r\nimport { UnifiedTransportManager } from '../network/UnifiedTransportManager.ts';\r\nimport { LoggerService } from '../subsys/LoggerService.ts';\r\n\r\n/**\r\n * Core abstract base class for the Pulsar engine ecosystem.\r\n * \r\n * Provides foundational lifecycle management, centralized event emitting, unified storage\r\n * initialization, queue registration\r\n*/\r\nexport abstract class PulsarCore {\r\n protected storage : PulsarUnifiedStorage;\r\n\r\n protected tickService : TickService;\r\n protected tickController: TickController;\r\n\r\n protected unifiedTransportManager : UnifiedTransportManager;\r\n protected swarmManager : SwarmManager;\r\n protected scheduler : Scheduler;\r\n protected queueService : QueueService;\r\n\r\n protected clock : PulsarClock;\r\n protected events : PulsarEventBus;\r\n\r\n protected queues : EngineQueuesConfig[] = [];\r\n protected consumers : EngineConsumerConfig[] = [];\r\n\r\n protected runtimeStrategy: PulsarRuntimeCore;\r\n\r\n public readonly logger : LoggerService;\r\n private readonly integrations = new Map<string, IIntegration>();\r\n\r\n constructor (baseConfig : EngineConfig) {\r\n config.initialize(baseConfig);\r\n\r\n this.logger = new LoggerService();\r\n\r\n if (baseConfig.integrations?.length) {\r\n this.runIntegrations(baseConfig.integrations);\r\n }\r\n\r\n for(const { consumer, ...queue } of config.raw.queues) {\r\n this.queues.push(queue);\r\n this.consumers.push(consumer);\r\n }\r\n\r\n const instanceId = config.get('instanceId');\r\n\r\n if(!instanceId) {\r\n throw new Error('[Pulsar] : instanceId is required.');\r\n }\r\n \r\n const instanceIdRegex = /^[a-zA-Z0-9_-]+$/;\r\n\r\n if (typeof instanceId !== 'string' || !instanceIdRegex.test(instanceId)) {\r\n throw new Error('[Pulsar] : Invalid instanceId format. It must contain only alphanumeric characters, hyphens, and underscores (e.g., \"string-like-this\" or \"or_this\").');\r\n }\r\n\r\n this.events = new PulsarEventBus();\r\n\r\n let maxExecutionBudgetMs = Infinity;\r\n\r\n const isV8Isolate = config.raw.runtime === PulsarRuntime.V8_ISOLATE;\r\n\r\n const isolate = config.get('isolate')!;\r\n\r\n if(isV8Isolate) {\r\n maxExecutionBudgetMs = Math.max(0, isolate.remainingTime - 5000);\r\n }\r\n\r\n this.storage = config.raw.storage;\r\n this.storage.connect();\r\n this.storage.bindInstanceId(instanceId);\r\n \r\n this.clock = new PulsarClock({\r\n maxExecutionBudgetMs,\r\n safetyBufferMs: 0,\r\n maxTrackHistory : 50,\r\n enabled : true\r\n })\r\n \r\n this.queueService = new QueueService(this.storage);\r\n this.scheduler = new Scheduler();\r\n\r\n this.runtimeStrategy = this.resolveRuntimeStrategy();\r\n\r\n if (!this.runtimeStrategy) {\r\n this.logger.error('[Pulsar] Failed to resolve a valid runtime strategy.');\r\n throw new Error('[Pulsar] Failed to resolve a valid runtime strategy.');\r\n }\r\n\r\n if(config.raw.runtime == PulsarRuntime.PERSISTENT) {\r\n this.unifiedTransportManager = new UnifiedTransportManager({\r\n ...config.raw.networkInterface,\r\n isServer : true\r\n }, this.storage, this.queueService);\r\n }\r\n else {\r\n this.unifiedTransportManager = new UnifiedTransportManager({\r\n mode : \"client\",\r\n isServer : false,\r\n port : 0,\r\n }, this.storage, this.queueService)\r\n }\r\n\r\n this.swarmManager = new SwarmManager(\r\n config.raw.swarmConfig?.globalMaxJobsPerTick ?? Infinity,\r\n config.raw.swarmConfig?.maxGlobalConcurrency ?? Infinity\r\n )\r\n \r\n this.tickService = new TickService({\r\n queue : this.queueService,\r\n storage : this.storage,\r\n swarmManager: this.swarmManager,\r\n unifiedTransportManager : this.unifiedTransportManager,\r\n events : this.events\r\n })\r\n\r\n this.tickController = new TickController({\r\n scheduler : this.scheduler,\r\n storage : this.storage,\r\n tickService : this.tickService,\r\n clock : this.clock,\r\n events : this.events,\r\n runtimeStrategy : this.runtimeStrategy\r\n })\r\n\r\n if(Number.isFinite(maxExecutionBudgetMs)) {\r\n this.logger.log(`[EngineRuntime] : isolate registred with id : [${isolate.id}]`);\r\n this.logger.log(`[Clock] : Synced execution timeout (${maxExecutionBudgetMs / 1000}s) with isolate [${isolate.id}]`);\r\n }\r\n else {\r\n this.logger.log(`[EngineRuntime] : Engine Started With No V8 Isolate (${new Date().toISOString()})`);\r\n }\r\n }\r\n\r\n private resolveRuntimeStrategy() : PulsarRuntimeCore {\r\n const deps : RuntimeDependencies = {\r\n queueService: this.queueService,\r\n clock: this.clock,\r\n queues : this.queues,\r\n storage : this.storage,\r\n isolate : this.V8Isolate,\r\n events : this.events,\r\n scheduler : this.scheduler\r\n }\r\n\r\n switch (config.get('runtime')) {\r\n case PulsarRuntime.PERSISTENT:\r\n return new PersistentRuntime(deps);\r\n case PulsarRuntime.SERVERLESS_VM:\r\n return new ServerlessRuntime(deps);\r\n case PulsarRuntime.V8_ISOLATE:\r\n return new IsolateRuntime(deps);\r\n default:\r\n throw new Error(`Unsupported Runtime`);\r\n }\r\n }\r\n\r\n protected async runIntegrations(integrations : Array<IntegrationConstructor | IIntegration>) {\r\n for (const item of integrations) {\r\n let instance : IIntegration;\r\n\r\n if (typeof item === \"function\") {\r\n instance = new item(\"ALL\");\r\n }\r\n else {\r\n instance = item;\r\n }\r\n\r\n await instance.main(this);\r\n\r\n this.integrations.set(instance.module, instance);\r\n }\r\n }\r\n\r\n public getIntegration<K extends keyof IntegrationMap>(moduleOrClass : K) : IntegrationMap[K];\r\n public getIntegration<T extends IIntegration>(moduleOrClass : new (...args : any[]) => T) : T;\r\n\r\n public getIntegration(moduleOrClass : any) : any {\r\n if (typeof moduleOrClass === \"string\") {\r\n return this.integrations.get(moduleOrClass);\r\n }\r\n\r\n for (const instance of this.integrations.values()) {\r\n if (instance instanceof moduleOrClass) {\r\n return instance;\r\n }\r\n }\r\n\r\n const name = typeof moduleOrClass === \"string\" ? moduleOrClass : moduleOrClass.name;\r\n throw new Error(`Integration \"${name}\" is not registered.`);\r\n }\r\n\r\n get runtime() : keyof typeof PulsarRuntime {\r\n return this.runtimeStrategy.type as keyof typeof PulsarRuntime;\r\n }\r\n\r\n get isV8Isolate() {\r\n return config.get('runtime') === PulsarRuntime.V8_ISOLATE\r\n }\r\n\r\n get V8Isolate() : IsolateInstance {\r\n return config.raw.isolate as IsolateInstance;\r\n }\r\n\r\n protected async exit() {\r\n await this.storage.disconnect();\r\n }\r\n}"
46
+ ],
47
+ "mappings": ";;;;oPAEA,FAAI,HAAM,CAAO,UAAU,eACvB,EAAS,IASb,SAAS,CAAM,EAAG,EASlB,GAAI,OAAO,QAOT,GANA,EAAO,UAAY,OAAO,OAAO,IAAI,EAMjC,CAAC,IAAI,EAAO,EAAE,UAAW,EAAS,GAYxC,SAAS,EAAE,CAAC,EAAI,EAAS,EAAM,CAC7B,KAAK,GAAK,EACV,KAAK,QAAU,EACf,KAAK,KAAO,GAAQ,GActB,SAAS,EAAW,CAAC,EAAS,EAAO,EAAI,EAAS,EAAM,CACtD,GAAI,OAAO,IAAO,WAChB,MAAU,UAAU,iCAAiC,EAGvD,IAAI,EAAW,IAAI,GAAG,EAAI,GAAW,EAAS,CAAI,EAC9C,EAAM,EAAS,EAAS,EAAQ,EAEpC,GAAI,CAAC,EAAQ,QAAQ,GAAM,EAAQ,QAAQ,GAAO,EAAU,EAAQ,eAC/D,QAAI,CAAC,EAAQ,QAAQ,GAAK,GAAI,EAAQ,QAAQ,GAAK,KAAK,CAAQ,EAChE,OAAQ,QAAQ,GAAO,CAAC,EAAQ,QAAQ,GAAM,CAAQ,EAE3D,OAAO,EAUT,SAAS,CAAU,CAAC,EAAS,EAAK,CAChC,GAAI,EAAE,EAAQ,eAAiB,EAAG,EAAQ,QAAU,IAAI,EACnD,YAAO,EAAQ,QAAQ,GAU9B,SAAS,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