UNPKG

@salesforce/o11y-reporter

Version:

A wrapper service around o11y and o11y_schema for telemetry reporting.

3 lines (2 loc) 9.81 kB
/* o11y-reporter - A wrapper service around o11y and o11y_schema for telemetry reporting */ var S=Object.create;var h=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var g=Object.getOwnPropertyNames;var O=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty;var P=(e,t)=>{for(var n in t)h(e,n,{get:t[n],enumerable:!0})},y=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of g(t))!E.call(e,o)&&o!==n&&h(e,o,{get:()=>t[o],enumerable:!(r=v(t,o))||r.enumerable});return e};var d=(e,t,n)=>(n=e!=null?S(O(e)):{},y(t||!e||!e.__esModule?h(n,"default",{value:e,enumerable:!0}):n,e)),w=e=>y(h({},"__esModule",{value:!0}),e);var A={};P(A,{O11yService:()=>p});module.exports=w(A);var m=null,f=async()=>(m||(m=(async()=>{let[e,t,n,r,o]=await Promise.all([import("o11y/client"),import("o11y_schema/version"),import("o11y_schema/sf_a4dInstrumentation"),import("o11y/simple_collector"),import("o11y/collectors")]),{registerInstrumentedApp:i,ConsoleCollector:s,_version:a,getInstrumentation:l}=e,{version:c}=t;return{o11yClientVersion:a,getInstrumentation:l,o11ySchemaVersion:c,registerInstrumentedApp:i,ConsoleCollector:s,a4d_instrumentation:n.a4dInstrumentationSchema,simpleCollectorModule:r,collectorsModule:o}})()),m);var p=class e{constructor(){this.O11Y_UPLOAD_THRESHOLD_BYTES=5e4;this.environment={};this.getConnectionMethod=null;this.dynamicO11yUploadEndpointPath="/services/data/v65.0/connect/proxy/ui-telemetry";this.flushTimer=null;this.shutdownHandler=null}static{this.instances=new Map}static{this.sharedResourcesInitPromise=null}static{this.sharedInstrumentation=null}static{this.sharedInstrApp=null}static{this.sharedO11yModules=null}static{this.sharedProtoEncoderFunc=null}static{this.loggedProtoEncoderNotInitialized=!1}static getInstance(t){if(!e.instances.has(t)){let n=new e;e.instances.set(t,n)}return e.instances.get(t)}async initialize(t,n,r,o){if(this.extensionName=t,this.o11yUploadEndpoint=n,this.getConnectionMethod=r||null,o?.dynamicO11yUploadEndpointPath&&(this.dynamicO11yUploadEndpointPath=o.dynamicO11yUploadEndpointPath.startsWith("/")?o.dynamicO11yUploadEndpointPath:`/${o.dynamicO11yUploadEndpointPath}`),e.sharedInstrApp||(e.sharedResourcesInitPromise||(e.sharedResourcesInitPromise=this.runInitializeSharedResourcesOnce()),await e.sharedResourcesInitPromise),!e.sharedO11yModules||!e.sharedInstrumentation){console.error("O11yService: Telemetry initialization failed - continuing without telemetry");return}this.instrumentation=e.sharedInstrumentation,this.a4dO11ySchema=e.sharedO11yModules.a4d_instrumentation;let{o11yClientVersion:i,o11ySchemaVersion:s}=e.sharedO11yModules;Object.assign(this.environment,{appName:"o11y-reporter-extensions",extensionName:this.extensionName,o11ySchemaVersion:s,sdkVersion:`${i}:${s}`})}runInitializeSharedResourcesOnce(){return this.initializeSharedResources().finally(()=>{e.sharedInstrApp||(e.sharedResourcesInitPromise=null)})}async initializeSharedResources(){try{if(e.sharedO11yModules=await f(),!e.sharedO11yModules){console.error("Failed to load O11y modules");return}let{o11yClientVersion:t,o11ySchemaVersion:n,getInstrumentation:r,registerInstrumentedApp:o}=e.sharedO11yModules,i="o11y-reporter-extensions-instrumentation";if(e.sharedInstrumentation=r(i),!e.sharedInstrumentation){console.error("Failed to create shared instrumentation:",i);return}let s="o11y-reporter-extensions";if(e.sharedInstrApp=o(s,{isProduction:!1,enableBuffering:!0}),!e.sharedInstrApp){console.error("Failed to register shared app:",s);return}if(e.sharedInstrApp&&(e.sharedInstrApp.simpleCollector=this.initSimpleCollector(e.sharedInstrApp,{appName:s,sdkVersion:`${t}:${n}`},e.sharedO11yModules)),e.sharedO11yModules){let{collectorsModule:a}=e.sharedO11yModules,l=a.default??a;if(typeof l.encodeCoreEnvelopeContentsRaw=="function")e.sharedProtoEncoderFunc=l.encodeCoreEnvelopeContentsRaw;else{console.error("Failed to initialize proto encoder function - encodeCoreEnvelopeContentsRaw is not a function");return}}else{console.error("sharedO11yModules is null after loading");return}}catch(t){console.error("Failed to initialize shared O11y resources:",t),e.sharedInstrApp=null,e.sharedO11yModules=null,e.sharedInstrumentation=null,e.sharedProtoEncoderFunc=null}}logEvent(t){if(!this.isInitialized()){console.error("O11yService: Cannot log event - Service not fully initialized"),console.error("Initialization status:",this.getInitializationStatus());return}this.instrumentation?this.instrumentation.log(this.a4dO11ySchema,{message:JSON.stringify(t)}):console.error("O11yService: Unable to log event - Instrumentation not initialized")}logEventWithSchema(t,n){if(!this.isInitialized()){console.error("O11yService: Cannot log event - Service not fully initialized"),console.error("Initialization status:",this.getInitializationStatus());return}if(!n){console.error("O11yService: Schema not provided to logEventWithSchema");return}this.instrumentation?this.instrumentation.log(n,t):console.error("O11yService: Unable to log event - Instrumentation not initialized")}isInitialized(){return!!(e.sharedProtoEncoderFunc&&e.sharedInstrApp&&e.sharedO11yModules&&this.instrumentation)}getInitializationStatus(){return{sharedProtoEncoderFunc:!!e.sharedProtoEncoderFunc,sharedInstrApp:!!e.sharedInstrApp,sharedO11yModules:!!e.sharedO11yModules,instrumentation:!!this.instrumentation}}async waitForInitialization(t=5e3){let n=Date.now();if(this.isInitialized())return!0;let r=5;for(;!this.isInitialized();){if(Date.now()-n>t)return console.error("O11yService: Initialization timeout after",t,"ms"),console.error("Final initialization status:",this.getInitializationStatus()),!1;await new Promise(o=>setTimeout(o,r)),r=Math.min(r*2,100)}return!0}async upload(){if(!this.isInitialized()){console.error("O11yService: Cannot upload - Service not fully initialized");return}try{await this.uploadAsNeededAsync(!0)}catch(t){console.error("Telemetry upload failed:",t)}}initSimpleCollector(t,n,r){if(!r)throw new Error("o11yModules is null");let{simpleCollectorModule:o}=r,i=o.default?.SimpleCollector??o.SimpleCollector,s=new i({environment:n});return t.registerLogCollector(s,{retroactive:!0}),t.registerMetricsCollector(s),s}uploadAsNeededAsync(t=!1){let n=[];if(!e.sharedProtoEncoderFunc)return e.loggedProtoEncoderNotInitialized||(e.loggedProtoEncoderNotInitialized=!0,console.error("O11yService: sharedProtoEncoderFunc is not initialized (shared telemetry init likely failed); uploads skipped.")),Promise.resolve([]);let r=e.sharedInstrApp?.simpleCollector,o=this.configuredThresholdBytes??this.O11Y_UPLOAD_THRESHOLD_BYTES;if(r?.hasData&&(t||r.estimatedByteSize>=o))try{let i=r.getRawContentsOfCoreEnvelope(),s=e.sharedProtoEncoderFunc(i);n.push(this.uploadToFalconAsync(s))}catch(i){return console.error("[O11yService][uploadAsNeededAsync] Error during upload encoding:",i),Promise.resolve([])}return Promise.allSettled(n).then(async i=>{for(let s of i)if(s.status==="fulfilled"){let a=s.value;(a.status<200||a.status>=300)&&console.error(`[O11yService][uploadAsNeededAsync] \u2717 Upload FAILED with status ${a.status} ${a.statusText}. Events may not be in Splunk.`)}else console.error("[O11yService][uploadAsNeededAsync] \u2717 Upload FAILED:",s.reason),s.reason instanceof Error&&console.error("[O11yService][uploadAsNeededAsync] Error stack:",s.reason.stack);return i})}async uploadToFalconAsync(t){let r={base64Env:Buffer.from(t).toString("base64")};if(this.getConnectionMethod)try{let s=await this.getConnectionMethod();if(s?.requestPost)return await s.requestPost(this.dynamicO11yUploadEndpointPath,r),{status:200,ok:!0}}catch{}let o=this.o11yUploadEndpoint||"";return o?this.postRequest(o,r):Promise.reject(new Error("o11yUploadEndpoint is not defined"))}postRequest(t,n){let r=JSON.stringify(n);return fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:r}).catch(i=>{throw console.error(`[O11yService][postRequest] \u2717 POST Request FAILED for ${t}:`,i),i instanceof Error&&console.error("[O11yService][postRequest] Error details:",i.message,i.stack),i})}async forceFlush(){if(this.getBatchStatus().hasData)return this.upload()}enableAutoBatching(t){let n=t?.flushInterval??3e4,r=t?.checkInterval??2e3,o=t?.enableShutdownHook??!0;this.configuredThresholdBytes=t?.thresholdBytes??this.O11Y_UPLOAD_THRESHOLD_BYTES,this.flushTimer&&clearInterval(this.flushTimer);let i=Date.now();if(this.flushTimer=setInterval(async()=>{try{let s=Date.now();await this.uploadAsNeededAsync(!1),s-i>=n&&(await this.uploadAsNeededAsync(!0),i=s)}catch(s){console.error("[O11yService] Auto-batching flush failed:",s)}},r),o){let s=t?.enableBeforeExitHook!==!1,a=I=>async()=>{try{this.getBatchStatus().hasData&&await this.uploadAsNeededAsync(!0)}catch(u){console.error(`[O11yService] Shutdown flush failed for ${I}:`,u),u instanceof Error&&console.error("[O11yService] Error stack:",u.stack)}},l=a("SIGINT"),c=a("SIGTERM");process.on("SIGINT",l),process.on("SIGTERM",c),s&&(this.shutdownHandler=a("beforeExit"),process.on("beforeExit",this.shutdownHandler)),this.shutdownHandlers={SIGINT:l,SIGTERM:c,...s&&this.shutdownHandler?{beforeExit:this.shutdownHandler}:{}}}return()=>{this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),o&&this.shutdownHandlers&&(this.shutdownHandlers.beforeExit&&process.removeListener("beforeExit",this.shutdownHandlers.beforeExit),process.removeListener("SIGINT",this.shutdownHandlers.SIGINT),process.removeListener("SIGTERM",this.shutdownHandlers.SIGTERM),this.shutdownHandler=null,this.shutdownHandlers=void 0)}}getBatchStatus(){let t=e.sharedInstrApp?.simpleCollector,n=t?.hasData||!1,r=t?.estimatedByteSize||0,o=this.configuredThresholdBytes??this.O11Y_UPLOAD_THRESHOLD_BYTES,i=r>=o;return{hasData:n,estimatedByteSize:r,thresholdBytes:o,isOverThreshold:i}}};0&&(module.exports={O11yService});