UNPKG

hud-sdk

Version:

Hud's Node SDK

2 lines 29.6 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 i=t();for(var r in i)("object"==typeof exports?exports:e)[r]=i[r]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},2546:e=>{e.exports=require("./lib")},2702:function(e,t,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=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||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const a=s(i(523)),d=i(8528),c=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!==d.KeepAliveMessage.msg)return;this._restartTimeout()}catch(e){c.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,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=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||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.tryFlushPendingLogs=t.init=void 0;const a=s(i(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,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainThread=void 0;const n=i(8167),o=i(2546),s=i(5809),a=i(8269),d=i(523),c=i(6281),g=r(i(7320));function l(){globalThis.hudInstrumentationOccured&&d.customer_logger.log(o.UserErrorLogs.YesInstrumentationNoMetrics())}t.MainThread=class{apiKey;service;startTime;tags;messenger;constructor(e,t,i,r){this.apiKey=e,this.service=t,this.startTime=i,this.tags=r,(0,a.storeCredentials)(e,t)}startFailed(e){e instanceof o.HudSessionThrottle?(d.customer_logger.log(o.UserLogs.InitIdleMode()),(0,c._detachAndTerminate)(!1,!1,!0)):e instanceof o.HudInitNetworkError&&e.originalAxiosErrorCode?(d.customer_logger.log((0,o.getNetworkError)(e.originalAxiosErrorCode)),d.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,c._detachAndTerminate)(!1,!1,!0)):(d.app_logger.critical("Failed to start worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,o.setFirstError)(e.code),(0,c._detachAndTerminate)(!0,!1,!0))}async _registerLambdaExtension(){const e=await(0,o.register)();return(0,a.setLambdaExtensionId)(e),e}async startMessenger(e){try{this.messenger=await this._createMessenger(e),await this._start(),d.customer_logger.log(o.UserLogs.HudInitSuccess())}catch(e){throw this.startFailed(e),e}}async start(){if(n.isMainThread)if(globalThis.hudRuningInsideLambda)try{const e=await this._registerLambdaExtension();d.app_logger.info("Lambda extension registered, not waiting for worker to start",{lambdaExtensionId:e}),(0,o.next)(e).then(async()=>{d.app_logger.info("Lambda got first event, creating messenger");try{await this.startMessenger(e)}catch{}}).catch(e=>{d.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 o.HudInitError("Messenger not initialized");try{const e=await this.messenger.checkWorkerInitialized(s.hudConfig.workerTimeout),t=e?.content?.sessionInfo;t&&(0,a.storeSessionInfo)(t),await this._initDynamicConfig(),globalThis.hudMetricsIndicator=setTimeout(l,s.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof o.HudSessionThrottle)throw e;throw d.app_logger.critical("Failed to start worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(e){const t=o.myRequire.resolve(`${s.SDK_MODULE_NAME}/worker`),i={...process.env};delete i.NODE_OPTIONS;const r=new n.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:i});let a;try{a=new g.default(r),await a.checkWorker(s.hudConfig.workerTimeout)}catch(e){if(e instanceof o.HudSessionThrottle)throw d.app_logger.info("Worker started in idle mode - session throttled"),e;throw d.app_logger.critical("Worker failed to start",{msg:e instanceof Error?e.message:void 0}),e}finally{r.unref()}return a}async _initDynamicConfig(){const e=await(this.messenger?.getRemoteConfig());e?(d.app_logger.info("Remote configuration exists"),s.hudConfig.dynamicConfig=(0,s.updateDynamicConfig)(e,s.hudConfig,d.app_logger),(0,s.updateInvestigationRateLimitGlobals)(),d.app_logger.info("Current dynamic configuration:",{currentDynamicConfig:s.hudConfig.dynamicConfig})):d.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,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,i){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void n.app_logger.warning("Already ran init!");if(globalThis.hudRunMutex=!0,(0,d.clearInitGuard)(),!n.app_logger.isValid()||!n.customer_logger.isValid())return(0,c.setFirstError)((new c.HudBadLoggerError).code),void h(!0,!0);(0,r.updateUserConfigFromInit)(e,t,i);const g=(0,d.validateAndGetUserInput)();if(!g)return;if(globalThis.hudRunningMode!==a.HudRunningMode.enabled)return void n.app_logger.critical("SDK running mode is not enabled - initialization aborted");if(n.app_logger.info("Initializing hud",{userConfig:Object.entries(s.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),l=new o.MainThread(g.apiKey,g.service,globalThis.hudStartTime,s.hudConfig.userConfig.tags?.value),await l.start(),l.messenger&&(0,c.safeCall)(n.app_logger,l.messenger.handleLogsTask()),globalThis.hudImportStartTime){const e=process.uptime()-globalThis.hudImportStartTime;n.app_logger.info("Hud initialized",{importTime:e,startTime:globalThis.hudImportStartTime})}}catch(e){try{if(e instanceof c.HudSessionThrottle)return;n.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{n.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,d.getShouldFlushOnInit)()&&((0,d.markShouldFlushOnInit)(!1),await f(e,t))};const r=i(2546),n=i(523),o=i(5994),s=i(5809),a=i(8528),d=i(8269),c=i(2546),g=i(7274);let l,u=!1;function h(e=!0,t=!1,i=!1){(0,d.detachHud)(e,t),i&&(0,c.safeCall)(n.app_logger,f()),l&&(0,c.safeCall)(n.app_logger,l.terminateMessenger());const o=(0,d.getLambdaExtensionId)();o&&!u&&(u=!0,(0,c.safeCall)(n.app_logger,(0,r.nextLoopDummy)(o))),(0,d.clearUserIndicatorsTimeouts)(),(0,g.resetCallers)()}async function f(e,t){const r=(0,d.getSessionInfo)(),o=(0,d.getStoredApiKey)(),s=(0,d.getStoredService)();try{const a=e||o;if(!a||"string"!=typeof a)return;const d=t||s||"unknown",c=(0,n.getSavedLogs)();for(const e of c){const{HudClient:t}=i(4672),o=new t;r?(n.app_logger.info("Flushing logs with session",{size:e.length,sessionId:r.sessionId,service:d}),o.setSession(r),await o.logs(e)):(n.app_logger.info("Flushing logs (sessionless)",{size:e.length,service:d}),await o.sessionslessLogs(e,a)),n.app_logger.info("Successfully flushed logs")}}catch(e){try{n.app_logger.error("Failed to flush logs",{msg:e instanceof Error?e.message:void 0,hasSession:null!==r})}catch{}}}},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._liftExceptions=s,t.prepCalls=function(e,t){const i=(new Date).toISOString(),o=[];return Object.entries(hudCalls).map(([r,a])=>{Object.entries(a).forEach(([a,d])=>{Object.entries(d).forEach(([d,c])=>{try{if(0===c.sampledCount)return;const n={function_id:r,wrapped_flow_id:d||void 0,wrapped_caller_id:a||void 0,timestamp:i,timeslice:e,exceptions:s(c.exceptions),count:c.count,sampled_count:c.sampledCount,sum_duration:c.sum,sum_squared_duration:c.squareSum,sketch:c.sketch?t.encode(c.sketch):void 0,is_linked_function:c.isLinkedFunction};o.push(n),function(e){e.count=0,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(c)}catch(e){n.app_logger.error("Failed preparing invocation, skipping",{func:r,wrappedCaller:a,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})})}),o.length>0&&(0,r.clearMetricsIndicator)(),o},t.resetCallers=function(){for(const e in globalThis.hudCalls)for(const t in globalThis.hudCalls[e])for(const i in globalThis.hudCalls[e][t])o(globalThis.hudCalls[e][t][i])};const r=i(8269),n=i(523);function o(e){e.samplingCounter=0}function s(e){const t={};for(const i in e)t[i]=[{count:e[i]}];return t}},7320:function(e,t,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=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||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=s(i(523)),d=s(i(6460)),c=i(5809),g=i(2546),l=i(8528),u=i(2546),h=i(7131),f=i(8269),m=i(2546),p=i(7274),v=i(2702),w=i(8269),k=i(2546),y=i(6281),b=i(8269),C=i(2546),_=i(6261),E=a.app_logger,T=m.safeCall.bind(m.safeCall,E);t.default=class{worker;tsNodeUpdated=!1;staticNextJsEndpointsSent=!1;abortController;workerKeepaliveGuard;messageQueue=[];MAX_QUEUE_SIZE=100;messageEmitter=new _.EventEmitter;constructor(e){this.worker=e,this.abortController=new AbortController,(0,_.setMaxListeners)(20,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,E.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,c.hudConfig.communicationKeepaliveGrace),this._updateTsNodeConfig()&&E.info("ts-node config updated from Messenger constructor")}handleWorkerError=e=>{try{e?.code===(new m.HudClientUnauthorizedError).code&&a.customer_logger.log(m.UserErrorLogs.ApiKeyDenied(c.hudConfig.userConfig.key?.source)),E.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,y._detachAndTerminate)(!0,!1,!0)}catch(e){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(),c.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),E.debug("sent data to worker",{msg:e,size:t.length}))}_sendObject(e,t){const i={msg:e,content:t};this.worker.postMessage(i)}async checkWorker(e){const t=["started"];let i;try{i=await this.getMessageFromWorker(t,e,!0)}catch(r){if(!(r instanceof m.HudTimeoutError))throw r;i=await this.getMessageFromWorker(t,e/2,!1)}if(!i)throw new m.HudInitError("Worker not started");return i}async checkWorkerInitialized(e){let t;const i=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(i,e,!0)}catch(r){if(!(r instanceof m.HudTimeoutError))throw r;t=await this.getMessageFromWorker(i,e/10,!1)}if("throttled"===t?.msg)throw new m.HudSessionThrottle;if("networkError"===t?.msg)throw E.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(c.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.start(),globalThis.hudRunningMode){case l.HudRunningMode.enabled:E.info("Enabled mode"),T(this.getMode()),T(this.periodicGetEndpointsDurationsInvestigationThresholds()),T(this.startPeriodicTasks()),T(this.periodicSendMetrics()),T(this.highFrequencySendInvestigations()),T(this.periodicSendProcessedFiles()),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(c.hudConfig.logsSendInterval)),T(this.sendRuntime()),T(this.sendPatchedModules()),T(this.sendPreloadedModules()),T(this.dumpModulesAfterWhile(6e4)),T(this.periodicSendThreadPerformanceMetrics());break;case l.HudRunningMode.disabled:E.info("Disabled mode"),T(this.getMode());break;case l.HudRunningMode.detached:E.info("Detached"),(0,y._detachAndTerminate)(!1,!1),this.stop();break;default:E.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,i=!1,r){let n;e=Array.isArray(e)?e:[e];const o=this.consumeMessageFromQueue(e);if(o)return E.info("Found message in queue",{msg:o.msg}),o;const s=new AbortController,a=()=>{s.abort()};this.abortController.signal.addEventListener("abort",a);const c=d.setTimeout(t,void 0,{signal:s.signal,ref:i}),g=t=>{try{e.includes(t.msg)&&(n=t,s.abort(),this.consumeMessageFromQueue([t.msg]),E.info("Received message from worker (canceling timeout)",t))}catch(e){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),r&&this.worker.postMessage(r);try{throw await c,E.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 n}async getMode(){for await(const e of(0,u.unrefSetInterval)(c.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,c.hudConfig.workerMessageTimeout,!1,e);if(t?.msg!==e.msg||void 0===t?.content.mode){E.error("Unexpected message from worker",t);continue}t.content.mode!==globalThis.hudRunningMode&&await this.restart(t?.content.mode)}catch(e){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,c.hudConfig.workerMessageTimeout,!0);if(t?.msg!==e||void 0===t?.content)throw new Error(`Unexpected message from worker: ${t}`);return t?.content}catch(e){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 periodicSaveMachineMetrics(){(0,f.saveMachineMetric)();for await(const e of(0,u.unrefSetInterval)(c.hudConfig.dynamicConfig.machineMetricsInterval,void 0,{signal:this.abortController.signal}))(0,f.saveMachineMetric)()}async resetCallerCounters(){const e=c.hudConfig.callerResetInterval;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{E.info("Resetting caller",{interval:e}),(0,p.resetCallers)()}catch(e){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 i=await this.getMessageFromWorker(t,c.hudConfig.workerMessageTimeout,!1,e);if(i?.msg!==t||void 0===i?.content)throw new Error(`Unexpected message from worker: ${i}`);(0,f.setInvestigationDurationThresholds)(i?.content),E.debug("Endpoints durations investigation thresholds updated",{thresholds:i?.content})}catch(e){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)(c.hudConfig.endpointsDurationsInvestigationThresholdsInterval,void 0,{signal:this.abortController.signal}))await this.updateEndpointDurationsInvestigationThresholds()}async periodicSendProcessedFiles(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;let i=!0;await this.setupPeriodicTask(e,t,()=>{if(i){i=!1;try{this._updateTsNodeConfig()&&E.info("ts-node config updated from periodicSendProcessedFiles")}catch{return!1}}const e=function(){const e=globalThis.hudProcessedFiles;return globalThis.hudProcessedFiles=[],e}();return this._sendArray("ProcessedFiles",e),!0},"periodicSendProcessedFiles")}async periodicSendKafkaJS(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,w.getKafkaJSTopics)();return this._sendArray("KafkaJSTopics",e),!0},"periodicSendKafkaJS")}async periodicSendSqs(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,w.getSqsQueues)();return e.length>0&&this._sendArray("SqsQueue",e),!0},"periodicSendSqs")}async periodicSendGraphQL(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=Object.values((0,w.getGraphQLOperations)());return e.length>0&&this._sendArray("GraphQLDeclaration",e),!0},"periodicSendGraphQL")}async periodicSendMetrics(){const e=new h.SketchManager(c.hudConfig.huddBinWidth),t=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,i=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,i,t=>{try{this.refreshInvestigations()}catch(e){E.error("Failed sending investigations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const i=(0,p.prepCalls)(t,e);i.length>0&&this._sendArray("Invocations",i)}catch(e){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){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 highFrequencySendInvestigations(){if(!c.hudConfig.dynamicConfig.enableInvestigation)return;const e=c.hudConfig.dynamicConfig.investigationFirstSendTimeout,t=c.hudConfig.dynamicConfig.investigationInterval;await this.setupPeriodicTask(e,t,()=>(this.refreshInvestigations(),!0),"highFrequencySendInvestigations")}refreshInvestigations(){const e=(0,w.getClosedInvestigations)();e.length>0&&this._sendArray("Investigations",e)}async periodicSendEndpoints(){const e=c.hudConfig.endpointsFirstSendWaitTime,t=c.hudConfig.endpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendEndpoints(),!0),"periodicSendEndpoints")}async periodicSendOutbounds(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendOutbounds(),!0),"periodicSendOutbounds")}async periodicSendLazyEndpoints(){const e=c.hudConfig.endpointsFirstSendWaitTime,t=c.hudConfig.lazyEndpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendLazyEndpoints(),!0),"periodicSendLazyEndpoints")}sendLazyEndpoints(){const e=(0,w.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,b.getLoadedOutboundsFromStorage)();e.length>0&&this._sendArray("LoadedOutbounds",e)}async terminateWorker(){try{const e=a.getSavedLogs();await this.getMessageFromWorker("terminated",c.hudConfig.workerGrace,!1,{msg:"Terminate",content:{grace:c.hudConfig.workerGrace,logBuffers:e}})}catch(e){if(!(e instanceof m.HudTimeoutError))throw E.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;E.critical("Grace period timeout - terminating worker",{error:e.message}),await this.worker.terminate()}E.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:i.c[i.s]?.filename};this._sendObject("Runtime",e)}async startPeriodicTasks(){this._sendObject("StartPeriodicTasks",{})}async sendPreloadedModules(){globalThis.hudLoadedModules?this._sendObject("PreInitLoadedModules",{modules:globalThis.hudLoadedModules}):E.warning("Didn't get module, weird....")}async periodicSendThreadPerformanceMetrics(){const e=c.hudConfig.dynamicConfig.performanceMetricsInterval,t=(0,g.createThreadStatsBaseline)();for await(const i of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){const e=(0,m.collectThreadPerformance)(t,E,"MainThread");e&&this._sendObject("PerformanceMetrics",e)}}async dumpModulesAfterWhile(e){await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(k.myRequire.cache);this._sendObject("PostInitLoadedModules",{modules:t})}async sendPatchedModules(){if(!globalThis.hudPatched)return void E.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){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){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,i,r){function n(e){let t=!0;try{t=i(e)}catch(e){E.error("Failed in periodic task",{taskName:r,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}),n(e)){for await(const e of(0,u.unrefSetInterval)(t,void 0,{signal:this.abortController.signal}))if(!n(t))return void E.warning("Periodic task failed, stopping task",{firstRun:!1,taskName:r})}else E.warning("Periodic task failed, stopping task",{firstRun:!0,taskName:r})}async periodicResetGlobalInvestigationCounter(){const e=c.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{E.info("Resetting global investigation counter",{interval:e}),(0,w.setGlobalInvestigationTracking)(0),(0,f.resetTotalInvestigationsDurationBased)(),(0,f.resetTotalInvestigationsErrorBased)()}catch(e){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=c.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{E.info("Resetting investigation deduping cache",{interval:e}),(0,w.resetInvestigationDedupingCache)(),(0,f.resetInvestigationDurationCounts)()}catch(e){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,C.getUserTsNodeConfig)();return!!e&&(this.tsNodeUpdated=!0,E.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,y._detachAndTerminate)(!1),e}}async sendStaticNextJsEndpointsOnce(){if(!(0,g.isNextJsApp)())return;const e=c.hudConfig.staticNextJsEndpointsInterval,t=c.hudConfig.staticNextJsEndpointsMaxAttempts;let i=0;for await(const r of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){if(i++,E.debug("Attempting to send static next.js endpoints",{attemptCount:i}),(0,w.isNextConfigExtracted)()&&!this.staticNextJsEndpointsSent){E.info("Sending static next.js endpoints",{isNextConfigExtracted:(0,w.isNextConfigExtracted)()}),this.staticNextJsEndpointsSent=!0;const e=(0,w.getNextConfig)();this._sendObject("StaticNextJsEndpoints",{NextConfig:JSON.stringify(e)});break}if(i>t){E.warning("Exceeded max attempts to send static next.js endpoints",{isNextConfigExtracted:(0,w.isNextConfigExtracted)(),attemptCount:i});break}}}async periodicSendReingest(){for await(const e of(0,u.unrefSetInterval)(c.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 i(r){var n=t[r];if(void 0!==n)return n.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,i),o.exports}return i.c=t,i(i.s=5119)})()); //# sourceMappingURL=core.js.map