@zuplo/otel 6.56.1 → 6.56.4
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/out/esm/chunk-MAM3UMUM.js +25 -0
- package/out/esm/index.js +1 -1
- package/package.json +2 -2
- package/out/esm/chunk-PI75EO3F.js +0 -25
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
|
|
2
|
+
/*---------------------------------------------------------------------------------------------
|
|
3
|
+
* Copyright (c) Zuplo, Inc. All rights reserved.
|
|
4
|
+
*
|
|
5
|
+
* This software and associated documentation files (the "Software") is intended to be used
|
|
6
|
+
* only by Zuplo customers solely to develop and test applications that will be deployed
|
|
7
|
+
* to Zuplo hosted services. You and others in your organization may use these files on your
|
|
8
|
+
* Development Devices solely for the above stated purpose.
|
|
9
|
+
*
|
|
10
|
+
* Outside of uses stated above, no license is granted for any other purpose including
|
|
11
|
+
* without limitation the rights to use, copy, modify, merge, publish, distribute,
|
|
12
|
+
* sublicense, host, and/or sell copies of the Software.
|
|
13
|
+
*
|
|
14
|
+
* The software may include third party components with separate legal notices or governed by
|
|
15
|
+
* other agreements, as described in licenses either embedded in or accompanying the Software.
|
|
16
|
+
*
|
|
17
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
|
18
|
+
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
|
19
|
+
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
|
|
20
|
+
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
21
|
+
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
22
|
+
* DEALINGS IN THE SOFTWARE.
|
|
23
|
+
*--------------------------------------------------------------------------------------------*/
|
|
24
|
+
|
|
25
|
+
var Ae=Object.defineProperty;var o=(t,e)=>Ae(t,"name",{value:e,configurable:!0});import{Buffer as _e}from"node:buffer";globalThis.Buffer=_e;import{TelemetryPlugin as Ft,trackFeature as wt}from"@zuplo/runtime";import{context as ve,propagation as gt,SpanStatusCode as ht,trace as Pe}from"@opentelemetry/api";import{SemanticAttributes as O}from"@zuplo/runtime";import{resourceFromAttributes as Ce}from"@opentelemetry/resources";import{context as re}from"@opentelemetry/api";function $(t){return!!t.spanProcessors}o($,"isSpanProcessorConfig");import{W3CTraceContextPropagator as Ue}from"@opentelemetry/core";import{ExportResultCode as Oe}from"@opentelemetry/core";import{JsonTraceSerializer as ke}from"@opentelemetry/otlp-transformer";var D=Symbol("unwrap");function B(t){return t&&!!t[D]}o(B,"isWrapped");function Ie(t){return t!==null&&typeof t=="object"||typeof t=="function"}o(Ie,"isProxyable");function y(t,e,r=!0){if(B(t)||!Ie(t))return t;let n=Object.assign({},e);return n.get=(a,s,i)=>{if(s===D)return t;if(e.get)return e.get(a,s,i);if(s==="bind")return()=>i;if(r)return N(a,s)},n.apply=(a,s,i)=>{if(e.apply)return e.apply(T(a),T(s),i)},new Proxy(t,n)}o(y,"wrap");function T(t){return t&&B(t)?t[D]:t}o(T,"unwrap");function N(t,e,r){let n=T(t);r=T(r)||n;let a=Reflect.get(n,e);return typeof a=="function"?a.constructor.name==="RpcProperty"?(...s)=>n[e](...s):a.bind(r):a}o(N,"passthroughGet");import{BackgroundDispatcher as Le}from"@zuplo/runtime";var He={accept:"application/json","content-type":"application/json"},v=class{static{o(this,"OTLPExporter")}headers;url;constructor(e){this.url=e.url,this.headers=Object.assign({},He,e.headers)}export(e,r){e.forEach(n=>{this.batcher.enqueue(n)}),r({code:Oe.SUCCESS})}shutdown(){throw new Error("Method not implemented.")}forceFlush(){throw new Error("Method not implemented.")}dispatchFunction=o(async e=>{if(e.length===0)return;let r=new TextDecoder,n=ke.serializeRequest(e),a=r.decode(n),s=await T(fetch)(this.url,{method:"POST",body:a,headers:this.headers});if(!s.ok)try{let i=await s.text();console.error("Error exporting traces",i)}catch{console.error("Error exporting traces")}},"dispatchFunction");batcher=new Le(this.dispatchFunction,{msDelay:10})};import{TraceFlags as K,SpanStatusCode as Me}from"@opentelemetry/api";import{ParentBasedSampler as X,TraceIdRatioBasedSampler as De}from"@opentelemetry/sdk-trace-base";import{SemanticAttributes as z}from"@zuplo/runtime";function Y(t){return e=>{let r=e.localRootSpan;return r.attributes[z.SystemTrace]??r.attributes[z.RouteSystem]??r.attributes[z.RouteTrace]===!1?!1:t(e)}}o(Y,"internalTailSampler");function J(t){return e=>t.reduce((r,n)=>r||n(e),!1)}o(J,"multiTailSampler");var Q=o(t=>(t.localRootSpan.spanContext().traceFlags&K.SAMPLED)===K.SAMPLED,"isHeadSampled"),ee=o(t=>t.localRootSpan.status.code===Me.ERROR,"isRootErrorSpan");function te(t){let e=new De(t.ratio);return typeof t.acceptRemote=="boolean"&&!t.acceptRemote?new X({root:e,remoteParentSampled:e,remoteParentNotSampled:e}):new X({root:e})}o(te,"createSampler");import{ExportResultCode as Ne}from"@opentelemetry/core";function ze(){let t=f();return t||console.log("Could not find config for sampling, sending everything by default"),t?t.sampling.tailSampler:()=>!0}o(ze,"getSampler");var U=class{static{o(this,"TraceState")}unexportedSpans=[];inprogressSpans=new Set;exporter;exportPromises=[];localRootSpan;traceDecision;isFlushed=!1;constructor(e){this.exporter=e}addSpan(e){let r=e;this.localRootSpan=this.localRootSpan||r,this.unexportedSpans.push(r),this.inprogressSpans.add(e.spanContext().spanId)}async endSpan(e){this.inprogressSpans.delete(e.spanContext().spanId),this.inprogressSpans.size===0&&await this.flush()}sample(){if(this.traceDecision===void 0&&this.unexportedSpans.length>0){let e=ze();this.traceDecision=e({traceId:this.localRootSpan.spanContext().traceId,localRootSpan:this.localRootSpan,spans:this.unexportedSpans})}this.unexportedSpans=this.traceDecision?this.unexportedSpans:[]}async flush(){if(this.unexportedSpans.length>0){let e=this.unexportedSpans.filter(r=>this.isSpanInProgress(r));for(let r of e)console.log(`Span ${r.spanContext().spanId} was not ended properly`),r.end();this.sample(),this.exportPromises.push(this.exportSpans(this.unexportedSpans)),this.unexportedSpans=[]}this.exportPromises.length>0&&(await Promise.allSettled(this.exportPromises),this.exportPromises=[],this.isFlushed=!0)}isSpanInProgress(e){return this.inprogressSpans.has(e.spanContext().spanId)}async exportSpans(e){await scheduler.wait(1),await new Promise((n,a)=>{this.exporter.export(e,s=>{s.code===Ne.SUCCESS?n():(console.log("exporting spans failed! "+s.error),a(s.error))})})}},P=class{constructor(e){this.exporter=e}static{o(this,"BatchTraceSpanProcessor")}traces={};getTraceState(e){let r=this.traces[e]||new U(this.exporter);return this.traces[e]=r,r}onStart(e,r){let n=e.spanContext().traceId;this.getTraceState(n).addSpan(e)}onEnd(e){let r=e.spanContext().traceId,n=this.getTraceState(r);n.endSpan(e).catch(a=>{console.log(a,"Failed to end span")}).finally(()=>{n.isFlushed&&delete this.traces[r]})}async forceFlush(e){if(e)await this.getTraceState(e).flush(),delete this.traces[e];else{let r=Object.values(this.traces).map(n=>n.flush);await Promise.allSettled(r),this.traces={}}}async shutdown(){await this.forceFlush()}};var ne=Symbol("Otel Tracing Configuration");function oe(t,e=re.active()){return e.setValue(ne,t)}o(oe,"setConfig");function f(){return re.active().getValue(ne)||void 0}o(f,"getActiveConfig");function We(t){return!!t.export}o(We,"isSpanExporter");function qe(t){return!!t.shouldSample}o(qe,"isSampler");function E(t){if($(t)){let e=t.sampling?.headSampler||{ratio:1},r=qe(e)?e:te(e),n=Array.isArray(t.spanProcessors)?t.spanProcessors:[t.spanProcessors];if(n.length===0)throw new Error("Warning! You must either specify an exporter or your own SpanProcessor(s)/Exporter combination in the open-telemetry configuration.");return{fetch:{includeTraceContext:t.fetch?.includeTraceContext??!0},handlers:{fetch:{acceptTraceContext:t.handlers?.fetch?.acceptTraceContext??!0}},postProcessor:t.postProcessor||(a=>a),sampling:{headSampler:r,tailSampler:Y(t.sampling?.tailSampler??J([Q,ee]))},service:t.service,spanProcessors:n,propagator:t.propagator||new Ue,instrumentation:{instrumentGlobalCache:t.instrumentation?.instrumentGlobalCache??!0,instrumentGlobalFetch:t.instrumentation?.instrumentGlobalFetch??!0}}}else{let e=We(t.exporter)?t.exporter:new v(t.exporter),r=[new P(e)],n=Object.assign(t,{exporter:void 0,spanProcessors:r});return E(n)}}o(E,"parseConfig");import{context as st,trace as it}from"@opentelemetry/api";import{ROOT_CONTEXT as je}from"@opentelemetry/api";import{AsyncLocalStorage as Ge}from"node:async_hooks";import{EventEmitter as Ve}from"node:events";var Ze=["addListener","on","once","prependListener","prependOnceListener"],W=class{static{o(this,"AbstractAsyncHooksContextManager")}bind(e,r){return r instanceof Ve?this._bindEventEmitter(e,r):typeof r=="function"?this._bindFunction(e,r):r}_bindFunction(e,r){let n=this,a=o(function(...s){return n.with(e,()=>r.apply(this,s))},"contextWrapper");return Object.defineProperty(a,"length",{enumerable:!1,configurable:!0,writable:!1,value:r.length}),a}_bindEventEmitter(e,r){return this._getPatchMap(r)!==void 0||(this._createPatchMap(r),Ze.forEach(a=>{r[a]!==void 0&&(r[a]=this._patchAddListener(r,r[a],e))}),typeof r.removeListener=="function"&&(r.removeListener=this._patchRemoveListener(r,r.removeListener)),typeof r.off=="function"&&(r.off=this._patchRemoveListener(r,r.off)),typeof r.removeAllListeners=="function"&&(r.removeAllListeners=this._patchRemoveAllListeners(r,r.removeAllListeners))),r}_patchRemoveListener(e,r){let n=this;return function(a,s){let i=n._getPatchMap(e)?.[a];if(i===void 0)return r.call(this,a,s);let c=i.get(s);return r.call(this,a,c||s)}}_patchRemoveAllListeners(e,r){let n=this;return function(a){let s=n._getPatchMap(e);return s!==void 0&&(arguments.length===0?n._createPatchMap(e):s[a]!==void 0&&delete s[a]),r.apply(this,arguments)}}_patchAddListener(e,r,n){let a=this;return function(s,i){if(a._wrapped)return r.call(this,s,i);let c=a._getPatchMap(e);c===void 0&&(c=a._createPatchMap(e));let l=c[s];l===void 0&&(l=new WeakMap,c[s]=l);let u=a.bind(n,i);l.set(i,u),a._wrapped=!0;try{return r.call(this,s,u)}finally{a._wrapped=!1}}}_createPatchMap(e){let r=Object.create(null);return e[this._kOtListeners]=r,r}_getPatchMap(e){return e[this._kOtListeners]}_kOtListeners=Symbol("OtListeners");_wrapped=!1},F=class extends W{static{o(this,"AsyncLocalStorageContextManager")}_asyncLocalStorage;constructor(){super(),this._asyncLocalStorage=new Ge}active(){return this._asyncLocalStorage.getStore()??je}with(e,r,n,...a){let s=n==null?r:r.bind(n);return this._asyncLocalStorage.run(e,s,...a)}enable(){return this}disable(){return this._asyncLocalStorage.disable(),this}};import{TraceFlags as ce,SpanKind as tt,context as G,trace as A}from"@opentelemetry/api";import{sanitizeAttributes as pe}from"@opentelemetry/core";import{RandomIdGenerator as rt,SamplingDecision as nt}from"@opentelemetry/sdk-trace-base";import{SpanKind as $e,SpanStatusCode as Be}from"@opentelemetry/api";import{hrTimeDuration as Ke,isAttributeValue as Xe,isTimeInput as Ye,sanitizeAttributes as ae}from"@opentelemetry/core";import{ATTR_EXCEPTION_MESSAGE as se,ATTR_EXCEPTION_STACKTRACE as Je,ATTR_EXCEPTION_TYPE as ie}from"@opentelemetry/semantic-conventions";function Qe(t){let e={};return typeof t=="string"?e[se]=t:(t.code?e[ie]=t.code.toString():t.name&&(e[ie]=t.name),t.message&&(e[se]=t.message),t.stack&&(e[Je]=t.stack)),e}o(Qe,"transformExceptionAttributes");function q(t){return[Math.trunc(t/1e3),t%1e3*1e6]}o(q,"millisToHr");function j(t){let e=Date.now();if(t){if(t instanceof Date)return q(t.getTime());if(typeof t=="number")return q(t);if(Array.isArray(t))return t}else return q(e);let r=t;throw new Error(`unreachable value: ${JSON.stringify(r)}`)}o(j,"getHrTime");function et(t){return typeof t=="string"&&t.length>0}o(et,"isAttributeKey");var w=class{static{o(this,"SpanImpl")}name;_spanContext;onEnd;parentSpanId;parentSpanContext;kind;attributes;status={code:Be.UNSET};endTime=[0,0];_duration=[0,0];startTime;events=[];links;resource;instrumentationScope={name:"@zuplo/otel"};_ended=!1;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;constructor(e){this.name=e.name,this._spanContext=e.spanContext,this.parentSpanId=e.parentSpanId,this.parentSpanContext=e.parentSpanContext,this.kind=e.spanKind||$e.INTERNAL,this.attributes=ae(e.attributes),this.startTime=j(e.startTime),this.links=e.links||[],this.resource=e.resource,this.onEnd=e.onEnd}addLink(e){return this.links.push(e),this}addLinks(e){return this.links.push(...e),this}spanContext(){return this._spanContext}setAttribute(e,r){return et(e)&&Xe(r)&&(this.attributes[e]=r),this}setAttributes(e){for(let[r,n]of Object.entries(e))this.setAttribute(r,n);return this}addEvent(e,r,n){Ye(r)&&(n=r,r=void 0);let a=ae(r),s=j(n);return this.events.push({name:e,attributes:a,time:s}),this}setStatus(e){return this.status=e,this}updateName(e){return this.name=e,this}end(e){this._ended||(this._ended=!0,this.endTime=j(e),this._duration=Ke(this.startTime,this.endTime),this.onEnd(this))}isRecording(){return!this._ended}recordException(e,r){let n=Qe(e);this.addEvent("exception",n,r)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}};var ue=new rt,le;function ot(t,e){return(t>>e-1&1)*e}o(ot,"getFlagAt");var g=class{static{o(this,"WorkerTracer")}spanProcessors;resource;constructor(e,r){this.spanProcessors=e,this.resource=r}async forceFlush(e){let r=this.spanProcessors.map(async n=>{await n.forceFlush(e)});await Promise.allSettled(r)}addToResource(e){this.resource.merge(e)}startSpan(e,r={},n=G.active()){r.root&&(n=A.deleteSpan(n));let a=f();if(!a)throw new Error("Config is undefined. This is a bug in the instrumentation logic");let s=A.getSpan(n)?.spanContext(),{traceId:i,randomTraceFlag:c}=at(s),l=r.kind||tt.INTERNAL,u=pe(r.attributes),C=a.sampling.headSampler.shouldSample(n,i,e,l,u,[]),{decision:S,traceState:R,attributes:b}=C,d=Object.assign({},r.attributes,b,le);le={};let p=ue.generateSpanId(),m=s?.spanId,L=(S===nt.RECORD_AND_SAMPLED?ce.SAMPLED:ce.NONE)+c,H={traceId:i,spanId:p,traceFlags:L,traceState:R},x=new w({attributes:pe(d),name:e,onEnd:o(M=>{this.spanProcessors.forEach(we=>{we.onEnd(M)})},"onEnd"),resource:this.resource,spanContext:H,parentSpanContext:s,parentSpanId:m,spanKind:l,startTime:r.startTime});return this.spanProcessors.forEach(M=>{M.onStart(x,n)}),x}startActiveSpan(e,...r){let n=r.length>1?r[0]:void 0,a=r.length>2?r[1]:G.active(),s=r[r.length-1],i=this.startSpan(e,n,a),c=A.setSpan(a,i);return G.with(c,s,void 0,i)}};function at(t){if(t&&A.isSpanContextValid(t)){let{traceId:e,traceFlags:r}=t;return{traceId:e,randomTraceFlag:ot(r,2)}}else return{traceId:ue.generateTraceId(),randomTraceFlag:2}}o(at,"getTraceInfo");var _=class{static{o(this,"ZuploTracerProvider")}spanProcessors;resource;tracers={};constructor(e,r){this.spanProcessors=e,this.resource=r}getTracer(e,r,n){let a=`${e}@${r||""}:${n?.schemaUrl||""}`;return this.tracers[a]||(this.tracers[a]=new g(this.spanProcessors,this.resource)),this.tracers[a]}register(){it.setGlobalTracerProvider(this),st.setGlobalContextManager(new F)}};import{trace as ct,SpanKind as me,propagation as fe,context as I,SpanStatusCode as pt}from"@opentelemetry/api";function ge(t){let e={},r=t.headers;e["http.request.method"]=t.method.toUpperCase(),e["http.request.body.size"]=r.get("content-length"),e["user_agent.original"]=r.get("user-agent"),e["http.mime_type"]=r.get("content-type"),e["http.accepts"]=r.get("accept");let n=new URL(t.url);return e["url.full"]=`${n.protocol}//${n.host}${n.pathname}${n.search}`,e["server.address"]=n.host,e["url.scheme"]=n.protocol,e["url.path"]=n.pathname,e["url.query"]=n.search,e}o(ge,"gatherRequestAttributes");function he(t){let e={};return e["http.response.status_code"]=t.status,t.headers.get("content-length")==null&&(e["http.response.body.size"]=t.headers.get("content-length")),e["http.mime_type"]=t.headers.get("content-type"),e}o(he,"gatherResponseAttributes");function lt(t){return fe.extract(I.active(),t,{get(e,r){return e.get(r)||void 0},keys(e){return[...e.keys()]}})}o(lt,"getParentContextFromHeaders");function ut(t){let e=f();return e===void 0?I.active():(typeof e.handlers.fetch.acceptTraceContext=="function"?e.handlers.fetch.acceptTraceContext(t):e.handlers.fetch.acceptTraceContext??!0)?lt(t.headers):I.active()}o(ut,"getParentContextFromRequest");function de(t,e){let r=t;if(r.attributes["http.route"]){let n=e.method.toUpperCase();t.updateName(`${n} ${r.attributes["http.route"]}`)}}o(de,"updateSpanNameOnRoute");var Se={getInitialSpanInfo:o(t=>{let e=ut(t),r={"faas.trigger":"http","faas.invocation_id":t.headers.get("zp-rid")??void 0,"cf.ray_id":t.headers.get("cf-ray")??void 0};return Object.assign(r,ge(t)),{name:`fetchHandler ${t.method.toUpperCase()}`,options:{attributes:r,kind:me.SERVER},context:e}},"getInitialSpanInfo"),getAttributesFromResult:o(t=>he(t),"getAttributesFromResult"),executionSuccess:de,executionFailed:de};function dt(t,e,r){return y(t,{apply:o((a,s,i)=>{let c=new Request(i[0],i[1]);if(!c.url.startsWith("http"))return Reflect.apply(a,s,i);let l=f();if(!l)return Reflect.apply(a,s,[c]);let u=e(l),h=ct.getTracer("fetcher"),C={kind:me.CLIENT,attributes:r},S=new URL(c.url).host,R=c.method.toUpperCase(),b=typeof r?.name=="string"?r?.name:`${R}: ${S}`;return h.startActiveSpan(b,C,async p=>{try{((typeof u.includeTraceContext=="function"?u.includeTraceContext(c):u.includeTraceContext)??!0)&&fe.inject(I.active(),c.headers,{set:o((L,H,x)=>L.set(H,typeof x=="string"?x:String(x)),"set")}),p.setAttributes(ge(c));let k=await Reflect.apply(a,s,[c]);return p.setAttributes(he(k)),k}catch(m){throw p.recordException(m),p.setStatus({code:pt.ERROR}),m}finally{p.end()}})},"apply")},!0)}o(dt,"instrumentClientFetch");function xe(){globalThis.fetch=dt(globalThis.fetch,t=>t.fetch)}o(xe,"instrumentGlobalFetch");import{trace as gn}from"@opentelemetry/api";var V=class{static{o(this,"PromiseTracker")}_outstandingPromises=[];get outstandingPromiseCount(){return this._outstandingPromises.length}track(e){this._outstandingPromises.push(e)}async wait(){await ft(this._outstandingPromises)}};function mt(t,e,r){return y(t,{apply(a,s,i){return r.track(i[0]),Reflect.apply(a,e,i)}})}o(mt,"createWaitUntil");function Te(t){let e=new V;return{event:new Proxy(t,{get(n,a){if(a==="waitUntil"){let s=Reflect.get(n,a);return mt(s,t,e)}else return N(n,a)}}),tracker:e}}o(Te,"proxyExecutionContext");async function ft(t){let e;do e=await Promise.allSettled(t);while(e.length!==t.length);return e}o(ft,"allSettledMutable");import{ATTR_CLOUD_ACCOUNT_ID as St,ATTR_CLOUD_PLATFORM as xt,ATTR_CLOUD_PROVIDER as Tt,ATTR_SERVICE_NAME as Ct,ATTR_SERVICE_NAMESPACE as Rt,ATTR_SERVICE_VERSION as bt,ATTR_TELEMETRY_SDK_NAME as yt}from"@opentelemetry/semantic-conventions/incubating";var vt=o((t,e)=>{let r={[Tt]:"zuplo",[xt]:"zuplo-api",[St]:t.accountName,"cloud.project.id":t.projectName,"cloud.resource_id":t.deploymentName,"cloud.instance_id":t.instanceId,"deployment.environment.name":t.environmentStage,[yt]:"@zuplo/otel",[O.ZuploBuildId]:t.buildId,[O.ZuploBuildVersion]:t.zuploVersion,[O.ZuploBuildCompatibilityDate]:t.compatibilityDate,[O.ZuploEnvironmentType]:t.environmentType},n=Ce({[Ct]:e.service.name,[Rt]:e.service.namespace,[bt]:e.service.version});return Ce(r).merge(n)},"createResource"),Re=!1;function be(t,e){if(!Re){e.instrumentation.instrumentGlobalFetch&&xe(),gt.setGlobalPropagator(e.propagator);let r=vt(t,e);new _(e.spanProcessors,r).register(),Re=!0}}o(be,"init");function Ee(t,e){return typeof e=="function"?r=>{let n=E(e(r));return be(t,n),n}:()=>{let r=E(e);return be(t,r),r}}o(Ee,"createInitializer");async function Pt(t,e){let r=Pe.getTracer("export");r instanceof g?(await scheduler.wait(1),await e?.wait(),await r.forceFlush(t)):console.error("The global tracer is not of type WorkerTracer and can not export spans")}o(Pt,"exportSpans");var ye=!0;function Et(t){return(e,r)=>{let[n,a]=r,{event:s,tracker:i}=Te(a),c=t.instrumentTrigger?t.instrumentTrigger(n):n,l=Pe.getTracer("handler"),{name:u,options:h,context:C}=t.getInitialSpanInfo(n),S=h.attributes||{};S["faas.coldstart"]=ye,h.attributes=S,ye=!1;let R=C||ve.active();return l.startActiveSpan(u,h,R,async d=>{try{let p=await e(c,s);if(t.getAttributesFromResult){let m=t.getAttributesFromResult(p);d.setAttributes(m)}return t.executionSuccess&&t.executionSuccess(d,n,p),p}catch(p){throw d.recordException(p),d.setStatus({code:ht.ERROR}),t.executionFailed&&t.executionFailed(d,n,p),p}finally{d.end(),a.waitUntil(Pt(d.spanContext().traceId,i))}})}}o(Et,"createHandlerFlowFn");function Fe(t,e,r){return(n,a)=>{let s=e(n),i=oe(s),c=Et(r);return ve.with(i,c,n,t,[n,a])}}o(Fe,"createHandlerProxy");var Z=class extends Ft{constructor(r){super();this.config=r;wt("opentelemetry")}static{o(this,"OpenTelemetryPlugin")}instrument(r){let n=Ee(r,this.config);return{requestHandlerProxy:o(s=>Fe(s,n,Se),"requestHandlerProxy")}}};export{Z as a};
|
package/out/esm/index.js
CHANGED
|
@@ -22,4 +22,4 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a}from"./chunk-
|
|
25
|
+
import{a}from"./chunk-MAM3UMUM.js";export{a as OpenTelemetryPlugin};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zuplo/otel",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "6.56.
|
|
4
|
+
"version": "6.56.4",
|
|
5
5
|
"repository": "https://github.com/zuplo/zuplo",
|
|
6
6
|
"author": "Zuplo, Inc.",
|
|
7
7
|
"exports": {
|
|
@@ -38,6 +38,6 @@
|
|
|
38
38
|
"@opentelemetry/semantic-conventions": "1.34.0"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
|
-
"@zuplo/runtime": "6.56.
|
|
41
|
+
"@zuplo/runtime": "6.56.4"
|
|
42
42
|
}
|
|
43
43
|
}
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
/*---------------------------------------------------------------------------------------------
|
|
3
|
-
* Copyright (c) Zuplo, Inc. All rights reserved.
|
|
4
|
-
*
|
|
5
|
-
* This software and associated documentation files (the "Software") is intended to be used
|
|
6
|
-
* only by Zuplo customers solely to develop and test applications that will be deployed
|
|
7
|
-
* to Zuplo hosted services. You and others in your organization may use these files on your
|
|
8
|
-
* Development Devices solely for the above stated purpose.
|
|
9
|
-
*
|
|
10
|
-
* Outside of uses stated above, no license is granted for any other purpose including
|
|
11
|
-
* without limitation the rights to use, copy, modify, merge, publish, distribute,
|
|
12
|
-
* sublicense, host, and/or sell copies of the Software.
|
|
13
|
-
*
|
|
14
|
-
* The software may include third party components with separate legal notices or governed by
|
|
15
|
-
* other agreements, as described in licenses either embedded in or accompanying the Software.
|
|
16
|
-
*
|
|
17
|
-
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
|
18
|
-
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
|
19
|
-
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
|
|
20
|
-
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
21
|
-
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
22
|
-
* DEALINGS IN THE SOFTWARE.
|
|
23
|
-
*--------------------------------------------------------------------------------------------*/
|
|
24
|
-
|
|
25
|
-
var Ae=Object.defineProperty;var o=(t,e)=>Ae(t,"name",{value:e,configurable:!0});import{Buffer as _e}from"node:buffer";globalThis.Buffer=_e;import{TelemetryPlugin as Ft,trackFeature as wt}from"@zuplo/runtime";import{context as ve,propagation as gt,SpanStatusCode as ht,trace as Pe}from"@opentelemetry/api";import{SemanticAttributes as O}from"@zuplo/runtime";import{resourceFromAttributes as Ce}from"@opentelemetry/resources";import{context as re}from"@opentelemetry/api";function $(t){return!!t.spanProcessors}o($,"isSpanProcessorConfig");import{W3CTraceContextPropagator as Ue}from"@opentelemetry/core";import{ExportResultCode as Oe}from"@opentelemetry/core";import{JsonTraceSerializer as ke}from"@opentelemetry/otlp-transformer";var D=Symbol("unwrap");function B(t){return t&&!!t[D]}o(B,"isWrapped");function Ie(t){return t!==null&&typeof t=="object"||typeof t=="function"}o(Ie,"isProxyable");function y(t,e,r=!0){if(B(t)||!Ie(t))return t;let n=Object.assign({},e);return n.get=(a,s,i)=>{if(s===D)return t;if(e.get)return e.get(a,s,i);if(s==="bind")return()=>i;if(r)return N(a,s)},n.apply=(a,s,i)=>{if(e.apply)return e.apply(T(a),T(s),i)},new Proxy(t,n)}o(y,"wrap");function T(t){return t&&B(t)?t[D]:t}o(T,"unwrap");function N(t,e,r){let n=T(t);r=T(r)||n;let a=Reflect.get(n,e);return typeof a=="function"?a.constructor.name==="RpcProperty"?(...s)=>n[e](...s):a.bind(r):a}o(N,"passthroughGet");import{BackgroundDispatcher as Le}from"@zuplo/runtime";var He={accept:"application/json","content-type":"application/json"},v=class{static{o(this,"OTLPExporter")}headers;url;constructor(e){this.url=e.url,this.headers=Object.assign({},He,e.headers)}export(e,r){e.forEach(n=>{this.batcher.enqueue(n)}),r({code:Oe.SUCCESS})}shutdown(){throw new Error("Method not implemented.")}forceFlush(){throw new Error("Method not implemented.")}dispatchFunction=o(async e=>{if(e.length===0)return;let r=new TextDecoder,n=ke.serializeRequest(e),a=r.decode(n),s=await T(fetch)(this.url,{method:"POST",body:a,headers:this.headers});if(!s.ok)try{let i=await s.text();console.error("Error exporting traces",i)}catch{console.error("Error exporting traces")}},"dispatchFunction");batcher=new Le(this.dispatchFunction,{msDelay:10})};import{TraceFlags as K,SpanStatusCode as Me}from"@opentelemetry/api";import{ParentBasedSampler as X,TraceIdRatioBasedSampler as De}from"@opentelemetry/sdk-trace-base";import{SemanticAttributes as z}from"@zuplo/runtime";function Y(t){return e=>{let r=e.localRootSpan;return r.attributes[z.SystemTrace]??r.attributes[z.RouteSystem]??r.attributes[z.RouteTrace]===!1?!1:t(e)}}o(Y,"internalTailSampler");function J(t){return e=>t.reduce((r,n)=>r||n(e),!1)}o(J,"multiTailSampler");var Q=o(t=>(t.localRootSpan.spanContext().traceFlags&K.SAMPLED)===K.SAMPLED,"isHeadSampled"),ee=o(t=>t.localRootSpan.status.code===Me.ERROR,"isRootErrorSpan");function te(t){let e=new De(t.ratio);return typeof t.acceptRemote=="boolean"&&!t.acceptRemote?new X({root:e,remoteParentSampled:e,remoteParentNotSampled:e}):new X({root:e})}o(te,"createSampler");import{ExportResultCode as Ne}from"@opentelemetry/core";function ze(){let t=f();return t||console.log("Could not find config for sampling, sending everything by default"),t?t.sampling.tailSampler:()=>!0}o(ze,"getSampler");var U=class{static{o(this,"TraceState")}unexportedSpans=[];inprogressSpans=new Set;exporter;exportPromises=[];localRootSpan;traceDecision;constructor(e){this.exporter=e}addSpan(e){let r=e;this.localRootSpan=this.localRootSpan||r,this.unexportedSpans.push(r),this.inprogressSpans.add(e.spanContext().spanId)}endSpan(e){this.inprogressSpans.delete(e.spanContext().spanId),this.inprogressSpans.size===0&&this.flush()}sample(){if(this.traceDecision===void 0&&this.unexportedSpans.length>0){let e=ze();this.traceDecision=e({traceId:this.localRootSpan.spanContext().traceId,localRootSpan:this.localRootSpan,spans:this.unexportedSpans})}this.unexportedSpans=this.traceDecision?this.unexportedSpans:[]}async flush(){if(this.unexportedSpans.length>0){let e=this.unexportedSpans.filter(r=>this.isSpanInProgress(r));for(let r of e)console.log(`Span ${r.spanContext().spanId} was not ended properly`),r.end();this.sample(),this.exportPromises.push(this.exportSpans(this.unexportedSpans)),this.unexportedSpans=[]}this.exportPromises.length>0&&await Promise.allSettled(this.exportPromises)}isSpanInProgress(e){return this.inprogressSpans.has(e.spanContext().spanId)}async exportSpans(e){await scheduler.wait(1),await new Promise((n,a)=>{this.exporter.export(e,s=>{s.code===Ne.SUCCESS?n():(console.log("exporting spans failed! "+s.error),a(s.error))})})}},P=class{constructor(e){this.exporter=e}static{o(this,"BatchTraceSpanProcessor")}traces={};getTraceState(e){let r=this.traces[e]||new U(this.exporter);return this.traces[e]=r,r}onStart(e,r){let n=e.spanContext().traceId;this.getTraceState(n).addSpan(e)}onEnd(e){let r=e.spanContext().traceId;this.getTraceState(r).endSpan(e)}async forceFlush(e){if(e)await this.getTraceState(e).flush();else{let r=Object.values(this.traces).map(n=>n.flush);await Promise.allSettled(r)}}async shutdown(){await this.forceFlush()}};var ne=Symbol("Otel Tracing Configuration");function oe(t,e=re.active()){return e.setValue(ne,t)}o(oe,"setConfig");function f(){return re.active().getValue(ne)||void 0}o(f,"getActiveConfig");function We(t){return!!t.export}o(We,"isSpanExporter");function qe(t){return!!t.shouldSample}o(qe,"isSampler");function E(t){if($(t)){let e=t.sampling?.headSampler||{ratio:1},r=qe(e)?e:te(e),n=Array.isArray(t.spanProcessors)?t.spanProcessors:[t.spanProcessors];if(n.length===0)throw new Error("Warning! You must either specify an exporter or your own SpanProcessor(s)/Exporter combination in the open-telemetry configuration.");return{fetch:{includeTraceContext:t.fetch?.includeTraceContext??!0},handlers:{fetch:{acceptTraceContext:t.handlers?.fetch?.acceptTraceContext??!0}},postProcessor:t.postProcessor||(a=>a),sampling:{headSampler:r,tailSampler:Y(t.sampling?.tailSampler??J([Q,ee]))},service:t.service,spanProcessors:n,propagator:t.propagator||new Ue,instrumentation:{instrumentGlobalCache:t.instrumentation?.instrumentGlobalCache??!0,instrumentGlobalFetch:t.instrumentation?.instrumentGlobalFetch??!0}}}else{let e=We(t.exporter)?t.exporter:new v(t.exporter),r=[new P(e)],n=Object.assign(t,{exporter:void 0,spanProcessors:r});return E(n)}}o(E,"parseConfig");import{context as st,trace as it}from"@opentelemetry/api";import{ROOT_CONTEXT as je}from"@opentelemetry/api";import{AsyncLocalStorage as Ge}from"node:async_hooks";import{EventEmitter as Ve}from"node:events";var Ze=["addListener","on","once","prependListener","prependOnceListener"],W=class{static{o(this,"AbstractAsyncHooksContextManager")}bind(e,r){return r instanceof Ve?this._bindEventEmitter(e,r):typeof r=="function"?this._bindFunction(e,r):r}_bindFunction(e,r){let n=this,a=o(function(...s){return n.with(e,()=>r.apply(this,s))},"contextWrapper");return Object.defineProperty(a,"length",{enumerable:!1,configurable:!0,writable:!1,value:r.length}),a}_bindEventEmitter(e,r){return this._getPatchMap(r)!==void 0||(this._createPatchMap(r),Ze.forEach(a=>{r[a]!==void 0&&(r[a]=this._patchAddListener(r,r[a],e))}),typeof r.removeListener=="function"&&(r.removeListener=this._patchRemoveListener(r,r.removeListener)),typeof r.off=="function"&&(r.off=this._patchRemoveListener(r,r.off)),typeof r.removeAllListeners=="function"&&(r.removeAllListeners=this._patchRemoveAllListeners(r,r.removeAllListeners))),r}_patchRemoveListener(e,r){let n=this;return function(a,s){let i=n._getPatchMap(e)?.[a];if(i===void 0)return r.call(this,a,s);let p=i.get(s);return r.call(this,a,p||s)}}_patchRemoveAllListeners(e,r){let n=this;return function(a){let s=n._getPatchMap(e);return s!==void 0&&(arguments.length===0?n._createPatchMap(e):s[a]!==void 0&&delete s[a]),r.apply(this,arguments)}}_patchAddListener(e,r,n){let a=this;return function(s,i){if(a._wrapped)return r.call(this,s,i);let p=a._getPatchMap(e);p===void 0&&(p=a._createPatchMap(e));let l=p[s];l===void 0&&(l=new WeakMap,p[s]=l);let u=a.bind(n,i);l.set(i,u),a._wrapped=!0;try{return r.call(this,s,u)}finally{a._wrapped=!1}}}_createPatchMap(e){let r=Object.create(null);return e[this._kOtListeners]=r,r}_getPatchMap(e){return e[this._kOtListeners]}_kOtListeners=Symbol("OtListeners");_wrapped=!1},F=class extends W{static{o(this,"AsyncLocalStorageContextManager")}_asyncLocalStorage;constructor(){super(),this._asyncLocalStorage=new Ge}active(){return this._asyncLocalStorage.getStore()??je}with(e,r,n,...a){let s=n==null?r:r.bind(n);return this._asyncLocalStorage.run(e,s,...a)}enable(){return this}disable(){return this._asyncLocalStorage.disable(),this}};import{TraceFlags as pe,SpanKind as tt,context as G,trace as A}from"@opentelemetry/api";import{sanitizeAttributes as ce}from"@opentelemetry/core";import{RandomIdGenerator as rt,SamplingDecision as nt}from"@opentelemetry/sdk-trace-base";import{SpanKind as $e,SpanStatusCode as Be}from"@opentelemetry/api";import{hrTimeDuration as Ke,isAttributeValue as Xe,isTimeInput as Ye,sanitizeAttributes as ae}from"@opentelemetry/core";import{ATTR_EXCEPTION_MESSAGE as se,ATTR_EXCEPTION_STACKTRACE as Je,ATTR_EXCEPTION_TYPE as ie}from"@opentelemetry/semantic-conventions";function Qe(t){let e={};return typeof t=="string"?e[se]=t:(t.code?e[ie]=t.code.toString():t.name&&(e[ie]=t.name),t.message&&(e[se]=t.message),t.stack&&(e[Je]=t.stack)),e}o(Qe,"transformExceptionAttributes");function q(t){return[Math.trunc(t/1e3),t%1e3*1e6]}o(q,"millisToHr");function j(t){let e=Date.now();if(t){if(t instanceof Date)return q(t.getTime());if(typeof t=="number")return q(t);if(Array.isArray(t))return t}else return q(e);let r=t;throw new Error(`unreachable value: ${JSON.stringify(r)}`)}o(j,"getHrTime");function et(t){return typeof t=="string"&&t.length>0}o(et,"isAttributeKey");var w=class{static{o(this,"SpanImpl")}name;_spanContext;onEnd;parentSpanId;parentSpanContext;kind;attributes;status={code:Be.UNSET};endTime=[0,0];_duration=[0,0];startTime;events=[];links;resource;instrumentationScope={name:"@zuplo/otel"};_ended=!1;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;constructor(e){this.name=e.name,this._spanContext=e.spanContext,this.parentSpanId=e.parentSpanId,this.parentSpanContext=e.parentSpanContext,this.kind=e.spanKind||$e.INTERNAL,this.attributes=ae(e.attributes),this.startTime=j(e.startTime),this.links=e.links||[],this.resource=e.resource,this.onEnd=e.onEnd}addLink(e){return this.links.push(e),this}addLinks(e){return this.links.push(...e),this}spanContext(){return this._spanContext}setAttribute(e,r){return et(e)&&Xe(r)&&(this.attributes[e]=r),this}setAttributes(e){for(let[r,n]of Object.entries(e))this.setAttribute(r,n);return this}addEvent(e,r,n){Ye(r)&&(n=r,r=void 0);let a=ae(r),s=j(n);return this.events.push({name:e,attributes:a,time:s}),this}setStatus(e){return this.status=e,this}updateName(e){return this.name=e,this}end(e){this._ended||(this._ended=!0,this.endTime=j(e),this._duration=Ke(this.startTime,this.endTime),this.onEnd(this))}isRecording(){return!this._ended}recordException(e,r){let n=Qe(e);this.addEvent("exception",n,r)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}};var ue=new rt,le;function ot(t,e){return(t>>e-1&1)*e}o(ot,"getFlagAt");var g=class{static{o(this,"WorkerTracer")}spanProcessors;resource;constructor(e,r){this.spanProcessors=e,this.resource=r}async forceFlush(e){let r=this.spanProcessors.map(async n=>{await n.forceFlush(e)});await Promise.allSettled(r)}addToResource(e){this.resource.merge(e)}startSpan(e,r={},n=G.active()){r.root&&(n=A.deleteSpan(n));let a=f();if(!a)throw new Error("Config is undefined. This is a bug in the instrumentation logic");let s=A.getSpan(n)?.spanContext(),{traceId:i,randomTraceFlag:p}=at(s),l=r.kind||tt.INTERNAL,u=ce(r.attributes),C=a.sampling.headSampler.shouldSample(n,i,e,l,u,[]),{decision:S,traceState:R,attributes:b}=C,d=Object.assign({},r.attributes,b,le);le={};let c=ue.generateSpanId(),m=s?.spanId,L=(S===nt.RECORD_AND_SAMPLED?pe.SAMPLED:pe.NONE)+p,H={traceId:i,spanId:c,traceFlags:L,traceState:R},x=new w({attributes:ce(d),name:e,onEnd:o(M=>{this.spanProcessors.forEach(we=>{we.onEnd(M)})},"onEnd"),resource:this.resource,spanContext:H,parentSpanContext:s,parentSpanId:m,spanKind:l,startTime:r.startTime});return this.spanProcessors.forEach(M=>{M.onStart(x,n)}),x}startActiveSpan(e,...r){let n=r.length>1?r[0]:void 0,a=r.length>2?r[1]:G.active(),s=r[r.length-1],i=this.startSpan(e,n,a),p=A.setSpan(a,i);return G.with(p,s,void 0,i)}};function at(t){if(t&&A.isSpanContextValid(t)){let{traceId:e,traceFlags:r}=t;return{traceId:e,randomTraceFlag:ot(r,2)}}else return{traceId:ue.generateTraceId(),randomTraceFlag:2}}o(at,"getTraceInfo");var _=class{static{o(this,"ZuploTracerProvider")}spanProcessors;resource;tracers={};constructor(e,r){this.spanProcessors=e,this.resource=r}getTracer(e,r,n){let a=`${e}@${r||""}:${n?.schemaUrl||""}`;return this.tracers[a]||(this.tracers[a]=new g(this.spanProcessors,this.resource)),this.tracers[a]}register(){it.setGlobalTracerProvider(this),st.setGlobalContextManager(new F)}};import{trace as pt,SpanKind as me,propagation as fe,context as I,SpanStatusCode as ct}from"@opentelemetry/api";function ge(t){let e={},r=t.headers;e["http.request.method"]=t.method.toUpperCase(),e["http.request.body.size"]=r.get("content-length"),e["user_agent.original"]=r.get("user-agent"),e["http.mime_type"]=r.get("content-type"),e["http.accepts"]=r.get("accept");let n=new URL(t.url);return e["url.full"]=`${n.protocol}//${n.host}${n.pathname}${n.search}`,e["server.address"]=n.host,e["url.scheme"]=n.protocol,e["url.path"]=n.pathname,e["url.query"]=n.search,e}o(ge,"gatherRequestAttributes");function he(t){let e={};return e["http.response.status_code"]=t.status,t.headers.get("content-length")==null&&(e["http.response.body.size"]=t.headers.get("content-length")),e["http.mime_type"]=t.headers.get("content-type"),e}o(he,"gatherResponseAttributes");function lt(t){return fe.extract(I.active(),t,{get(e,r){return e.get(r)||void 0},keys(e){return[...e.keys()]}})}o(lt,"getParentContextFromHeaders");function ut(t){let e=f();return e===void 0?I.active():(typeof e.handlers.fetch.acceptTraceContext=="function"?e.handlers.fetch.acceptTraceContext(t):e.handlers.fetch.acceptTraceContext??!0)?lt(t.headers):I.active()}o(ut,"getParentContextFromRequest");function de(t,e){let r=t;if(r.attributes["http.route"]){let n=e.method.toUpperCase();t.updateName(`${n} ${r.attributes["http.route"]}`)}}o(de,"updateSpanNameOnRoute");var Se={getInitialSpanInfo:o(t=>{let e=ut(t),r={"faas.trigger":"http","faas.invocation_id":t.headers.get("zp-rid")??void 0,"cf.ray_id":t.headers.get("cf-ray")??void 0};return Object.assign(r,ge(t)),{name:`fetchHandler ${t.method.toUpperCase()}`,options:{attributes:r,kind:me.SERVER},context:e}},"getInitialSpanInfo"),getAttributesFromResult:o(t=>he(t),"getAttributesFromResult"),executionSuccess:de,executionFailed:de};function dt(t,e,r){return y(t,{apply:o((a,s,i)=>{let p=new Request(i[0],i[1]);if(!p.url.startsWith("http"))return Reflect.apply(a,s,i);let l=f();if(!l)return Reflect.apply(a,s,[p]);let u=e(l),h=pt.getTracer("fetcher"),C={kind:me.CLIENT,attributes:r},S=new URL(p.url).host,R=p.method.toUpperCase(),b=typeof r?.name=="string"?r?.name:`${R}: ${S}`;return h.startActiveSpan(b,C,async c=>{try{((typeof u.includeTraceContext=="function"?u.includeTraceContext(p):u.includeTraceContext)??!0)&&fe.inject(I.active(),p.headers,{set:o((L,H,x)=>L.set(H,typeof x=="string"?x:String(x)),"set")}),c.setAttributes(ge(p));let k=await Reflect.apply(a,s,[p]);return c.setAttributes(he(k)),k}catch(m){throw c.recordException(m),c.setStatus({code:ct.ERROR}),m}finally{c.end()}})},"apply")},!0)}o(dt,"instrumentClientFetch");function xe(){globalThis.fetch=dt(globalThis.fetch,t=>t.fetch)}o(xe,"instrumentGlobalFetch");import{trace as gn}from"@opentelemetry/api";var V=class{static{o(this,"PromiseTracker")}_outstandingPromises=[];get outstandingPromiseCount(){return this._outstandingPromises.length}track(e){this._outstandingPromises.push(e)}async wait(){await ft(this._outstandingPromises)}};function mt(t,e,r){return y(t,{apply(a,s,i){return r.track(i[0]),Reflect.apply(a,e,i)}})}o(mt,"createWaitUntil");function Te(t){let e=new V;return{event:new Proxy(t,{get(n,a){if(a==="waitUntil"){let s=Reflect.get(n,a);return mt(s,t,e)}else return N(n,a)}}),tracker:e}}o(Te,"proxyExecutionContext");async function ft(t){let e;do e=await Promise.allSettled(t);while(e.length!==t.length);return e}o(ft,"allSettledMutable");import{ATTR_CLOUD_ACCOUNT_ID as St,ATTR_CLOUD_PLATFORM as xt,ATTR_CLOUD_PROVIDER as Tt,ATTR_SERVICE_NAME as Ct,ATTR_SERVICE_NAMESPACE as Rt,ATTR_SERVICE_VERSION as bt,ATTR_TELEMETRY_SDK_NAME as yt}from"@opentelemetry/semantic-conventions/incubating";var vt=o((t,e)=>{let r={[Tt]:"zuplo",[xt]:"zuplo-api",[St]:t.accountName,"cloud.project.id":t.projectName,"cloud.resource_id":t.deploymentName,"cloud.instance_id":t.instanceId,"deployment.environment.name":t.environmentStage,[yt]:"@zuplo/otel",[O.ZuploBuildId]:t.buildId,[O.ZuploBuildVersion]:t.zuploVersion,[O.ZuploBuildCompatibilityDate]:t.compatibilityDate,[O.ZuploEnvironmentType]:t.environmentType},n=Ce({[Ct]:e.service.name,[Rt]:e.service.namespace,[bt]:e.service.version});return Ce(r).merge(n)},"createResource"),Re=!1;function be(t,e){if(!Re){e.instrumentation.instrumentGlobalFetch&&xe(),gt.setGlobalPropagator(e.propagator);let r=vt(t,e);new _(e.spanProcessors,r).register(),Re=!0}}o(be,"init");function Ee(t,e){return typeof e=="function"?r=>{let n=E(e(r));return be(t,n),n}:()=>{let r=E(e);return be(t,r),r}}o(Ee,"createInitializer");async function Pt(t,e){let r=Pe.getTracer("export");r instanceof g?(await scheduler.wait(1),await e?.wait(),await r.forceFlush(t)):console.error("The global tracer is not of type WorkerTracer and can not export spans")}o(Pt,"exportSpans");var ye=!0;function Et(t){return(e,r)=>{let[n,a]=r,{event:s,tracker:i}=Te(a),p=t.instrumentTrigger?t.instrumentTrigger(n):n,l=Pe.getTracer("handler"),{name:u,options:h,context:C}=t.getInitialSpanInfo(n),S=h.attributes||{};S["faas.coldstart"]=ye,h.attributes=S,ye=!1;let R=C||ve.active();return l.startActiveSpan(u,h,R,async d=>{try{let c=await e(p,s);if(t.getAttributesFromResult){let m=t.getAttributesFromResult(c);d.setAttributes(m)}return t.executionSuccess&&t.executionSuccess(d,n,c),c}catch(c){throw d.recordException(c),d.setStatus({code:ht.ERROR}),t.executionFailed&&t.executionFailed(d,n,c),c}finally{d.end(),a.waitUntil(Pt(d.spanContext().traceId,i))}})}}o(Et,"createHandlerFlowFn");function Fe(t,e,r){return(n,a)=>{let s=e(n),i=oe(s),p=Et(r);return ve.with(i,p,n,t,[n,a])}}o(Fe,"createHandlerProxy");var Z=class extends Ft{constructor(r){super();this.config=r;wt("opentelemetry")}static{o(this,"OpenTelemetryPlugin")}instrument(r){let n=Ee(r,this.config);return{requestHandlerProxy:o(s=>Fe(s,n,Se),"requestHandlerProxy")}}};export{Z as a};
|