@hamim_4444/pulsar 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var P_=Object.create;var{getPrototypeOf:F_,defineProperty:Y_,getOwnPropertyNames:T_}=Object;var j_=Object.prototype.hasOwnProperty;function N_(_){return this[_]}var O_,B_,h_=(_,$,X)=>{var K=_!=null&&typeof _==="object";if(K){var L=$?O_??=new WeakMap:B_??=new WeakMap,Z=L.get(_);if(Z)return Z}X=_!=null?P_(F_(_)):{};let W=$||!_||!_.__esModule?Y_(X,"default",{value:_,enumerable:!0}):X;for(let D of T_(_))if(!j_.call(W,D))Y_(W,D,{get:N_.bind(_,D),enumerable:!0});if(K)L.set(_,W);return W};var R_=(_,$)=>()=>($||_(($={exports:{}}).exports,$),$.exports);var A_=R_((f$,u)=>{var S_=Object.prototype.hasOwnProperty,E="~";function I(){}if(Object.create){if(I.prototype=Object.create(null),!new I().__proto__)E=!1}function g_(_,$,X){this.fn=_,this.context=$,this.once=X||!1}function M_(_,$,X,K,L){if(typeof X!=="function")throw TypeError("The listener must be a function");var Z=new g_(X,K||_,L),W=E?E+$:$;if(!_._events[W])_._events[W]=Z,_._eventsCount++;else if(!_._events[W].fn)_._events[W].push(Z);else _._events[W]=[_._events[W],Z];return _}function f(_,$){if(--_._eventsCount===0)_._events=new I;else delete _._events[$]}function z(){this._events=new I,this._eventsCount=0}z.prototype.eventNames=function(){var $=[],X,K;if(this._eventsCount===0)return $;for(K in X=this._events)if(S_.call(X,K))$.push(E?K.slice(1):K);if(Object.getOwnPropertySymbols)return $.concat(Object.getOwnPropertySymbols(X));return $};z.prototype.listeners=function($){var X=E?E+$:$,K=this._events[X];if(!K)return[];if(K.fn)return[K.fn];for(var L=0,Z=K.length,W=Array(Z);L<Z;L++)W[L]=K[L].fn;return W};z.prototype.listenerCount=function($){var X=E?E+$:$,K=this._events[X];if(!K)return 0;if(K.fn)return 1;return K.length};z.prototype.emit=function($,X,K,L,Z,W){var D=E?E+$:$;if(!this._events[D])return!1;var Y=this._events[D],A=arguments.length,V,M;if(Y.fn){if(Y.once)this.removeListener($,Y.fn,void 0,!0);switch(A){case 1:return Y.fn.call(Y.context),!0;case 2:return Y.fn.call(Y.context,X),!0;case 3:return Y.fn.call(Y.context,X,K),!0;case 4:return Y.fn.call(Y.context,X,K,L),!0;case 5:return Y.fn.call(Y.context,X,K,L,Z),!0;case 6:return Y.fn.call(Y.context,X,K,L,Z,W),!0}for(M=1,V=Array(A-1);M<A;M++)V[M-1]=arguments[M];Y.fn.apply(Y.context,V)}else{var J=Y.length,Q;for(M=0;M<J;M++){if(Y[M].once)this.removeListener($,Y[M].fn,void 0,!0);switch(A){case 1:Y[M].fn.call(Y[M].context);break;case 2:Y[M].fn.call(Y[M].context,X);break;case 3:Y[M].fn.call(Y[M].context,X,K);break;case 4:Y[M].fn.call(Y[M].context,X,K,L);break;default:if(!V)for(Q=1,V=Array(A-1);Q<A;Q++)V[Q-1]=arguments[Q];Y[M].fn.apply(Y[M].context,V)}}}return!0};z.prototype.on=function($,X,K){return M_(this,$,X,K,!1)};z.prototype.once=function($,X,K){return M_(this,$,X,K,!0)};z.prototype.removeListener=function($,X,K,L){var Z=E?E+$:$;if(!this._events[Z])return this;if(!X)return f(this,Z),this;var W=this._events[Z];if(W.fn){if(W.fn===X&&(!L||W.once)&&(!K||W.context===K))f(this,Z)}else{for(var D=0,Y=[],A=W.length;D<A;D++)if(W[D].fn!==X||L&&!W[D].once||K&&W[D].context!==K)Y.push(W[D]);if(Y.length)this._events[Z]=Y.length===1?Y[0]:Y;else f(this,Z)}return this};z.prototype.removeAllListeners=function($){var X;if($){if(X=E?E+$:$,this._events[X])f(this,X)}else this._events=new I,this._eventsCount=0;return this};z.prototype.off=z.prototype.removeListener;z.prototype.addListener=z.prototype.on;z.prefixed=E;z.EventEmitter=z;if(typeof u<"u")u.exports=z});var m;((K)=>{K.POSTGRES_NOTIFY="POSTGRES_NOTIFY";K.WEBHOOK="WEBHOOK";K.POLLING="POLLING"})(m||={});function y_(_){return{..._,consumer:{..._.consumer,queue:_.queue}}}class D_{MAX_ISOLATE_LIFESPAN_MS;constructor(_){this.MAX_ISOLATE_LIFESPAN_MS=_;this.set("isolate_id",crypto.randomUUID()),this.set("isolate_start_time",Date.now()),this.set("isolate_max_life_span_ms",this.MAX_ISOLATE_LIFESPAN_MS)}isSameIsolate(_){return _===this.get("isolate_id")}get id(){return this.get("isolate_id")??crypto.randomUUID()}get remainingTime(){let _=this.get("isolate_start_time"),$=this.get("isolate_max_life_span_ms")??this.MAX_ISOLATE_LIFESPAN_MS;if(typeof _!=="number")return $;let X=Date.now()-_;return Math.max(0,$-X)}get uptime(){let _=this.get("isolate_start_time");return typeof _==="number"?Date.now()-_:0}get maxTime(){return this.get("isolate_max_life_span_ms")??this.MAX_ISOLATE_LIFESPAN_MS}set(_,$){globalThis[_]=$}get(_){return globalThis[_]}}var h;((K)=>{K.V8_ISOLATE="v8-isolate";K.SERVERLESS_VM="serverless-vm";K.PERSISTENT="persistent"})(h||={});import C_ from"js-sha256";class v{target=new EventTarget;emit(_,$){this.target.dispatchEvent(new CustomEvent(_,{detail:$}))}on(_,$){let X=(K)=>$(K.detail);return this.target.addEventListener(_,X),()=>this.target.removeEventListener(_,X)}once(_,$){let X=(K)=>$(K.detail);this.target.addEventListener(_,X,{once:!0})}}class l{tracks=[];startTime;maxExecutionBudgetMs;safetyBufferMs;maxTrackHistory;enabled;cpuExecutionMicroseconds=0;constructor(_={}){this.startTime=performance.now(),this.maxExecutionBudgetMs=_.maxExecutionBudgetMs??25000,this.safetyBufferMs=_.safetyBufferMs??2000,this.maxTrackHistory=_.maxTrackHistory??100,this.enabled=_.enabled??!1}async trackExecutionTime({contextId:_},$){let X=performance.now();try{return await $()}finally{if(this.enabled==!0){let L=performance.now()-X;if(this.tracks.push({id:crypto.randomUUID(),duration:L,contextId:_}),this.tracks.length>this.maxTrackHistory)this.tracks.shift()}}}getElapsedTotalTime(){return performance.now()-this.startTime}getTimeRemaining(){let _=this.getElapsedTotalTime(),$=this.maxExecutionBudgetMs-_-this.safetyBufferMs;return Math.max(0,$)}getAverageTickDuration(_=5){if(this.tracks.length===0)return 0;let $=this.tracks.slice(-_);return $.reduce((K,L)=>K+L.duration,0)/$.length}isSafeToContinue(){if(!this.enabled)return!0;let _=this.getTimeRemaining();if(_<=0)return!1;let $=this.getAverageTickDuration(5);if($>0&&_<$)return!1;return!0}clear(_){this.tracks=this.tracks.filter(($)=>$.contextId!==_)}}class d{sql;constructor(_){this.sql=_.db.getNativeClient()}async triggerUrl({body:_={},delaySeconds:$=0,headers:X={"Content-Type":"application/json"},url:K}){return await this.sql`
1
+ var P_=Object.create;var{getPrototypeOf:F_,defineProperty:Y_,getOwnPropertyNames:T_}=Object;var j_=Object.prototype.hasOwnProperty;function N_(_){return this[_]}var O_,B_,h_=(_,$,X)=>{var K=_!=null&&typeof _==="object";if(K){var L=$?O_??=new WeakMap:B_??=new WeakMap,Z=L.get(_);if(Z)return Z}X=_!=null?P_(F_(_)):{};let W=$||!_||!_.__esModule?Y_(X,"default",{value:_,enumerable:!0}):X;for(let D of T_(_))if(!j_.call(W,D))Y_(W,D,{get:N_.bind(_,D),enumerable:!0});if(K)L.set(_,W);return W};var R_=(_,$)=>()=>($||_(($={exports:{}}).exports,$),$.exports);var A_=R_((x$,u)=>{var S_=Object.prototype.hasOwnProperty,E="~";function I(){}if(Object.create){if(I.prototype=Object.create(null),!new I().__proto__)E=!1}function m_(_,$,X){this.fn=_,this.context=$,this.once=X||!1}function M_(_,$,X,K,L){if(typeof X!=="function")throw TypeError("The listener must be a function");var Z=new m_(X,K||_,L),W=E?E+$:$;if(!_._events[W])_._events[W]=Z,_._eventsCount++;else if(!_._events[W].fn)_._events[W].push(Z);else _._events[W]=[_._events[W],Z];return _}function x(_,$){if(--_._eventsCount===0)_._events=new I;else delete _._events[$]}function z(){this._events=new I,this._eventsCount=0}z.prototype.eventNames=function(){var $=[],X,K;if(this._eventsCount===0)return $;for(K in X=this._events)if(S_.call(X,K))$.push(E?K.slice(1):K);if(Object.getOwnPropertySymbols)return $.concat(Object.getOwnPropertySymbols(X));return $};z.prototype.listeners=function($){var X=E?E+$:$,K=this._events[X];if(!K)return[];if(K.fn)return[K.fn];for(var L=0,Z=K.length,W=Array(Z);L<Z;L++)W[L]=K[L].fn;return W};z.prototype.listenerCount=function($){var X=E?E+$:$,K=this._events[X];if(!K)return 0;if(K.fn)return 1;return K.length};z.prototype.emit=function($,X,K,L,Z,W){var D=E?E+$:$;if(!this._events[D])return!1;var Y=this._events[D],A=arguments.length,V,M;if(Y.fn){if(Y.once)this.removeListener($,Y.fn,void 0,!0);switch(A){case 1:return Y.fn.call(Y.context),!0;case 2:return Y.fn.call(Y.context,X),!0;case 3:return Y.fn.call(Y.context,X,K),!0;case 4:return Y.fn.call(Y.context,X,K,L),!0;case 5:return Y.fn.call(Y.context,X,K,L,Z),!0;case 6:return Y.fn.call(Y.context,X,K,L,Z,W),!0}for(M=1,V=Array(A-1);M<A;M++)V[M-1]=arguments[M];Y.fn.apply(Y.context,V)}else{var J=Y.length,Q;for(M=0;M<J;M++){if(Y[M].once)this.removeListener($,Y[M].fn,void 0,!0);switch(A){case 1:Y[M].fn.call(Y[M].context);break;case 2:Y[M].fn.call(Y[M].context,X);break;case 3:Y[M].fn.call(Y[M].context,X,K);break;case 4:Y[M].fn.call(Y[M].context,X,K,L);break;default:if(!V)for(Q=1,V=Array(A-1);Q<A;Q++)V[Q-1]=arguments[Q];Y[M].fn.apply(Y[M].context,V)}}}return!0};z.prototype.on=function($,X,K){return M_(this,$,X,K,!1)};z.prototype.once=function($,X,K){return M_(this,$,X,K,!0)};z.prototype.removeListener=function($,X,K,L){var Z=E?E+$:$;if(!this._events[Z])return this;if(!X)return x(this,Z),this;var W=this._events[Z];if(W.fn){if(W.fn===X&&(!L||W.once)&&(!K||W.context===K))x(this,Z)}else{for(var D=0,Y=[],A=W.length;D<A;D++)if(W[D].fn!==X||L&&!W[D].once||K&&W[D].context!==K)Y.push(W[D]);if(Y.length)this._events[Z]=Y.length===1?Y[0]:Y;else x(this,Z)}return this};z.prototype.removeAllListeners=function($){var X;if($){if(X=E?E+$:$,this._events[X])x(this,X)}else this._events=new I,this._eventsCount=0;return this};z.prototype.off=z.prototype.removeListener;z.prototype.addListener=z.prototype.on;z.prefixed=E;z.EventEmitter=z;if(typeof u<"u")u.exports=z});var g;((K)=>{K.POSTGRES_NOTIFY="POSTGRES_NOTIFY";K.WEBHOOK="WEBHOOK";K.POLLING="POLLING"})(g||={});function y_(_){return{..._,consumer:{..._.consumer,queue:_.queue}}}class D_{MAX_ISOLATE_LIFESPAN_MS;constructor(_){this.MAX_ISOLATE_LIFESPAN_MS=_;this.set("isolate_id",crypto.randomUUID()),this.set("isolate_start_time",Date.now()),this.set("isolate_max_life_span_ms",this.MAX_ISOLATE_LIFESPAN_MS)}isSameIsolate(_){return _===this.get("isolate_id")}get id(){return this.get("isolate_id")??crypto.randomUUID()}get remainingTime(){let _=this.get("isolate_start_time"),$=this.get("isolate_max_life_span_ms")??this.MAX_ISOLATE_LIFESPAN_MS;if(typeof _!=="number")return $;let X=Date.now()-_;return Math.max(0,$-X)}get uptime(){let _=this.get("isolate_start_time");return typeof _==="number"?Date.now()-_:0}get maxTime(){return this.get("isolate_max_life_span_ms")??this.MAX_ISOLATE_LIFESPAN_MS}set(_,$){globalThis[_]=$}get(_){return globalThis[_]}}var h;((K)=>{K.V8_ISOLATE="v8-isolate";K.SERVERLESS_VM="serverless-vm";K.PERSISTENT="persistent"})(h||={});import C_ from"js-sha256";class v{target=new EventTarget;emit(_,$){this.target.dispatchEvent(new CustomEvent(_,{detail:$}))}on(_,$){let X=(K)=>$(K.detail);return this.target.addEventListener(_,X),()=>this.target.removeEventListener(_,X)}once(_,$){let X=(K)=>$(K.detail);this.target.addEventListener(_,X,{once:!0})}}class l{tracks=[];startTime;maxExecutionBudgetMs;safetyBufferMs;maxTrackHistory;enabled;cpuExecutionMicroseconds=0;constructor(_={}){this.startTime=performance.now(),this.maxExecutionBudgetMs=_.maxExecutionBudgetMs??25000,this.safetyBufferMs=_.safetyBufferMs??2000,this.maxTrackHistory=_.maxTrackHistory??100,this.enabled=_.enabled??!1}async trackExecutionTime({contextId:_},$){let X=performance.now();try{return await $()}finally{if(this.enabled==!0){let L=performance.now()-X;if(this.tracks.push({id:crypto.randomUUID(),duration:L,contextId:_}),this.tracks.length>this.maxTrackHistory)this.tracks.shift()}}}getElapsedTotalTime(){return performance.now()-this.startTime}getTimeRemaining(){let _=this.getElapsedTotalTime(),$=this.maxExecutionBudgetMs-_-this.safetyBufferMs;return Math.max(0,$)}getAverageTickDuration(_=5){if(this.tracks.length===0)return 0;let $=this.tracks.slice(-_);return $.reduce((K,L)=>K+L.duration,0)/$.length}isSafeToContinue(){if(!this.enabled)return!0;let _=this.getTimeRemaining();if(_<=0)return!1;let $=this.getAverageTickDuration(5);if($>0&&_<$)return!1;return!0}clear(_){this.tracks=this.tracks.filter(($)=>$.contextId!==_)}}class d{sql;constructor(_){this.sql=_.db.getNativeClient()}async triggerUrl({body:_={},delaySeconds:$=0,headers:X={"Content-Type":"application/json"},url:K}){return await this.sql`
2
2
  select public.schedule_http_request(
3
3
  ${K},
4
4
  ${$},
@@ -42,6 +42,6 @@ var P_=Object.create;var{getPrototypeOf:F_,defineProperty:Y_,getOwnPropertyNames
42
42
  ${$.toString()},
43
43
  ${X}
44
44
  ) AS set_vt
45
- `;return Boolean(K[0]?.set_vt)}async getSingleQueueMetrics(_){try{let $=await this.sql`SELECT * FROM pgmq.get_single_queue_metrics(${_})`,X=Array.from($);if(!X.length)return null;let K=X[0];return{queueName:K.queue_name,readyJobs:Number(K.ready_jobs??0),delayedJobs:Number(K.delayed_jobs??0),total:Number(K.total_jobs??0),nextVisibleAt:K.next_visible_at?new Date(K.next_visible_at).getTime():null}}catch($){return console.error(`Failed to fetch metrics for queue: ${_}`,$),null}}async getAllQueueMetrics(){let _=await this.sql`SELECT * FROM pgmq.get_queue_metrics()`;return Array.from(_).map(($)=>({queue_name:$.queue_name,ready_jobs:Number($.ready_jobs),delayed_jobs:Number($.delayed_jobs),total:Number($.total_jobs),next_visible_at:Number($.next_visible_at)}))}async closeQueue(){await this.sql.end()}}class c{maxGlobalJobsPerTick;maxGlobalConcurrency;constructor(_,$){this.maxGlobalJobsPerTick=_;this.maxGlobalConcurrency=$}getMaxGlobalConcurrency(){return this.maxGlobalConcurrency}getMaxGlobalJobsPerTick(){return this.maxGlobalJobsPerTick}}class H_{log(_,...$){console.log(_,...$)}warn(_,...$){console.warn(_,...$)}error(_,...$){console.error(_,...$)}debug(_,...$){console.debug(_,...$)}}class G{static provider=new H_;setProvider(_){G.provider=_}log(_,...$){G.provider.log(_,...$)}warn(_,...$){G.provider.warn(_,...$)}error(_,...$){G.provider.error(_,...$)}debug(_,...$){if(G.provider.debug)G.provider.debug(_,...$)}}var b_=new Set(["storage","runtime","onEvents","isolate","queue"]),w_=new Set(["queue","deadLetterQueue"]);class R{static instance;_config;initialSnapshot;logger;constructor(){this.logger=new G}static getInstance(){if(!R.instance)R.instance=new R;return R.instance}initialize(_){this._config={swarmConfig:{globalMaxJobsPerTick:1e5,maxGlobalConcurrency:1e4,spawnerAlgorithm:"ROUND_ROBIN",..._.swarmConfig},..._,engine:{..._.runtime=="persistent"?{poolingIntervalSec:5}:{},..._.runtime=="serverless-vm"||"v8-isolate"?{selfInvocationMethod:"auto_using_pgnet",selfInvocationIntervalSec:1,healthCheckIntervalSec:15,selfRestartIntervalSec:60}:{},tickConcurrency:"sequential",cycleTickLimit:1000,..._.engine},queues:_.queues.map(($)=>({stateTransitionPolicy:{enabled:!0,idleThresholdTicks:10,idleTimingProfile:"RELAXED"},...$}))},this.throwExpectionOnInvalidConfiguration(this._config),this.initialSnapshot=Object.freeze(JSON.parse(JSON.stringify(this._config)))}throwExpectionOnInvalidConfiguration(_){let $=_.queues;if($.length==0)throw this.logger.error('[Pulsar] Runtime configuration error: "queues" atleast 1 queue is required to operate.'),Error('[Pulsar] Runtime configuration error: "queues" atleast 1 queue is required to operate.');if(_.runtime==="v8-isolate"&&!_.isolate)throw this.logger.error(`[Pulsar] Runtime configuration error: "isolate" instance is required when running in "${"v8-isolate"}" mode.`),Error(`[Pulsar] Runtime configuration error: "isolate" instance is required when running in "${"v8-isolate"}" mode.`);let X=$.reduce((Z,W)=>{return Z[W.queue]=(Z[W.queue]||0)+1,Z},{}),K=Object.keys(X).filter((Z)=>X[Z]>1);if(K.length>0)throw this.logger.error("[ConfigurationStore]: Duplicate queues found -> ",K),Error("Duplicate queue names detected in the configuration.");let L=$.map((Z)=>Z.consumer);if(_.runtime!=="persistent"){let Z=L.find((W)=>W.type=="socket");if(Z)throw this.logger.error(`${JSON.stringify(Z)}`),Error("Consumers do not support non-persistent socket types. Please either remove the 'socket' type from the consumer or update the runtime to PERSISTENT.")}for(let Z of L)if(Z.type=="http")try{let W=new URL(Z.url);if(W.protocol!=="http:"&&W.protocol!=="https:")throw this.logger.error(`${Z.queue} - ${Z.url}`),Error(`Invalid protocol '${W.protocol}' for consumer URL. Only HTTP and HTTPS are supported.`)}catch(W){this.logger.error(`${Z.queue} - ${Z.url}`);let D=W instanceof Error?W.message:"An unknown error occurred while parsing the consumer URL.";throw Error(`Failed to validate consumer URL: ${D}`)}else if(Z.type=="callback"){if(!Z.handler)throw Error("Consumer handler is required. Please provide a valid handler function.")}}ensureInitialized(){if(!this._config)throw Error("[ConfigurationStore]: Engine configuration store is not initialized. Call initialize() first.");if(!this.initialSnapshot)throw Error("[ConfigurationStore]: Engine initial snapshot is not initialized")}get raw(){return this.ensureInitialized(),this._config}get(_){this.ensureInitialized();let $=_.split("."),X=this._config;for(let K of $){if(X===void 0||X===null)return;X=X[K]}return X}getInitialSnapshot(){return this.ensureInitialized(),Object.freeze({...this.initialSnapshot})}set(_,$){this.ensureInitialized();let X=_.split("."),K=X[0];if(b_.has(K))throw Error(`[ConfigurationStore]: Modifying path '${_}' via set() is forbidden.`);let L=this._config;for(let Z=0;Z<X.length-1;Z++){let W=X[Z];if(!(W in L)||typeof L[W]!=="object")L[W]={};L=L[W]}L[X[X.length-1]]=$}modifyQueue(_,$,X){if(this.ensureInitialized(),w_.has($))throw Error(`[ConfigurationStore]: Property '${String($)}' on queue '${_}' cannot be modified at runtime.`);let K=this._config.queues.findIndex((L)=>L.queue==_);if(!this._config.queues[K])throw Error(`[ConfigurationStore]: Modifying queue '${_}' not found.`);this._config.queues[K][$]=X}async reconcileConfiguration(_){let $=this.getInitialSnapshot(),X=$.runtime==="serverless-vm"||$.runtime==="v8-isolate"?$.engine.selfURL:"NOT_REQUIRED",K={queues:$.queues.map((Z)=>({queue:Z.queue,pooler:Z.pooler})),runtime:$.runtime,event_trigger_strategy:$.runtime=="persistent"?$.eventTriggerStrategy:"WEBHOOK",self_url:X},L=await _.verifyAndSyncConfiguration("PULSAR_STANDALONE",$.instanceId,X,K);if(!L.isChanged&&!L.isNew)return this.logger.log("[Configuration] status : [VALID]."),"[Configuration] status : [VALID].";else return this.logger.log("[Configuration] status : [INVALID & Reconciled]."),"[Configuration] status : [INVALID & Reconciled]."}}var H=R.getInstance();var T={REALTIME:{activePollMs:1000,backoffPollMs:1000,idlePollMs:1000,maxTimerMs:5000},STANDARD:{activePollMs:100,backoffPollMs:500,idlePollMs:1e4,maxTimerMs:60000},BALANCED:{activePollMs:1e4,backoffPollMs:500,idlePollMs:1e4,maxTimerMs:60000},RELAXED:{activePollMs:1000,backoffPollMs:20000,idlePollMs:30000,maxTimerMs:60000},ULTRA_EFFICIENT:{activePollMs:5000,backoffPollMs:1e5,idlePollMs:120000,maxTimerMs:240000}};var I_=2147483647;class q{timers=new Map;profiles=new Map;constructor(){}registerQueueProfile(_,$){if(typeof $==="string"){let X=$!=="CUSTOM"?T[$]:void 0;this.profiles.set(_,X??T.STANDARD)}else this.profiles.set(_,$)}getProfile(_){let X=H.get("queues")?.find((K)=>K.queue===_)?.profile;if(X){if(typeof X==="string")return X!=="CUSTOM"?T[X]:T.STANDARD;if(typeof X==="object")return X}return this.profiles.get(_)??T.STANDARD}cancel(_){let $=this.timers.get(_);if($)clearTimeout($);this.timers.delete(_)}scheduleNext(_){let{metrics:$,onNext:X,onUpcomingDelayedNext:K,onFutureSchedule:L}=_,{queue:Z,readyJobs:W,delayedJobs:D,availableSlots:Y,nextVisibleAt:A}=$;this.cancel(Z);let V=this.getProfile(Z);if(W>0&&Y>0){this.setTimer(Z,X,V.activePollMs);return}if(W>0&&Y===0){this.setTimer(Z,X,V.backoffPollMs);return}if(D>0&&A){let M=Math.max(0,A-Date.now());if(M<=V.maxTimerMs){if(K)K(M);this.setTimer(Z,X,M);return}if(L)L(A).catch((J)=>console.error(`Scheduler error setting long delay for ${Z}:`,J));return}if(V.idlePollMs)this.setTimer(Z,X,V.idlePollMs)}setTimer(_,$,X){let K=Math.min(Math.max(0,X),I_),L=()=>{this.timers.delete(_),$()};if(K===0){let W=setTimeout(L);this.timers.set(_,W);return}let Z=setTimeout(L,K);this.timers.set(_,Z)}}class i{logger;transitionItems=new Set;constructor(_){this.logger=_}transitionToIdleMode({queue:_,stateTransitionPolicy:$}){if(this.transitionItems.has(_))return;if(this.transitionItems.add(_),this.logger.log(`[ENGINE_STATE] Transitioning engine execution profile to IDLE. Queue config: (${_})`),$?.enabled){let X=$.idleTimingProfile;if(X){let K=typeof X==="object"?{activePollMs:X.activePollMs,backoffPollMs:X.backoffPollMs,idlePollMs:X.idlePollMs}:T[X];H.modifyQueue(_,"profile",K)}}}transitionToActiveMode({queue:_,profile:$,stateTransitionPolicy:X}){if(this.transitionItems.delete(_),X?.enabled)H.modifyQueue(_,"profile",$);this.logger.log(`[ENGINE_STATE] Transitioning engine execution profile to ACTIVE. Queue config: (${_})`)}}class s{storage;queue;dispatcher;executionProfileSwitcher;unifiedTransportManager;swarmManager;PROCESS_ID;globalSequence=0;consecutiveEmptyTicks=0;logger;events;constructor({dispatcher:_,queue:$,storage:X,swarmManager:K,unifiedTransportManager:L,events:Z}){this.storage=X,this.dispatcher=_,this.queue=$,this.swarmManager=K,this.unifiedTransportManager=L,this.logger=new G,this.executionProfileSwitcher=new i(this.logger),this.PROCESS_ID=crypto.randomUUID().slice(0,12),this.globalSequence=0,this.events=Z}async run(_,$){let{concurrency:X,queue:K}=_,L=this.swarmManager.getMaxGlobalConcurrency(),{batches:Z,window:W}=await this.getCandidatesBatch({queueConfig:_,maxGlobalSlotsAllowed:$}),D=_.stateTransitionPolicy?.enabled==!0;if(!Z||Z.length===0){if(D){if(this.consecutiveEmptyTicks++,this.consecutiveEmptyTicks>=(_.stateTransitionPolicy?.idleThresholdTicks??10))this.executionProfileSwitcher.transitionToIdleMode(_)}this.logger.warn(`[Tick] : [${K}] - Empty Tick Executred)`);return}if(D&&this.consecutiveEmptyTicks>0)this.consecutiveEmptyTicks=0,this.executionProfileSwitcher.transitionToActiveMode(_);let Y=await this.storage.repository.registerWorker(K,Z,X,L),A=new Set(Y),V=Z.filter((M)=>!A.has(M.workerId));if(V.length>0){let M=V.reduce((J,Q)=>J+Q.batch.length,0);await this.storage.repository.refundGlobalJobBudget(M,W)}if(Y.length===0)return;this.logger.log(`[Tick] : [${K}] - Tick Executred. Total Jobs (${Z.reduce((M,J)=>M+J.batch.length,0)})`),await this.spwanWorkers({candidateBatches:Z,grantedWorkerIds:Y,queueConfig:_})}async spwanWorkers({grantedWorkerIds:_,candidateBatches:$,queueConfig:{queue:X}}){if(!_?.length)return;let K=new Set(_),L=$.filter((Z)=>K.has(Z.workerId));await Promise.allSettled(L.map(({batch:Z,workerId:W})=>{return this.unifiedTransportManager.dispatchToNetwork(X,{batch:Z,worker_id:W})}))}async getCandidatesBatch({queueConfig:_,maxGlobalSlotsAllowed:$}){let{concurrency:X,maxJobsPerTick:K,queue:L,sleep:Z,n:W}=_,D=await this.storage.repository.getActiveWorkersCount(L),Y=Math.max(0,X-D);if(Y===0)return{batches:[],window:""};let A=Math.min(Y,$);if(A===0)return{batches:[],window:""};let V=A*W,M=K!==void 0&&K>0?K:1/0,J=Math.min(V,M);if(J<=0)return{batches:[],window:""};let Q=this.swarmManager.getMaxGlobalJobsPerTick(),{granted:P,window:F}=await this.storage.repository.claimGlobalJobBudget(J,Q);if(P<=0)return{batches:[],window:F};let N=await this.queue.read(L,Z??1,P),y=N.length;if(y===0)return await this.storage.repository.refundGlobalJobBudget(P,F),{batches:[],window:F};if(y<P){let B=P-N.length;await this.storage.repository.refundGlobalJobBudget(B,F)}let b=Math.ceil(y/W),O=Array(b),C=Date.now(),p=0;for(let B=0;B<y;B+=W)O[p++]={workerId:`w_${this.PROCESS_ID}_${C}_${this.globalSequence++}`,batch:N.slice(B,B+W)};return{batches:O,window:F}}}class o{clock;tickService;scheduler;storage;events;runtimeStrategy;tickState=new Map;activeTicks=new Set;lastHealthCheckAt=0;logger;constructor({scheduler:_,storage:$,tickService:X,clock:K,events:L,runtimeStrategy:Z}){this.logger=new G,this.clock=K,this.tickService=X,this.scheduler=_,this.storage=$,this.events=L,this.runtimeStrategy=Z,this.initializeState()}initializeState(){this.tickState.clear(),this.activeTicks.clear()}async runTick(_){await this.runtimeStrategy.executeTick(_,async()=>{let{queue:$}=_;if(this.initializeTickState(_),this.activeTicks.has($)||this.tickState.get($)?.stopped)return;this.activeTicks.add($),this.scheduler.cancel($);try{let X=1/0,K=H.get("swarmConfig")?.maxGlobalConcurrency;if(K!==void 0){let L=await this.storage.repository.getGlobalActiveWorkersCount();X=Math.max(0,K-L)}if(X>0&&!this.tickState.get($)?.stopped)await this.tickService.run(_,X)}catch(X){this.logger.error(`Orchestrator error on ${$}:`,X)}finally{this.activeTicks.delete($),this.updateTickCounter($)}if(this.tickState.get($)?.stopped==!0)return;await this.runtimeStrategy.scheduleTick(_,()=>this.runTick(_))})}endTick(_){let $=this.tickState.get(_);if($){if($.stopped==!0)return;if(this.tickState.set(_,{...$,stopped:!0}),this.scheduler.cancel(_),this.clock.clear(_),H.raw.queues.every((K)=>{let L=this.tickState.get(K.queue);return L?L.stopped:!0}))this.events.emit("tick:cycle-completed",{queue:_,cycles:this.tickState.get(_)?.count??1})}}initializeTickState(_){if(!this.tickState.get(_.queue))this.tickState.set(_.queue,{count:0,max:_.cycleTickLimit??10,registred:!0,stopped:!1})}updateTickCounter(_){let $=this.tickState.get(_)??{count:0,stopped:!1,max:10,registred:!1},X=$.count+1,K=$.max,L=X>=K;if(($.stopped||L)&&!$.stopped)this.tickState.set(_,{count:X,stopped:$.stopped,max:K,registred:$.registred}),this.endTick(_);else this.tickState.set(_,{count:X,stopped:$.stopped,max:K,registred:$.registred});this.triggerPeriodicHealthCheck()}triggerPeriodicHealthCheck(){let _=Date.now(),$=this.runtimeStrategy.shouldShutdownOnCycleComplete,X=(H.get("engine.healthCheckIntervalSec")??15)*1000;if(_-this.lastHealthCheckAt>=X&&!$)this.lastHealthCheckAt=_,this.events.emit("engine:health-check-requested",{timestamp:_})}}class j{queueService;clock;queues;storage;isolate;events;scheduler;logger;constructor(_){this.queueService=_.queueService,this.clock=_.clock,this.queues=_.queues,this.isolate=_.isolate,this.storage=_.storage,this.events=_.events,this.scheduler=_.scheduler,this.logger=new G}async executeQueuesTick(_){let $=H.get("engine.tickConcurrency");if(this.logger.log(`[Tick Controller] : Execution tick mode has been selected with concurrency ${$}`),$=="sequential"){for(let X of this.queues)if(X.pooler=="interval-driven-pooler")await _(X)}else{let X=await Promise.allSettled(this.queues.filter((K)=>K.pooler==="interval-driven-pooler").map((K)=>_(K)));for(let K of X)if(K.status==="rejected")this.logger.error("[Tick] : Error >>",K.reason)}}async triggerSelfInvocation(_){let{queue:$,pooler:X,delaySec:K,continuationOwnerId:L,isIdpLock:Z,isEdpLock:W,targetEdpQueue:D}=_,Y=H.get("engine.selfURL"),V=H.raw.engine.selfInvocationMethod,M={idpInvoked:!1,continuationScheduledForCurrentLock:!1};if(X==="interval-driven-pooler"){if(M.idpInvoked=!0,Z)M.continuationScheduledForCurrentLock=!0;this.logger.log(`(IDP) : Invoking Self in ${K} seconds...`)}else if(X==="event-driven-pooler"){if(W&&$===D)M.continuationScheduledForCurrentLock=!0;this.logger.log(`(EDP) : Invoking Self in ${K} seconds...`)}let J={"content-type":"application/json","x-last-execution-id":L,"x-last-execution-at":new Date().toISOString(),"x-execution-owner":"engine","x-restart":"false","x-pooler":X,"x-target-queue":$};if(V=="auto_using_pgnet")await this.queueService.triggerUrl({url:Y,headers:J,delaySeconds:K});else if(typeof V==="object"&&V!==null&&V.method==="manual")await V.handler(Y);return M}}class r{storage;logger;pgNotifyChannel="channel_pulsar_event_driven_queue";runtimeExecutionId=crypto.randomUUID();constructor(_,$){this.storage=_;this.logger=$}async registerPgNotifyHandler(_){await this.storage.ops.subscribeToDatabaseEvents(this.pgNotifyChannel,async($)=>{this.logger.log(`[Persistent Runtime] : Recived PgNotification Event - ${new Date().toISOString()}`);let X=H.get("queues").find((L)=>L.queue===$.queue_name);if(!X){this.logger.error(`[Persistent Runtime] : Received notification for unregistered or unmanaged queue: '${$.queue_name}' on channel: ${this.pgNotifyChannel}`);return}if(await this.handleTriggerValidity(X.queue,$.fencing_token))await _.runTick(X)},()=>{this.logger.log(`[Persistent Runtime] : Successfully established PostgreSQL notification listener on channel : ${this.pgNotifyChannel}`)})}async registerPollingHandler(_){setInterval(async()=>{let $=await this.storage.ops.getPollingQueueEntries("q_3");for(let X of $){let K=X.payload.queue_name,L=X.payload.fencing_token,Z=await this.handleTriggerValidity(K,L);if(Z)await _.runTick(Z),await this.storage.ops.deletePollingQueueEntry(X.id)}},H.get("engine.poolingIntervalMS"))}async handleTriggerValidity(_,$){let X=H.get("queues").find((D)=>D.queue===_);if(!X)return this.logger.error(`[Persistent Runtime] : pool entry for unregistered or unmanaged queue: '${_}'`),null;if(!await this.storage.ops.checkFencingTokenValidity(_,$)){let D=`[EventDrivenPoller]-[ExecutionTrigger]-[${_}] : Engine execution rejected : Invalid fencing token.`;return this.logger.error(D),null}let L=`lock:edp:${_}`,Z=120000;if(await this.storage.repository.acquireQueueLock(L,this.runtimeExecutionId,Z))await this.storage.repository.clearDispatchPending(L);else return this.logger.log(`[Persistent Runtime] : Engine busy for queue ${_}, skipping trigger.`),null;return X}}class w{minBootRequirementSec;scheduler;events;clock;logger;constructor(_,$,X,K,L){this.minBootRequirementSec=_;this.scheduler=$;this.events=X;this.clock=K;this.logger=L}timers=new Map;watchdogTimer=null;isShutdownTriggered=!1;evaluateUpcomingDelayedNext(_,$){let X=H.raw.isolate;if(!X)throw Error("Isolate is not configured for V8_Isolate_Runtime!");let K=H.get("engine.selfInvocationIntervalSec")??1,L=this.minBootRequirementSec,Z=(K+L)*1000;if(X.remainingTime-_<Z){this.logger.log(`[Isolate Runtime] Sleep duration of ${_}ms exceeds safe isolate budget. Canceling timer sleep and initiating shutdown.`),this.scheduler.cancel($),this.triggerGracefulShutdown($);return}this.startDelayedSleepWatchdog($,Z)}startDelayedSleepWatchdog(_,$){this.stopRuntimeWatchdog(),this.isShutdownTriggered=!1,this.watchdogTimer=setInterval(()=>{let X=H.raw.isolate;if(!X||this.isShutdownTriggered)return;if(X.remainingTime<=$)this.logger.log(`[Isolate Watchdog] Remaining isolate budget (${X.remainingTime}ms) expired during delayed sleep. Canceling wakeup and executing graceful shutdown.`),this.scheduler.cancel(_),this.triggerGracefulShutdown(_)},1000)}triggerGracefulShutdown(_){if(this.isShutdownTriggered)return;this.isShutdownTriggered=!0,this.stopRuntimeWatchdog(),this.events.emit("tick:time-exceeded",{queue:_,elapsedMs:this.clock.getElapsedTotalTime()}),this.events.emit("tick:cycle-completed",{queue:_,cycles:1})}stopRuntimeWatchdog(){if(this.watchdogTimer)clearInterval(this.watchdogTimer),this.watchdogTimer=null}clearTimer(_){let $=this.timers.get(_);if($)clearTimeout($);this.timers.delete(_)}forceExecuteTickLater(_,$){let K=`Extended time limit reached ${$}ms elapsed, overriding standard caps !`,L=()=>this.events.emit("tick:force-run",{queue:_,reason:K}),Z=$-Date.now();if(Z>2147483647)this.timers.set(_.queue,setTimeout(()=>{this.forceExecuteTickLater(_,$)},2147483647));this.timers.set(_.queue,setTimeout(()=>{L()},Math.max(0,Z)))}}class U{static store=new Map;kv={set:(_,$)=>{U.store.set(_,$)},get:(_)=>{return U.store.get(_)},has:(_)=>{return U.store.has(_)},delete:(_)=>{return U.store.delete(_)},clear:()=>{U.store.clear()}};lists={add:(_,$)=>{if(!U.store.has(_))U.store.set(_,new Set);let X=U.store.get(_);if(X instanceof Set)X.add($)},remove:(_,$)=>{let X=U.store.get(_);if(X instanceof Set)return X.delete($);return!1},get:(_)=>{let $=U.store.get(_);return $ instanceof Set?$:void 0},has:(_,$)=>{let X=U.store.get(_);if(X instanceof Set)return X.has($);return!1}}}var k=()=>new U;class n extends j{type="PERSISTENT";shouldShutdownOnCycleComplete=!1;minBootRequirementSec=1;deferredTickEvaluator;runtimeEventBridge;rs;constructor(_){super(_);this.deferredTickEvaluator=new w(this.minBootRequirementSec,this.scheduler,this.events,this.clock,this.logger),this.runtimeEventBridge=new r(this.storage,this.logger),this.rs=k()}async onStart(_){this.logger.log("Initialized Persistent Runtime.");let $=this.runtimeEventBridge;if(H.raw.runtime=="persistent")switch(H.raw.eventTriggerStrategy){case"POSTGRES_NOTIFY":await $.registerPgNotifyHandler(_);break;case"POLLING":await $.registerPollingHandler(_);break;case"WEBHOOK":this.logger.log("[Persistent Runtime] : Event Driven Queue triggers will heppen via webhook endpoint.");break}await this.executeQueuesTick(_.runTick)}async executeTick(_,$){this.deferredTickEvaluator.clearTimer(_.queue);let{isValid:X,reason:K}=this.validateTickRun(_);if(!X){this.logger.warn(`[Tick] : [${_.queue}] - Rejected, invalid tick run: ${K}. Please Reconnect Worker ASAP.`);return}await $()}validateTickRun({queue:_}){let $=H.raw.queues.find((X)=>X.queue===_);if(!$)return{isValid:!1,reason:`Queue configuration could not be found for '${_}'.`};if($.consumer.type==="socket"){let X=this.rs.lists.get(_);if(!X)return this.events.emit("tick:end",{queue:_,reason:"Socket consumer connection list does not exist"}),{isValid:!1,reason:`Socket consumer connection list does not exist for queue '${_}'.`};let K=Array.from(X.values());if(K.length==0)return this.events.emit("tick:end",{queue:_,reason:`Socket consumer has (${K.length}) active connections.`}),{isValid:!1,reason:`Socket consumer for queue '${_}' has (${K.length}) active connections.`}}return{isValid:!0,reason:"Tick run validation passed successfully."}}async scheduleTick(_,$){let{queue:X,concurrency:K,pooler:L}=_,Z=await this.queueService.getSingleQueueMetrics(X);if(!Z)return;if(Z?.total==0){if(L=="event-driven-pooler"){this.logger.log(`[Tick] : [${X}] - Tick Process Ended. Cycle Limit Reached`),this.events.emit("tick:cycle-completed",{queue:X,cycles:1});return}}let W=await this.storage.repository.getActiveWorkersCount(X),D=Math.max(0,K-W);this.deferredTickEvaluator.clearTimer(X),this.scheduler.scheduleNext({metrics:{queue:X,availableSlots:D,...Z},onNext:$,onUpcomingDelayedNext:(Y)=>{this.logger.log(`[Scheduler] : Next tick scheduled in ${(Y/1000).toFixed(2)}s`)},onFutureSchedule:async(Y)=>{let A=Y-Date.now();this.logger.log(`[Scheduler] : Deffered tick execution in ${(Math.max(0,A)/1000).toFixed(2)}s`),this.deferredTickEvaluator.forceExecuteTickLater(_,Y)}})}async handleCycleCompletion(){return!1}async handleRestart(){this.logger.log("[Persistent Runtime] : Restart triggered. Handled by process manager (PM2/systemd).")}}class a extends j{type="SERVERLESS_VM";shouldShutdownOnCycleComplete=!0;minBootRequirementSec=1;constructor(_){super(_);this.logger.log("Initialized Serverless VM Runtime.")}async onStart(_){await this.executeQueuesTick(_.runTick)}async executeTick(_,$){await $()}async scheduleTick(_,$){await $()}async handleCycleCompletion(_){let $=!1,X=!1,K=_.currentExecutionId,L=_.lockKey,Z=L?.startsWith("pulsar:lock:edp:"),W=L==="pulsar:lock:idp",D=Z?L?.replace("pulsar:lock:edp:",""):null;for(let{queue:Y,pooler:A}of _.getActiveQueues())try{if(A=="interval-driven-pooler"&&$)continue;if(Z&&Y!==D)continue;let V=await this.queueService.getSingleQueueMetrics(Y);if(!V||V.total===0){console.log(`[Pulsar] Failed to fetch metrics for ${Y}. Halting queue.`),_.endTick(Y);continue}let M=V.total;if(!await this.storage.repository.evaluateDeadRun(Y,A,M,K,15000)){console.log(`[Pulsar] Should not invoke for ${Y}. Skipping.`);continue}let Q=H.get("engine.selfInvocationIntervalSec")??1,P=await this.triggerSelfInvocation({queue:Y,pooler:A,delaySec:Q,continuationOwnerId:K,isIdpLock:W,isEdpLock:Z,targetEdpQueue:D});if(P.idpInvoked)$=!0;if(P.continuationScheduledForCurrentLock)X=!0}catch(V){console.log(`[deadRun] Error checking queue ${Y}:`,V)}return X}async handleRestart(_){}}class t extends j{deps;type="V8_ISOLATE";shouldShutdownOnCycleComplete=!0;minBootRequirementSec=5;deferredTickEvaluator;constructor(_){super(_);this.deps=_;this.logger.log("[EngineRuntime] : Initialized V8 Isolate Runtime."),this.deferredTickEvaluator=new w(this.minBootRequirementSec,this.scheduler,this.events,this.clock,this.logger)}async onStart(_){await this.executeQueuesTick(_.runTick)}async executeTick(_,$){let{queue:X}=_;this.deferredTickEvaluator.stopRuntimeWatchdog();let K=this.deps.clock.isSafeToContinue(),L=this.deps.events;if(!K){this.logger.log("[EngineRuntime] : Ending All Ticks due to time limit."),L.emit("tick:time-exceeded",{queue:X,elapsedMs:this.deps.clock.getElapsedTotalTime()}),L.emit("tick:cycle-completed",{queue:X,cycles:1});return}await this.deps.clock.trackExecutionTime({contextId:X},$)}async scheduleTick(_,$){let{queue:X,concurrency:K,pooler:L}=_,Z=await this.queueService.getSingleQueueMetrics(X);if(!Z)return;if(Z?.total==0){if(L=="event-driven-pooler"){this.logger.log(`[Tick] : [${X}] - Tick Process Ended. Cycle Limit Reached`),this.events.emit("tick:cycle-completed",{queue:X,cycles:1});return}}let W=await this.storage.repository.getActiveWorkersCount(X),D=Math.max(0,K-W),Y=async()=>{this.deferredTickEvaluator.stopRuntimeWatchdog(),await $()};this.scheduler.scheduleNext({metrics:{queue:X,availableSlots:D,...Z},onNext:Y,onUpcomingDelayedNext:(A)=>{return this.logger.log(`[Scheduler] : Next tick scheduled in ${(A/1000).toFixed(2)}s`),this.deferredTickEvaluator.evaluateUpcomingDelayedNext(A,X)},onFutureSchedule:async(A)=>{this.logger.log("[Scheduler] : scheduled tick execution request",A)}});return}async handleCycleCompletion(_){let $=!1,X=!1,K=_.currentExecutionId,L=_.lockKey,Z=L?.startsWith("pulsar:lock:edp:"),W=L==="pulsar:lock:idp",D=Z?L?.replace("pulsar:lock:edp:",""):null;for(let{queue:Y,pooler:A}of _.getActiveQueues())try{if(A=="interval-driven-pooler"&&$)continue;if(Z&&Y!==D)continue;let V=await this.queueService.getSingleQueueMetrics(Y);if(!V)continue;if(V.total===0)if(this.logger.log(`[Engine] : Queue ${Y} is empty (total: 0) using ${A} pooler. Halting tick.`),A=="event-driven-pooler"){_.endTick(Y);continue}else _.endTick(Y);let M=V.total;if(!await this.storage.repository.evaluateDeadRun(Y,A,M,K,15000)){this.logger.log(`[Engine] : Should not invoke for ${Y}. Skipping.`);continue}let Q=H.get("engine.selfInvocationIntervalSec")??1,P=H.get("runtime")=="v8-isolate",F=Q;if(P&&H.raw.isolate){let b=H.raw.isolate.remainingTime/1000,O=this.minBootRequirementSec,C=Q+O;if(b<C)return this.logger.log(`[EngineRuntime] : Isolate remaining time (${b.toFixed(3)}s) is insufficient for self-invocation (${Q}s delay + ${O}s min work). Triggering restart.`),await this.handleRestart(_),!0;let p=Math.max(1,b-O);F=Math.min(Q,p)}let N=await this.triggerSelfInvocation({queue:Y,pooler:A,delaySec:F,continuationOwnerId:K,isIdpLock:W,isEdpLock:Z,targetEdpQueue:D});if(N.idpInvoked)$=!0;if(N.continuationScheduledForCurrentLock)X=!0}catch(V){this.logger.log(`[deadRun] : Error checking queue ${Y}:`,V)}return X}async handleRestart(_){let $=!1,X=_.currentExecutionId,K=H.get("engine.selfRestartIntervalSec"),L=_.getActiveQueues();for(let{queue:Z,pooler:W}of L){if(W=="interval-driven-pooler"&&$)continue;let D={"content-type":"application/json","x-last-execution-id":X,"x-last-execution-at":new Date().toISOString(),"x-execution-owner":"engine","x-restart":"true","x-pooler":W,"x-target-queue":Z};if(this.logger.log(`(${W}) : invoking engine via restartTick (${K})`),W=="interval-driven-pooler")$=!0;let Y=_.lockKey;await this.storage.repository.releaseQueueLock(Y,_.isolateId),await this.storage.ops.addRestart(L),await this.queueService.triggerUrl({url:H.get("engine.selfURL"),headers:D,delaySeconds:K}),await this.storage.ops.updateRestartOwnership(Z,"handled_by_engine")}}}import{serve as m_}from"crossws/server";var V_=h_(A_(),1);var G_=V_.default;class e extends G_{config;serverInstance=null;logger;onFetch;constructor(_){super();this.config=_;this.logger=new G}async start(){let _=this;this.logger.log(`[Network] : Initializing server on port ${this.config.port} in [${this.config.mode}] mode`);let $=this.config.mode==="hybrid"||this.config.mode==="websocket";if($)this.logger.log(`[Network] : WebSocket server handlers attached on port ${this.config.port}`);this.serverInstance=m_({port:this.config.port,...$?{websocket:{open(X){_.emit("open",X)},message(X,K){_.emit("message",X,K)},close(X,K){_.emit("close",X,K)}}}:{},fetch(X){if(_.onFetch)return _.onFetch(X);return _.logger.warn(`[Network] : Unhandled route accessed: ${X.method} ${X.url}`),new Response(null,{status:404})},gracefulShutdown:!1,maxRequestBodySize:void 0}),await this.serverInstance.ready(),this.logger.log(`[Server] Successfully started and listening on port ${this.config.port}`)}async close(){try{await this.serverInstance?.close(!0)}catch(_){this.logger.error("[Network] : Error closing server:",_)}}}function __(_){return!!_&&typeof _.clone==="function"&&typeof _.text==="function"&&typeof _.url==="string"&&typeof _.headers?.get==="function"}function $_(_){let $={};if(!_)return $;if(typeof _.forEach==="function"&&typeof _.get==="function")return _.forEach((X,K)=>{$[String(K).toLowerCase()]=String(X)}),$;for(let[X,K]of Object.entries(_)){if(K==null)continue;$[X.toLowerCase()]=Array.isArray(K)?K.join(", "):String(K)}return $}function S(_){let $={};if(!_)return $;let X=(K,L)=>{if(L==null)return;$[K]=K in $?`${$[K]},${L}`:String(L)};if(typeof _.forEach==="function")_.forEach((K,L)=>X(L,K));else for(let[K,L]of Object.entries(_))X(K,Array.isArray(L)?L.join(","):L);return $}function Q_(_){let $=_.indexOf("?");return $===-1?{}:S(new URLSearchParams(_.slice($+1)))}function k_(_){let $=atob(_),X=Uint8Array.from($,(K)=>K.charCodeAt(0));return new TextDecoder().decode(X)}function E_(_){return new TextDecoder().decode(_)}async function f_(_){let $=new TextEncoder,X=[];for await(let W of _)X.push(typeof W==="string"?$.encode(W):W);let K=X.reduce((W,D)=>W+D.length,0),L=new Uint8Array(K),Z=0;for(let W of X)L.set(W,Z),Z+=W.length;return new TextDecoder().decode(L)}function x_(_,$){let X=$.toLowerCase();if(X.includes("json"))try{return JSON.parse(_)}catch{return _}if(X.includes("application/x-www-form-urlencoded"))return S(new URLSearchParams(_));if(!X){let K=_.trimStart();if(K.startsWith("{")||K.startsWith("["))try{return JSON.parse(_)}catch{}}return _}function X_(_,$,X=!1){if(_==null||_==="")return{body:null,rawBody:null};let K;if(typeof _==="string")K=X?k_(_):_;else if(_ instanceof ArrayBuffer||ArrayBuffer.isView(_))K=E_(_);else return{body:_,rawBody:null};return{body:x_(K,$),rawBody:K}}var z_=new Set(["GET","HEAD"]);async function J_(_){if(!_)throw Error("[YourSDK] No request object/event provided.");let $=_;if(!__($)&&__($.request))$=$.request;else if($.req&&$.req.headers&&!$.headers)$=$.req;if(__($)){let X=$.clone(),K=String(X.method||"GET").toUpperCase(),L=$_(X.headers),Z=null;if(!z_.has(K))try{Z=await X.text()}catch{Z=null}let{body:W,rawBody:D}=X_(Z,L["content-type"]||"");return{method:K,url:X.url,headers:L,query:S(new URL(X.url).searchParams),body:W,rawBody:D}}if($.requestContext||$.httpMethod||$.rawPath){let X=$_($.headers),K=String($.requestContext?.http?.method||$.httpMethod||"POST").toUpperCase(),L=$.rawPath||$.path||"/",Z=$.rawQueryString?`?${$.rawQueryString}`:"",W=X["x-forwarded-proto"]||"https",D=X.host||"lambda.local",Y=$.rawUrl||`${W}://${D}${L}${Z}`,A=$.queryStringParameters&&Object.keys($.queryStringParameters).length?S($.queryStringParameters):$.rawQueryString?Q_(`?${$.rawQueryString}`):{},{body:V,rawBody:M}=X_($.body,X["content-type"]||"",!!$.isBase64Encoded);return{method:K,url:Y,headers:X,query:A,body:V,rawBody:M}}if($.headers&&$.method){let X=$_($.headers),K=String($.method).toUpperCase(),L=$.originalUrl||$.url||"/",Z=L;if(!/^https?:\/\//i.test(L)){let V=X["x-forwarded-proto"]?.split(",")[0]?.trim()||$.protocol||($.socket?.encrypted?"https":"http"),M=X["x-forwarded-host"]||X.host||"localhost";Z=`${V}://${M}${L}`}let D=$.query&&Object.keys($.query).length>0?S($.query):Q_(Z),Y=$.body!==void 0?$.body:$.rawBody;if(Y===void 0&&!z_.has(K)&&typeof $[Symbol.asyncIterator]==="function")Y=await f_($);let A=X_(Y,X["content-type"]||"");if(A.rawBody===null&&$.rawBody!=null)A.rawBody=typeof $.rawBody==="string"?$.rawBody:E_($.rawBody);return{method:K,url:Z,headers:X,query:D,body:A.body,rawBody:A.rawBody}}throw Error("[YourSDK] Could not identify runtime payload type.")}class g{config;isRunning=!1;logger;rs;constructor(_){this.config=_;this.logger=new G,this.rs=k()}}class K_ extends g{networkConfig;networkInterface;storage;queueService;interface="HTTP";consumersMap;triggerHandler;constructor(_,$,X,K){super(_);this.networkConfig=_;this.networkInterface=$;this.storage=X;this.queueService=K;let L=H.get("queues"),Z=new Map;L.forEach(({consumer:W,queue:D})=>Z.set(D,W)),this.consumersMap=Z,this.networkInterface.onFetch=async(W)=>{return await this.handleFetch(W)}}async start(){}async broadcast(_,$){let X=this.consumersMap.get(_);if(!X)throw Error(`No consumer registered for queue: "${_}"`);if(X.type!=="http")return;let{worker_id:K,batch:L}=$;try{await fetch(X.url,{method:"POST",headers:{"content-type":"application/json",...X.headers,"x-worker-id":K,"x-batch-size":L.length.toString(),"x-pulsar-callback-url":H.get("engine.selfURL"),"x-test-mode":"SAFE","x-queue":_,"x-execution-signature":crypto.randomUUID()},body:JSON.stringify({worker_id:K,batch:L})})}catch(Z){this.logger.error("Error dispatching jobs to http consumer,",Z)}}getActiveConnections(_){return[]}onTrigger(_){this.triggerHandler=_}async stop(){}async handleFetch(_){let{url:$,method:X,body:K,headers:L}=await J_(_),Z=new URL($),W={headers:L,body:K};if(Z.pathname.endsWith("/ack")&&X==="POST"){let D=await this.handleAck(W);return new Response(D.message,{status:D.status})}if(Z.pathname.endsWith("/nack")&&X==="POST"){let D=await this.handleNack(W);return new Response(D.message,{status:D.status})}if(Z.pathname.endsWith("/retry")&&X==="POST"){let D=await this.handleRetry(W);return new Response(D.message,{status:D.status})}if(Z.pathname.endsWith("/deregister")&&X==="POST"){let D=await this.handleDeregister(W);return new Response(D.message,{status:D.status})}return new Response("HELLO MEWAOOOO",{status:200})}async performBatchAction(_,$,X,K){try{switch(K){case"ACK":await this.queueService.ackBatch(_,X);break;case"NACK":await this.queueService.ackBatch(_,X);break;case"RETRY":await this.queueService.retryBatch(_,X);break;case"DEREGISTER":await this.storage.repository.deregisterWorker($,_);break}}catch(L){throw this.logger.error(`Error performing batch action [${K}] for queue [${_}]:`,L),L}}parseBody(_){if(typeof _==="string")try{return JSON.parse(_)}catch($){throw Error(`Failed to parse request body: ${$.message}`)}return _}extractContext(_){let $=_.headers,X=this.parseBody(_.body),K=$["x-queue"],L=$["x-worker-id"]??"";if(!K)throw Error("[HttpNetworkDriver] Queue not found in headers");return{headers:$,body:X,queue:K,workerId:L}}async getMessageIds(_){let{queue:$,body:X,workerId:K}=this.extractContext(_),Z=(Array.isArray(X?.msg_ids)?X.msg_ids:[]).map((W)=>Number.parseInt(String(W),10)).filter((W)=>Number.isInteger(W)&&W>=0);return{queue:$,messageIds:Z,workerId:K}}async handleAck(_){let{messageIds:$,queue:X,workerId:K}=await this.getMessageIds(_);return await this.performBatchAction(X,K,$,"ACK"),{message:"Jobs Acknowledged",status:200}}async handleNack(_){let{messageIds:$,queue:X,workerId:K}=await this.getMessageIds(_);return await this.performBatchAction(X,K,$,"NACK"),{message:"Jobs Not Acknowledged",status:200}}async handleRetry(_){let{queue:$,workerId:X,messageIds:K}=await this.getMessageIds(_);return await this.performBatchAction($,X,K,"RETRY"),{message:"Jobs Retry Applied",status:200}}async handleDeregister(_){let{queue:$,workerId:X}=this.extractContext(_);if(!X)throw Error("[HttpNetworkDriver] Worker ID not found in headers");return await this.performBatchAction($,X,[],"DEREGISTER"),{message:"Worker Deregistered",status:200}}}class L_ extends g{networkInterface;interface="WEBSOCKET";queuePeers=new Map;triggerHandler;boundOpen=(_)=>this.onConnectionOpen(_);boundMessage=(_,$)=>this.onMessage(_,$);boundClose=(_)=>this.onConnectionClose(_);constructor(_,$){super(_);this.networkInterface=$;this.networkInterface.on("open",this.boundOpen),this.networkInterface.on("message",this.boundMessage),this.networkInterface.on("close",this.boundClose)}async start(){}async broadcast(_,$){let X=this.queuePeers.get(_);if(!X||X.size===0){this.logger.warn(`[Network] : No active workers listening on queue: ${_}`);return}let K=JSON.stringify($);for(let L of X)try{L.send(K)}catch(Z){this.logger.error(`[Network] : Failed to send message to peer ${L.id}:`,Z)}}getActiveConnections(_){let $=this.queuePeers.get(_);if(!$)return[];return Array.from($.values()).map((X)=>X.id)}onTrigger(_){this.triggerHandler=_}async stop(){this.networkInterface.off("open",this.boundOpen),this.networkInterface.off("message",this.boundMessage),this.networkInterface.off("close",this.boundClose);for(let _ of this.queuePeers.values())for(let $ of _)try{$.close(1001,"server shutting down")}catch{}this.queuePeers.clear()}onConnectionOpen(_){this.logger.log("[Network] : Worker connected:",_.id)}onMessage(_,$){let X=JSON.parse($.toString());X.type==="REGISTER"?this.handleWorkerRegistration(_,X):this.handleWorkerMessage(X)}handleWorkerRegistration(_,$){let X=this.queuePeers.get($.queue);if(!X)X=new Set,this.queuePeers.set($.queue,X);if(X.has(_)){this.logger.log(`[Network] : Worker ${_.id} is already registered to queue: ${$.queue}`);return}_.subscribe($.queue),X.add(_),this.rs.lists.add($.queue,_.id),this.logger.log(`[Network] : Worker ${_.id} registered to queue: ${$.queue}`)}handleWorkerMessage(_){if(this.triggerHandler){let $=_.queue,X=_.data!==void 0?_?.data:_;if($)this.triggerHandler($,X)}}onConnectionClose(_){this.logger.log("[Network] : [WebSocketNetworkDriver] - Worker disconnected:",_.id);for(let[$,X]of this.queuePeers.entries())if(X.has(_)){if(X.delete(_),this.rs.lists.remove($,_.id),X.size===0)this.queuePeers.delete($)}}}class x{config;storage;queueServuce;drivers=[];topology;networkInterface;isServerMode;constructor(_,$,X){this.config=_;this.storage=$;this.queueServuce=X;if(this.topology=_.mode,this.isServerMode=_.isServer,this.isServerMode)this.initializeTopology()}initializeTopology(){if(this.networkInterface=new e(this.config),this.config.mode==="websocket"||this.config.mode==="hybrid")this.drivers.push(new L_(this.config,this.networkInterface));if(this.config.mode==="http"||this.config.mode==="hybrid")this.drivers.push(new K_(this.config,this.networkInterface,this.storage,this.queueServuce))}async bootAll(){if(!this.isServerMode||!this.networkInterface)return;await this.networkInterface.start();for(let _ of this.drivers)await _.start()}async shutdownAll(){if(!this.isServerMode)return;for(let _ of this.drivers)await _.stop();await this.networkInterface?.close()}onTrigger(_){for(let $ of this.drivers)$.onTrigger(_)}async dispatchToNetwork(_,$){let X=H.get("queues").find((W)=>W.queue===_),K={http:"HTTP",socket:"WEBSOCKET"},L=X.consumer.type,Z=K[L];if(!Z)throw Error(`[DispatchToNetwork] : Unsupported consumer type "${L}" for queue: "${_}"`);for(let W of this.drivers)if(W.interface===Z)await W.broadcast(_,$)}}class Z_{engineUrl;consumersMap;constructor(_,$){this.engineUrl=$;let X=new Map;_.forEach((K)=>X.set(K.queue,K)),this.consumersMap=X}async dispatch(_,$,X){let K=this.consumersMap.get(_);if(!K)throw Error(`No consumer registered for queue: "${_}"`);if(K.type=="http")await fetch(K.url,{method:"POST",headers:{"content-type":"application/json",...K.headers,"x-worker-id":$,"x-batch-size":X.length.toString(),"x-pulsar-callback-url":this.engineUrl,"x-test-mode":"SAFE","x-queue":_,"x-execution-signature":crypto.randomUUID()},body:JSON.stringify({messages:X})}).catch((L)=>{console.log(`[${_}] Unbounded HTTP dispatch failed for worker ${$}:`,L)});else if(K.type=="socket");else K?.handler({queue:K.queue,payload:X,attempts:1,workerId:$,timestamp:new Date().getTime()})}}class W_{storage;tickService;tickController;unifiedTransportManager;dispatcher;swarmManager;scheduler;queueService;clock;events;queues=[];consumers=[];runtimeStrategy;logger;integrations=new Map;constructor(_){if(H.initialize(_),this.logger=new G,_.integrations?.length)this.runIntegrations(_.integrations);for(let{consumer:W,...D}of H.raw.queues)this.queues.push(D),this.consumers.push(W);let $=H.get("instanceId");if(!$)throw Error("[Pulsar] : instanceId is required.");if(typeof $!=="string"||!/^[a-zA-Z0-9_-]+$/.test($))throw Error('[Pulsar] : Invalid instanceId format. It must contain only alphanumeric characters, hyphens, and underscores (e.g., "string-like-this" or "or_this").');this.events=new v;let K=1/0,L=H.raw.runtime==="v8-isolate",Z=H.get("isolate");if(L)K=Math.max(0,Z.remainingTime-5000);if(this.storage=H.raw.storage,this.storage.connect(),this.storage.bindInstanceId($),this.clock=new l({maxExecutionBudgetMs:K,safetyBufferMs:0,maxTrackHistory:50,enabled:!0}),this.dispatcher=new Z_(this.consumers,H.get("engine.selfURL")),this.queueService=new d(this.storage),this.scheduler=new q,this.runtimeStrategy=this.resolveRuntimeStrategy(),!this.runtimeStrategy)throw this.logger.error("[Pulsar] Failed to resolve a valid runtime strategy."),Error("[Pulsar] Failed to resolve a valid runtime strategy.");if(H.raw.runtime=="persistent")this.unifiedTransportManager=new x({...H.raw.networkInterface,isServer:!0},this.storage,this.queueService);else this.unifiedTransportManager=new x({mode:"client",isServer:!1,port:0},this.storage,this.queueService);if(this.swarmManager=new c(H.raw.swarmConfig?.globalMaxJobsPerTick??1/0,H.raw.swarmConfig?.maxGlobalConcurrency??1/0),this.tickService=new s({dispatcher:this.dispatcher,queue:this.queueService,storage:this.storage,swarmManager:this.swarmManager,unifiedTransportManager:this.unifiedTransportManager,events:this.events}),this.tickController=new o({scheduler:this.scheduler,storage:this.storage,tickService:this.tickService,clock:this.clock,events:this.events,runtimeStrategy:this.runtimeStrategy}),Number.isFinite(K))this.logger.log(`[EngineRuntime] : isolate registred with id : [${Z.id}]`),this.logger.log(`[Clock] : Synced execution timeout (${K/1000}s) with isolate [${Z.id}]`);else this.logger.log(`[EngineRuntime] : Engine Started With No V8 Isolate (${new Date().toISOString()})`)}resolveRuntimeStrategy(){let _={queueService:this.queueService,clock:this.clock,queues:this.queues,storage:this.storage,isolate:this.V8Isolate,events:this.events,scheduler:this.scheduler};switch(H.get("runtime")){case"persistent":return new n(_);case"serverless-vm":return new a(_);case"v8-isolate":return new t(_);default:throw Error("Unsupported Runtime")}}async runIntegrations(_){for(let $ of _){let X;if(typeof $==="function")X=new $("ALL");else X=$;await X.main(this),this.integrations.set(X.module,X)}}getIntegration(_){if(typeof _==="string")return this.integrations.get(_);for(let X of this.integrations.values())if(X instanceof _)return X;let $=typeof _==="string"?_:_.name;throw Error(`Integration "${$}" is not registered.`)}get runtime(){return this.runtimeStrategy.type}get isV8Isolate(){return H.get("runtime")==="v8-isolate"}get V8Isolate(){return H.raw.isolate}async exit(){await this.storage.disconnect()}}class U_ extends W_{baseConfig;isolateId;currentExecutionId;lockKey;shutdownPromise=null;eventCleanUps=[];activeQueues=new Set;constructor(_){super(_);this.baseConfig=_;if(this.registerEvents(),!this.isV8Isolate)this.isolateId=crypto.randomUUID();else this.isolateId=this.V8Isolate.id;if(this.isV8Isolate)this.currentExecutionId=this.V8Isolate.get("current_execution_id"),this.lockKey=this.V8Isolate.get("lock_key");else this.currentExecutionId=this.generateCurrentExecutionIdFromConfig(),this.lockKey="lock-template-static-defination-for-non-v8";this.tickController.initializeState()}async start(){await this.unifiedTransportManager.bootAll(),await H.reconcileConfiguration(this.storage.ops),this.tickController.initializeState(),this.configureQueueProfiles(),await this.runtimeStrategy.onStart(this.executionContext)}async triggerQueue(_){let $=this.queues.find((X)=>X.queue===_);if(!$)throw Error("[Pulsar] Target queue is missing.");this.logger.log(`[Pulsar] : Event-driven trigger for (${_})`),await this.validateConfiguration(),await this.runTick($)}async validateConfiguration(){return{status:200,message:await H.reconcileConfiguration(this.storage.ops)}}configureQueueProfiles(){for(let _ of this.queues){let $=_.profile||"REALTIME";this.scheduler.registerQueueProfile(_.queue,$)}}async runTick(_){return this.activeQueues.add(_),await this.tickController.runTick(_)}async shutdown(){if(this.logger.log("Engine Shutdown ⚠️."),this.removeRegisteredEvents(),this.unifiedTransportManager)await this.unifiedTransportManager.shutdownAll();if(!await this.runtimeStrategy.handleCycleCompletion(this.executionContext))await this.releaseExecutionLock(this.lockKey,this.currentExecutionId);await this.storage.ops.pingHealthCheck(),await this.storage.disconnect()}async scheduleRestart(_){if(_){let X=this.queues.find((K)=>K.queue==_);if(X)this.activeQueues.add(X)}let $=Array.from(this.activeQueues.values());await this.releaseExecutionLock(this.lockKey,this.isolateId),await this.storage.ops.addRestart($),await this.runtimeStrategy.handleRestart(this.executionContext),await this.storage.ops.updateRestartOwnership(_,"handled_by_engine")}async restartForSameIsolate(_){let $=30;if(this.isV8Isolate)$=this.V8Isolate.remainingTime+5;this.logger.log(`Estimated Restart in (${$})S`),await this.queueService.triggerUrl({url:H.get("engine.selfURL"),headers:_,delaySeconds:$})}get executionContext(){return{lockKey:this.lockKey,currentExecutionId:this.currentExecutionId,isolateId:this.isolateId,getActiveQueues:()=>Array.from(this.activeQueues.values()),runTick:(_)=>this.runTick(_),endTick:(_)=>this.tickController.endTick(_)}}setCurrentExecutionId(_){this.currentExecutionId=_}generateCurrentExecutionIdFromConfig(){let _=this.baseConfig.queues.map(($)=>`${$.queue}:${$.pooler}`).join(",");return C_(_)}registerEvents(){let _=this.runtimeStrategy.shouldShutdownOnCycleComplete;this.eventCleanUps.push(this.events.on("tick:cycle-completed",async()=>{if(_)await this.shutdown();else this.logger.log("[Pulsar Persistent] : Cycle completed. Resetting state for next execution round."),this.tickController.initializeState()})),this.eventCleanUps.push(this.events.on("tick:force-run",async({queue:$,reason:X})=>{this.logger.log(`[Tick] : Force executing tick for queue [${$.queue}] Trigger Reason: ${X}`),await this.runTick($)})),this.eventCleanUps.push(this.events.on("tick:end",({queue:$,reason:X})=>{this.logger.log(`[Tick] : Force stoping tick for queue [${$}] (Trigger Reason: ${X})`),this.tickController.endTick($)})),this.eventCleanUps.push(this.events.on("tick:time-exceeded",async()=>{if(_)await this.shutdown()})),this.eventCleanUps.push(this.events.on("engine:health-check-requested",async()=>{this.logger.log(`Pulsar : Health checking ping at (${new Date().toISOString()})`),await this.storage.ops.pingHealthCheck()}))}removeRegisteredEvents(){this.eventCleanUps.forEach((_)=>_()),this.eventCleanUps=[]}async awaitPendingShutdown(){if(this.shutdownPromise)await this.shutdownPromise}async deleteScheduledRestart(_){await this.storage.ops.deleteRestart(_)}async acquireExecutionLock(_,$,X){return await this.storage.repository.acquireQueueLock(_,$,X)}async releaseExecutionLock(_,$){return await this.storage.repository.releaseQueueLock(_,$)}}export{y_ as createQueue,h as PulsarRuntime,U_ as Pulsar,D_ as IsolateInstance,m as EventTriggerStrategy};
45
+ `;return Boolean(K[0]?.set_vt)}async getSingleQueueMetrics(_){try{let $=await this.sql`SELECT * FROM pgmq.get_single_queue_metrics(${_})`,X=Array.from($);if(!X.length)return null;let K=X[0];return{queueName:K.queue_name,readyJobs:Number(K.ready_jobs??0),delayedJobs:Number(K.delayed_jobs??0),total:Number(K.total_jobs??0),nextVisibleAt:K.next_visible_at?new Date(K.next_visible_at).getTime():null}}catch($){return console.error(`Failed to fetch metrics for queue: ${_}`,$),null}}async getAllQueueMetrics(){let _=await this.sql`SELECT * FROM pgmq.get_queue_metrics()`;return Array.from(_).map(($)=>({queue_name:$.queue_name,ready_jobs:Number($.ready_jobs),delayed_jobs:Number($.delayed_jobs),total:Number($.total_jobs),next_visible_at:Number($.next_visible_at)}))}async closeQueue(){await this.sql.end()}}class c{maxGlobalJobsPerTick;maxGlobalConcurrency;constructor(_,$){this.maxGlobalJobsPerTick=_;this.maxGlobalConcurrency=$}getMaxGlobalConcurrency(){return this.maxGlobalConcurrency}getMaxGlobalJobsPerTick(){return this.maxGlobalJobsPerTick}}class H_{log(_,...$){console.log(_,...$)}warn(_,...$){console.warn(_,...$)}error(_,...$){console.error(_,...$)}debug(_,...$){console.debug(_,...$)}}class G{static provider=new H_;setProvider(_){G.provider=_}log(_,...$){G.provider.log(_,...$)}warn(_,...$){G.provider.warn(_,...$)}error(_,...$){G.provider.error(_,...$)}debug(_,...$){if(G.provider.debug)G.provider.debug(_,...$)}}var b_=new Set(["storage","runtime","onEvents","isolate","queue"]),w_=new Set(["queue","deadLetterQueue"]);class R{static instance;_config;initialSnapshot;logger;constructor(){this.logger=new G}static getInstance(){if(!R.instance)R.instance=new R;return R.instance}initialize(_){this._config={swarmConfig:{globalMaxJobsPerTick:1e5,maxGlobalConcurrency:1e4,spawnerAlgorithm:"ROUND_ROBIN",..._.swarmConfig},..._,engine:{..._.runtime=="persistent"?{poolingIntervalSec:5}:{},..._.runtime=="serverless-vm"||_.runtime=="v8-isolate"?{selfInvocationMethod:"auto_using_pgnet",selfInvocationIntervalSec:1,healthCheckIntervalSec:15,selfRestartIntervalSec:60}:{},tickConcurrency:"sequential",cycleTickLimit:1000,..._.engine},queues:_.queues.map(($)=>({stateTransitionPolicy:{enabled:!0,idleThresholdTicks:10,idleTimingProfile:"RELAXED"},...$}))},this.throwExpectionOnInvalidConfiguration(this._config),this.initialSnapshot=Object.freeze(JSON.parse(JSON.stringify(this._config)))}throwExpectionOnInvalidConfiguration(_){let $=_.queues;if($.length==0)throw this.logger.error('[Pulsar] Runtime configuration error: "queues" atleast 1 queue is required to operate.'),Error('[Pulsar] Runtime configuration error: "queues" atleast 1 queue is required to operate.');if(_.runtime==="v8-isolate"&&!_.isolate)throw this.logger.error(`[Pulsar] Runtime configuration error: "isolate" instance is required when running in "${"v8-isolate"}" mode.`),Error(`[Pulsar] Runtime configuration error: "isolate" instance is required when running in "${"v8-isolate"}" mode.`);let X=$.reduce((Z,W)=>{return Z[W.queue]=(Z[W.queue]||0)+1,Z},{}),K=Object.keys(X).filter((Z)=>X[Z]>1);if(K.length>0)throw this.logger.error("[ConfigurationStore]: Duplicate queues found -> ",K),Error("Duplicate queue names detected in the configuration.");let L=$.map((Z)=>Z.consumer);if(_.runtime!=="persistent"){let Z=L.find((W)=>W.type=="socket");if(Z)throw this.logger.error(`${JSON.stringify(Z)}`),Error("Consumers do not support non-persistent socket types. Please either remove the 'socket' type from the consumer or update the runtime to PERSISTENT.")}for(let Z of L)if(Z.type=="http")try{let W=new URL(Z.url);if(W.protocol!=="http:"&&W.protocol!=="https:")throw this.logger.error(`${Z.queue} - ${Z.url}`),Error(`Invalid protocol '${W.protocol}' for consumer URL. Only HTTP and HTTPS are supported.`)}catch(W){this.logger.error(`${Z.queue} - ${Z.url}`);let D=W instanceof Error?W.message:"An unknown error occurred while parsing the consumer URL.";throw Error(`Failed to validate consumer URL: ${D}`)}else if(Z.type=="callback"){if(!Z.handler)throw Error("Consumer handler is required. Please provide a valid handler function.")}}ensureInitialized(){if(!this._config)throw Error("[ConfigurationStore]: Engine configuration store is not initialized. Call initialize() first.");if(!this.initialSnapshot)throw Error("[ConfigurationStore]: Engine initial snapshot is not initialized")}get raw(){return this.ensureInitialized(),this._config}get(_){this.ensureInitialized();let $=_.split("."),X=this._config;for(let K of $){if(X===void 0||X===null)return;X=X[K]}return X}getInitialSnapshot(){return this.ensureInitialized(),Object.freeze({...this.initialSnapshot})}set(_,$){this.ensureInitialized();let X=_.split("."),K=X[0];if(b_.has(K))throw Error(`[ConfigurationStore]: Modifying path '${_}' via set() is forbidden.`);let L=this._config;for(let Z=0;Z<X.length-1;Z++){let W=X[Z];if(!(W in L)||typeof L[W]!=="object")L[W]={};L=L[W]}L[X[X.length-1]]=$}modifyQueue(_,$,X){if(this.ensureInitialized(),w_.has($))throw Error(`[ConfigurationStore]: Property '${String($)}' on queue '${_}' cannot be modified at runtime.`);let K=this._config.queues.findIndex((L)=>L.queue==_);if(!this._config.queues[K])throw Error(`[ConfigurationStore]: Modifying queue '${_}' not found.`);this._config.queues[K][$]=X}async reconcileConfiguration(_){let $=this.getInitialSnapshot(),X=$.runtime==="serverless-vm"||$.runtime==="v8-isolate"?$.engine.selfURL:"NOT_REQUIRED",K={queues:$.queues.map((Z)=>({queue:Z.queue,pooler:Z.pooler})),runtime:$.runtime,event_trigger_strategy:$.runtime=="persistent"?$.eventTriggerStrategy:"WEBHOOK",self_url:X},L=await _.verifyAndSyncConfiguration("PULSAR_STANDALONE",$.instanceId,X,K);if(!L.isChanged&&!L.isNew)return this.logger.log("[Configuration] status : [VALID]."),"[Configuration] status : [VALID].";else return this.logger.log("[Configuration] status : [INVALID & Reconciled]."),"[Configuration] status : [INVALID & Reconciled]."}}var H=R.getInstance();var T={REALTIME:{activePollMs:1000,backoffPollMs:1000,idlePollMs:1000,maxTimerMs:5000},STANDARD:{activePollMs:100,backoffPollMs:500,idlePollMs:1e4,maxTimerMs:60000},BALANCED:{activePollMs:1e4,backoffPollMs:500,idlePollMs:1e4,maxTimerMs:60000},RELAXED:{activePollMs:1000,backoffPollMs:20000,idlePollMs:30000,maxTimerMs:60000},ULTRA_EFFICIENT:{activePollMs:5000,backoffPollMs:1e5,idlePollMs:120000,maxTimerMs:240000}};var I_=2147483647;class q{timers=new Map;profiles=new Map;constructor(){}registerQueueProfile(_,$){if(typeof $==="string"){let X=$!=="CUSTOM"?T[$]:void 0;this.profiles.set(_,X??T.STANDARD)}else this.profiles.set(_,$)}getProfile(_){let X=H.get("queues")?.find((K)=>K.queue===_)?.profile;if(X){if(typeof X==="string")return X!=="CUSTOM"?T[X]:T.STANDARD;if(typeof X==="object")return X}return this.profiles.get(_)??T.STANDARD}cancel(_){let $=this.timers.get(_);if($)clearTimeout($);this.timers.delete(_)}scheduleNext(_){let{metrics:$,onNext:X,onUpcomingDelayedNext:K,onFutureSchedule:L}=_,{queue:Z,readyJobs:W,delayedJobs:D,availableSlots:Y,nextVisibleAt:A}=$;this.cancel(Z);let V=this.getProfile(Z);if(W>0&&Y>0){this.setTimer(Z,X,V.activePollMs);return}if(W>0&&Y===0){this.setTimer(Z,X,V.backoffPollMs);return}if(D>0&&A){let M=Math.max(0,A-Date.now());if(M<=V.maxTimerMs){if(K)K(M);this.setTimer(Z,X,M);return}if(L)L(A).catch((J)=>console.error(`Scheduler error setting long delay for ${Z}:`,J));return}if(V.idlePollMs)this.setTimer(Z,X,V.idlePollMs)}setTimer(_,$,X){let K=Math.min(Math.max(0,X),I_),L=()=>{this.timers.delete(_),$()};if(K===0){let W=setTimeout(L);this.timers.set(_,W);return}let Z=setTimeout(L,K);this.timers.set(_,Z)}}class i{logger;transitionItems=new Set;constructor(_){this.logger=_}transitionToIdleMode({queue:_,stateTransitionPolicy:$}){if(this.transitionItems.has(_))return;if(this.transitionItems.add(_),this.logger.log(`[ENGINE_STATE] Transitioning engine execution profile to IDLE. Queue config: (${_})`),$?.enabled){let X=$.idleTimingProfile;if(X){let K=typeof X==="object"?{activePollMs:X.activePollMs,backoffPollMs:X.backoffPollMs,idlePollMs:X.idlePollMs}:T[X];H.modifyQueue(_,"profile",K)}}}transitionToActiveMode({queue:_,profile:$,stateTransitionPolicy:X}){if(this.transitionItems.delete(_),X?.enabled)H.modifyQueue(_,"profile",$);this.logger.log(`[ENGINE_STATE] Transitioning engine execution profile to ACTIVE. Queue config: (${_})`)}}class s{storage;queue;dispatcher;executionProfileSwitcher;unifiedTransportManager;swarmManager;PROCESS_ID;globalSequence=0;consecutiveEmptyTicks=0;logger;events;constructor({dispatcher:_,queue:$,storage:X,swarmManager:K,unifiedTransportManager:L,events:Z}){this.storage=X,this.dispatcher=_,this.queue=$,this.swarmManager=K,this.unifiedTransportManager=L,this.logger=new G,this.executionProfileSwitcher=new i(this.logger),this.PROCESS_ID=crypto.randomUUID().slice(0,12),this.globalSequence=0,this.events=Z}async run(_,$){let{concurrency:X,queue:K}=_,L=this.swarmManager.getMaxGlobalConcurrency(),{batches:Z,window:W}=await this.getCandidatesBatch({queueConfig:_,maxGlobalSlotsAllowed:$}),D=_.stateTransitionPolicy?.enabled==!0;if(!Z||Z.length===0){if(D){if(this.consecutiveEmptyTicks++,this.consecutiveEmptyTicks>=(_.stateTransitionPolicy?.idleThresholdTicks??10))this.executionProfileSwitcher.transitionToIdleMode(_)}this.logger.warn(`[Tick] : [${K}] - Empty Tick Executred)`);return}if(D&&this.consecutiveEmptyTicks>0)this.consecutiveEmptyTicks=0,this.executionProfileSwitcher.transitionToActiveMode(_);let Y=await this.storage.repository.registerWorker(K,Z,X,L),A=new Set(Y),V=Z.filter((M)=>!A.has(M.workerId));if(V.length>0){let M=V.reduce((J,Q)=>J+Q.batch.length,0);await this.storage.repository.refundGlobalJobBudget(M,W)}if(Y.length===0)return;this.logger.log(`[Tick] : [${K}] - Tick Executred. Total Jobs (${Z.reduce((M,J)=>M+J.batch.length,0)})`),await this.spwanWorkers({candidateBatches:Z,grantedWorkerIds:Y,queueConfig:_})}async spwanWorkers({grantedWorkerIds:_,candidateBatches:$,queueConfig:{queue:X}}){if(!_?.length)return;let K=new Set(_),L=$.filter((Z)=>K.has(Z.workerId));await Promise.allSettled(L.map(({batch:Z,workerId:W})=>{return this.unifiedTransportManager.dispatchToNetwork(X,{batch:Z,worker_id:W})}))}async getCandidatesBatch({queueConfig:_,maxGlobalSlotsAllowed:$}){let{concurrency:X,maxJobsPerTick:K,queue:L,sleep:Z,n:W}=_,D=await this.storage.repository.getActiveWorkersCount(L),Y=Math.max(0,X-D);if(Y===0)return{batches:[],window:""};let A=Math.min(Y,$);if(A===0)return{batches:[],window:""};let V=A*W,M=K!==void 0&&K>0?K:1/0,J=Math.min(V,M);if(J<=0)return{batches:[],window:""};let Q=this.swarmManager.getMaxGlobalJobsPerTick(),{granted:P,window:F}=await this.storage.repository.claimGlobalJobBudget(J,Q);if(P<=0)return{batches:[],window:F};let N=await this.queue.read(L,Z??1,P),y=N.length;if(y===0)return await this.storage.repository.refundGlobalJobBudget(P,F),{batches:[],window:F};if(y<P){let B=P-N.length;await this.storage.repository.refundGlobalJobBudget(B,F)}let b=Math.ceil(y/W),O=Array(b),C=Date.now(),p=0;for(let B=0;B<y;B+=W)O[p++]={workerId:`w_${this.PROCESS_ID}_${C}_${this.globalSequence++}`,batch:N.slice(B,B+W)};return{batches:O,window:F}}}class o{clock;tickService;scheduler;storage;events;runtimeStrategy;tickState=new Map;activeTicks=new Set;lastHealthCheckAt=0;logger;constructor({scheduler:_,storage:$,tickService:X,clock:K,events:L,runtimeStrategy:Z}){this.logger=new G,this.clock=K,this.tickService=X,this.scheduler=_,this.storage=$,this.events=L,this.runtimeStrategy=Z,this.initializeState()}initializeState(){this.tickState.clear(),this.activeTicks.clear()}async runTick(_){await this.runtimeStrategy.executeTick(_,async()=>{let{queue:$}=_;if(this.initializeTickState(_),this.activeTicks.has($)||this.tickState.get($)?.stopped)return;this.activeTicks.add($),this.scheduler.cancel($);try{let X=1/0,K=H.get("swarmConfig")?.maxGlobalConcurrency;if(K!==void 0){let L=await this.storage.repository.getGlobalActiveWorkersCount();X=Math.max(0,K-L)}if(X>0&&!this.tickState.get($)?.stopped)await this.tickService.run(_,X)}catch(X){this.logger.error(`Orchestrator error on ${$}:`,X)}finally{this.activeTicks.delete($),this.updateTickCounter($)}if(this.tickState.get($)?.stopped==!0)return;await this.runtimeStrategy.scheduleTick(_,()=>this.runTick(_))})}endTick(_){let $=this.tickState.get(_);if($){if($.stopped==!0)return;if(this.tickState.set(_,{...$,stopped:!0}),this.scheduler.cancel(_),this.clock.clear(_),H.raw.queues.every((K)=>{let L=this.tickState.get(K.queue);return L?L.stopped:!0}))this.events.emit("tick:cycle-completed",{queue:_,cycles:this.tickState.get(_)?.count??1})}}initializeTickState(_){if(!this.tickState.get(_.queue))this.tickState.set(_.queue,{count:0,max:_.cycleTickLimit??10,registred:!0,stopped:!1})}updateTickCounter(_){let $=this.tickState.get(_)??{count:0,stopped:!1,max:10,registred:!1},X=$.count+1,K=$.max,L=X>=K;if(($.stopped||L)&&!$.stopped)this.tickState.set(_,{count:X,stopped:$.stopped,max:K,registred:$.registred}),this.endTick(_);else this.tickState.set(_,{count:X,stopped:$.stopped,max:K,registred:$.registred});this.triggerPeriodicHealthCheck()}triggerPeriodicHealthCheck(){let _=Date.now(),$=this.runtimeStrategy.shouldShutdownOnCycleComplete,X=(H.get("engine.healthCheckIntervalSec")??15)*1000;if(_-this.lastHealthCheckAt>=X&&!$)this.lastHealthCheckAt=_,this.events.emit("engine:health-check-requested",{timestamp:_})}}class j{queueService;clock;queues;storage;isolate;events;scheduler;logger;constructor(_){this.queueService=_.queueService,this.clock=_.clock,this.queues=_.queues,this.isolate=_.isolate,this.storage=_.storage,this.events=_.events,this.scheduler=_.scheduler,this.logger=new G}async executeQueuesTick(_){let $=H.get("engine.tickConcurrency");if(this.logger.log(`[Tick Controller] : Execution tick mode has been selected with concurrency ${$}`),$=="sequential"){for(let X of this.queues)if(X.pooler=="interval-driven-pooler")await _(X)}else{let X=await Promise.allSettled(this.queues.filter((K)=>K.pooler==="interval-driven-pooler").map((K)=>_(K)));for(let K of X)if(K.status==="rejected")this.logger.error("[Tick] : Error >>",K.reason)}}async triggerSelfInvocation(_){let{queue:$,pooler:X,delaySec:K,continuationOwnerId:L,isIdpLock:Z,isEdpLock:W,targetEdpQueue:D}=_,Y=H.get("engine.selfURL"),V=H.raw.engine.selfInvocationMethod,M={idpInvoked:!1,continuationScheduledForCurrentLock:!1};if(X==="interval-driven-pooler"){if(M.idpInvoked=!0,Z)M.continuationScheduledForCurrentLock=!0;this.logger.log(`(IDP) : Invoking Self in ${K} seconds...`)}else if(X==="event-driven-pooler"){if(W&&$===D)M.continuationScheduledForCurrentLock=!0;this.logger.log(`(EDP) : Invoking Self in ${K} seconds...`)}let J={"content-type":"application/json","x-last-execution-id":L,"x-last-execution-at":new Date().toISOString(),"x-execution-owner":"engine","x-restart":"false","x-pooler":X,"x-target-queue":$};if(V=="auto_using_pgnet")await this.queueService.triggerUrl({url:Y,headers:J,delaySeconds:K});else if(typeof V==="object"&&V!==null&&V.method==="manual")await V.handler(Y);return M}}class r{storage;logger;pgNotifyChannel="channel_pulsar_event_driven_queue";runtimeExecutionId=crypto.randomUUID();constructor(_,$){this.storage=_;this.logger=$}async registerPgNotifyHandler(_){await this.storage.ops.subscribeToDatabaseEvents(this.pgNotifyChannel,async($)=>{this.logger.log(`[Persistent Runtime] : Recived PgNotification Event - ${new Date().toISOString()}`);let X=H.get("queues").find((L)=>L.queue===$.queue_name);if(!X){this.logger.error(`[Persistent Runtime] : Received notification for unregistered or unmanaged queue: '${$.queue_name}' on channel: ${this.pgNotifyChannel}`);return}if(await this.handleTriggerValidity(X.queue,$.fencing_token))await _.runTick(X)},()=>{this.logger.log(`[Persistent Runtime] : Successfully established PostgreSQL notification listener on channel : ${this.pgNotifyChannel}`)})}async registerPollingHandler(_){setInterval(async()=>{let $=await this.storage.ops.getPollingQueueEntries("q_3");for(let X of $){let K=X.payload.queue_name,L=X.payload.fencing_token,Z=await this.handleTriggerValidity(K,L);if(Z)await _.runTick(Z),await this.storage.ops.deletePollingQueueEntry(X.id)}},H.get("engine.poolingIntervalMS"))}async handleTriggerValidity(_,$){let X=H.get("queues").find((D)=>D.queue===_);if(!X)return this.logger.error(`[Persistent Runtime] : pool entry for unregistered or unmanaged queue: '${_}'`),null;if(!await this.storage.ops.checkFencingTokenValidity(_,$)){let D=`[EventDrivenPoller]-[ExecutionTrigger]-[${_}] : Engine execution rejected : Invalid fencing token.`;return this.logger.error(D),null}let L=`lock:edp:${_}`,Z=120000;if(await this.storage.repository.acquireQueueLock(L,this.runtimeExecutionId,Z))await this.storage.repository.clearDispatchPending(L);else return this.logger.log(`[Persistent Runtime] : Engine busy for queue ${_}, skipping trigger.`),null;return X}}class w{minBootRequirementSec;scheduler;events;clock;logger;constructor(_,$,X,K,L){this.minBootRequirementSec=_;this.scheduler=$;this.events=X;this.clock=K;this.logger=L}timers=new Map;watchdogTimer=null;isShutdownTriggered=!1;evaluateUpcomingDelayedNext(_,$){let X=H.raw.isolate;if(!X)throw Error("Isolate is not configured for V8_Isolate_Runtime!");let K=H.get("engine.selfInvocationIntervalSec")??1,L=this.minBootRequirementSec,Z=(K+L)*1000;if(X.remainingTime-_<Z){this.logger.log(`[Isolate Runtime] Sleep duration of ${_}ms exceeds safe isolate budget. Canceling timer sleep and initiating shutdown.`),this.scheduler.cancel($),this.triggerGracefulShutdown($);return}this.startDelayedSleepWatchdog($,Z)}startDelayedSleepWatchdog(_,$){this.stopRuntimeWatchdog(),this.isShutdownTriggered=!1,this.watchdogTimer=setInterval(()=>{let X=H.raw.isolate;if(!X||this.isShutdownTriggered)return;if(X.remainingTime<=$)this.logger.log(`[Isolate Watchdog] Remaining isolate budget (${X.remainingTime}ms) expired during delayed sleep. Canceling wakeup and executing graceful shutdown.`),this.scheduler.cancel(_),this.triggerGracefulShutdown(_)},1000)}triggerGracefulShutdown(_){if(this.isShutdownTriggered)return;this.isShutdownTriggered=!0,this.stopRuntimeWatchdog(),this.events.emit("tick:time-exceeded",{queue:_,elapsedMs:this.clock.getElapsedTotalTime()}),this.events.emit("tick:cycle-completed",{queue:_,cycles:1})}stopRuntimeWatchdog(){if(this.watchdogTimer)clearInterval(this.watchdogTimer),this.watchdogTimer=null}clearTimer(_){let $=this.timers.get(_);if($)clearTimeout($);this.timers.delete(_)}forceExecuteTickLater(_,$){let K=`Extended time limit reached ${$}ms elapsed, overriding standard caps !`,L=()=>this.events.emit("tick:force-run",{queue:_,reason:K}),Z=$-Date.now();if(Z>2147483647)this.timers.set(_.queue,setTimeout(()=>{this.forceExecuteTickLater(_,$)},2147483647));this.timers.set(_.queue,setTimeout(()=>{L()},Math.max(0,Z)))}}class U{static store=new Map;kv={set:(_,$)=>{U.store.set(_,$)},get:(_)=>{return U.store.get(_)},has:(_)=>{return U.store.has(_)},delete:(_)=>{return U.store.delete(_)},clear:()=>{U.store.clear()}};lists={add:(_,$)=>{if(!U.store.has(_))U.store.set(_,new Set);let X=U.store.get(_);if(X instanceof Set)X.add($)},remove:(_,$)=>{let X=U.store.get(_);if(X instanceof Set)return X.delete($);return!1},get:(_)=>{let $=U.store.get(_);return $ instanceof Set?$:void 0},has:(_,$)=>{let X=U.store.get(_);if(X instanceof Set)return X.has($);return!1}}}var k=()=>new U;class n extends j{type="PERSISTENT";shouldShutdownOnCycleComplete=!1;minBootRequirementSec=1;deferredTickEvaluator;runtimeEventBridge;rs;constructor(_){super(_);this.deferredTickEvaluator=new w(this.minBootRequirementSec,this.scheduler,this.events,this.clock,this.logger),this.runtimeEventBridge=new r(this.storage,this.logger),this.rs=k()}async onStart(_){this.logger.log("Initialized Persistent Runtime.");let $=this.runtimeEventBridge;if(H.raw.runtime=="persistent")switch(H.raw.eventTriggerStrategy){case"POSTGRES_NOTIFY":await $.registerPgNotifyHandler(_);break;case"POLLING":await $.registerPollingHandler(_);break;case"WEBHOOK":this.logger.log("[Persistent Runtime] : Event Driven Queue triggers will heppen via webhook endpoint.");break}await this.executeQueuesTick(_.runTick)}async executeTick(_,$){this.deferredTickEvaluator.clearTimer(_.queue);let{isValid:X,reason:K}=this.validateTickRun(_);if(!X){this.logger.warn(`[Tick] : [${_.queue}] - Rejected, invalid tick run: ${K}. Please Reconnect Worker ASAP.`);return}await $()}validateTickRun({queue:_}){let $=H.raw.queues.find((X)=>X.queue===_);if(!$)return{isValid:!1,reason:`Queue configuration could not be found for '${_}'.`};if($.consumer.type==="socket"){let X=this.rs.lists.get(_);if(!X)return this.events.emit("tick:end",{queue:_,reason:"Socket consumer connection list does not exist"}),{isValid:!1,reason:`Socket consumer connection list does not exist for queue '${_}'.`};let K=Array.from(X.values());if(K.length==0)return this.events.emit("tick:end",{queue:_,reason:`Socket consumer has (${K.length}) active connections.`}),{isValid:!1,reason:`Socket consumer for queue '${_}' has (${K.length}) active connections.`}}return{isValid:!0,reason:"Tick run validation passed successfully."}}async scheduleTick(_,$){let{queue:X,concurrency:K,pooler:L}=_,Z=await this.queueService.getSingleQueueMetrics(X);if(!Z)return;if(Z?.total==0){if(L=="event-driven-pooler"){this.logger.log(`[Tick] : [${X}] - Tick Process Ended. Cycle Limit Reached`),this.events.emit("tick:cycle-completed",{queue:X,cycles:1});return}}let W=await this.storage.repository.getActiveWorkersCount(X),D=Math.max(0,K-W);this.deferredTickEvaluator.clearTimer(X),this.scheduler.scheduleNext({metrics:{queue:X,availableSlots:D,...Z},onNext:$,onUpcomingDelayedNext:(Y)=>{this.logger.log(`[Scheduler] : Next tick scheduled in ${(Y/1000).toFixed(2)}s`)},onFutureSchedule:async(Y)=>{let A=Y-Date.now();this.logger.log(`[Scheduler] : Deffered tick execution in ${(Math.max(0,A)/1000).toFixed(2)}s`),this.deferredTickEvaluator.forceExecuteTickLater(_,Y)}})}async handleCycleCompletion(){return!1}async handleRestart(){this.logger.log("[Persistent Runtime] : Restart triggered. Handled by process manager (PM2/systemd).")}}class a extends j{type="SERVERLESS_VM";shouldShutdownOnCycleComplete=!0;minBootRequirementSec=1;constructor(_){super(_);this.logger.log("Initialized Serverless VM Runtime.")}async onStart(_){await this.executeQueuesTick(_.runTick)}async executeTick(_,$){await $()}async scheduleTick(_,$){await $()}async handleCycleCompletion(_){let $=!1,X=!1,K=_.currentExecutionId,L=_.lockKey,Z=L?.startsWith("pulsar:lock:edp:"),W=L==="pulsar:lock:idp",D=Z?L?.replace("pulsar:lock:edp:",""):null;for(let{queue:Y,pooler:A}of _.getActiveQueues())try{if(A=="interval-driven-pooler"&&$)continue;if(Z&&Y!==D)continue;let V=await this.queueService.getSingleQueueMetrics(Y);if(!V||V.total===0){console.log(`[Pulsar] Failed to fetch metrics for ${Y}. Halting queue.`),_.endTick(Y);continue}let M=V.total;if(!await this.storage.repository.evaluateDeadRun(Y,A,M,K,15000)){console.log(`[Pulsar] Should not invoke for ${Y}. Skipping.`);continue}let Q=H.get("engine.selfInvocationIntervalSec")??1,P=await this.triggerSelfInvocation({queue:Y,pooler:A,delaySec:Q,continuationOwnerId:K,isIdpLock:W,isEdpLock:Z,targetEdpQueue:D});if(P.idpInvoked)$=!0;if(P.continuationScheduledForCurrentLock)X=!0}catch(V){console.log(`[deadRun] Error checking queue ${Y}:`,V)}return X}async handleRestart(_){}}class t extends j{deps;type="V8_ISOLATE";shouldShutdownOnCycleComplete=!0;minBootRequirementSec=5;deferredTickEvaluator;constructor(_){super(_);this.deps=_;this.logger.log("[EngineRuntime] : Initialized V8 Isolate Runtime."),this.deferredTickEvaluator=new w(this.minBootRequirementSec,this.scheduler,this.events,this.clock,this.logger)}async onStart(_){await this.executeQueuesTick(_.runTick)}async executeTick(_,$){let{queue:X}=_;this.deferredTickEvaluator.stopRuntimeWatchdog();let K=this.deps.clock.isSafeToContinue(),L=this.deps.events;if(!K){this.logger.log("[EngineRuntime] : Ending All Ticks due to time limit."),L.emit("tick:time-exceeded",{queue:X,elapsedMs:this.deps.clock.getElapsedTotalTime()}),L.emit("tick:cycle-completed",{queue:X,cycles:1});return}await this.deps.clock.trackExecutionTime({contextId:X},$)}async scheduleTick(_,$){let{queue:X,concurrency:K,pooler:L}=_,Z=await this.queueService.getSingleQueueMetrics(X);if(!Z)return;if(Z?.total==0){if(L=="event-driven-pooler"){this.logger.log(`[Tick] : [${X}] - Tick Process Ended. Cycle Limit Reached`),this.events.emit("tick:cycle-completed",{queue:X,cycles:1});return}}let W=await this.storage.repository.getActiveWorkersCount(X),D=Math.max(0,K-W),Y=async()=>{this.deferredTickEvaluator.stopRuntimeWatchdog(),await $()};this.scheduler.scheduleNext({metrics:{queue:X,availableSlots:D,...Z},onNext:Y,onUpcomingDelayedNext:(A)=>{return this.logger.log(`[Scheduler] : Next tick scheduled in ${(A/1000).toFixed(2)}s`),this.deferredTickEvaluator.evaluateUpcomingDelayedNext(A,X)},onFutureSchedule:async(A)=>{this.logger.log("[Scheduler] : scheduled tick execution request",A)}});return}async handleCycleCompletion(_){let $=!1,X=!1,K=_.currentExecutionId,L=_.lockKey,Z=L?.startsWith("pulsar:lock:edp:"),W=L==="pulsar:lock:idp",D=Z?L?.replace("pulsar:lock:edp:",""):null;for(let{queue:Y,pooler:A}of _.getActiveQueues())try{if(A=="interval-driven-pooler"&&$)continue;if(Z&&Y!==D)continue;let V=await this.queueService.getSingleQueueMetrics(Y);if(!V)continue;if(V.total===0)if(this.logger.log(`[Engine] : Queue ${Y} is empty (total: 0) using ${A} pooler. Halting tick.`),A=="event-driven-pooler"){_.endTick(Y);continue}else _.endTick(Y);let M=V.total;if(!await this.storage.repository.evaluateDeadRun(Y,A,M,K,15000)){this.logger.log(`[Engine] : Should not invoke for ${Y}. Skipping.`);continue}let Q=H.get("engine.selfInvocationIntervalSec")??1,P=H.get("runtime")=="v8-isolate",F=Q;if(P&&H.raw.isolate){let b=H.raw.isolate.remainingTime/1000,O=this.minBootRequirementSec,C=Q+O;if(b<C)return this.logger.log(`[EngineRuntime] : Isolate remaining time (${b.toFixed(3)}s) is insufficient for self-invocation (${Q}s delay + ${O}s min work). Triggering restart.`),await this.handleRestart(_),!0;let p=Math.max(1,b-O);F=Math.min(Q,p)}let N=await this.triggerSelfInvocation({queue:Y,pooler:A,delaySec:F,continuationOwnerId:K,isIdpLock:W,isEdpLock:Z,targetEdpQueue:D});if(N.idpInvoked)$=!0;if(N.continuationScheduledForCurrentLock)X=!0}catch(V){this.logger.log(`[deadRun] : Error checking queue ${Y}:`,V)}return X}async handleRestart(_){let $=!1,X=_.currentExecutionId,K=H.get("engine.selfRestartIntervalSec"),L=_.getActiveQueues();for(let{queue:Z,pooler:W}of L){if(W=="interval-driven-pooler"&&$)continue;let D={"content-type":"application/json","x-last-execution-id":X,"x-last-execution-at":new Date().toISOString(),"x-execution-owner":"engine","x-restart":"true","x-pooler":W,"x-target-queue":Z};if(this.logger.log(`(${W}) : invoking engine via restartTick (${K})`),W=="interval-driven-pooler")$=!0;let Y=_.lockKey;await this.storage.repository.releaseQueueLock(Y,_.isolateId),await this.storage.ops.addRestart(L),await this.queueService.triggerUrl({url:H.get("engine.selfURL"),headers:D,delaySeconds:K}),await this.storage.ops.updateRestartOwnership(Z,"handled_by_engine")}}}import{serve as g_}from"crossws/server";var V_=h_(A_(),1);var G_=V_.default;class e extends G_{config;serverInstance=null;logger;onFetch;constructor(_){super();this.config=_;this.logger=new G}async start(){let _=this;this.logger.log(`[Network] : Initializing server on port ${this.config.port} in [${this.config.mode}] mode`);let $=this.config.mode==="hybrid"||this.config.mode==="websocket";if($)this.logger.log(`[Network] : WebSocket server handlers attached on port ${this.config.port}`);this.serverInstance=g_({port:this.config.port,...$?{websocket:{open(X){_.emit("open",X)},message(X,K){_.emit("message",X,K)},close(X,K){_.emit("close",X,K)}}}:{},fetch(X){if(_.onFetch)return _.onFetch(X);return _.logger.warn(`[Network] : Unhandled route accessed: ${X.method} ${X.url}`),new Response(null,{status:404})},gracefulShutdown:!1,maxRequestBodySize:void 0}),await this.serverInstance.ready(),this.logger.log(`[Server] Successfully started and listening on port ${this.config.port}`)}async close(){try{await this.serverInstance?.close(!0)}catch(_){this.logger.error("[Network] : Error closing server:",_)}}}function __(_){return!!_&&typeof _.clone==="function"&&typeof _.text==="function"&&typeof _.url==="string"&&typeof _.headers?.get==="function"}function $_(_){let $={};if(!_)return $;if(typeof _.forEach==="function"&&typeof _.get==="function")return _.forEach((X,K)=>{$[String(K).toLowerCase()]=String(X)}),$;for(let[X,K]of Object.entries(_)){if(K==null)continue;$[X.toLowerCase()]=Array.isArray(K)?K.join(", "):String(K)}return $}function S(_){let $={};if(!_)return $;let X=(K,L)=>{if(L==null)return;$[K]=K in $?`${$[K]},${L}`:String(L)};if(typeof _.forEach==="function")_.forEach((K,L)=>X(L,K));else for(let[K,L]of Object.entries(_))X(K,Array.isArray(L)?L.join(","):L);return $}function Q_(_){let $=_.indexOf("?");return $===-1?{}:S(new URLSearchParams(_.slice($+1)))}function k_(_){let $=atob(_),X=Uint8Array.from($,(K)=>K.charCodeAt(0));return new TextDecoder().decode(X)}function E_(_){return new TextDecoder().decode(_)}async function x_(_){let $=new TextEncoder,X=[];for await(let W of _)X.push(typeof W==="string"?$.encode(W):W);let K=X.reduce((W,D)=>W+D.length,0),L=new Uint8Array(K),Z=0;for(let W of X)L.set(W,Z),Z+=W.length;return new TextDecoder().decode(L)}function f_(_,$){let X=$.toLowerCase();if(X.includes("json"))try{return JSON.parse(_)}catch{return _}if(X.includes("application/x-www-form-urlencoded"))return S(new URLSearchParams(_));if(!X){let K=_.trimStart();if(K.startsWith("{")||K.startsWith("["))try{return JSON.parse(_)}catch{}}return _}function X_(_,$,X=!1){if(_==null||_==="")return{body:null,rawBody:null};let K;if(typeof _==="string")K=X?k_(_):_;else if(_ instanceof ArrayBuffer||ArrayBuffer.isView(_))K=E_(_);else return{body:_,rawBody:null};return{body:f_(K,$),rawBody:K}}var z_=new Set(["GET","HEAD"]);async function J_(_){if(!_)throw Error("[YourSDK] No request object/event provided.");let $=_;if(!__($)&&__($.request))$=$.request;else if($.req&&$.req.headers&&!$.headers)$=$.req;if(__($)){let X=$.clone(),K=String(X.method||"GET").toUpperCase(),L=$_(X.headers),Z=null;if(!z_.has(K))try{Z=await X.text()}catch{Z=null}let{body:W,rawBody:D}=X_(Z,L["content-type"]||"");return{method:K,url:X.url,headers:L,query:S(new URL(X.url).searchParams),body:W,rawBody:D}}if($.requestContext||$.httpMethod||$.rawPath){let X=$_($.headers),K=String($.requestContext?.http?.method||$.httpMethod||"POST").toUpperCase(),L=$.rawPath||$.path||"/",Z=$.rawQueryString?`?${$.rawQueryString}`:"",W=X["x-forwarded-proto"]||"https",D=X.host||"lambda.local",Y=$.rawUrl||`${W}://${D}${L}${Z}`,A=$.queryStringParameters&&Object.keys($.queryStringParameters).length?S($.queryStringParameters):$.rawQueryString?Q_(`?${$.rawQueryString}`):{},{body:V,rawBody:M}=X_($.body,X["content-type"]||"",!!$.isBase64Encoded);return{method:K,url:Y,headers:X,query:A,body:V,rawBody:M}}if($.headers&&$.method){let X=$_($.headers),K=String($.method).toUpperCase(),L=$.originalUrl||$.url||"/",Z=L;if(!/^https?:\/\//i.test(L)){let V=X["x-forwarded-proto"]?.split(",")[0]?.trim()||$.protocol||($.socket?.encrypted?"https":"http"),M=X["x-forwarded-host"]||X.host||"localhost";Z=`${V}://${M}${L}`}let D=$.query&&Object.keys($.query).length>0?S($.query):Q_(Z),Y=$.body!==void 0?$.body:$.rawBody;if(Y===void 0&&!z_.has(K)&&typeof $[Symbol.asyncIterator]==="function")Y=await x_($);let A=X_(Y,X["content-type"]||"");if(A.rawBody===null&&$.rawBody!=null)A.rawBody=typeof $.rawBody==="string"?$.rawBody:E_($.rawBody);return{method:K,url:Z,headers:X,query:D,body:A.body,rawBody:A.rawBody}}throw Error("[YourSDK] Could not identify runtime payload type.")}class m{config;isRunning=!1;logger;rs;constructor(_){this.config=_;this.logger=new G,this.rs=k()}}class K_ extends m{networkConfig;networkInterface;storage;queueService;interface="HTTP";consumersMap;triggerHandler;constructor(_,$,X,K){super(_);this.networkConfig=_;this.networkInterface=$;this.storage=X;this.queueService=K;let L=H.get("queues"),Z=new Map;L.forEach(({consumer:W,queue:D})=>Z.set(D,W)),this.consumersMap=Z,this.networkInterface.onFetch=async(W)=>{return await this.handleFetch(W)}}async start(){}async broadcast(_,$){let X=this.consumersMap.get(_);if(!X)throw Error(`No consumer registered for queue: "${_}"`);if(X.type!=="http")return;let{worker_id:K,batch:L}=$;try{await fetch(X.url,{method:"POST",headers:{"content-type":"application/json",...X.headers,"x-worker-id":K,"x-batch-size":L.length.toString(),"x-pulsar-callback-url":H.get("engine.selfURL"),"x-test-mode":"SAFE","x-queue":_,"x-execution-signature":crypto.randomUUID()},body:JSON.stringify({worker_id:K,batch:L})})}catch(Z){this.logger.error("Error dispatching jobs to http consumer,",Z)}}getActiveConnections(_){return[]}onTrigger(_){this.triggerHandler=_}async stop(){}async handleFetch(_){let{url:$,method:X,body:K,headers:L}=await J_(_),Z=new URL($),W={headers:L,body:K};if(Z.pathname.endsWith("/ack")&&X==="POST"){let D=await this.handleAck(W);return new Response(D.message,{status:D.status})}if(Z.pathname.endsWith("/nack")&&X==="POST"){let D=await this.handleNack(W);return new Response(D.message,{status:D.status})}if(Z.pathname.endsWith("/retry")&&X==="POST"){let D=await this.handleRetry(W);return new Response(D.message,{status:D.status})}if(Z.pathname.endsWith("/deregister")&&X==="POST"){let D=await this.handleDeregister(W);return new Response(D.message,{status:D.status})}return new Response("HELLO MEWAOOOO",{status:200})}async performBatchAction(_,$,X,K){try{switch(K){case"ACK":await this.queueService.ackBatch(_,X);break;case"NACK":await this.queueService.ackBatch(_,X);break;case"RETRY":await this.queueService.retryBatch(_,X);break;case"DEREGISTER":await this.storage.repository.deregisterWorker($,_);break}}catch(L){throw this.logger.error(`Error performing batch action [${K}] for queue [${_}]:`,L),L}}parseBody(_){if(typeof _==="string")try{return JSON.parse(_)}catch($){throw Error(`Failed to parse request body: ${$.message}`)}return _}extractContext(_){let $=_.headers,X=this.parseBody(_.body),K=$["x-queue"],L=$["x-worker-id"]??"";if(!K)throw Error("[HttpNetworkDriver] Queue not found in headers");return{headers:$,body:X,queue:K,workerId:L}}async getMessageIds(_){let{queue:$,body:X,workerId:K}=this.extractContext(_),Z=(Array.isArray(X?.msg_ids)?X.msg_ids:[]).map((W)=>Number.parseInt(String(W),10)).filter((W)=>Number.isInteger(W)&&W>=0);return{queue:$,messageIds:Z,workerId:K}}async handleAck(_){let{messageIds:$,queue:X,workerId:K}=await this.getMessageIds(_);return await this.performBatchAction(X,K,$,"ACK"),{message:"Jobs Acknowledged",status:200}}async handleNack(_){let{messageIds:$,queue:X,workerId:K}=await this.getMessageIds(_);return await this.performBatchAction(X,K,$,"NACK"),{message:"Jobs Not Acknowledged",status:200}}async handleRetry(_){let{queue:$,workerId:X,messageIds:K}=await this.getMessageIds(_);return await this.performBatchAction($,X,K,"RETRY"),{message:"Jobs Retry Applied",status:200}}async handleDeregister(_){let{queue:$,workerId:X}=this.extractContext(_);if(!X)throw Error("[HttpNetworkDriver] Worker ID not found in headers");return await this.performBatchAction($,X,[],"DEREGISTER"),{message:"Worker Deregistered",status:200}}}class L_ extends m{networkInterface;interface="WEBSOCKET";queuePeers=new Map;triggerHandler;boundOpen=(_)=>this.onConnectionOpen(_);boundMessage=(_,$)=>this.onMessage(_,$);boundClose=(_)=>this.onConnectionClose(_);constructor(_,$){super(_);this.networkInterface=$;this.networkInterface.on("open",this.boundOpen),this.networkInterface.on("message",this.boundMessage),this.networkInterface.on("close",this.boundClose)}async start(){}async broadcast(_,$){let X=this.queuePeers.get(_);if(!X||X.size===0){this.logger.warn(`[Network] : No active workers listening on queue: ${_}`);return}let K=JSON.stringify($);for(let L of X)try{L.send(K)}catch(Z){this.logger.error(`[Network] : Failed to send message to peer ${L.id}:`,Z)}}getActiveConnections(_){let $=this.queuePeers.get(_);if(!$)return[];return Array.from($.values()).map((X)=>X.id)}onTrigger(_){this.triggerHandler=_}async stop(){this.networkInterface.off("open",this.boundOpen),this.networkInterface.off("message",this.boundMessage),this.networkInterface.off("close",this.boundClose);for(let _ of this.queuePeers.values())for(let $ of _)try{$.close(1001,"server shutting down")}catch{}this.queuePeers.clear()}onConnectionOpen(_){this.logger.log("[Network] : Worker connected:",_.id)}onMessage(_,$){let X=JSON.parse($.toString());X.type==="REGISTER"?this.handleWorkerRegistration(_,X):this.handleWorkerMessage(X)}handleWorkerRegistration(_,$){let X=this.queuePeers.get($.queue);if(!X)X=new Set,this.queuePeers.set($.queue,X);if(X.has(_)){this.logger.log(`[Network] : Worker ${_.id} is already registered to queue: ${$.queue}`);return}_.subscribe($.queue),X.add(_),this.rs.lists.add($.queue,_.id),this.logger.log(`[Network] : Worker ${_.id} registered to queue: ${$.queue}`)}handleWorkerMessage(_){if(this.triggerHandler){let $=_.queue,X=_.data!==void 0?_?.data:_;if($)this.triggerHandler($,X)}}onConnectionClose(_){this.logger.log("[Network] : [WebSocketNetworkDriver] - Worker disconnected:",_.id);for(let[$,X]of this.queuePeers.entries())if(X.has(_)){if(X.delete(_),this.rs.lists.remove($,_.id),X.size===0)this.queuePeers.delete($)}}}class f{config;storage;queueServuce;drivers=[];topology;networkInterface;isServerMode;constructor(_,$,X){this.config=_;this.storage=$;this.queueServuce=X;if(this.topology=_.mode,this.isServerMode=_.isServer,this.isServerMode)this.initializeTopology()}initializeTopology(){if(this.networkInterface=new e(this.config),this.config.mode==="websocket"||this.config.mode==="hybrid")this.drivers.push(new L_(this.config,this.networkInterface));if(this.config.mode==="http"||this.config.mode==="hybrid")this.drivers.push(new K_(this.config,this.networkInterface,this.storage,this.queueServuce))}async bootAll(){if(!this.isServerMode||!this.networkInterface)return;await this.networkInterface.start();for(let _ of this.drivers)await _.start()}async shutdownAll(){if(!this.isServerMode)return;for(let _ of this.drivers)await _.stop();await this.networkInterface?.close()}onTrigger(_){for(let $ of this.drivers)$.onTrigger(_)}async dispatchToNetwork(_,$){let X=H.get("queues").find((W)=>W.queue===_),K={http:"HTTP",socket:"WEBSOCKET"},L=X.consumer.type,Z=K[L];if(!Z)throw Error(`[DispatchToNetwork] : Unsupported consumer type "${L}" for queue: "${_}"`);for(let W of this.drivers)if(W.interface===Z)await W.broadcast(_,$)}}class Z_{engineUrl;consumersMap;constructor(_,$){this.engineUrl=$;let X=new Map;_.forEach((K)=>X.set(K.queue,K)),this.consumersMap=X}async dispatch(_,$,X){let K=this.consumersMap.get(_);if(!K)throw Error(`No consumer registered for queue: "${_}"`);if(K.type=="http")await fetch(K.url,{method:"POST",headers:{"content-type":"application/json",...K.headers,"x-worker-id":$,"x-batch-size":X.length.toString(),"x-pulsar-callback-url":this.engineUrl,"x-test-mode":"SAFE","x-queue":_,"x-execution-signature":crypto.randomUUID()},body:JSON.stringify({messages:X})}).catch((L)=>{console.log(`[${_}] Unbounded HTTP dispatch failed for worker ${$}:`,L)});else if(K.type=="socket");else K?.handler({queue:K.queue,payload:X,attempts:1,workerId:$,timestamp:new Date().getTime()})}}class W_{storage;tickService;tickController;unifiedTransportManager;dispatcher;swarmManager;scheduler;queueService;clock;events;queues=[];consumers=[];runtimeStrategy;logger;integrations=new Map;constructor(_){if(H.initialize(_),this.logger=new G,_.integrations?.length)this.runIntegrations(_.integrations);for(let{consumer:W,...D}of H.raw.queues)this.queues.push(D),this.consumers.push(W);let $=H.get("instanceId");if(!$)throw Error("[Pulsar] : instanceId is required.");if(typeof $!=="string"||!/^[a-zA-Z0-9_-]+$/.test($))throw Error('[Pulsar] : Invalid instanceId format. It must contain only alphanumeric characters, hyphens, and underscores (e.g., "string-like-this" or "or_this").');this.events=new v;let K=1/0,L=H.raw.runtime==="v8-isolate",Z=H.get("isolate");if(L)K=Math.max(0,Z.remainingTime-5000);if(this.storage=H.raw.storage,this.storage.connect(),this.storage.bindInstanceId($),this.clock=new l({maxExecutionBudgetMs:K,safetyBufferMs:0,maxTrackHistory:50,enabled:!0}),this.dispatcher=new Z_(this.consumers,H.get("engine.selfURL")),this.queueService=new d(this.storage),this.scheduler=new q,this.runtimeStrategy=this.resolveRuntimeStrategy(),!this.runtimeStrategy)throw this.logger.error("[Pulsar] Failed to resolve a valid runtime strategy."),Error("[Pulsar] Failed to resolve a valid runtime strategy.");if(H.raw.runtime=="persistent")this.unifiedTransportManager=new f({...H.raw.networkInterface,isServer:!0},this.storage,this.queueService);else this.unifiedTransportManager=new f({mode:"client",isServer:!1,port:0},this.storage,this.queueService);if(this.swarmManager=new c(H.raw.swarmConfig?.globalMaxJobsPerTick??1/0,H.raw.swarmConfig?.maxGlobalConcurrency??1/0),this.tickService=new s({dispatcher:this.dispatcher,queue:this.queueService,storage:this.storage,swarmManager:this.swarmManager,unifiedTransportManager:this.unifiedTransportManager,events:this.events}),this.tickController=new o({scheduler:this.scheduler,storage:this.storage,tickService:this.tickService,clock:this.clock,events:this.events,runtimeStrategy:this.runtimeStrategy}),Number.isFinite(K))this.logger.log(`[EngineRuntime] : isolate registred with id : [${Z.id}]`),this.logger.log(`[Clock] : Synced execution timeout (${K/1000}s) with isolate [${Z.id}]`);else this.logger.log(`[EngineRuntime] : Engine Started With No V8 Isolate (${new Date().toISOString()})`)}resolveRuntimeStrategy(){let _={queueService:this.queueService,clock:this.clock,queues:this.queues,storage:this.storage,isolate:this.V8Isolate,events:this.events,scheduler:this.scheduler};switch(H.get("runtime")){case"persistent":return new n(_);case"serverless-vm":return new a(_);case"v8-isolate":return new t(_);default:throw Error("Unsupported Runtime")}}async runIntegrations(_){for(let $ of _){let X;if(typeof $==="function")X=new $("ALL");else X=$;await X.main(this),this.integrations.set(X.module,X)}}getIntegration(_){if(typeof _==="string")return this.integrations.get(_);for(let X of this.integrations.values())if(X instanceof _)return X;let $=typeof _==="string"?_:_.name;throw Error(`Integration "${$}" is not registered.`)}get runtime(){return this.runtimeStrategy.type}get isV8Isolate(){return H.get("runtime")==="v8-isolate"}get V8Isolate(){return H.raw.isolate}async exit(){await this.storage.disconnect()}}class U_ extends W_{baseConfig;isolateId;currentExecutionId;lockKey;shutdownPromise=null;eventCleanUps=[];activeQueues=new Set;constructor(_){super(_);this.baseConfig=_;if(this.registerEvents(),!this.isV8Isolate)this.isolateId=crypto.randomUUID();else this.isolateId=this.V8Isolate.id;if(this.isV8Isolate)this.currentExecutionId=this.V8Isolate.get("current_execution_id"),this.lockKey=this.V8Isolate.get("lock_key");else this.currentExecutionId=this.generateCurrentExecutionIdFromConfig(),this.lockKey="lock-template-static-defination-for-non-v8";this.tickController.initializeState()}async start(){await this.unifiedTransportManager.bootAll(),await H.reconcileConfiguration(this.storage.ops),this.tickController.initializeState(),this.configureQueueProfiles(),await this.runtimeStrategy.onStart(this.executionContext)}async triggerQueue(_){let $=this.queues.find((X)=>X.queue===_);if(!$)throw Error("[Pulsar] Target queue is missing.");this.logger.log(`[Pulsar] : Event-driven trigger for (${_})`),await this.validateConfiguration(),await this.runTick($)}async validateConfiguration(){return{status:200,message:await H.reconcileConfiguration(this.storage.ops)}}configureQueueProfiles(){for(let _ of this.queues){let $=_.profile||"REALTIME";this.scheduler.registerQueueProfile(_.queue,$)}}async runTick(_){return this.activeQueues.add(_),await this.tickController.runTick(_)}async shutdown(){if(this.logger.log("Engine Shutdown ⚠️."),this.removeRegisteredEvents(),this.unifiedTransportManager)await this.unifiedTransportManager.shutdownAll();if(!await this.runtimeStrategy.handleCycleCompletion(this.executionContext))await this.releaseExecutionLock(this.lockKey,this.currentExecutionId);await this.storage.ops.pingHealthCheck(),await this.storage.disconnect()}async scheduleRestart(_){if(_){let X=this.queues.find((K)=>K.queue==_);if(X)this.activeQueues.add(X)}let $=Array.from(this.activeQueues.values());await this.releaseExecutionLock(this.lockKey,this.isolateId),await this.storage.ops.addRestart($),await this.runtimeStrategy.handleRestart(this.executionContext),await this.storage.ops.updateRestartOwnership(_,"handled_by_engine")}async restartForSameIsolate(_){let $=30;if(this.isV8Isolate)$=this.V8Isolate.remainingTime+5;this.logger.log(`Estimated Restart in (${$})S`),await this.queueService.triggerUrl({url:H.get("engine.selfURL"),headers:_,delaySeconds:$})}get executionContext(){return{lockKey:this.lockKey,currentExecutionId:this.currentExecutionId,isolateId:this.isolateId,getActiveQueues:()=>Array.from(this.activeQueues.values()),runTick:(_)=>this.runTick(_),endTick:(_)=>this.tickController.endTick(_)}}setCurrentExecutionId(_){this.currentExecutionId=_}generateCurrentExecutionIdFromConfig(){let _=this.baseConfig.queues.map(($)=>`${$.queue}:${$.pooler}`).join(",");return C_(_)}registerEvents(){let _=this.runtimeStrategy.shouldShutdownOnCycleComplete;this.eventCleanUps.push(this.events.on("tick:cycle-completed",async()=>{if(_)await this.shutdown();else this.logger.log("[Pulsar Persistent] : Cycle completed. Resetting state for next execution round."),this.tickController.initializeState()})),this.eventCleanUps.push(this.events.on("tick:force-run",async({queue:$,reason:X})=>{this.logger.log(`[Tick] : Force executing tick for queue [${$.queue}] Trigger Reason: ${X}`),await this.runTick($)})),this.eventCleanUps.push(this.events.on("tick:end",({queue:$,reason:X})=>{this.logger.log(`[Tick] : Force stoping tick for queue [${$}] (Trigger Reason: ${X})`),this.tickController.endTick($)})),this.eventCleanUps.push(this.events.on("tick:time-exceeded",async()=>{if(_)await this.shutdown()})),this.eventCleanUps.push(this.events.on("engine:health-check-requested",async()=>{this.logger.log(`Pulsar : Health checking ping at (${new Date().toISOString()})`),await this.storage.ops.pingHealthCheck()}))}removeRegisteredEvents(){this.eventCleanUps.forEach((_)=>_()),this.eventCleanUps=[]}async awaitPendingShutdown(){if(this.shutdownPromise)await this.shutdownPromise}async deleteScheduledRestart(_){await this.storage.ops.deleteRestart(_)}async acquireExecutionLock(_,$,X){return await this.storage.repository.acquireQueueLock(_,$,X)}async releaseExecutionLock(_,$){return await this.storage.repository.releaseQueueLock(_,$)}}export{y_ as createQueue,h as PulsarRuntime,U_ as Pulsar,D_ as IsolateInstance,g as EventTriggerStrategy};
46
46
 
47
- //# debugId=9CEEB9B5A8D57B8964756E2164756E21
47
+ //# debugId=A9FB2A83A3509ED164756E2164756E21