@zuplo/otel 6.52.3 → 6.52.5
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.
|
@@ -22,4 +22,4 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
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};
|
|
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};
|
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-PI75EO3F.js";export{a as OpenTelemetryPlugin};
|
package/out/types/index.d.ts
CHANGED
|
@@ -44,8 +44,62 @@ declare interface LocalTrace {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
/**
|
|
47
|
-
* OpenTelemetry plugin for Zuplo
|
|
47
|
+
* OpenTelemetry plugin for distributed tracing in Zuplo.
|
|
48
|
+
* Automatically instruments HTTP requests, policies, and handlers to provide
|
|
49
|
+
* comprehensive observability data that can be exported to various backends.
|
|
50
|
+
*
|
|
48
51
|
* @public
|
|
52
|
+
* @example
|
|
53
|
+
* ```typescript
|
|
54
|
+
* // zuplo.runtime.ts
|
|
55
|
+
* import { RuntimeExtensions, environment } from "@zuplo/runtime";
|
|
56
|
+
* import { OpenTelemetryPlugin } from "@zuplo/otel";
|
|
57
|
+
*
|
|
58
|
+
* export function runtimeInit(runtime: RuntimeExtensions) {
|
|
59
|
+
* // Configure OTLP exporter
|
|
60
|
+
* runtime.addPlugin(
|
|
61
|
+
* new OpenTelemetryPlugin({
|
|
62
|
+
* url: environment.OTLP_ENDPOINT,
|
|
63
|
+
* headers: {
|
|
64
|
+
* "api-key": environment.OTLP_API_KEY
|
|
65
|
+
* }
|
|
66
|
+
* })
|
|
67
|
+
* );
|
|
68
|
+
* }
|
|
69
|
+
* ```
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* ```typescript
|
|
73
|
+
* // With custom span processors
|
|
74
|
+
* import { OpenTelemetryPlugin } from "@zuplo/otel";
|
|
75
|
+
* import { ConsoleSpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
|
|
76
|
+
*
|
|
77
|
+
* runtime.addPlugin(
|
|
78
|
+
* new OpenTelemetryPlugin({
|
|
79
|
+
* spanProcessors: [
|
|
80
|
+
* new SimpleSpanProcessor(new ConsoleSpanExporter())
|
|
81
|
+
* ]
|
|
82
|
+
* })
|
|
83
|
+
* );
|
|
84
|
+
* ```
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* ```typescript
|
|
88
|
+
* // Multiple exporters with custom configuration
|
|
89
|
+
* runtime.addPlugin(
|
|
90
|
+
* new OpenTelemetryPlugin({
|
|
91
|
+
* url: "https://otel-collector.example.com/v1/traces",
|
|
92
|
+
* headers: {
|
|
93
|
+
* "Authorization": "Bearer " + environment.OTEL_TOKEN
|
|
94
|
+
* },
|
|
95
|
+
* // Custom resource attributes
|
|
96
|
+
* serviceName: "my-api",
|
|
97
|
+
* serviceVersion: "1.0.0",
|
|
98
|
+
* // Sampling configuration
|
|
99
|
+
* samplingRate: 0.1 // Sample 10% of requests
|
|
100
|
+
* })
|
|
101
|
+
* );
|
|
102
|
+
* ```
|
|
49
103
|
*/
|
|
50
104
|
export declare class OpenTelemetryPlugin extends TelemetryPlugin {
|
|
51
105
|
private config;
|
|
@@ -67,8 +121,6 @@ declare interface ParentRatioSamplingConfig {
|
|
|
67
121
|
|
|
68
122
|
declare type PostProcessorFn = (spans: ReadableSpan[]) => ReadableSpan[];
|
|
69
123
|
|
|
70
|
-
/* Excluded from this release type: RequestHandlerProxy */
|
|
71
|
-
|
|
72
124
|
declare interface SamplingConfig<HS extends HeadSamplerConf = HeadSamplerConf> {
|
|
73
125
|
headSampler?: HS;
|
|
74
126
|
tailSampler?: TailSampleFn;
|
|
@@ -82,10 +134,49 @@ declare interface ServiceConfig {
|
|
|
82
134
|
|
|
83
135
|
declare type TailSampleFn = (traceInfo: LocalTrace) => boolean;
|
|
84
136
|
|
|
85
|
-
|
|
86
|
-
|
|
137
|
+
/**
|
|
138
|
+
* Configuration for OpenTelemetry tracing in Zuplo.
|
|
139
|
+
* Can be configured with either an explicit exporter or custom span processors.
|
|
140
|
+
*
|
|
141
|
+
* @public
|
|
142
|
+
* @example
|
|
143
|
+
* ```typescript
|
|
144
|
+
* // Using OTLP exporter
|
|
145
|
+
* const config: TraceConfig = {
|
|
146
|
+
* exporter: {
|
|
147
|
+
* url: "https://otel-collector.example.com/v1/traces",
|
|
148
|
+
* headers: { "api-key": "secret" }
|
|
149
|
+
* },
|
|
150
|
+
* service: {
|
|
151
|
+
* name: "my-api",
|
|
152
|
+
* version: "1.0.0"
|
|
153
|
+
* },
|
|
154
|
+
* sampling: {
|
|
155
|
+
* headSampler: {
|
|
156
|
+
* ratio: 0.1 // Sample 10% of requests
|
|
157
|
+
* }
|
|
158
|
+
* }
|
|
159
|
+
* };
|
|
160
|
+
*
|
|
161
|
+
* // Using custom span processors
|
|
162
|
+
* const config: TraceConfig = {
|
|
163
|
+
* spanProcessors: [
|
|
164
|
+
* new SimpleSpanProcessor(new ConsoleSpanExporter()),
|
|
165
|
+
* new BatchSpanProcessor(customExporter)
|
|
166
|
+
* ],
|
|
167
|
+
* service: {
|
|
168
|
+
* name: "my-api",
|
|
169
|
+
* namespace: "production"
|
|
170
|
+
* }
|
|
171
|
+
* };
|
|
172
|
+
* ```
|
|
173
|
+
*/
|
|
87
174
|
export declare type TraceConfig = TraceConfigExporter | TraceConfigSpanProcessors;
|
|
88
175
|
|
|
176
|
+
/**
|
|
177
|
+
* Base configuration for OpenTelemetry tracing
|
|
178
|
+
* @public
|
|
179
|
+
*/
|
|
89
180
|
declare interface TraceConfigBase {
|
|
90
181
|
service: ServiceConfig;
|
|
91
182
|
handlers?: HandlerConfig;
|
|
@@ -96,10 +187,18 @@ declare interface TraceConfigBase {
|
|
|
96
187
|
instrumentation?: InstrumentationOptions;
|
|
97
188
|
}
|
|
98
189
|
|
|
190
|
+
/**
|
|
191
|
+
* Trace configuration with an explicit exporter
|
|
192
|
+
* @public
|
|
193
|
+
*/
|
|
99
194
|
declare interface TraceConfigExporter extends TraceConfigBase {
|
|
100
195
|
exporter: ExporterConfig;
|
|
101
196
|
}
|
|
102
197
|
|
|
198
|
+
/**
|
|
199
|
+
* Trace configuration with span processors
|
|
200
|
+
* @public
|
|
201
|
+
*/
|
|
103
202
|
declare interface TraceConfigSpanProcessors extends TraceConfigBase {
|
|
104
203
|
spanProcessors: SpanProcessor | SpanProcessor[];
|
|
105
204
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zuplo/otel",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "6.52.
|
|
4
|
+
"version": "6.52.5",
|
|
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.52.
|
|
41
|
+
"@zuplo/runtime": "6.52.5"
|
|
42
42
|
}
|
|
43
43
|
}
|