@zuplo/otel 6.51.32 → 6.51.34
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-IY4CD3QP.js +25 -0
- package/out/esm/index.js +1 -1
- package/out/types/index.d.ts +17 -11
- package/package.json +3 -4
- package/out/esm/chunk-RKVZF2YJ.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(x(a),x(s),i)},new Proxy(t,n)}o(y,"wrap");function x(t){return t&&B(t)?t[D]:t}o(x,"unwrap");function N(t,e,r){let n=x(t);r=x(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 x(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},T=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(T,n)}),T}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,T)=>L.set(H,typeof T=="string"?T:String(T)),"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 Te(){globalThis.fetch=dt(globalThis.fetch,t=>t.fetch)}o(Te,"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 xe(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(xe,"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 Tt,ATTR_CLOUD_PROVIDER as xt,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={[xt]:"zuplo",[Tt]:"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&&Te(),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}=xe(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};
|
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-IY4CD3QP.js";export{a as OpenTelemetryPlugin};
|
package/out/types/index.d.ts
CHANGED
|
@@ -15,14 +15,28 @@ declare interface FetcherConfig {
|
|
|
15
15
|
includeTraceContext?: boolean | IncludeTraceContextFn;
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
+
declare interface FetchHandlerConfig {
|
|
19
|
+
/**
|
|
20
|
+
* Whether to enable context propagation for incoming requests to `fetch`.
|
|
21
|
+
* This enables or disables distributed tracing from W3C Trace Context headers.
|
|
22
|
+
* @default true
|
|
23
|
+
*/
|
|
24
|
+
acceptTraceContext?: boolean | AcceptTraceContextFn;
|
|
25
|
+
}
|
|
26
|
+
|
|
18
27
|
declare interface HandlerConfig {
|
|
19
|
-
fetch?:
|
|
28
|
+
fetch?: FetchHandlerConfig;
|
|
20
29
|
}
|
|
21
30
|
|
|
22
31
|
declare type HeadSamplerConf = Sampler | ParentRatioSamplingConfig;
|
|
23
32
|
|
|
24
33
|
declare type IncludeTraceContextFn = (request: Request) => boolean;
|
|
25
34
|
|
|
35
|
+
declare interface InstrumentationOptions {
|
|
36
|
+
instrumentGlobalFetch?: boolean;
|
|
37
|
+
instrumentGlobalCache?: boolean;
|
|
38
|
+
}
|
|
39
|
+
|
|
26
40
|
declare interface LocalTrace {
|
|
27
41
|
readonly traceId: string;
|
|
28
42
|
readonly localRootSpan: ReadableSpan;
|
|
@@ -53,15 +67,6 @@ declare interface ParentRatioSamplingConfig {
|
|
|
53
67
|
|
|
54
68
|
declare type PostProcessorFn = (spans: ReadableSpan[]) => ReadableSpan[];
|
|
55
69
|
|
|
56
|
-
declare interface RequestHandlerConfig {
|
|
57
|
-
/**
|
|
58
|
-
* Whether to enable context propagation for incoming requests to `fetch`.
|
|
59
|
-
* This enables or disables distributed tracing from W3C Trace Context headers.
|
|
60
|
-
* @default true
|
|
61
|
-
*/
|
|
62
|
-
acceptTraceContext?: boolean | AcceptTraceContextFn;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
70
|
/* Excluded from this release type: RequestHandlerProxy */
|
|
66
71
|
|
|
67
72
|
declare interface SamplingConfig<HS extends HeadSamplerConf = HeadSamplerConf> {
|
|
@@ -70,7 +75,7 @@ declare interface SamplingConfig<HS extends HeadSamplerConf = HeadSamplerConf> {
|
|
|
70
75
|
}
|
|
71
76
|
|
|
72
77
|
declare interface ServiceConfig {
|
|
73
|
-
name
|
|
78
|
+
name: string;
|
|
74
79
|
namespace?: string;
|
|
75
80
|
version?: string;
|
|
76
81
|
}
|
|
@@ -88,6 +93,7 @@ declare interface TraceConfigBase {
|
|
|
88
93
|
postProcessor?: PostProcessorFn;
|
|
89
94
|
sampling?: SamplingConfig;
|
|
90
95
|
propagator?: TextMapPropagator;
|
|
96
|
+
instrumentation?: InstrumentationOptions;
|
|
91
97
|
}
|
|
92
98
|
|
|
93
99
|
declare interface TraceConfigExporter extends TraceConfigBase {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zuplo/otel",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "6.51.
|
|
4
|
+
"version": "6.51.34",
|
|
5
5
|
"repository": "https://github.com/zuplo/zuplo",
|
|
6
6
|
"author": "Zuplo, Inc.",
|
|
7
7
|
"exports": {
|
|
@@ -35,10 +35,9 @@
|
|
|
35
35
|
"@opentelemetry/otlp-transformer": "0.201.1",
|
|
36
36
|
"@opentelemetry/resources": "2.0.1",
|
|
37
37
|
"@opentelemetry/sdk-trace-base": "2.0.1",
|
|
38
|
-
"@opentelemetry/semantic-conventions": "1.34.0"
|
|
39
|
-
"ts-checked-fsm": "^1.1.0"
|
|
38
|
+
"@opentelemetry/semantic-conventions": "1.34.0"
|
|
40
39
|
},
|
|
41
40
|
"peerDependencies": {
|
|
42
|
-
"@zuplo/runtime": "6.51.
|
|
41
|
+
"@zuplo/runtime": "6.51.34"
|
|
43
42
|
}
|
|
44
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 he=Object.defineProperty;var a=(r,e)=>he(r,"name",{value:e,configurable:!0});import{Buffer as xe}from"node:buffer";globalThis.Buffer=xe;import{TelemetryPlugin as wt,trackFeature as It}from"@zuplo/runtime";import{SpanKind as ze,SpanStatusCode as Ue,context as z,propagation as We,trace as je}from"@opentelemetry/api";import{context as G}from"@opentelemetry/api";var B=Symbol("Otel Tracing Configuration");function K(r,e=G.active()){return e.setValue(B,r)}a(K,"setConfig");function m(){return G.active().getValue(B)}a(m,"getActiveConfig");var k=Symbol("unwrap");function Z(r){return r&&!!r[k]}a(Z,"isWrapped");function Te(r){return typeof r=="object"||typeof r=="function"}a(Te,"isProxyable");function S(r,e,t=!0){if(Z(r)||!Te(r))return r;let n=Object.assign({},e);return n.get=(o,s,i)=>{if(s===k)return r;if(e.get)return e.get(o,s,i);if(s==="bind")return()=>i;if(t)return L(o,s)},n.apply=(o,s,i)=>{if(e.apply)return e.apply(g(o),g(s),i)},new Proxy(r,n)}a(S,"wrap");function g(r){return r&&Z(r)?r[k]:r}a(g,"unwrap");function L(r,e,t){let n=Reflect.get(g(r),e);return typeof n=="function"?(t=t||g(r),n.bind(t)):n}a(L,"passthroughGet");import{trace as ke}from"@opentelemetry/api";import{SpanKind as Ae,TraceFlags as Q,context as M,trace as b}from"@opentelemetry/api";import{sanitizeAttributes as we}from"@opentelemetry/core";import{RandomIdGenerator as Ie,SamplingDecision as Fe}from"@opentelemetry/sdk-trace-base";import{SpanKind as Ce,SpanStatusCode as Re}from"@opentelemetry/api";import{hrTimeDuration as ye,isAttributeValue as be,isTimeInput as Pe,sanitizeAttributes as X}from"@opentelemetry/core";import{ATTR_EXCEPTION_MESSAGE as Y,ATTR_EXCEPTION_STACKTRACE as Ee,ATTR_EXCEPTION_TYPE as J}from"@opentelemetry/semantic-conventions";function ve(r){let e={};return typeof r=="string"?e[Y]=r:(r.code?e[J]=r.code.toString():r.name&&(e[J]=r.name),r.message&&(e[Y]=r.message),r.stack&&(e[Ee]=r.stack)),e}a(ve,"transformExceptionAttributes");function O(r){return[Math.trunc(r/1e3),r%1e3*1e6]}a(O,"millisToHr");function H(r){let e=Date.now();if(r){if(r instanceof Date)return O(r.getTime());if(typeof r=="number")return O(r);if(Array.isArray(r))return r}else return O(e);let t=r;throw new Error(`unreachable value: ${JSON.stringify(t)}`)}a(H,"getHrTime");function _e(r){return typeof r=="string"&&r.length>0}a(_e,"isAttributeKey");var y=class{static{a(this,"SpanImpl")}name;_spanContext;onEnd;parentSpanId;parentSpanContext;kind;attributes;status={code:Re.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||Ce.INTERNAL,this.attributes=X(e.attributes),this.startTime=H(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,t){return _e(e)&&be(t)&&(this.attributes[e]=t),this}setAttributes(e){for(let[t,n]of Object.entries(e))this.setAttribute(t,n);return this}addEvent(e,t,n){Pe(t)&&(n=t,t=void 0);let o=X(t),s=H(n);return this.events.push({name:e,attributes:o,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=H(e),this._duration=ye(this.startTime,this.endTime),this.onEnd(this))}isRecording(){return!this._ended}recordException(e,t){let n=ve(e);this.addEvent("exception",n,t)}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 h=class{static{a(this,"WorkerTracer")}_spanProcessors;resource;idGenerator=new Ie;constructor(e,t){this._spanProcessors=e,this.resource=t}get spanProcessors(){return this._spanProcessors}addToResource(e){this.resource.merge(e)}startSpan(e,t={},n=M.active()){t.root&&(n=b.deleteSpan(n));let s=b.getSpan(n)?.spanContext(),i=s&&b.isSpanContextValid(s),p=i?s.traceId:this.idGenerator.generateTraceId(),l=t.kind||Ae.INTERNAL,c=we(t.attributes),u=m().sampling.headSampler.shouldSample(n,p,e,l,c,[]),{decision:x,traceState:w,attributes:I}=u,V=Object.assign({},c,I),T=this.idGenerator.generateSpanId(),$=i?s.spanId:void 0,C=x===Fe.RECORD_AND_SAMPLED?Q.SAMPLED:Q.NONE,F={traceId:p,spanId:T,traceFlags:C,traceState:w},R=new y({attributes:V,name:e,onEnd:a(f=>{this.spanProcessors.forEach(Se=>{Se.onEnd(f)})},"onEnd"),resource:this.resource,spanContext:F,parentSpanId:$,spanKind:l,startTime:t.startTime});return this.spanProcessors.forEach(f=>{f.onStart(R,n)}),R}startActiveSpan(e,...t){let n=t.length>1?t[0]:void 0,o=t.length>2?t[1]:M.active(),s=t[t.length-1],i=this.startSpan(e,n,o),p=b.setSpan(o,i);return M.with(p,s,void 0,i)}};var N=class{static{a(this,"PromiseTracker")}_outstandingPromises=[];get outstandingPromiseCount(){return this._outstandingPromises.length}track(e){this._outstandingPromises.push(e)}async wait(){await Oe(this._outstandingPromises)}};function Le(r,e,t){return S(r,{apply(o,s,i){return t.track(i[0]),Reflect.apply(o,e,i)}})}a(Le,"createWaitUntil");function ee(r){let e=new N;return{event:new Proxy(r,{get(n,o){if(o==="waitUntil"){let s=Reflect.get(n,o);return Le(s,r,e)}else return L(n,o)}}),tracker:e}}a(ee,"proxyExecutionContext");async function te(r){let e=ke.getTracer("export");if(e instanceof h){typeof scheduler<"u"?await scheduler.wait(1):await new Promise(n=>{setTimeout(n,1)}),r&&await r.wait();let t=e.spanProcessors.map(async n=>{await n.forceFlush()});await Promise.allSettled(t)}else console.error("The global tracer is not of type WorkerTracer and can not export spans")}a(te,"exportSpans");async function Oe(r){let e;do e=await Promise.allSettled(r);while(e.length!==r.length);return e}a(Oe,"allSettledMutable");import{SpanKind as He,context as Me,propagation as Ne,trace as qe}from"@opentelemetry/api";function q(r){let e={},t=r.headers,n=r.cf;e["http.request.method"]=r.method.toUpperCase(),e["network.protocol.name"]="http",e["network.protocol.version"]=n?.httpProtocol;let o=t.get("content-length");o&&(e["http.request.body.size"]=o);let s=t.get("user-agent");s&&(e["user_agent.original"]=s);let i=t.get("content-type");i&&(e["http.mime_type"]=i),e["http.accepts"]=n?.clientAcceptEncoding;let p=new URL(r.url);return e["url.full"]=`${p.protocol}//${p.host}${p.pathname}${p.search}`,e["server.address"]=p.host,e["url.scheme"]=p.protocol,e["url.path"]=p.pathname,e["url.query"]=p.search,e}a(q,"gatherRequestAttributes");function D(r){let e={};e["http.response.status_code"]=r.status;let t=r.headers.get("content-length");t&&(e["http.response.body.size"]=t);let n=r.headers.get("content-type");return n&&(e["http.mime_type"]=n),e}a(D,"gatherResponseAttributes");function re(r){let e={},t=r.cf;return e["net.colo"]=t?.colo,e["net.country"]=t?.country,e["net.request_priority"]=t?.requestPriority,e["net.tls_cipher"]=t?.tlsCipher,e["net.tls_version"]=t?.tlsVersion,e["net.asn"]=t?.asn,e["net.tcp_rtt"]=t?.clientTcpRtt,e}a(re,"gatherIncomingCfAttributes");function De(r,e,t){return S(r,{apply:a((o,s,i)=>{let p=new Request(i[0],i[1]);if(!p.url.startsWith("http"))return Reflect.apply(o,s,i);let l=m(),c=e(l),d=qe.getTracer("fetcher"),u={kind:He.CLIENT,attributes:t},x=new URL(p.url).host,w=p.method.toUpperCase(),I=typeof t?.name=="string"?t?.name:`${w}: ${x}`;return d.startActiveSpan(I,u,async T=>{((typeof c.includeTraceContext=="function"?c.includeTraceContext(p):c.includeTraceContext)??!0)&&Ne.inject(Me.active(),p.headers,{set:a((F,R,f)=>F.set(R,typeof f=="string"?f:String(f)),"set")}),T.setAttributes(q(p));let C=await Reflect.apply(o,s,[p]);return T.setAttributes(D(C)),T.end(),C})},"apply")},!0)}a(De,"instrumentClientFetch");function ne(){globalThis.fetch=De(globalThis.fetch,r=>r.fetch)}a(ne,"instrumentGlobalFetch");function Ve(r){return We.extract(z.active(),r,{get(e,t){return e.get(t)||void 0},keys(e){return[...e.keys()]}})}a(Ve,"getParentContextFromHeaders");function $e(r){let e=m();return(typeof e.handlers.fetch.acceptTraceContext=="function"?e.handlers.fetch.acceptTraceContext(r):e.handlers.fetch.acceptTraceContext??!0)?Ve(r.headers):z.active()}a($e,"getParentContextFromRequest");var oe=!0;function Ge(r,[e,t]){let n=$e(e),o=je.getTracer("pipeline"),s={"faas.trigger":"http","faas.coldstart":oe,"faas.invocation_id":e.headers.get("zp-rid")??void 0,"cf.ray_id":e.headers.get("cf-ray")??void 0};oe=!1,Object.assign(s,q(e)),Object.assign(s,re(e));let i={attributes:s,kind:ze.SERVER},p=e.method.toUpperCase();return o.startActiveSpan(p,i,n,async c=>{let d=c;try{let u=await r(e,t);return c.setAttributes(D(u)),d.attributes["http.route"]&&c.updateName(`${p} ${d.attributes["http.route"]}`),u}catch(u){throw d.attributes["http.route"]&&c.updateName(`${p} ${d.attributes["http.route"]}`),c.recordException(u),c.setStatus({code:Ue.ERROR}),u}finally{c.end()}})}a(Ge,"executeRequestHandler");function ae(r,e){return S(r,{apply:a(async(n,o,s)=>{let[i,p]=s,l=e(i),{event:c,tracker:d}=ee(p),u=K(l);try{let x=[i,c];return await z.with(u,Ge,void 0,n,x)}finally{p.waitUntil(te(d))}},"apply")})}a(ae,"createHandlerProxy");import{propagation as mt}from"@opentelemetry/api";import{W3CTraceContextPropagator as ft}from"@opentelemetry/core";import{resourceFromAttributes as ue}from"@opentelemetry/resources";import{AlwaysOnSampler as gt,ParentBasedSampler as de,TraceIdRatioBasedSampler as St}from"@opentelemetry/sdk-trace-base";import{ATTR_SERVICE_NAME as ht,ATTR_SERVICE_VERSION as xt,ATTR_TELEMETRY_SDK_NAME as Tt}from"@opentelemetry/semantic-conventions";import{SemanticAttributes as A}from"@zuplo/runtime";import{ExportResultCode as Be}from"@opentelemetry/core";import{JsonTraceSerializer as Ke}from"@opentelemetry/otlp-transformer";import{BackgroundDispatcher as Ze}from"@zuplo/runtime";var Xe={accept:"application/json","content-type":"application/json"},P=class{static{a(this,"OTLPExporter")}headers;url;constructor(e){this.url=e.url,this.headers=Object.assign({},Xe,e.headers)}export(e,t){e.forEach(n=>{this.batcher.enqueue(n)}),t({code:Be.SUCCESS})}shutdown(){throw new Error("Method not implemented.")}forceFlush(){throw new Error("Method not implemented.")}dispatchFunction=a(async e=>{if(e.length===0)return;let t=new TextDecoder,n=Ke.serializeRequest(e),o=t.decode(n),s=await g(fetch)(this.url,{method:"POST",body:o,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 Ze(this.dispatchFunction,{msDelay:10})};import{context as tt,trace as rt}from"@opentelemetry/api";import{AsyncLocalStorage as Ye}from"node:async_hooks";import{EventEmitter as Je}from"node:events";import{ROOT_CONTEXT as Qe}from"@opentelemetry/api";var et=["addListener","on","once","prependListener","prependOnceListener"],U=class{static{a(this,"AbstractAsyncHooksContextManager")}bind(e,t){return t instanceof Je?this._bindEventEmitter(e,t):typeof t=="function"?this._bindFunction(e,t):t}_bindFunction(e,t){let n=this,o=a(function(...s){return n.with(e,()=>t.apply(this,s))},"contextWrapper");return Object.defineProperty(o,"length",{enumerable:!1,configurable:!0,writable:!1,value:t.length}),o}_bindEventEmitter(e,t){return this._getPatchMap(t)!==void 0||(this._createPatchMap(t),et.forEach(o=>{t[o]!==void 0&&(t[o]=this._patchAddListener(t,t[o],e))}),typeof t.removeListener=="function"&&(t.removeListener=this._patchRemoveListener(t,t.removeListener)),typeof t.off=="function"&&(t.off=this._patchRemoveListener(t,t.off)),typeof t.removeAllListeners=="function"&&(t.removeAllListeners=this._patchRemoveAllListeners(t,t.removeAllListeners))),t}_patchRemoveListener(e,t){let n=this;return function(o,s){let i=n._getPatchMap(e)?.[o];if(i===void 0)return t.call(this,o,s);let p=i.get(s);return t.call(this,o,p||s)}}_patchRemoveAllListeners(e,t){let n=this;return function(o){let s=n._getPatchMap(e);return s!==void 0&&(arguments.length===0?n._createPatchMap(e):s[o]!==void 0&&delete s[o]),t.apply(this,arguments)}}_patchAddListener(e,t,n){let o=this;return function(s,i){if(o._wrapped)return t.call(this,s,i);let p=o._getPatchMap(e);p===void 0&&(p=o._createPatchMap(e));let l=p[s];l===void 0&&(l=new WeakMap,p[s]=l);let c=o.bind(n,i);l.set(i,c),o._wrapped=!0;try{return t.call(this,s,c)}finally{o._wrapped=!1}}}_createPatchMap(e){let t=Object.create(null);return e[this._kOtListeners]=t,t}_getPatchMap(e){return e[this._kOtListeners]}_kOtListeners=Symbol("OtListeners");_wrapped=!1},E=class extends U{static{a(this,"AsyncLocalStorageContextManager")}_asyncLocalStorage;constructor(){super(),this._asyncLocalStorage=new Ye}active(){return this._asyncLocalStorage.getStore()??Qe}with(e,t,n,...o){let s=n==null?t:t.bind(n);return this._asyncLocalStorage.run(e,s,...o)}enable(){return this}disable(){return this._asyncLocalStorage.disable(),this}};var v=class{static{a(this,"ZuploTracerProvider")}spanProcessors;resource;tracers={};constructor(e,t){this.spanProcessors=e,this.resource=t}getTracer(e,t,n){let o=`${e}@${t||""}:${n?.schemaUrl||""}`;return this.tracers[o]||(this.tracers[o]=new h(this.spanProcessors,this.resource)),this.tracers[o]}register(){rt.setGlobalTracerProvider(this),tt.setGlobalContextManager(new E)}};import{SpanStatusCode as nt,TraceFlags as ot}from"@opentelemetry/api";import{SemanticAttributes as W}from"@zuplo/runtime";function se(r){return e=>{let t=e.localRootSpan;return t.attributes[W.SystemTrace]??t.attributes[W.RouteSystem]??t.attributes[W.RouteTrace]===!1?!1:r(e)}}a(se,"internalTailSampler");function ie(r){return e=>r.reduce((t,n)=>t||n(e),!1)}a(ie,"multiTailSampler");var pe=a(r=>r.localRootSpan.spanContext().traceFlags===ot.SAMPLED,"isHeadSampled"),ce=a(r=>r.localRootSpan.status.code===nt.ERROR,"isRootErrorSpan");import{trace as at}from"@opentelemetry/api";import{ExportResultCode as st}from"@opentelemetry/core";import{stateMachine as it}from"ts-checked-fsm";function pt(r,{span:e}){let t=e.spanContext().spanId;return{...r,stateName:"in_progress",traceId:e.spanContext().traceId,localRootSpan:e,completedSpans:[],inProgressSpanIds:new Set([t])}}a(pt,"newTrace");function ct(r,{span:e}){let t=e.spanContext().spanId;return r.inProgressSpanIds.add(t),{...r}}a(ct,"newSpan");function lt(r,{span:e}){return r.completedSpans.push(e),r.inProgressSpanIds.delete(e.spanContext().spanId),r.inProgressSpanIds.size===0?{stateName:"trace_complete",traceId:r.traceId,localRootSpan:r.localRootSpan,completedSpans:r.completedSpans}:{...r}}a(lt,"endSpan");function ut(r,{args:e}){let{exporter:t,tailSampler:n,postProcessor:o}=e,{traceId:s,localRootSpan:i,completedSpans:p}=r;if(n({traceId:s,localRootSpan:i,spans:p})){let c=o(p);return{stateName:"exporting",promise:new Promise(u=>{t.export(c,u)})}}else return{stateName:"done"}}a(ut,"startExport");var{nextState:dt}=it().state("not_started").state("in_progress").state("trace_complete").state("exporting").state("done").transition("not_started","in_progress").transition("in_progress","in_progress").transition("in_progress","trace_complete").transition("trace_complete","exporting").transition("trace_complete","done").transition("exporting","done").action("startSpan").action("endSpan").action("startExport").action("exportDone").actionHandler("not_started","startSpan",pt).actionHandler("in_progress","startSpan",ct).actionHandler("in_progress","endSpan",lt).actionHandler("trace_complete","startExport",ut).actionHandler("exporting","exportDone",(r,e)=>({stateName:"done"})).done(),_=class{constructor(e){this.exporter=e}static{a(this,"BatchTraceSpanProcessor")}traceLookup=new Map;localRootSpanLookup=new Map;inprogressExports=new Map;action(e,t){let n=this.traceLookup.get(e)||{stateName:"not_started"},o=dt(n,t);return o.stateName==="done"?this.traceLookup.delete(e):this.traceLookup.set(e,o),o}export(e){let{sampling:t,postProcessor:n}=m(),o={exporter:this.exporter,tailSampler:t.tailSampler,postProcessor:n},s=this.action(e,{actionName:"startExport",args:o});if(s.stateName==="exporting"){let i=s.promise;this.inprogressExports.set(e,i),i.then(p=>{p.code===st.FAILED&&console.log("Error sending spans to exporter:",p.error),this.action(e,{actionName:"exportDone"}),this.inprogressExports.delete(e)})}}onStart(e,t){let n=e.spanContext().spanId,o=at.getSpan(t)?.spanContext()?.spanId,i=(o?this.localRootSpanLookup.get(o):void 0)||n;this.localRootSpanLookup.set(n,i),this.action(i,{actionName:"startSpan",span:e})}onEnd(e){let t=e.spanContext().spanId,n=this.localRootSpanLookup.get(t);if(n){let o=this.action(n,{actionName:"endSpan",span:e});o.stateName==="trace_complete"&&(o.completedSpans.forEach(s=>{this.localRootSpanLookup.delete(s.spanContext().spanId)}),this.export(n))}}async forceFlush(){await Promise.allSettled(this.inprogressExports.values())}async shutdown(){}};function le(r){return!!r.spanProcessors}a(le,"isSpanProcessorConfig");import{ATTR_CLOUD_ACCOUNT_ID as Ct,ATTR_CLOUD_PLATFORM as Rt,ATTR_CLOUD_PROVIDER as yt,ATTR_SERVICE_NAMESPACE as bt}from"@opentelemetry/semantic-conventions/incubating";var Pt=a((r,e)=>{let t={[yt]:"zuplo",[Rt]:"zuplo-api",[Ct]:r.accountName,"cloud.project.id":r.projectName,"cloud.resource_id":r.deploymentName,"cloud.instance_id":r.instanceId,"deployment.environment.name":r.environmentStage,[Tt]:"@zuplo/otel",[A.ZuploBuildId]:r.buildId,[A.ZuploBuildVersion]:r.zuploVersion,[A.ZuploBuildCompatibilityDate]:r.compatibilityDate,[A.ZuploEnvironmentType]:r.environmentType},n=ue({[ht]:e.service.name,[bt]:e.service.namespace,[xt]:e.service.version});return ue(t).merge(n)},"createResource");function Et(r){return!!r.export}a(Et,"isSpanExporter");function vt(r){return!!r.shouldSample}a(vt,"isSampler");function _t(r){let e=new St(r.ratio);return typeof r.acceptRemote=="boolean"&&!r.acceptRemote?new de({root:e,remoteParentSampled:e,remoteParentNotSampled:e}):new de({root:e})}a(_t,"createSampler");var me=!1;function At(r,e){if(!me){ne(),mt.setGlobalPropagator(e.propagator);let t=Pt(r,e);new v(e.spanProcessors,t).register(),me=!0}}a(At,"init");function fe(r,e){if(le(e)){let t=e.sampling?.headSampler,n=t?vt(t)?t:_t(t):new gt,o=Array.isArray(e.spanProcessors)?e.spanProcessors:[e.spanProcessors];return o.length===0&&console.log("Warning! You must either specify an exporter or your own SpanProcessor(s)/Exporter combination in the open-telemetry configuration."),{fetch:{includeTraceContext:e.fetch?.includeTraceContext??!0},handlers:{fetch:{acceptTraceContext:e.handlers?.fetch?.acceptTraceContext??!0}},postProcessor:e.postProcessor??(s=>s),sampling:{headSampler:n,tailSampler:se(e.sampling?.tailSampler??ie([pe,ce]))},service:{name:e.service?.name??r.deploymentName,version:e.service?.version,namespace:e.service?.namespace},spanProcessors:o,propagator:e.propagator??new ft}}else{let t=Et(e.exporter)?e.exporter:new P(e.exporter),n=[new _(t)],o=Object.assign(e,{exporter:void 0,spanProcessors:n});return fe(r,o)}}a(fe,"parseConfig");function ge(r,e){return()=>{let t=fe(r,e);return At(r,t),t}}a(ge,"createInitializer");var j=class extends wt{constructor(t){super();this.config=t;It("opentelemetry")}static{a(this,"OpenTelemetryPlugin")}instrument(t){let n=ge(t,this.config);return{requestHandlerProxy:a(s=>ae(s,n),"requestHandlerProxy")}}};export{j as a};
|