UNPKG

hud-sdk

Version:

Hud's Node SDK

2 lines 33.2 kB
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},2546:e=>{e.exports=require("./lib")},2702:function(e,t,n){var i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),s=0;s<n.length;s++)"default"!==n[s]&&o(t,e,n[s]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const a=s(n(523)),c=n(8528),d=a.app_logger;t.WorkerKeepaliveGuard=class{worker;keepaliveGrace;timeoutId=void 0;eventHandler=this.keepalive.bind(this);constructor(e,t){this.worker=e,this.keepaliveGrace=t}keepalive(e){try{if(e.msg!==c.KeepAliveMessage.msg)return;this._restartTimeout()}catch(e){d.error("Error in keepalive",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_restartTimeout(){const e=setTimeout(()=>{},this.keepaliveGrace);clearTimeout(this.timeoutId),this.timeoutId=e}start(){this.stop(),this.worker.on("message",this.eventHandler).unref()}stop(){void 0!==this.timeoutId&&clearTimeout(this.timeoutId),this.worker.off("message",this.eventHandler),this.timeoutId=void 0}}},4672:e=>{e.exports=require("./client")},5119:function(e,t,n){var i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),s=0;s<n.length;s++)"default"!==n[s]&&o(t,e,n[s]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.tryFlushPendingLogs=t.init=void 0;const a=s(n(6281));t.init=a.default,Object.defineProperty(t,"tryFlushPendingLogs",{enumerable:!0,get:function(){return a.tryFlushPendingLogs}})},5809:e=>{e.exports=require("./config")},5994:function(e,t,n){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainThread=void 0;const o=n(8167),r=n(2546),s=n(5809),a=n(8269),c=n(523),d=n(7274),g=n(6281),l=i(n(7320));function u(){globalThis.hudInstrumentationOccured&&c.customer_logger.logEntry(r.UserErrorLogs.YesInstrumentationNoMetrics())}t.MainThread=class{apiKey;service;startTime;tags;messenger;constructor(e,t,n,i){this.apiKey=e,this.service=t,this.startTime=n,this.tags=i,(0,a.storeCredentials)(e,t)}startFailed(e){e instanceof r.HudSessionThrottle?(c.customer_logger.logEntry(r.UserLogs.InitIdleMode()),(0,g._detachAndTerminate)(!1,!1,!0)):e instanceof r.HudInitNetworkError&&e.originalAxiosErrorCode?(c.customer_logger.logEntry((0,r.getNetworkError)(e.originalAxiosErrorCode)),c.app_logger.critical("Failed to start worker because of network error",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,g._detachAndTerminate)(!1,!1,!0)):(c.app_logger.critical("Failed to start worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,r.setFirstError)(e.code),(0,g._detachAndTerminate)(!0,!1,!0))}async _registerLambdaExtension(){const e=await(0,r.register)();return(0,a.setLambdaExtensionId)(e),e}async startMessenger(e){try{this.messenger=await this._createMessenger(e),await this._start(),c.customer_logger.logEntry(r.UserLogs.HudInitSuccess())}catch(e){throw this.startFailed(e),e}}async start(){if(o.isMainThread)if(globalThis.hudRuningInsideLambda)try{const e=await this._registerLambdaExtension();c.app_logger.info("Lambda extension registered, not waiting for worker to start",{lambdaExtensionId:e}),(0,r.next)(e).then(async()=>{c.app_logger.info("Lambda got first event, creating messenger");try{await this.startMessenger(e)}catch{}}).catch(e=>{c.app_logger.error("Failed to send first event to lambda",{msg:e instanceof Error?e.message:void 0}),this.startFailed(e)})}catch(e){throw this.startFailed(e),e}else await this.startMessenger(void 0)}async _start(){if(!this.messenger)throw new r.HudInitError("Messenger not initialized");try{const e=await this.messenger.checkWorkerInitialized(s.hudConfig.workerTimeout),t=e?.content?.sessionInfo;if(t&&(0,a.storeSessionInfo)(t),await this._initDynamicConfig(),s.hudConfig.dynamicConfig.functionDetachEnabled&&!s.hudConfig.userConfig.disableDetachedFunctions?.value){const e=await(this.messenger?.getKnownDetachedFunctions(!0));e&&(0,d.applyKnownDetachedFunctions)(e)}globalThis.hudMetricsIndicator=setTimeout(u,s.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof r.HudSessionThrottle)throw e;throw c.app_logger.critical("Failed to start worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(e){const t=r.myRequire.resolve(`${s.SDK_MODULE_NAME}/worker`),n={...process.env};delete n.NODE_OPTIONS;const i=new o.Worker(t,{workerData:{apiKey:this.apiKey,service:this.service,startTime:this.startTime,tags:this.tags,lambdaExtensionId:e,shouldCreateDeclaraionWorker:!!e,userConfig:s.hudConfig.userConfig},execArgv:[],env:n});let a;try{a=new l.default(i),await a.checkWorker(s.hudConfig.workerTimeout)}catch(e){if(e instanceof r.HudSessionThrottle)throw c.app_logger.info("Worker started in idle mode - session throttled"),e;throw c.app_logger.critical("Worker failed to start",{msg:e instanceof Error?e.message:void 0}),e}finally{i.unref()}return a}async _initDynamicConfig(){const e=await(this.messenger?.getRemoteConfig());e?(c.app_logger.info("Remote configuration exists"),s.hudConfig.dynamicConfig=(0,s.updateDynamicConfig)(e,s.hudConfig,c.app_logger),(0,s.updateInvestigationRateLimitGlobals)(),c.app_logger.info("Current dynamic configuration:",{currentDynamicConfig:s.hudConfig.dynamicConfig})):c.app_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:s.hudConfig.dynamicConfig})}async terminateMessenger(){await(this.messenger?.terminateWorker()),this.messenger?.stop(),this.messenger=void 0}}},6261:e=>{e.exports=require("events")},6281:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,n){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void o.app_logger.warning("Already ran init!");globalThis.hudRunMutex=!0,(0,c.clearInitGuard)(),(0,i.updateUserConfigFromInit)(e,t,n);const g=(0,c.validateAndGetUserInput)();if(!g)return;if(globalThis.hudRunningMode!==a.HudRunningMode.enabled)return void o.app_logger.critical("SDK running mode is not enabled - initialization aborted");if(o.app_logger.info("Initializing hud",{userConfig:Object.entries(s.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),l=new r.MainThread(g.apiKey,g.service,globalThis.hudStartTime,s.hudConfig.userConfig.tags?.value),await l.start(),l.messenger&&(0,d.safeCall)(o.app_logger,l.messenger.handleLogsTask()),globalThis.hudImportStartTime){const e=process.uptime()-globalThis.hudImportStartTime;o.app_logger.info("Hud initialized",{importTime:e,startTime:globalThis.hudImportStartTime})}}catch(e){try{if(e instanceof d.HudSessionThrottle)return;o.app_logger.critical("Something went wrong in init",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}catch{o.app_logger.critical("Something went wrong in init & e.stack raised an exception")}h(!0,!1,!0)}},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},t._detachAndTerminate=h,t.flushLogs=f,t.tryFlushPendingLogs=async function(e,t){(0,c.getShouldFlushOnInit)()&&((0,c.markShouldFlushOnInit)(!1),await f(e,t))};const i=n(2546),o=n(523),r=n(5994),s=n(5809),a=n(8528),c=n(8269),d=n(2546),g=n(7274);let l,u=!1;function h(e=!0,t=!1,n=!1){(0,c.detachHud)(e,t),n&&(0,d.safeCall)(o.app_logger,f()),l&&(0,d.safeCall)(o.app_logger,l.terminateMessenger());const r=(0,c.getLambdaExtensionId)();r&&!u&&(u=!0,(0,d.safeCall)(o.app_logger,(0,i.nextLoopDummy)(r))),(0,c.clearUserIndicatorsTimeouts)(),(0,g.resetCallers)()}async function f(e,t){const i=(0,c.getSessionInfo)(),r=(0,c.getStoredApiKey)(),s=(0,c.getStoredService)();try{const a=e||r;if(!a||"string"!=typeof a)return;const c=t||s||"unknown",d=(0,o.getSavedLogs)();for(const e of d){const{HudClient:t}=n(4672),r=new t;i?(o.app_logger.info("Flushing logs with session",{size:e.length,sessionId:i.sessionId,service:c}),r.setSession(i),await r.logs(e)):(o.app_logger.info("Flushing logs (sessionless)",{size:e.length,service:c}),await r.sessionslessLogs(e,a)),o.app_logger.info("Successfully flushed logs")}}catch(e){try{o.app_logger.error("Failed to flush logs",{msg:e instanceof Error?e.message:void 0,hasSession:null!==i})}catch{}}}},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._setLastPrepCallsTimestamp=c,t._liftExceptions=g,t.prepCalls=function(e,t){let n=null;if(i.hudConfig.dynamicConfig.functionDetachEnabled&&!i.hudConfig.userConfig.disableDetachedFunctions?.value){const e=process.hrtime.bigint();let t;t=null===a?i.hudConfig.dynamicConfig.aggregationInterval:Number(e-a)/1e6,c(e),n=i.hudConfig.dynamicConfig.functionDetachThresholdPerSecond*(t/1e3)}const d=(new Date).toISOString(),l=[];return Object.entries(hudCalls).map(([o,a])=>{const c=a.shouldDetach;let u=0;var h;Object.entries(a).forEach(([n,s])=>{"shouldDetach"!==n&&Object.entries(s).forEach(([s,a])=>{try{if(!i.hudConfig.dynamicConfig.functionDetachEnabled||i.hudConfig.userConfig.disableDetachedFunctions?.value||c||(u+=a.count),0===a.sampledCount)return;const r={function_id:o,wrapped_flow_id:s||void 0,wrapped_caller_id:n||void 0,timestamp:d,timeslice:e,exceptions:g(a.exceptions),count:a.count,sampled_count:a.sampledCount,sum_duration:a.sum,sum_squared_duration:a.squareSum,sketch:a.sketch?t.encode(a.sketch):void 0,is_linked_function:a.isLinkedFunction};l.push(r),function(e){e.count=0,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(a)}catch(e){r.app_logger.error("Failed preparing invocation, skipping",{func:o,wrappedCaller:n,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})}),i.hudConfig.dynamicConfig.functionDetachEnabled&&!i.hudConfig.userConfig.disableDetachedFunctions?.value&&null!==n&&u>n&&(hudCalls[o].shouldDetach=!0,h=o,s.push(h),r.app_logger.info("Detaching function",{func:o,totalFunctionCalls:u}))}),l.length>0&&(0,o.clearMetricsIndicator)(),l},t.resetCallers=function(){for(const e in globalThis.hudCalls)for(const t in globalThis.hudCalls[e])if("shouldDetach"!==t)for(const n in globalThis.hudCalls[e][t])d(globalThis.hudCalls[e][t][n])},t.getAndClearDetachedFunctions=function(){const e=s;return s=[],e},t.applyKnownDetachedFunctions=function(e){if(e&&0!==e.length&&!i.hudConfig.userConfig.disableDetachedFunctions?.value){l!==e.length&&(r.app_logger.info("Applying known detached functions from host",{count:e.length}),l=e.length);for(const t of e)try{globalThis.hudCalls[t]?globalThis.hudCalls[t].shouldDetach=!0:globalThis.hudCalls[t]={shouldDetach:!0}}catch(e){r.app_logger.error("Failed to apply detached function, skipping",{rawFunctionId:t,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}};const i=n(5809),o=n(8269),r=n(523);let s=[],a=null;function c(e){a=e}function d(e){e.samplingCounter=0}function g(e){const t={};for(const n in e)t[n]=[{count:e[n]}];return t}let l=0},7320:function(e,t,n){var i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),s=0;s<n.length;s++)"default"!==n[s]&&o(t,e,n[s]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=s(n(523)),c=s(n(6460)),d=n(5809),g=n(2546),l=n(8528),u=n(2546),h=n(7131),f=n(8269),m=n(2546),p=n(7274),v=n(2702),y=n(8269),w=n(2546),C=n(6281),k=n(8269),b=n(2546),E=n(6261),_=a.app_logger,T=m.safeCall.bind(m.safeCall,_);t.default=class{worker;tsNodeUpdated=!1;staticNextJsEndpointsSent=!1;abortController;workerKeepaliveGuard;messageQueue=[];MAX_QUEUE_SIZE=100;messageEmitter=new E.EventEmitter;constructor(e){this.worker=e,this.abortController=new AbortController,(0,E.setMaxListeners)(25,this.abortController.signal);let t=!1;this.worker.on("message",e=>{e.msg!==l.KeepAliveMessage.msg&&(this.messageQueue.length>=this.MAX_QUEUE_SIZE&&(t||(t=!0,_.error("Message queue is at max size, dropping oldest message",{msg:e.msg})),this.messageQueue.shift()),this.messageQueue.push(e),this.messageEmitter.emit("message",e))}).unref(),this.worker.on("error",this.handleWorkerError).unref(),this.workerKeepaliveGuard=new v.WorkerKeepaliveGuard(e,d.hudConfig.communicationKeepaliveGrace),this._updateTsNodeConfig()&&_.info("ts-node config updated from Messenger constructor")}handleWorkerError=e=>{try{e?.code===(new m.HudClientUnauthorizedError).code&&a.customer_logger.logEntry(m.UserErrorLogs.ApiKeyDenied(d.hudConfig.userConfig.key?.source)),_.critical("Error from worker, stopping hud",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,m.setFirstError)(e?.code),this.stop(),(0,C._detachAndTerminate)(!0,!1,!0)}catch(e){_.critical("Error stopping hud after worker crash",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};stop(){this.abortWorker(),d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.abortController.abort(),this.abortController=new AbortController,this.messageQueue=[],this.messageEmitter.removeAllListeners(),(0,f.resetGlobals)()}abortWorker(){this._sendObject("Abort",{})}async restart(e){this.stop(),globalThis.hudRunningMode=e,await this.start()}_sendArray(e,t){t.length>0&&(this._sendObject(e,t),_.debug("sent data to worker",{msg:e,size:t.length}))}_sendObject(e,t){const n={msg:e,content:t};this.worker.postMessage(n)}async checkWorker(e){const t=["started"];let n;try{n=await this.getMessageFromWorker(t,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;n=await this.getMessageFromWorker(t,e/2,!1)}if(!n)throw new m.HudInitError("Worker not started");return n}async checkWorkerInitialized(e){let t;const n=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(n,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;t=await this.getMessageFromWorker(n,e/10,!1)}if("throttled"===t?.msg)throw new m.HudSessionThrottle;if("networkError"===t?.msg)throw _.error("networkError",{error:t.content.error}),new m.HudInitNetworkError(t.content.message,t.content.originalMessage);if(!t||"initialized"!==t?.msg||void 0===t?.content)throw new m.HudInitError("Worker not initialized successfully");if(t?.content.status!==l.HudSessionInitStatus.success)throw new m.HudInitError("Worker not initialized successfully");return t}async start(){switch(d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.start(),globalThis.hudRunningMode){case l.HudRunningMode.enabled:_.info("Enabled mode"),T(this.getMode()),T(this.periodicGetEndpointsDurationsInvestigationThresholds()),T(this.startPeriodicTasks()),T(this.periodicSendMetrics()),T(this.periodicSendDetachedFunctions()),T(this.periodicFetchKnownDetachedFunctions()),T(this.highFrequencySendInvestigations()),T(this.periodicSendProcessedFiles()),T(this.delayedStateCollection()),T(this.periodicSendEndpoints()),T(this.periodicSendOutbounds()),T(this.periodicSendLazyEndpoints()),T(this.periodicSendKafkaJS()),T(this.periodicSendSqs()),T(this.periodicSendGraphQL()),T(this.sendStaticNextJsEndpointsOnce()),T(this.periodicSaveMachineMetrics()),T(this.periodicSendReingest()),T(this.resetCallerCounters()),T(this.periodicResetGlobalInvestigationCounter()),T(this.periodicResetInvestigationDedupingCache()),T(this.sendLogsPeriodically(d.hudConfig.logsSendInterval)),T(this.sendRuntime()),T(this.sendPatchedModules()),T(this.sendPreloadedModules()),T(this.dumpModulesAfterWhile(6e4)),T(this.periodicSendThreadPerformanceMetrics());break;case l.HudRunningMode.disabled:_.info("Disabled mode"),T(this.getMode());break;case l.HudRunningMode.detached:_.info("Detached"),(0,C._detachAndTerminate)(!1,!1),this.stop();break;default:_.error("Running mode not handled")}}consumeMessageFromQueue(e){const t=this.messageQueue.findIndex(t=>e.includes(t.msg));if(-1!==t)return this.messageQueue.splice(t,1)[0]}async getMessageFromWorker(e,t,n=!1,i){let o;e=Array.isArray(e)?e:[e];const r=this.consumeMessageFromQueue(e);if(r)return _.info("Found message in queue",{msg:r.msg}),r;const s=new AbortController,a=()=>{s.abort()};this.abortController.signal.addEventListener("abort",a);const d=c.setTimeout(t,void 0,{signal:s.signal,ref:n}),g=t=>{try{e.includes(t.msg)&&(o=t,s.abort(),this.consumeMessageFromQueue([t.msg]),_.info("Received message from worker (canceling timeout)",t))}catch(e){_.error("Failed handling message from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};this.messageEmitter.on("message",g),i&&this.worker.postMessage(i);try{throw await d,_.warning("Timeout waiting for message from worker"),new m.HudTimeoutError}catch(e){if(!(0,m.isAbortError)(e))throw(0,m.setFirstError)(e.code),e}finally{this.abortController.signal.removeEventListener("abort",a),this.messageEmitter.off("message",g)}return o}async getMode(){for await(const e of(0,u.unrefSetInterval)(d.hudConfig.modeInterval,void 0,{signal:this.abortController.signal}))try{const e={msg:"GetMode",content:{startTime:globalThis.hudStartTime,runningMode:globalThis.hudRunningMode}},t=await this.getMessageFromWorker(e.msg,d.hudConfig.workerMessageTimeout,!1,e);if(t?.msg!==e.msg||void 0===t?.content.mode){_.error("Unexpected message from worker",t);continue}t.content.mode!==globalThis.hudRunningMode&&await this.restart(t?.content.mode)}catch(e){_.error("Failed getting mode from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async getRemoteConfig(){const e="initDynamicConfig";try{const t=await this.getMessageFromWorker(e,d.hudConfig.workerMessageTimeout,!0);if(t?.msg!==e||void 0===t?.content)throw new Error(`Unexpected message from worker: ${t}`);return t?.content}catch(e){_.error("Failed getting remote configuration from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async getKnownDetachedFunctions(e=!1){const t="KnownDetachedFunctions",n={msg:"GetKnownDetachedFunctions",content:{}};try{const i=await this.getMessageFromWorker(t,d.hudConfig.workerMessageTimeout,e,n);if(i?.msg!==t||void 0===i?.content)throw new Error(`Unexpected message from worker: ${i}`);return i?.content}catch(e){return _.error("Failed getting known detached functions from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),[]}}async periodicSaveMachineMetrics(){(0,f.saveMachineMetric)();for await(const e of(0,u.unrefSetInterval)(d.hudConfig.dynamicConfig.machineMetricsInterval,void 0,{signal:this.abortController.signal}))(0,f.saveMachineMetric)()}async resetCallerCounters(){const e=d.hudConfig.callerResetInterval;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{_.info("Resetting caller",{interval:e}),(0,p.resetCallers)()}catch(e){_.error("Failed reseting caller counters",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async updateEndpointDurationsInvestigationThresholds(){const e={msg:"EndpointsDurationsInvestigationThresholds"},t="EndpointsDurationsInvestigationThresholds";try{const n=await this.getMessageFromWorker(t,d.hudConfig.workerMessageTimeout,!1,e);if(n?.msg!==t||void 0===n?.content)throw new Error(`Unexpected message from worker: ${n}`);(0,f.setInvestigationDurationThresholds)(n?.content),_.debug("Endpoints durations investigation thresholds updated",{thresholds:n?.content})}catch(e){_.error("Failed getting endpoints durations investigation thresholds from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicGetEndpointsDurationsInvestigationThresholds(){await this.updateEndpointDurationsInvestigationThresholds();for await(const e of(0,u.unrefSetInterval)(d.hudConfig.endpointsDurationsInvestigationThresholdsInterval,void 0,{signal:this.abortController.signal}))await this.updateEndpointDurationsInvestigationThresholds()}async delayedStateCollection(){await this.setupPeriodicTask(0,d.hudConfig.workerStateCollectionDelay,()=>{try{this._updateTsNodeConfig()&&_.info("ts-node config updated from delayed task")}catch(e){_.error("Failed collecting state from delayed task",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"delayedStateCollecgtion",!0)}async periodicSendProcessedFiles(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=function(){const e=globalThis.hudProcessedFiles;return globalThis.hudProcessedFiles=[],e}();return this._sendArray("ProcessedFiles",e),!0},"periodicSendProcessedFiles")}async periodicSendKafkaJS(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,y.getKafkaJSTopics)();return this._sendArray("KafkaJSTopics",e),!0},"periodicSendKafkaJS")}async periodicSendSqs(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,y.getSqsQueues)();return e.length>0&&this._sendArray("SqsQueue",e),!0},"periodicSendSqs")}async periodicSendGraphQL(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=Object.values((0,y.getGraphQLOperations)());return e.length>0&&this._sendArray("GraphQLDeclaration",e),!0},"periodicSendGraphQL")}async periodicSendMetrics(){const e=new h.SketchManager(d.hudConfig.huddBinWidth),t=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,n=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,n,t=>{try{this.refreshInvestigations()}catch(e){_.error("Failed sending investigations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const n=(0,p.prepCalls)(t,e);n.length>0&&this._sendArray("Invocations",n)}catch(e){_.error("Failed sending invocations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const e=(0,f.getFlowMetrics)(t);Object.keys(e).length>0&&this._sendObject("FlowMetrics",{aggregatedMetrics:e})}catch(e){_.error("Failed sending flow metrics",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendMetrics")}async periodicSendDetachedFunctions(){if(!d.hudConfig.dynamicConfig.functionDetachEnabled||d.hudConfig.userConfig.disableDetachedFunctions?.value)return;const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{try{const e=(0,p.getAndClearDetachedFunctions)();e.length>0&&this._sendArray("DetachedFunctions",e)}catch(e){_.error("Failed sending detached functions",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendDetachedFunctions")}async fetchKnownDetachedFunctions(){try{const e=await this.getKnownDetachedFunctions();e&&e.length>0&&(0,p.applyKnownDetachedFunctions)(e)}catch(e){_.error("Failed fetching known detached functions",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicFetchKnownDetachedFunctions(){if(d.hudConfig.dynamicConfig.functionDetachEnabled&&!d.hudConfig.userConfig.disableDetachedFunctions?.value)for await(const e of(0,u.unrefSetInterval)(d.hudConfig.dynamicConfig.aggregationInterval,void 0,{signal:this.abortController.signal}))await this.fetchKnownDetachedFunctions()}async highFrequencySendInvestigations(){if(!d.hudConfig.dynamicConfig.enableInvestigation)return;const e=d.hudConfig.dynamicConfig.investigationFirstSendTimeout,t=d.hudConfig.dynamicConfig.investigationInterval;await this.setupPeriodicTask(e,t,()=>(this.refreshInvestigations(),!0),"highFrequencySendInvestigations")}refreshInvestigations(){const e=(0,y.getClosedInvestigations)();e.length>0&&this._sendArray("Investigations",e)}async periodicSendEndpoints(){const e=d.hudConfig.endpointsFirstSendWaitTime,t=d.hudConfig.endpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendEndpoints(),!0),"periodicSendEndpoints")}async periodicSendOutbounds(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendOutbounds(),!0),"periodicSendOutbounds")}async periodicSendLazyEndpoints(){const e=d.hudConfig.endpointsFirstSendWaitTime,t=d.hudConfig.lazyEndpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendLazyEndpoints(),!0),"periodicSendLazyEndpoints")}sendLazyEndpoints(){const e=(0,y.getExpressEndpointDeclarations)().map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",e)}sendEndpoints(){const e=(0,f.getEndpointDeclarationsFromStorage)().map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",e)}sendOutbounds(){const e=(0,k.getLoadedOutboundsFromStorage)();e.length>0&&this._sendArray("LoadedOutbounds",e);const t=(0,k.getIoredisCommandsFromStorage)();t.length>0&&this._sendArray("IoredisCommands",t)}async terminateWorker(){try{const e=a.getSavedLogs();await this.getMessageFromWorker("terminated",d.hudConfig.workerGrace,!1,{msg:"Terminate",content:{grace:d.hudConfig.workerGrace,logBuffers:e}})}catch(e){if(!(e instanceof m.HudTimeoutError))throw _.critical("Unexpected error during worker termination",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),await this.worker.terminate(),e;_.critical("Grace period timeout - terminating worker",{error:e.message}),await this.worker.terminate()}_.info("Worker terminated successfully.")}async sendRuntime(){const e={nodeVersion:process.version,nodeDependencyVersions:process.versions,platform:process.platform,architecture:process.arch,pid:process.pid,cwd:process.cwd(),execPath:process.execPath,execArgv:process.execArgv,argv:process.argv,uptime:process.uptime(),mainModulePath:n.c[n.s]?.filename};this._sendObject("Runtime",e)}async startPeriodicTasks(){this._sendObject("StartPeriodicTasks",{})}async sendPreloadedModules(){globalThis.hudLoadedModules?this._sendObject("PreInitLoadedModules",{modules:globalThis.hudLoadedModules}):_.warning("Didn't get module, weird....")}async periodicSendThreadPerformanceMetrics(){const e=d.hudConfig.dynamicConfig.performanceMetricsInterval,t=(0,g.createThreadStatsBaseline)();for await(const n of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){const e=(0,m.collectThreadPerformance)(t,_,"MainThread");e&&this._sendObject("PerformanceMetrics",e)}}async dumpModulesAfterWhile(e){await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(w.myRequire.cache);this._sendObject("PostInitLoadedModules",{modules:t})}async sendPatchedModules(){if(!globalThis.hudPatched)return void _.error("Cant find patched modules");const e=Array.from(globalThis.hudPatched);this._sendObject("PatchedModules",{modules:e})}async handleLogsTask(){try{const e=a.getSavedLogs();for(const t of e)try{this._sendObject("Logs",{logs:t})}catch(e){_.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}catch(e){_.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async sendLogsPeriodically(e){for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))await this.handleLogsTask()}async setupPeriodicTask(e,t,n,i,o=!1){function r(e){let t=!0;try{t=n(e)}catch(e){_.error("Failed in periodic task",{taskName:i,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t}if(await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal}),r(e)){if(!o)for await(const e of(0,u.unrefSetInterval)(t,void 0,{signal:this.abortController.signal}))if(!r(t))return void _.warning("Periodic task failed, stopping task",{firstRun:!1,taskName:i})}else _.warning("Periodic task failed, stopping task",{firstRun:!0,taskName:i})}async periodicResetGlobalInvestigationCounter(){const e=d.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{_.info("Resetting global investigation counter",{interval:e}),(0,y.setGlobalInvestigationTracking)(0),(0,f.resetTotalInvestigationsDurationBased)(),(0,f.resetTotalInvestigationsErrorBased)()}catch(e){_.error("Failed resetting global investigation counter",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicResetInvestigationDedupingCache(){const e=d.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{_.info("Resetting investigation deduping cache",{interval:e}),(0,y.resetInvestigationDedupingCache)(),(0,f.resetInvestigationDurationCounts)()}catch(e){_.error("Failed resetting investigation deduping cache",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_updateTsNodeConfig(){if(this.tsNodeUpdated)return!1;try{const e=(0,b.getUserTsNodeConfig)();return!!e&&(this.tsNodeUpdated=!0,_.info("tsconfig found, sending config to worker"),this._sendObject("TsNodeConfig",{tsConfig:e}),!0)}catch(e){throw this.tsNodeUpdated=!0,this.stop(),e instanceof m.HudError&&(0,m.setFirstError)(e.code),(0,C._detachAndTerminate)(!1),e}}async sendStaticNextJsEndpointsOnce(){if(!(0,g.isNextJsApp)())return;const e=d.hudConfig.staticNextJsEndpointsInterval,t=d.hudConfig.staticNextJsEndpointsMaxAttempts;let n=0;for await(const i of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){if(n++,_.debug("Attempting to send static next.js endpoints",{attemptCount:n}),(0,y.isNextConfigExtracted)()&&!this.staticNextJsEndpointsSent){_.info("Sending static next.js endpoints",{isNextConfigExtracted:(0,y.isNextConfigExtracted)()}),this.staticNextJsEndpointsSent=!0;const e=(0,y.getNextConfig)();this._sendObject("StaticNextJsEndpoints",{NextConfig:JSON.stringify(e)});break}if(n>t){_.warning("Exceeded max attempts to send static next.js endpoints",{isNextConfigExtracted:(0,y.isNextConfigExtracted)(),attemptCount:n});break}}}async periodicSendReingest(){for await(const e of(0,u.unrefSetInterval)(d.hudConfig.dynamicConfig.reingestInterval,void 0,{signal:this.abortController.signal})){const e=(0,f.getAndClearReingestValues)();e.size>0&&this._sendArray("Reingest",Array.from(e))}}}},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")}},t={};function n(i){var o=t[i];if(void 0!==o)return o.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}return n.c=t,n(n.s=5119)})()); //# sourceMappingURL=core.js.map