@onelog-sdk/node 0.1.5 → 0.1.7
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/README.md +36 -2
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +15 -1
- package/dist/index.d.ts +15 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +6 -1
package/README.md
CHANGED
|
@@ -10,9 +10,18 @@ npm install @onelog/node
|
|
|
10
10
|
## Quickstart
|
|
11
11
|
```ts
|
|
12
12
|
import express from 'express';
|
|
13
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
sdkStartPromise,
|
|
15
|
+
metricsStartPromise,
|
|
16
|
+
instrumentApp,
|
|
17
|
+
createLogger,
|
|
18
|
+
errorMiddleware,
|
|
19
|
+
httpCall,
|
|
20
|
+
createCounter,
|
|
21
|
+
} from '@onelog/node';
|
|
14
22
|
|
|
15
23
|
const logger = createLogger();
|
|
24
|
+
const requestCounter = createCounter('requests_total', { description: 'Total incoming requests' });
|
|
16
25
|
const app = express();
|
|
17
26
|
const PORT = process.env.PORT || 8700;
|
|
18
27
|
|
|
@@ -23,6 +32,7 @@ app.get('/health', (_req, res) => res.json({ status: 'ok', module: process.env.M
|
|
|
23
32
|
|
|
24
33
|
app.post('/do', async (req, res, next) => {
|
|
25
34
|
try {
|
|
35
|
+
requestCounter.add(1, { route: '/do' });
|
|
26
36
|
const reply = await httpCall(
|
|
27
37
|
process.env.PEER_URL || 'http://localhost:3001/work',
|
|
28
38
|
{ method: 'POST', body: req.body },
|
|
@@ -35,7 +45,7 @@ app.post('/do', async (req, res, next) => {
|
|
|
35
45
|
|
|
36
46
|
app.use(errorMiddleware(logger));
|
|
37
47
|
|
|
38
|
-
sdkStartPromise.finally(() => {
|
|
48
|
+
Promise.all([sdkStartPromise, metricsStartPromise]).finally(() => {
|
|
39
49
|
app.listen(PORT, () => logger.info({ port: PORT }, 'Service started'));
|
|
40
50
|
});
|
|
41
51
|
```
|
|
@@ -70,6 +80,7 @@ await withRequestAttributes({ tenant: 'acme' }, async () => {
|
|
|
70
80
|
- **Logging** (`createLogger`) — Pino with dual transports: OTLP-friendly output plus pretty console, pre-tagged with env/app/module.
|
|
71
81
|
- **Exceptions** (`errorMiddleware`) — records exceptions on the active span, sets span status to ERROR, logs details, and returns JSON.
|
|
72
82
|
- **HTTP calls** (`httpCall`) — fetch wrapper with consistent logging, JSON handling, and error propagation.
|
|
83
|
+
- **Metrics** (`metricsStartPromise`, `createCounter`, `createHistogram`, `getMeter`) — OTLP metrics pipeline with helpers that auto-attach global/request attributes and the active span context (exemplars) for correlation with traces/logs.
|
|
73
84
|
- **Runtime attributes** (`setGlobalAttributes`, `setRequestAttributes`) — update attributes on the fly (globally or per request) and they flow into spans, logs, outbound calls, and error responses.
|
|
74
85
|
|
|
75
86
|
## Environment variables
|
|
@@ -84,6 +95,29 @@ await withRequestAttributes({ tenant: 'acme' }, async () => {
|
|
|
84
95
|
- `ONELOG_EXPRESS_LAYERS` — set to `true` to include middleware/request_handler spans (defaults to lean mode without them).
|
|
85
96
|
- `HTTP_PROXY` / `HTTPS_PROXY` (also lowercase variants) — if present, outbound HTTP (including OTLP export) uses the proxy.
|
|
86
97
|
|
|
98
|
+
## Metrics quickstart
|
|
99
|
+
```ts
|
|
100
|
+
import { createCounter, createHistogram, metricsStartPromise } from '@onelog/node';
|
|
101
|
+
|
|
102
|
+
const requestCounter = createCounter('http.server.requests', { description: 'Total requests' });
|
|
103
|
+
const requestDuration = createHistogram('http.server.duration', { unit: 'ms' });
|
|
104
|
+
|
|
105
|
+
app.use((req, res, next) => {
|
|
106
|
+
const start = Date.now();
|
|
107
|
+
requestCounter.add(1, { method: req.method, route: req.path });
|
|
108
|
+
res.on('finish', () => {
|
|
109
|
+
requestDuration.record(Date.now() - start, {
|
|
110
|
+
method: req.method,
|
|
111
|
+
route: req.path,
|
|
112
|
+
status: res.statusCode,
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
next();
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
await metricsStartPromise; // optional: ensure exporter/reader are ready
|
|
119
|
+
```
|
|
120
|
+
|
|
87
121
|
## Build (for contributors)
|
|
88
122
|
```bash
|
|
89
123
|
npm install
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Re=Object.create;var v=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var he=Object.getOwnPropertyNames;var Ae=Object.getPrototypeOf,Se=Object.prototype.hasOwnProperty;var Pe=(e,t)=>{for(var r in t)v(e,r,{get:t[r],enumerable:!0})},Y=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of he(t))!Se.call(e,n)&&n!==r&&v(e,n,{get:()=>t[n],enumerable:!(o=Le(t,n))||o.enumerable});return e};var Ie=(e,t,r)=>(r=e!=null?Re(Ae(e)):{},Y(t||!e||!e.__esModule?v(r,"default",{value:e,enumerable:!0}):r,e)),ge=e=>Y(v({},"__esModule",{value:!0}),e);var ut={};Pe(ut,{createLogger:()=>fe,errorMiddleware:()=>de,getGlobalAttributes:()=>p,getRequestAttributes:()=>c,httpCall:()=>me,instrumentApp:()=>le,mergeGlobalAttributes:()=>oe,mergeRequestAttributes:()=>ne,runWithRequestContext:()=>y,sdkStartPromise:()=>pe,setGlobalAttributes:()=>re,setRequestAttributes:()=>S,withRequestAttributes:()=>se});module.exports=ge(ut);var u=require("@opentelemetry/api"),ie=require("@opentelemetry/sdk-node");var W=require("@opentelemetry/api"),xe=(0,W.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function X(e){return e.setValue(xe,!0)}var Q=require("@opentelemetry/api");function Z(){return function(e){Q.diag.error(Ne(e))}}function Ne(e){return typeof e=="string"?e:JSON.stringify(ye(e))}function ye(e){for(var t={},r=e;r!==null;)Object.getOwnPropertyNames(r).forEach(function(o){if(!t[o]){var n=r[o];n&&(t[o]=String(n))}}),r=Object.getPrototypeOf(r);return t}var Ce=Z();function b(e){try{Ce(e)}catch{}}var f=require("@opentelemetry/api");var M;(function(e){e.AlwaysOff="always_off",e.AlwaysOn="always_on",e.ParentBasedAlwaysOff="parentbased_always_off",e.ParentBasedAlwaysOn="parentbased_always_on",e.ParentBasedTraceIdRatio="parentbased_traceidratio",e.TraceIdRatio="traceidratio"})(M||(M={}));var ve=",",be=["OTEL_SDK_DISABLED"];function Me(e){return be.indexOf(e)>-1}var Ue=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function Be(e){return Ue.indexOf(e)>-1}var De=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function we(e){return De.indexOf(e)>-1}var G=1/0,H=128,Xe=128,Ge=128,F={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:f.DiagLogLevel.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:G,OTEL_ATTRIBUTE_COUNT_LIMIT:H,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:G,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:H,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:G,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:H,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:Xe,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:Ge,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:M.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative",OTEL_SEMCONV_STABILITY_OPT_IN:[]};function He(e,t,r){if(!(typeof r[e]>"u")){var o=String(r[e]);t[e]=o.toLowerCase()==="true"}}function Fe(e,t,r,o,n){if(o===void 0&&(o=-1/0),n===void 0&&(n=1/0),typeof r[e]<"u"){var s=Number(r[e]);isNaN(s)||(s<o?t[e]=o:s>n?t[e]=n:t[e]=s)}}function Ve(e,t,r,o){o===void 0&&(o=ve);var n=r[e];typeof n=="string"&&(t[e]=n.split(o).map(function(s){return s.trim()}))}var Ke={ALL:f.DiagLogLevel.ALL,VERBOSE:f.DiagLogLevel.VERBOSE,DEBUG:f.DiagLogLevel.DEBUG,INFO:f.DiagLogLevel.INFO,WARN:f.DiagLogLevel.WARN,ERROR:f.DiagLogLevel.ERROR,NONE:f.DiagLogLevel.NONE};function ze(e,t,r){var o=r[e];if(typeof o=="string"){var n=Ke[o.toUpperCase()];n!=null&&(t[e]=n)}}function J(e){var t={};for(var r in F){var o=r;switch(o){case"OTEL_LOG_LEVEL":ze(o,t,e);break;default:if(Me(o))He(o,t,e);else if(Be(o))Fe(o,t,e);else if(we(o))Ve(o,t,e);else{var n=e[o];typeof n<"u"&&n!==null&&(t[o]=String(n))}}}return t}function I(){var e=J(process.env);return Object.assign({},F,e)}function g(e){e.unref()}var x;(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"})(x||(x={}));var k=(function(){function e(){var t=this;this._promise=new Promise(function(r,o){t._resolve=r,t._reject=o})}return Object.defineProperty(e.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),e.prototype.resolve=function(t){this._resolve(t)},e.prototype.reject=function(t){this._reject(t)},e})();var Ze=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,s=[],i;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(E){i={error:E}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},Je=function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,s;o<n;o++)(s||!(o in t))&&(s||(s=Array.prototype.slice.call(t,0,o)),s[o]=t[o]);return e.concat(s||Array.prototype.slice.call(t))},V=(function(){function e(t,r){this._callback=t,this._that=r,this._isCalled=!1,this._deferred=new k}return Object.defineProperty(e.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),e.prototype.call=function(){for(var t,r=this,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((t=this._callback).call.apply(t,Je([this._that],Ze(o),!1))).then(function(s){return r._deferred.resolve(s)},function(s){return r._deferred.reject(s)})}catch(s){this._deferred.reject(s)}}return this._deferred.promise},e})();var d=require("@opentelemetry/api");var ee=(function(){function e(t,r){this._exporter=t,this._isExporting=!1,this._finishedSpans=[],this._droppedSpansCount=0;var o=I();this._maxExportBatchSize=typeof r?.maxExportBatchSize=="number"?r.maxExportBatchSize:o.OTEL_BSP_MAX_EXPORT_BATCH_SIZE,this._maxQueueSize=typeof r?.maxQueueSize=="number"?r.maxQueueSize:o.OTEL_BSP_MAX_QUEUE_SIZE,this._scheduledDelayMillis=typeof r?.scheduledDelayMillis=="number"?r.scheduledDelayMillis:o.OTEL_BSP_SCHEDULE_DELAY,this._exportTimeoutMillis=typeof r?.exportTimeoutMillis=="number"?r.exportTimeoutMillis:o.OTEL_BSP_EXPORT_TIMEOUT,this._shutdownOnce=new V(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(d.diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}return e.prototype.forceFlush=function(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()},e.prototype.onStart=function(t,r){},e.prototype.onEnd=function(t){this._shutdownOnce.isCalled||(t.spanContext().traceFlags&d.TraceFlags.SAMPLED)!==0&&this._addToBuffer(t)},e.prototype.shutdown=function(){return this._shutdownOnce.call()},e.prototype._shutdown=function(){var t=this;return Promise.resolve().then(function(){return t.onShutdown()}).then(function(){return t._flushAll()}).then(function(){return t._exporter.shutdown()})},e.prototype._addToBuffer=function(t){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&d.diag.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(d.diag.warn("Dropped "+this._droppedSpansCount+" spans because maxQueueSize reached"),this._droppedSpansCount=0),this._finishedSpans.push(t),this._maybeStartTimer()},e.prototype._flushAll=function(){var t=this;return new Promise(function(r,o){for(var n=[],s=Math.ceil(t._finishedSpans.length/t._maxExportBatchSize),i=0,E=s;i<E;i++)n.push(t._flushOneBatch());Promise.all(n).then(function(){r()}).catch(o)})},e.prototype._flushOneBatch=function(){var t=this;return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise(function(r,o){var n=setTimeout(function(){o(new Error("Timeout"))},t._exportTimeoutMillis);d.context.with(X(d.context.active()),function(){var s;t._finishedSpans.length<=t._maxExportBatchSize?(s=t._finishedSpans,t._finishedSpans=[]):s=t._finishedSpans.splice(0,t._maxExportBatchSize);for(var i=function(){return t._exporter.export(s,function(l){var m;clearTimeout(n),l.code===x.SUCCESS?r():o((m=l.error)!==null&&m!==void 0?m:new Error("BatchSpanProcessor: span export failed"))})},E=null,_=0,R=s.length;_<R;_++){var O=s[_];O.resource.asyncAttributesPending&&O.resource.waitForAsyncAttributes&&(E??(E=[]),E.push(O.resource.waitForAsyncAttributes()))}E===null?i():Promise.all(E).then(i,function(l){b(l),o(l)})})})},e.prototype._maybeStartTimer=function(){var t=this;if(!this._isExporting){var r=function(){t._isExporting=!0,t._flushOneBatch().finally(function(){t._isExporting=!1,t._finishedSpans.length>0&&(t._clearTimer(),t._maybeStartTimer())}).catch(function(o){t._isExporting=!1,b(o)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return r();this._timer===void 0&&(this._timer=setTimeout(function(){return r()},this._scheduledDelayMillis),g(this._timer))}},e.prototype._clearTimer=function(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)},e})();var $e=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function o(){this.constructor=t}t.prototype=r===null?Object.create(r):(o.prototype=r.prototype,new o)}})(),N=(function(e){$e(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onShutdown=function(){},t})(ee);var z=require("@opentelemetry/resources"),ae=require("@opentelemetry/exporter-trace-otlp-http"),Ee=require("@opentelemetry/auto-instrumentations-node"),D=require("undici");var te=require("async_hooks"),B=new te.AsyncLocalStorage,U={},A=e=>({...e||{}}),p=()=>A(U),re=e=>{U=A(e)},oe=e=>{U={...U,...A(e)}},c=()=>B.getStore()?.requestAttributes||{},S=(e,t)=>{let r=B.getStore();if(!r)return;let o=t?.append===!1?A(e):{...r.requestAttributes,...A(e)};r.requestAttributes=o},ne=e=>S(e),se=(e,t,r)=>B.getStore()?(S(e,r),t()):y(()=>t(),e),y=(e,t)=>B.run({requestAttributes:A(t)},e);u.diag.setLogger(new u.DiagConsoleLogger,u.DiagLogLevel.WARN);var et=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",tt=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",rt=process.env.MAIN_ENV||process.env.NODE_ENV||"development",_e=process.env.MAIN_MODULE||"unknown-module",ot=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),nt=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",Te=process.env.MAIN_MODULE||_e,K=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0);if(K)try{(0,D.setGlobalDispatcher)(new D.ProxyAgent(K)),console.log(`[onelog] Proxy enabled for outbound traffic: ${K}`)}catch(e){console.error("[onelog] Failed to configure proxy agent:",e.message)}var st=z.Resource.default().merge(new z.Resource({"service.name":et,"service.namespace":tt,"deployment.environment":rt,"module.name":Te})),q=class{constructor(t){this.moduleName=t}onStart(t){if(!t)return;let r=t.name||t._name||"";this.moduleName&&!r.startsWith(`[${this.moduleName}] `)&&t.updateName(`[${this.moduleName}] ${r}`),this.moduleName&&t.setAttribute("module.name",this.moduleName);let o={...p(),...c()};for(let[n,s]of Object.entries(o))s!==void 0&&t.setAttribute(n,s)}onEnd(t){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}},j=class{constructor(t){this.processors=t}onStart(t,r){for(let o of this.processors)o.onStart(t,r)}onEnd(t){for(let r of this.processors)r.onEnd(t)}shutdown(){return Promise.all(this.processors.map(t=>t.shutdown())).then(()=>{})}forceFlush(){return Promise.all(this.processors.map(t=>t.forceFlush())).then(()=>{})}},it=(0,Ee.getNodeAutoInstrumentations)({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:nt?[]:["middleware","request_handler"]},"@opentelemetry/instrumentation-undici":{enabled:!0},"@opentelemetry/instrumentation-ioredis":{enabled:!1},"@opentelemetry/instrumentation-redis":{enabled:!1},"@opentelemetry/instrumentation-fs":{enabled:!1},"@opentelemetry/instrumentation-dns":{enabled:!1},"@opentelemetry/instrumentation-net":{enabled:!1}}),at=new ae.OTLPTraceExporter({url:`${ot}/v1/traces`}),Et=new j([new q(Te),new N(at)]),ue=new ie.NodeSDK({resource:st,instrumentations:[it],spanProcessor:Et}),pe=Promise.resolve(ue.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),ce=async()=>{try{await ue.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",ce);process.on("SIGINT",ce);var le=(e,t,r)=>{let o=r||process.env.MAIN_MODULE||_e;e.use((n,s,i)=>{y(()=>{let E=u.propagation.getBaggage(u.context.active()),_=E?Object.fromEntries((E.getAllEntries?.()||[]).map(([C,L])=>[C,L.value])):{},R=n.headers["organization-id"]||n.headers.activeorgid||n.headers["active-org-id"]||n.headers.activeOrgID||_["organization-id"],O=n.headers["session-id"]||_["session-id"],l=n.headers["execution-id"]||n.headers.executionid||n.headers.execution_id||_["execution-id"],m=n.headers["user-id"]||_["user-id"],a=n.headers["request-id"]||_["request-id"];S({"module.name":o,"http.method":n.method,"http.target":n.path,"organization.id":R,"organization-id":R,"session.id":O,"session-id":O,"execution.id":l,"execution-id":l,"user.id":m,"user-id":m,"request.id":a,"request-id":a,..._});let T=u.trace.getActiveSpan();if(T){T.setAttribute("module.name",o),T.updateName(`[${o}] ${n.method} ${n.path}`);let C={...p(),...c()};for(let[L,h]of Object.entries(C))h!==void 0&&T.setAttribute(L,h)}t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),i()})})};var Oe=Ie(require("pino"),1);var _t=["fatal","error","warn","info","debug","trace"],Tt=e=>{let t=()=>({...p(),...c()});return new Proxy(e,{get(r,o,n){let s=Reflect.get(r,o,n);return typeof o=="string"&&_t.includes(o)&&typeof s=="function"?(i,...E)=>{let _=t();return i&&typeof i=="object"&&!Array.isArray(i)?s.call(r,{..._,...i},...E):s.call(r,{..._},i,...E)}:s}})};function fe(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",r=process.env.MAIN_MODULE||"unknown-module",n=(0,Oe.default)({transport:{targets:[{target:"pino-opentelemetry-transport",level:"info",options:{resourceAttributes:{"service.name":t,"service.namespace":e,"deployment.environment":e,"module.name":r,"host.name":require("os").hostname()}}},{target:"pino-pretty",level:"debug",options:{colorize:!0,translateTime:"HH:MM:ss Z",ignore:"pid,hostname"}}]}}).child({env:e,app:t,module:r});return Tt(n)}var w=require("@opentelemetry/api");var de=e=>(t,r,o,n)=>{let s={...p(),...c()};e&&e.error({...s,error:t.message,stack:t.stack,path:r.path},"Unhandled error");let i=w.trace.getActiveSpan();if(i&&(i.recordException(t),i.setStatus({code:w.SpanStatusCode.ERROR,message:t.message})),o.headersSent)return n(t);o.status(500).json({error:t.message,attributes:s,module:process.env.MAIN_MODULE||"unknown-module"})};var P=require("@opentelemetry/api");async function me(e,t={},r,o={}){let n={...t},s=(n.method||"GET").toString().toUpperCase();n.body&&typeof n.body!="string"&&!(n.body instanceof Buffer)&&!(n.body instanceof ArrayBuffer)&&(n.body=JSON.stringify(n.body),n.headers={"Content-Type":"application/json",...n.headers||{}});let i={...p(),...c(),...o},E=Object.entries({...n.headers,"organization-id":i["organization-id"]||i["organization.id"],"session-id":i["session-id"]||i["session.id"],"execution-id":i["execution-id"]||i["execution.id"],"user-id":i["user-id"]||i["user.id"],"request-id":i["request-id"]||i["request.id"]}).filter(([,a])=>a!=null).map(([a,T])=>[a,String(T)]),R={...Object.fromEntries(E)},O={};for(let[a,T]of Object.entries(i))if(T!=null)try{O[a]={value:typeof T=="string"?T:JSON.stringify(T)}}catch{}let l=P.propagation.createBaggage(O),m=P.propagation.setBaggage(P.context.active(),l);P.propagation.inject(m,R),n.headers=R,r&&r.info({...i,url:e,method:s},"HTTP call start");try{let a=await fetch(e,n),L=(a.headers.get("content-type")||"").includes("application/json")?await a.json().catch(()=>null):await a.text().catch(()=>null);if(!a.ok){let h=new Error(`HTTP ${a.status} ${a.statusText||""}`.trim());throw h.status=a.status,h.data=L,r&&r.error({...i,url:e,method:s,status:a.status,data:L},"HTTP call failed"),h}return r&&r.info({...i,url:e,method:s,status:a.status},"HTTP call success"),L}catch(a){throw r&&r.error({...i,url:e,method:s,error:a.message},"HTTP call error"),a}}0&&(module.exports={createLogger,errorMiddleware,getGlobalAttributes,getRequestAttributes,httpCall,instrumentApp,mergeGlobalAttributes,mergeRequestAttributes,runWithRequestContext,sdkStartPromise,setGlobalAttributes,setRequestAttributes,withRequestAttributes});
|
|
1
|
+
"use strict";var De=Object.create;var M=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Ge=Object.getOwnPropertyNames;var He=Object.getPrototypeOf,Fe=Object.prototype.hasOwnProperty;var Ve=(e,t)=>{for(var r in t)M(e,r,{get:t[r],enumerable:!0})},ee=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ge(t))!Fe.call(e,n)&&n!==r&&M(e,n,{get:()=>t[n],enumerable:!(o=Xe(t,n))||o.enumerable});return e};var Ke=(e,t,r)=>(r=e!=null?De(He(e)):{},ee(t||!e||!e.__esModule?M(r,"default",{value:e,enumerable:!0}):r,e)),ze=e=>ee(M({},"__esModule",{value:!0}),e);var Ht={};Ve(Ht,{createCounter:()=>Be,createHistogram:()=>we,createLogger:()=>Pe,errorMiddleware:()=>Se,getGlobalAttributes:()=>u,getMeter:()=>H,getRequestAttributes:()=>p,httpCall:()=>ge,instrumentApp:()=>he,mergeGlobalAttributes:()=>Te,mergeRequestAttributes:()=>ue,metricsStartPromise:()=>be,runWithRequestContext:()=>y,sdkStartPromise:()=>Re,setGlobalAttributes:()=>_e,setRequestAttributes:()=>S,withRequestAttributes:()=>pe});module.exports=ze(Ht);var c=require("@opentelemetry/api"),ce=require("@opentelemetry/sdk-node");var te=require("@opentelemetry/api"),qe=(0,te.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function K(e){return e.setValue(qe,!0)}var re=require("@opentelemetry/api");function oe(){return function(e){re.diag.error(je(e))}}function je(e){return typeof e=="string"?e:JSON.stringify(Ye(e))}function Ye(e){for(var t={},r=e;r!==null;)Object.getOwnPropertyNames(r).forEach(function(o){if(!t[o]){var n=r[o];n&&(t[o]=String(n))}}),r=Object.getPrototypeOf(r);return t}var We=oe();function b(e){try{We(e)}catch{}}var m=require("@opentelemetry/api");var U;(function(e){e.AlwaysOff="always_off",e.AlwaysOn="always_on",e.ParentBasedAlwaysOff="parentbased_always_off",e.ParentBasedAlwaysOn="parentbased_always_on",e.ParentBasedTraceIdRatio="parentbased_traceidratio",e.TraceIdRatio="traceidratio"})(U||(U={}));var Qe=",",Je=["OTEL_SDK_DISABLED"];function $e(e){return Je.indexOf(e)>-1}var Ze=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function ke(e){return Ze.indexOf(e)>-1}var et=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function tt(e){return et.indexOf(e)>-1}var z=1/0,q=128,rt=128,ot=128,j={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:m.DiagLogLevel.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:z,OTEL_ATTRIBUTE_COUNT_LIMIT:q,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:z,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:q,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:z,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:q,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:rt,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:ot,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:U.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative",OTEL_SEMCONV_STABILITY_OPT_IN:[]};function nt(e,t,r){if(!(typeof r[e]>"u")){var o=String(r[e]);t[e]=o.toLowerCase()==="true"}}function st(e,t,r,o,n){if(o===void 0&&(o=-1/0),n===void 0&&(n=1/0),typeof r[e]<"u"){var s=Number(r[e]);isNaN(s)||(s<o?t[e]=o:s>n?t[e]=n:t[e]=s)}}function it(e,t,r,o){o===void 0&&(o=Qe);var n=r[e];typeof n=="string"&&(t[e]=n.split(o).map(function(s){return s.trim()}))}var at={ALL:m.DiagLogLevel.ALL,VERBOSE:m.DiagLogLevel.VERBOSE,DEBUG:m.DiagLogLevel.DEBUG,INFO:m.DiagLogLevel.INFO,WARN:m.DiagLogLevel.WARN,ERROR:m.DiagLogLevel.ERROR,NONE:m.DiagLogLevel.NONE};function Et(e,t,r){var o=r[e];if(typeof o=="string"){var n=at[o.toUpperCase()];n!=null&&(t[e]=n)}}function ne(e){var t={};for(var r in j){var o=r;switch(o){case"OTEL_LOG_LEVEL":Et(o,t,e);break;default:if($e(o))nt(o,t,e);else if(ke(o))st(o,t,e);else if(tt(o))it(o,t,e);else{var n=e[o];typeof n<"u"&&n!==null&&(t[o]=String(n))}}}return t}function I(){var e=ne(process.env);return Object.assign({},j,e)}function x(e){e.unref()}var N;(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"})(N||(N={}));var ie=(function(){function e(){var t=this;this._promise=new Promise(function(r,o){t._resolve=r,t._reject=o})}return Object.defineProperty(e.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),e.prototype.resolve=function(t){this._resolve(t)},e.prototype.reject=function(t){this._reject(t)},e})();var lt=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,s=[],i;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(E){i={error:E}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},Ot=function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,s;o<n;o++)(s||!(o in t))&&(s||(s=Array.prototype.slice.call(t,0,o)),s[o]=t[o]);return e.concat(s||Array.prototype.slice.call(t))},Y=(function(){function e(t,r){this._callback=t,this._that=r,this._isCalled=!1,this._deferred=new ie}return Object.defineProperty(e.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),e.prototype.call=function(){for(var t,r=this,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((t=this._callback).call.apply(t,Ot([this._that],lt(o),!1))).then(function(s){return r._deferred.resolve(s)},function(s){return r._deferred.reject(s)})}catch(s){this._deferred.reject(s)}}return this._deferred.promise},e})();var f=require("@opentelemetry/api");var ae=(function(){function e(t,r){this._exporter=t,this._isExporting=!1,this._finishedSpans=[],this._droppedSpansCount=0;var o=I();this._maxExportBatchSize=typeof r?.maxExportBatchSize=="number"?r.maxExportBatchSize:o.OTEL_BSP_MAX_EXPORT_BATCH_SIZE,this._maxQueueSize=typeof r?.maxQueueSize=="number"?r.maxQueueSize:o.OTEL_BSP_MAX_QUEUE_SIZE,this._scheduledDelayMillis=typeof r?.scheduledDelayMillis=="number"?r.scheduledDelayMillis:o.OTEL_BSP_SCHEDULE_DELAY,this._exportTimeoutMillis=typeof r?.exportTimeoutMillis=="number"?r.exportTimeoutMillis:o.OTEL_BSP_EXPORT_TIMEOUT,this._shutdownOnce=new Y(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(f.diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}return e.prototype.forceFlush=function(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()},e.prototype.onStart=function(t,r){},e.prototype.onEnd=function(t){this._shutdownOnce.isCalled||(t.spanContext().traceFlags&f.TraceFlags.SAMPLED)!==0&&this._addToBuffer(t)},e.prototype.shutdown=function(){return this._shutdownOnce.call()},e.prototype._shutdown=function(){var t=this;return Promise.resolve().then(function(){return t.onShutdown()}).then(function(){return t._flushAll()}).then(function(){return t._exporter.shutdown()})},e.prototype._addToBuffer=function(t){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&f.diag.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(f.diag.warn("Dropped "+this._droppedSpansCount+" spans because maxQueueSize reached"),this._droppedSpansCount=0),this._finishedSpans.push(t),this._maybeStartTimer()},e.prototype._flushAll=function(){var t=this;return new Promise(function(r,o){for(var n=[],s=Math.ceil(t._finishedSpans.length/t._maxExportBatchSize),i=0,E=s;i<E;i++)n.push(t._flushOneBatch());Promise.all(n).then(function(){r()}).catch(o)})},e.prototype._flushOneBatch=function(){var t=this;return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise(function(r,o){var n=setTimeout(function(){o(new Error("Timeout"))},t._exportTimeoutMillis);f.context.with(K(f.context.active()),function(){var s;t._finishedSpans.length<=t._maxExportBatchSize?(s=t._finishedSpans,t._finishedSpans=[]):s=t._finishedSpans.splice(0,t._maxExportBatchSize);for(var i=function(){return t._exporter.export(s,function(O){var L;clearTimeout(n),O.code===N.SUCCESS?r():o((L=O.error)!==null&&L!==void 0?L:new Error("BatchSpanProcessor: span export failed"))})},E=null,_=0,A=s.length;_<A;_++){var d=s[_];d.resource.asyncAttributesPending&&d.resource.waitForAsyncAttributes&&(E??(E=[]),E.push(d.resource.waitForAsyncAttributes()))}E===null?i():Promise.all(E).then(i,function(O){b(O),o(O)})})})},e.prototype._maybeStartTimer=function(){var t=this;if(!this._isExporting){var r=function(){t._isExporting=!0,t._flushOneBatch().finally(function(){t._isExporting=!1,t._finishedSpans.length>0&&(t._clearTimer(),t._maybeStartTimer())}).catch(function(o){t._isExporting=!1,b(o)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return r();this._timer===void 0&&(this._timer=setTimeout(function(){return r()},this._scheduledDelayMillis),x(this._timer))}},e.prototype._clearTimer=function(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)},e})();var dt=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function o(){this.constructor=t}t.prototype=r===null?Object.create(r):(o.prototype=r.prototype,new o)}})(),v=(function(e){dt(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onShutdown=function(){},t})(ae);var Q=require("@opentelemetry/resources"),le=require("@opentelemetry/exporter-trace-otlp-http"),Oe=require("@opentelemetry/auto-instrumentations-node"),D=require("undici");var Ee=require("async_hooks"),w=new Ee.AsyncLocalStorage,B={},P=e=>({...e||{}}),u=()=>P(B),_e=e=>{B=P(e)},Te=e=>{B={...B,...P(e)}},p=()=>w.getStore()?.requestAttributes||{},S=(e,t)=>{let r=w.getStore();if(!r)return;let o=t?.append===!1?P(e):{...r.requestAttributes,...P(e)};r.requestAttributes=o},ue=e=>S(e),pe=(e,t,r)=>w.getStore()?(S(e,r),t()):y(()=>t(),e),y=(e,t)=>w.run({requestAttributes:P(t)},e);c.diag.setLogger(new c.DiagConsoleLogger,c.DiagLogLevel.WARN);var ft=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",Rt=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",Lt=process.env.MAIN_ENV||process.env.NODE_ENV||"development",de=process.env.MAIN_MODULE||"unknown-module",ht=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),At=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",me=process.env.MAIN_MODULE||de,W=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0);if(W)try{(0,D.setGlobalDispatcher)(new D.ProxyAgent(W)),console.log(`[onelog] Proxy enabled for outbound traffic: ${W}`)}catch(e){console.error("[onelog] Failed to configure proxy agent:",e.message)}var Pt=Q.Resource.default().merge(new Q.Resource({"service.name":ft,"service.namespace":Rt,"deployment.environment":Lt,"module.name":me})),J=class{constructor(t){this.moduleName=t}onStart(t){if(!t)return;let r=t.name||t._name||"";this.moduleName&&!r.startsWith(`[${this.moduleName}] `)&&t.updateName(`[${this.moduleName}] ${r}`),this.moduleName&&t.setAttribute("module.name",this.moduleName);let o={...u(),...p()};for(let[n,s]of Object.entries(o))s!==void 0&&t.setAttribute(n,s)}onEnd(t){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}},$=class{constructor(t){this.processors=t}onStart(t,r){for(let o of this.processors)o.onStart(t,r)}onEnd(t){for(let r of this.processors)r.onEnd(t)}shutdown(){return Promise.all(this.processors.map(t=>t.shutdown())).then(()=>{})}forceFlush(){return Promise.all(this.processors.map(t=>t.forceFlush())).then(()=>{})}},St=(0,Oe.getNodeAutoInstrumentations)({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:At?[]:["middleware","request_handler"]},"@opentelemetry/instrumentation-undici":{enabled:!0},"@opentelemetry/instrumentation-ioredis":{enabled:!1},"@opentelemetry/instrumentation-redis":{enabled:!1},"@opentelemetry/instrumentation-fs":{enabled:!1},"@opentelemetry/instrumentation-dns":{enabled:!1},"@opentelemetry/instrumentation-net":{enabled:!1}}),gt=new le.OTLPTraceExporter({url:`${ht}/v1/traces`}),It=new $([new J(me),new v(gt)]),fe=new ce.NodeSDK({resource:Pt,instrumentations:[St],spanProcessor:It}),Re=Promise.resolve(fe.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),Le=async()=>{try{await fe.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",Le);process.on("SIGINT",Le);var he=(e,t,r)=>{let o=r||process.env.MAIN_MODULE||de;e.use((n,s,i)=>{y(()=>{let E=c.propagation.getBaggage(c.context.active()),_=E?Object.fromEntries((E.getAllEntries?.()||[]).map(([l,V])=>[l,V.value])):{},A=n.headers["organization-id"]||n.headers.activeorgid||n.headers["active-org-id"]||n.headers.activeOrgID||_["organization-id"],d=n.headers["session-id"]||_["session-id"],O=n.headers["execution-id"]||n.headers.executionid||n.headers.execution_id||_["execution-id"],L=n.headers["user-id"]||_["user-id"],a=n.headers["request-id"]||_["request-id"],T=n.headers["x-onelog-attr"]||n.headers["x-onelog-attrs"]||_["x-onelog-attr"],F={};if(T)try{let l=typeof T=="string"?JSON.parse(T):T;l&&typeof l=="object"&&(F=l)}catch{}S({"module.name":o,"http.method":n.method,"http.target":n.path,"organization.id":A,"organization-id":A,"session.id":d,"session-id":d,"execution.id":O,"execution-id":O,"user.id":L,"user-id":L,"request.id":a,"request-id":a,..._,...F});let h=c.trace.getActiveSpan();if(h){h.setAttribute("module.name",o),h.updateName(`[${o}] ${n.method} ${n.path}`);let l={...u(),...p()};for(let[V,k]of Object.entries(l))k!==void 0&&h.setAttribute(V,k)}t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),i()})})};var Ae=Ke(require("pino"),1);var xt=["fatal","error","warn","info","debug","trace"],Nt=e=>{let t=()=>({...u(),...p()});return new Proxy(e,{get(r,o,n){let s=Reflect.get(r,o,n);return typeof o=="string"&&xt.includes(o)&&typeof s=="function"?(i,...E)=>{let _=t();return i&&typeof i=="object"&&!Array.isArray(i)?s.call(r,{..._,...i},...E):s.call(r,{..._},i,...E)}:s}})};function Pe(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",r=process.env.MAIN_MODULE||"unknown-module",n=(0,Ae.default)({transport:{targets:[{target:"pino-opentelemetry-transport",level:"info",options:{resourceAttributes:{"service.name":t,"service.namespace":e,"deployment.environment":e,"module.name":r,"host.name":require("os").hostname()}}},{target:"pino-pretty",level:"debug",options:{colorize:!0,translateTime:"HH:MM:ss Z",ignore:"pid,hostname"}}]}}).child({env:e,app:t,module:r});return Nt(n)}var X=require("@opentelemetry/api");var Se=e=>(t,r,o,n)=>{let s={...u(),...p()};e&&e.error({...s,error:t.message,stack:t.stack,path:r.path},"Unhandled error");let i=X.trace.getActiveSpan();if(i&&(i.recordException(t),i.setStatus({code:X.SpanStatusCode.ERROR,message:t.message})),o.headersSent)return n(t);o.status(500).json({error:t.message,attributes:s,module:process.env.MAIN_MODULE||"unknown-module"})};var g=require("@opentelemetry/api");async function ge(e,t={},r,o={}){let n={...t},s=(n.method||"GET").toString().toUpperCase();n.body&&typeof n.body!="string"&&!(n.body instanceof Buffer)&&!(n.body instanceof ArrayBuffer)&&(n.body=JSON.stringify(n.body),n.headers={"Content-Type":"application/json",...n.headers||{}});let i={...u(),...p(),...o},E=Object.entries({...n.headers,"organization-id":i["organization-id"]||i["organization.id"],"session-id":i["session-id"]||i["session.id"],"execution-id":i["execution-id"]||i["execution.id"],"user-id":i["user-id"]||i["user.id"],"request-id":i["request-id"]||i["request.id"],"x-onelog-attr":JSON.stringify(i)}).filter(([,a])=>a!=null).map(([a,T])=>[a,String(T)]),A={...Object.fromEntries(E)},d={};for(let[a,T]of Object.entries(i))if(T!=null)try{d[a]={value:typeof T=="string"?T:JSON.stringify(T)}}catch{}let O=g.propagation.createBaggage(d),L=g.propagation.setBaggage(g.context.active(),O);g.propagation.inject(L,A),n.headers=A,r&&r.info({...i,url:e,method:s},"HTTP call start");try{let a=await fetch(e,n),h=(a.headers.get("content-type")||"").includes("application/json")?await a.json().catch(()=>null):await a.text().catch(()=>null);if(!a.ok){let l=new Error(`HTTP ${a.status} ${a.statusText||""}`.trim());throw l.status=a.status,l.data=h,r&&r.error({...i,url:e,method:s,status:a.status,data:h},"HTTP call failed"),l}return r&&r.info({...i,url:e,method:s,status:a.status},"HTTP call success"),h}catch(a){throw r&&r.error({...i,url:e,method:s,error:a.message},"HTTP call error"),a}}var C=require("@opentelemetry/api"),Z=require("@opentelemetry/resources"),G=require("@opentelemetry/sdk-metrics"),ve=require("@opentelemetry/exporter-metrics-otlp-http"),ye=require("@opentelemetry/host-metrics"),Ce=require("@opentelemetry/instrumentation-runtime-node");var vt=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",yt=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",Ct=process.env.MAIN_ENV||process.env.NODE_ENV||"development",Mt=process.env.MAIN_MODULE||"unknown-module",bt=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),Ut=(process.env.ONELOG_HOST_METRICS||"true").toLowerCase()==="true",Bt=(process.env.ONELOG_RUNTIME_METRICS||"false").toLowerCase()==="true",wt=Z.Resource.default().merge(new Z.Resource({"service.name":vt,"service.namespace":yt,"deployment.environment":Ct,"module.name":Mt})),R,Ie=!1,xe=!1,Ne=!1,Dt=()=>{if(Ie)return;Ie=!0;let e=async()=>{if(R)try{await R.shutdown()}catch(t){console.error("[onelog] Error shutting down metrics provider",t.message)}};process.on("SIGTERM",e),process.on("SIGINT",e)},Me=()=>{if(R)return R;let e=new ve.OTLPMetricExporter({url:`${bt}/v1/metrics`});return R=new G.MeterProvider({resource:wt,readers:[new G.PeriodicExportingMetricReader({exporter:e})]}),C.metrics.setGlobalMeterProvider(R),Xt(R),Gt(R),Dt(),R},Xt=e=>{if(!(!Ut||xe))try{new ye.HostMetrics({meterProvider:e,name:"onelog-host-metrics"}).start(),xe=!0}catch(t){console.error("[onelog] Failed to start host metrics instrumentation",t.message)}},Gt=e=>{if(!(!Bt||Ne))try{let t=new Ce.RuntimeNodeInstrumentation;t.setMeterProvider(e),t.enable(),Ne=!0}catch(t){console.error("[onelog] Failed to start runtime metrics instrumentation",t.message)}},be=Promise.resolve().then(()=>Me()),H=(e="onelog-metrics")=>Me().getMeter(e),Ue=e=>({...u(),...p(),...e||{}}),Be=(e,t)=>{let r=H().createCounter(e,t);return{add:(o,n)=>{r.add(o,Ue(n),C.context.active())},instrument:r}},we=(e,t)=>{let r=H().createHistogram(e,t);return{record:(o,n)=>{r.record(o,Ue(n),C.context.active())},instrument:r}};0&&(module.exports={createCounter,createHistogram,createLogger,errorMiddleware,getGlobalAttributes,getMeter,getRequestAttributes,httpCall,instrumentApp,mergeGlobalAttributes,mergeRequestAttributes,metricsStartPromise,runWithRequestContext,sdkStartPromise,setGlobalAttributes,setRequestAttributes,withRequestAttributes});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/sampling.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/timer-util.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/ExportResult.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/promise.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/callback.ts","../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../src/attributes.ts","../src/logger.ts","../src/exceptions.ts","../src/http-caller.ts"],"sourcesContent":["export { sdkStartPromise, instrumentApp } from './tracing.js';\nexport { createLogger } from './logger.js';\nexport { errorMiddleware } from './exceptions.js';\nexport { httpCall } from './http-caller.js';\nexport {\n getGlobalAttributes,\n setGlobalAttributes,\n mergeGlobalAttributes,\n getRequestAttributes,\n setRequestAttributes,\n mergeRequestAttributes,\n withRequestAttributes,\n runWithRequestContext,\n} from './attributes.js';\n","import { diag, DiagConsoleLogger, DiagLogLevel, trace, context as otContext, propagation } from '@opentelemetry/api';\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { SpanProcessor, ReadableSpan, BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { Resource } from '@opentelemetry/resources';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { ProxyAgent, setGlobalDispatcher } from 'undici';\nimport type { Application, Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\nimport {\n getGlobalAttributes,\n getRequestAttributes,\n runWithRequestContext,\n setRequestAttributes,\n} from './attributes.js';\n\ndiag.setLogger(new DiagConsoleLogger(), DiagLogLevel.WARN);\n\nconst serviceName =\n process.env.OTEL_SERVICE_NAME ||\n process.env.MAIN_MODULE ||\n 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE ||\n process.env.OTEL_SERVICE_NAMESPACE ||\n process.env.MAIN_APP ||\n 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\nconst expressLayersEnabled = (process.env.ONELOG_EXPRESS_LAYERS || '').toLowerCase() === 'true';\nconst moduleLabel = process.env.MAIN_MODULE || moduleName;\n\n// Optional proxy support for environments with HTTP(S)_PROXY set\nconst proxyUrl = [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy]\n .find((v) => v && v.trim().length > 0);\n\nif (proxyUrl) {\n try {\n setGlobalDispatcher(new ProxyAgent(proxyUrl));\n // eslint-disable-next-line no-console\n console.log(`[onelog] Proxy enabled for outbound traffic: ${proxyUrl}`);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure proxy agent:', (err as Error).message);\n }\n}\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleLabel,\n }),\n);\n\nclass ModuleNameSpanProcessor implements SpanProcessor {\n constructor(private readonly moduleName: string) {}\n onStart(span: any): void {\n if (!span) return;\n const currentName = (span as any).name || (span as any)._name || '';\n if (this.moduleName && !currentName.startsWith(`[${this.moduleName}] `)) {\n span.updateName(`[${this.moduleName}] ${currentName}`);\n }\n if (this.moduleName) {\n span.setAttribute('module.name', this.moduleName);\n }\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(dynamicAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n onEnd(_span: ReadableSpan): void {\n // no-op\n }\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nclass CombinedSpanProcessor implements SpanProcessor {\n constructor(private readonly processors: SpanProcessor[]) {}\n onStart(span: any, ctx?: any): void {\n for (const p of this.processors) p.onStart(span as any, ctx);\n }\n onEnd(span: ReadableSpan): void {\n for (const p of this.processors) p.onEnd(span);\n }\n shutdown(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.shutdown())).then(() => undefined);\n }\n forceFlush(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.forceFlush())).then(() => undefined);\n }\n}\n\nconst instrumentations = getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-http': {\n enabled: true,\n },\n '@opentelemetry/instrumentation-express': {\n enabled: true,\n ignoreLayersType: expressLayersEnabled ? [] : (['middleware', 'request_handler'] as any),\n },\n '@opentelemetry/instrumentation-undici': {\n enabled: true,\n },\n // Redis instrumentation is noisy in our workloads; keep it off by default\n '@opentelemetry/instrumentation-ioredis': { enabled: false },\n '@opentelemetry/instrumentation-redis': { enabled: false },\n '@opentelemetry/instrumentation-fs': { enabled: false },\n '@opentelemetry/instrumentation-dns': { enabled: false },\n '@opentelemetry/instrumentation-net': { enabled: false },\n});\n\nconst exporter = new OTLPTraceExporter({\n url: `${otlpEndpoint}/v1/traces`,\n});\n\nconst spanProcessor = new CombinedSpanProcessor([\n new ModuleNameSpanProcessor(moduleLabel),\n new BatchSpanProcessor(exporter),\n]);\n\nconst sdk = new NodeSDK({\n resource,\n instrumentations: [instrumentations],\n spanProcessor,\n});\n\nexport const sdkStartPromise = Promise.resolve(sdk.start()).catch((error) => {\n console.error('Failed to start OpenTelemetry SDK', error);\n return Promise.resolve();\n});\n\nconst shutdown = async () => {\n try {\n await sdk.shutdown();\n } catch (error) {\n console.error('Error shutting down OpenTelemetry SDK', error);\n }\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nexport const instrumentApp = (app: Application, logger?: Logger, customModuleName?: string) => {\n const moduleLabel = customModuleName || process.env.MAIN_MODULE || moduleName;\n app.use((req: Request, _res: Response, next: NextFunction) => {\n runWithRequestContext(() => {\n const baggage = propagation.getBaggage(otContext.active());\n const baggageAttrs = baggage\n ? Object.fromEntries(\n (baggage.getAllEntries?.() || []).map(([key, entry]) => [key, entry.value]),\n )\n : {};\n\n const orgId =\n (req.headers['organization-id'] as string) ||\n (req.headers['activeorgid'] as string) ||\n (req.headers['active-org-id'] as string) ||\n (req.headers['activeOrgID'] as string) ||\n (baggageAttrs['organization-id'] as string);\n const sessionId = (req.headers['session-id'] as string) || (baggageAttrs['session-id'] as string);\n const executionId =\n (req.headers['execution-id'] as string) ||\n (req.headers['executionid'] as string) ||\n (req.headers['execution_id'] as string) ||\n (baggageAttrs['execution-id'] as string);\n const userId = (req.headers['user-id'] as string) || (baggageAttrs['user-id'] as string);\n const requestId = (req.headers['request-id'] as string) || (baggageAttrs['request-id'] as string);\n\n setRequestAttributes({\n 'module.name': moduleLabel,\n 'http.method': req.method,\n 'http.target': req.path,\n 'organization.id': orgId,\n 'organization-id': orgId,\n 'session.id': sessionId,\n 'session-id': sessionId,\n 'execution.id': executionId,\n 'execution-id': executionId,\n 'user.id': userId,\n 'user-id': userId,\n 'request.id': requestId,\n 'request-id': requestId,\n ...baggageAttrs,\n });\n\n const span = trace.getActiveSpan();\n if (span) {\n span.setAttribute('module.name', moduleLabel);\n span.updateName(`[${moduleLabel}] ${req.method} ${req.path}`);\n const requestAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(requestAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n if (logger) {\n logger.info(\n {\n method: req.method,\n path: req.path,\n ip: req.ip,\n },\n 'Incoming request',\n );\n }\n next();\n });\n });\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, Exception } from '@opentelemetry/api';\nimport { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n 'OTEL_SEMCONV_STABILITY_OPT_IN',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required<ENVIRONMENT> = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n OTEL_SEMCONV_STABILITY_OPT_IN: [],\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_ENVIRONMENT,\n ENVIRONMENT,\n RAW_ENVIRONMENT,\n parseEnvironment,\n} from '../../utils/environment';\n\n/**\n * Gets the environment variables\n */\nexport function getEnv(): Required<ENVIRONMENT> {\n const processEnv = parseEnvironment(process.env as RAW_ENVIRONMENT);\n return Object.assign({}, DEFAULT_ENVIRONMENT, processEnv);\n}\n\nexport function getEnvWithoutDefaults(): ENVIRONMENT {\n return parseEnvironment(process.env as RAW_ENVIRONMENT);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function unrefTimer(timer: NodeJS.Timer): void {\n timer.unref();\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context, Context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getEnv,\n globalErrorHandler,\n suppressTracing,\n unrefTimer,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { BufferConfig } from '../types';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(\n private readonly _exporter: SpanExporter,\n config?: T\n ) {\n const env = getEnv();\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : env.OTEL_BSP_MAX_QUEUE_SIZE;\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : env.OTEL_BSP_SCHEDULE_DELAY;\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : env.OTEL_BSP_EXPORT_TIMEOUT;\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n unrefTimer(this._timer);\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport type AttributeMap = Record<string, any>;\n\ntype RequestAttributeContext = {\n requestAttributes: AttributeMap;\n};\n\nconst requestAttributeStorage = new AsyncLocalStorage<RequestAttributeContext>();\n\nlet globalAttributes: AttributeMap = {};\n\nconst clone = (attrs?: AttributeMap) => ({ ...(attrs || {}) });\n\nexport const getGlobalAttributes = (): AttributeMap => clone(globalAttributes);\n\nexport const setGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = clone(attrs);\n};\n\nexport const mergeGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = { ...globalAttributes, ...clone(attrs) };\n};\n\nexport const getRequestAttributes = (): AttributeMap => {\n const store = requestAttributeStorage.getStore();\n return store?.requestAttributes || {};\n};\n\nexport const setRequestAttributes = (attrs: AttributeMap, options?: { append?: boolean }) => {\n const store = requestAttributeStorage.getStore();\n if (!store) return;\n\n const nextAttributes =\n options?.append === false ? clone(attrs) : { ...store.requestAttributes, ...clone(attrs) };\n store.requestAttributes = nextAttributes;\n};\n\nexport const mergeRequestAttributes = (attrs: AttributeMap) => setRequestAttributes(attrs);\n\nexport const withRequestAttributes = <T>(\n attrs: AttributeMap,\n fn: () => T,\n options?: { append?: boolean },\n): T => {\n const store = requestAttributeStorage.getStore();\n if (!store) {\n return runWithRequestContext(() => fn(), attrs);\n }\n setRequestAttributes(attrs, options);\n return fn();\n};\n\nexport const runWithRequestContext = <T>(fn: () => T, initialAttributes?: AttributeMap): T => {\n return requestAttributeStorage.run(\n {\n requestAttributes: clone(initialAttributes),\n },\n fn,\n );\n};\n","import pino, { Logger } from 'pino';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nconst levelMethods = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'] as const;\n\nconst wrapWithDynamicAttributes = (logger: Logger): Logger => {\n const buildAttrs = () => ({ ...getGlobalAttributes(), ...getRequestAttributes() });\n\n return new Proxy(logger, {\n get(target, prop, receiver) {\n const original = Reflect.get(target, prop, receiver);\n if (typeof prop === 'string' && levelMethods.includes(prop as any) && typeof original === 'function') {\n return (firstArg?: any, ...rest: any[]) => {\n const attrs = buildAttrs();\n if (firstArg && typeof firstArg === 'object' && !Array.isArray(firstArg)) {\n return (original as any).call(target, { ...attrs, ...firstArg }, ...rest);\n }\n return (original as any).call(target, { ...attrs }, firstArg, ...rest);\n };\n }\n return original;\n },\n });\n};\n\nexport function createLogger() {\n const mainEnv = process.env.MAIN_ENV || 'development';\n const mainApp = process.env.MAIN_APP || 'app';\n const mainModule = process.env.MAIN_MODULE || 'unknown-module';\n\n const logger = pino({\n transport: {\n targets: [\n {\n target: 'pino-opentelemetry-transport',\n level: 'info',\n options: {\n resourceAttributes: {\n 'service.name': mainApp,\n 'service.namespace': mainEnv,\n 'deployment.environment': mainEnv,\n 'module.name': mainModule,\n 'host.name': require('os').hostname(),\n },\n },\n },\n {\n target: 'pino-pretty',\n level: 'debug',\n options: {\n colorize: true,\n translateTime: 'HH:MM:ss Z',\n ignore: 'pid,hostname',\n },\n },\n ],\n },\n });\n\n const base = logger.child({\n env: mainEnv,\n app: mainApp,\n module: mainModule,\n });\n\n return wrapWithDynamicAttributes(base);\n}\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\nimport type { Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\n\nexport const errorMiddleware =\n (logger?: Logger) =>\n (err: Error, req: Request, res: Response, next: NextFunction) => {\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n\n if (logger) {\n logger.error(\n {\n ...dynamicAttributes,\n error: err.message,\n stack: err.stack,\n path: req.path,\n },\n 'Unhandled error',\n );\n }\n\n const span = trace.getActiveSpan();\n if (span) {\n span.recordException(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n }\n\n if (res.headersSent) {\n return next(err);\n }\n\n res.status(500).json({\n error: err.message,\n attributes: dynamicAttributes,\n module: process.env.MAIN_MODULE || 'unknown-module',\n });\n };\n","import { context, propagation } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nexport interface HttpCallContext {\n [key: string]: any;\n}\n\nexport interface HttpCallOptions extends RequestInit {\n body?: any;\n}\n\nexport async function httpCall(\n url: string,\n options: HttpCallOptions = {},\n logger?: { info: Function; error: Function },\n logContext: HttpCallContext = {},\n) {\n const fetchOptions: RequestInit = { ...options };\n const method = (fetchOptions.method || 'GET').toString().toUpperCase();\n\n if (\n fetchOptions.body &&\n typeof fetchOptions.body !== 'string' &&\n !(fetchOptions.body instanceof Buffer) &&\n !(fetchOptions.body instanceof ArrayBuffer)\n ) {\n fetchOptions.body = JSON.stringify(fetchOptions.body);\n fetchOptions.headers = {\n 'Content-Type': 'application/json',\n ...(fetchOptions.headers || {}),\n };\n }\n\n const dynamicContext = { ...getGlobalAttributes(), ...getRequestAttributes(), ...logContext };\n\n // Inject trace context + baggage, and forward standard IDs as headers for downstream services\n const headerEntries = Object.entries({\n ...(fetchOptions.headers as any),\n 'organization-id':\n (dynamicContext['organization-id'] as string) || (dynamicContext['organization.id'] as string),\n 'session-id': (dynamicContext['session-id'] as string) || (dynamicContext['session.id'] as string),\n 'execution-id':\n (dynamicContext['execution-id'] as string) || (dynamicContext['execution.id'] as string),\n 'user-id': (dynamicContext['user-id'] as string) || (dynamicContext['user.id'] as string),\n 'request-id': (dynamicContext['request-id'] as string) || (dynamicContext['request.id'] as string),\n })\n .filter(([, v]) => v !== undefined && v !== null)\n .map(([k, v]) => [k, String(v)]) as [string, string][];\n\n const headers: Record<string, string> = Object.fromEntries(headerEntries);\n\n const carrier: Record<string, any> = { ...headers };\n\n // Build baggage from all attributes to propagate custom keys\n const baggageEntries: Record<string, { value: string }> = {};\n for (const [key, value] of Object.entries(dynamicContext)) {\n if (value === undefined || value === null) continue;\n try {\n baggageEntries[key] = { value: typeof value === 'string' ? value : JSON.stringify(value) };\n } catch {\n // skip values that can't be stringified\n }\n }\n const baggage = propagation.createBaggage(baggageEntries);\n const ctxWithBaggage = propagation.setBaggage(context.active(), baggage);\n propagation.inject(ctxWithBaggage, carrier);\n\n fetchOptions.headers = carrier;\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method }, 'HTTP call start');\n }\n\n try {\n const res = await fetch(url, fetchOptions);\n const contentType = res.headers.get('content-type') || '';\n const isJson = contentType.includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : await res.text().catch(() => null);\n\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status} ${res.statusText || ''}`.trim());\n (error as any).status = res.status;\n (error as any).data = data;\n if (logger) {\n logger.error({ ...dynamicContext, url, method, status: res.status, data }, 'HTTP call failed');\n }\n throw error;\n }\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method, status: res.status }, 'HTTP call success');\n }\n\n return data;\n } catch (err: any) {\n if (logger) {\n logger.error({ ...dynamicContext, url, method, error: err.message }, 'HTTP call error');\n }\n throw err;\n }\n}\n"],"mappings":"ukBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,kBAAAE,GAAA,oBAAAC,GAAA,wBAAAC,EAAA,yBAAAC,EAAA,aAAAC,GAAA,kBAAAC,GAAA,0BAAAC,GAAA,2BAAAC,GAAA,0BAAAC,EAAA,oBAAAC,GAAA,wBAAAC,GAAA,yBAAAC,EAAA,0BAAAC,KAAA,eAAAC,GAAAf,ICAA,IAAAgB,EAAgG,8BAChGC,GAAwB,mCCexB,IAAAC,EAA0C,8BAEpCC,MAAuB,oBAC3B,gDAAgD,EAG5C,SAAUC,EAAgBC,EAAgB,CAC9C,OAAOA,EAAQ,SAASF,GAAsB,EAAI,CACpD,CCRA,IAAAG,EAAgC,8BAO1B,SAAUC,GAAmB,CACjC,OAAO,SAACC,EAAa,CACnB,OAAK,MAAMC,GAAmBD,CAAE,CAAC,CACnC,CACF,CAMA,SAASC,GAAmBD,EAAsB,CAChD,OAAI,OAAOA,GAAO,SACTA,EAEA,KAAK,UAAUE,GAAiBF,CAAE,CAAC,CAE9C,CAOA,SAASE,GAAiBF,EAAa,CAIrC,QAHMG,EAAS,CAAA,EACXC,EAAUJ,EAEPI,IAAY,MACjB,OAAO,oBAAoBA,CAAO,EAAE,QAAQ,SAAAC,EAAY,CACtD,GAAI,CAAAF,EAAOE,CAAY,EACvB,KAAMC,EAAQF,EAAQC,CAAoC,EACtDC,IACFH,EAAOE,CAAY,EAAI,OAAOC,CAAK,GAEvC,CAAC,EACDF,EAAU,OAAO,eAAeA,CAAO,EAGzC,OAAOD,CACT,CCzCA,IAAII,GAAkBC,EAAmB,EAcnC,SAAUC,EAAmBC,EAAa,CAC9C,GAAI,CACFC,GAAgBD,CAAE,OACZ,CAAA,CACV,CCvBA,IAAAE,EAA6B,8BCA7B,IAAYC,GAAZ,SAAYA,EAAmB,CAC7BA,EAAA,UAAA,aAC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Q,OAAO,EAAGD,CAAO,EACvE,cAAY,OAAOC,EAAgBL,CAAO,EAE1CR,EAAa,QAAUQ,EAEnBV,GACFA,EAAO,KAAK,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,CAAO,EAAG,iBAAiB,EAGnE,GAAI,CACF,IAAMa,EAAM,MAAM,MAAMlB,EAAKI,CAAY,EAGnCe,GAFcD,EAAI,QAAQ,IAAI,cAAc,GAAK,IAC5B,SAAS,kBAAkB,EAChC,MAAMA,EAAI,KAAK,EAAE,MAAM,IAAM,IAAI,EAAI,MAAMA,EAAI,KAAK,EAAE,MAAM,IAAM,IAAI,EAE5F,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQ,IAAI,MAAM,QAAQF,EAAI,MAAM,IAAIA,EAAI,YAAc,EAAE,GAAG,KAAK,CAAC,EAC3E,MAACE,EAAc,OAASF,EAAI,OAC3BE,EAAc,KAAOD,EAClBjB,GACFA,EAAO,MAAM,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,OAAQa,EAAI,OAAQ,KAAAC,CAAK,EAAG,kBAAkB,EAEzFC,CACR,CAEA,OAAIlB,GACFA,EAAO,KAAK,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,OAAQa,EAAI,MAAO,EAAG,mBAAmB,EAGlFC,CACT,OAASE,EAAU,CACjB,MAAInB,GACFA,EAAO,MAAM,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,MAAOgB,EAAI,OAAQ,EAAG,iBAAiB,EAElFA,CACR,CACF","names":["index_exports","__export","createLogger","errorMiddleware","getGlobalAttributes","getRequestAttributes","httpCall","instrumentApp","mergeGlobalAttributes","mergeRequestAttributes","runWithRequestContext","sdkStartPromise","setGlobalAttributes","setRequestAttributes","withRequestAttributes","__toCommonJS","import_api","import_sdk_node","import_api","SUPPRESS_TRACING_KEY","suppressTracing","context","import_api","loggingErrorHandler","ex","stringifyException","flattenException","result","current","propertyName","value","delegateHandler","loggingErrorHandler","globalErrorHandler","ex","delegateHandler","import_api","TracesSamplerValues","DEFAULT_LIST_SEPARATOR","ENVIRONMENT_BOOLEAN_KEYS","isEnvVarABoolean","key","ENVIRONMENT_NUMBERS_KEYS","isEnvVarANumber","ENVIRONMENT_LISTS_KEYS","isEnvVarAList","DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT","DEFAULT_ATTRIBUTE_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","DEFAULT_ENVIRONMENT","TracesSamplerValues","parseBoolean","environment","values","value","parseNumber","name","min","max","parseStringList","output","input","separator","givenValue","v","logLevelMap","setLogLevelFromEnv","theLevel","parseEnvironment","env","getEnv","processEnv","parseEnvironment","DEFAULT_ENVIRONMENT","unrefTimer","timer","ExportResultCode","Deferred","_this","resolve","reject","val","err","BindOnceFuture","_callback","_that","Deferred","_this","args","_i","_a","__spreadArray","__read","val","err","import_api","BatchSpanProcessorBase","_exporter","config","env","getEnv","BindOnceFuture","_span","_parentContext","span","_this","resolve","reject","promises","count","j","timer","suppressTracing","spans","doExport","result","ExportResultCode","_a","pendingResources","i","len","err","globalErrorHandler","flush","e","unrefTimer","BatchSpanProcessor","_super","__extends","BatchSpanProcessorBase","import_resources","import_exporter_trace_otlp_http","import_auto_instrumentations_node","import_undici","import_node_async_hooks","requestAttributeStorage","globalAttributes","clone","attrs","getGlobalAttributes","setGlobalAttributes","mergeGlobalAttributes","getRequestAttributes","setRequestAttributes","options","store","nextAttributes","mergeRequestAttributes","withRequestAttributes","fn","runWithRequestContext","initialAttributes","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","expressLayersEnabled","moduleLabel","proxyUrl","v","err","resource","ModuleNameSpanProcessor","span","currentName","dynamicAttributes","getGlobalAttributes","getRequestAttributes","key","value","_span","CombinedSpanProcessor","processors","ctx","p","instrumentations","exporter","spanProcessor","BatchSpanProcessor","sdk","sdkStartPromise","error","shutdown","instrumentApp","app","logger","customModuleName","req","_res","next","runWithRequestContext","baggage","otContext","baggageAttrs","entry","orgId","sessionId","executionId","userId","requestId","setRequestAttributes","requestAttributes","import_pino","levelMethods","wrapWithDynamicAttributes","logger","buildAttrs","getGlobalAttributes","getRequestAttributes","target","prop","receiver","original","firstArg","rest","attrs","createLogger","mainEnv","mainApp","mainModule","base","pino","import_api","errorMiddleware","logger","err","req","res","next","dynamicAttributes","getGlobalAttributes","getRequestAttributes","span","import_api","httpCall","url","options","logger","logContext","fetchOptions","method","dynamicContext","getGlobalAttributes","getRequestAttributes","headerEntries","v","k","carrier","baggageEntries","key","value","baggage","ctxWithBaggage","res","data","error","err"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/sampling.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/timer-util.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/ExportResult.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/promise.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/callback.ts","../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../src/attributes.ts","../src/logger.ts","../src/exceptions.ts","../src/http-caller.ts","../src/metrics.ts"],"sourcesContent":["export { sdkStartPromise, instrumentApp } from './tracing.js';\nexport { createLogger } from './logger.js';\nexport { errorMiddleware } from './exceptions.js';\nexport { httpCall } from './http-caller.js';\nexport { metricsStartPromise, getMeter, createCounter, createHistogram } from './metrics.js';\nexport {\n getGlobalAttributes,\n setGlobalAttributes,\n mergeGlobalAttributes,\n getRequestAttributes,\n setRequestAttributes,\n mergeRequestAttributes,\n withRequestAttributes,\n runWithRequestContext,\n} from './attributes.js';\n","import { diag, DiagConsoleLogger, DiagLogLevel, trace, context as otContext, propagation } from '@opentelemetry/api';\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { SpanProcessor, ReadableSpan, BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { Resource } from '@opentelemetry/resources';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { ProxyAgent, setGlobalDispatcher } from 'undici';\nimport type { Application, Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\nimport {\n getGlobalAttributes,\n getRequestAttributes,\n runWithRequestContext,\n setRequestAttributes,\n} from './attributes.js';\n\ndiag.setLogger(new DiagConsoleLogger(), DiagLogLevel.WARN);\n\nconst serviceName =\n process.env.OTEL_SERVICE_NAME ||\n process.env.MAIN_MODULE ||\n 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE ||\n process.env.OTEL_SERVICE_NAMESPACE ||\n process.env.MAIN_APP ||\n 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\nconst expressLayersEnabled = (process.env.ONELOG_EXPRESS_LAYERS || '').toLowerCase() === 'true';\nconst moduleLabel = process.env.MAIN_MODULE || moduleName;\n\n// Optional proxy support for environments with HTTP(S)_PROXY set\nconst proxyUrl = [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy]\n .find((v) => v && v.trim().length > 0);\n\nif (proxyUrl) {\n try {\n setGlobalDispatcher(new ProxyAgent(proxyUrl));\n // eslint-disable-next-line no-console\n console.log(`[onelog] Proxy enabled for outbound traffic: ${proxyUrl}`);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure proxy agent:', (err as Error).message);\n }\n}\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleLabel,\n }),\n);\n\nclass ModuleNameSpanProcessor implements SpanProcessor {\n constructor(private readonly moduleName: string) {}\n onStart(span: any): void {\n if (!span) return;\n const currentName = (span as any).name || (span as any)._name || '';\n if (this.moduleName && !currentName.startsWith(`[${this.moduleName}] `)) {\n span.updateName(`[${this.moduleName}] ${currentName}`);\n }\n if (this.moduleName) {\n span.setAttribute('module.name', this.moduleName);\n }\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(dynamicAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n onEnd(_span: ReadableSpan): void {\n // no-op\n }\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nclass CombinedSpanProcessor implements SpanProcessor {\n constructor(private readonly processors: SpanProcessor[]) {}\n onStart(span: any, ctx?: any): void {\n for (const p of this.processors) p.onStart(span as any, ctx);\n }\n onEnd(span: ReadableSpan): void {\n for (const p of this.processors) p.onEnd(span);\n }\n shutdown(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.shutdown())).then(() => undefined);\n }\n forceFlush(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.forceFlush())).then(() => undefined);\n }\n}\n\nconst instrumentations = getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-http': {\n enabled: true,\n },\n '@opentelemetry/instrumentation-express': {\n enabled: true,\n ignoreLayersType: expressLayersEnabled ? [] : (['middleware', 'request_handler'] as any),\n },\n '@opentelemetry/instrumentation-undici': {\n enabled: true,\n },\n // Redis instrumentation is noisy in our workloads; keep it off by default\n '@opentelemetry/instrumentation-ioredis': { enabled: false },\n '@opentelemetry/instrumentation-redis': { enabled: false },\n '@opentelemetry/instrumentation-fs': { enabled: false },\n '@opentelemetry/instrumentation-dns': { enabled: false },\n '@opentelemetry/instrumentation-net': { enabled: false },\n});\n\nconst exporter = new OTLPTraceExporter({\n url: `${otlpEndpoint}/v1/traces`,\n});\n\nconst spanProcessor = new CombinedSpanProcessor([\n new ModuleNameSpanProcessor(moduleLabel),\n new BatchSpanProcessor(exporter),\n]);\n\nconst sdk = new NodeSDK({\n resource,\n instrumentations: [instrumentations],\n spanProcessor,\n});\n\nexport const sdkStartPromise = Promise.resolve(sdk.start()).catch((error) => {\n console.error('Failed to start OpenTelemetry SDK', error);\n return Promise.resolve();\n});\n\nconst shutdown = async () => {\n try {\n await sdk.shutdown();\n } catch (error) {\n console.error('Error shutting down OpenTelemetry SDK', error);\n }\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nexport const instrumentApp = (app: Application, logger?: Logger, customModuleName?: string) => {\n const moduleLabel = customModuleName || process.env.MAIN_MODULE || moduleName;\n app.use((req: Request, _res: Response, next: NextFunction) => {\n runWithRequestContext(() => {\n const baggage = propagation.getBaggage(otContext.active());\n const baggageAttrs = baggage\n ? Object.fromEntries(\n (baggage.getAllEntries?.() || []).map(([key, entry]) => [key, entry.value]),\n )\n : {};\n\n const orgId =\n (req.headers['organization-id'] as string) ||\n (req.headers['activeorgid'] as string) ||\n (req.headers['active-org-id'] as string) ||\n (req.headers['activeOrgID'] as string) ||\n (baggageAttrs['organization-id'] as string);\n const sessionId = (req.headers['session-id'] as string) || (baggageAttrs['session-id'] as string);\n const executionId =\n (req.headers['execution-id'] as string) ||\n (req.headers['executionid'] as string) ||\n (req.headers['execution_id'] as string) ||\n (baggageAttrs['execution-id'] as string);\n const userId = (req.headers['user-id'] as string) || (baggageAttrs['user-id'] as string);\n const requestId = (req.headers['request-id'] as string) || (baggageAttrs['request-id'] as string);\n const rawOnelogAttr =\n (req.headers['x-onelog-attr'] as string) ||\n (req.headers['x-onelog-attrs'] as string) ||\n (baggageAttrs['x-onelog-attr'] as string);\n let parsedOnelogAttrs: Record<string, any> = {};\n if (rawOnelogAttr) {\n try {\n const parsed = typeof rawOnelogAttr === 'string' ? JSON.parse(rawOnelogAttr) : rawOnelogAttr;\n if (parsed && typeof parsed === 'object') parsedOnelogAttrs = parsed;\n } catch {\n // ignore malformed\n }\n }\n\n setRequestAttributes({\n 'module.name': moduleLabel,\n 'http.method': req.method,\n 'http.target': req.path,\n 'organization.id': orgId,\n 'organization-id': orgId,\n 'session.id': sessionId,\n 'session-id': sessionId,\n 'execution.id': executionId,\n 'execution-id': executionId,\n 'user.id': userId,\n 'user-id': userId,\n 'request.id': requestId,\n 'request-id': requestId,\n ...baggageAttrs,\n ...parsedOnelogAttrs,\n });\n\n const span = trace.getActiveSpan();\n if (span) {\n span.setAttribute('module.name', moduleLabel);\n span.updateName(`[${moduleLabel}] ${req.method} ${req.path}`);\n const requestAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(requestAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n if (logger) {\n logger.info(\n {\n method: req.method,\n path: req.path,\n ip: req.ip,\n },\n 'Incoming request',\n );\n }\n next();\n });\n });\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, Exception } from '@opentelemetry/api';\nimport { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n 'OTEL_SEMCONV_STABILITY_OPT_IN',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required<ENVIRONMENT> = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n OTEL_SEMCONV_STABILITY_OPT_IN: [],\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_ENVIRONMENT,\n ENVIRONMENT,\n RAW_ENVIRONMENT,\n parseEnvironment,\n} from '../../utils/environment';\n\n/**\n * Gets the environment variables\n */\nexport function getEnv(): Required<ENVIRONMENT> {\n const processEnv = parseEnvironment(process.env as RAW_ENVIRONMENT);\n return Object.assign({}, DEFAULT_ENVIRONMENT, processEnv);\n}\n\nexport function getEnvWithoutDefaults(): ENVIRONMENT {\n return parseEnvironment(process.env as RAW_ENVIRONMENT);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function unrefTimer(timer: NodeJS.Timer): void {\n timer.unref();\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context, Context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getEnv,\n globalErrorHandler,\n suppressTracing,\n unrefTimer,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { BufferConfig } from '../types';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(\n private readonly _exporter: SpanExporter,\n config?: T\n ) {\n const env = getEnv();\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : env.OTEL_BSP_MAX_QUEUE_SIZE;\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : env.OTEL_BSP_SCHEDULE_DELAY;\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : env.OTEL_BSP_EXPORT_TIMEOUT;\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n unrefTimer(this._timer);\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport type AttributeMap = Record<string, any>;\n\ntype RequestAttributeContext = {\n requestAttributes: AttributeMap;\n};\n\nconst requestAttributeStorage = new AsyncLocalStorage<RequestAttributeContext>();\n\nlet globalAttributes: AttributeMap = {};\n\nconst clone = (attrs?: AttributeMap) => ({ ...(attrs || {}) });\n\nexport const getGlobalAttributes = (): AttributeMap => clone(globalAttributes);\n\nexport const setGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = clone(attrs);\n};\n\nexport const mergeGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = { ...globalAttributes, ...clone(attrs) };\n};\n\nexport const getRequestAttributes = (): AttributeMap => {\n const store = requestAttributeStorage.getStore();\n return store?.requestAttributes || {};\n};\n\nexport const setRequestAttributes = (attrs: AttributeMap, options?: { append?: boolean }) => {\n const store = requestAttributeStorage.getStore();\n if (!store) return;\n\n const nextAttributes =\n options?.append === false ? clone(attrs) : { ...store.requestAttributes, ...clone(attrs) };\n store.requestAttributes = nextAttributes;\n};\n\nexport const mergeRequestAttributes = (attrs: AttributeMap) => setRequestAttributes(attrs);\n\nexport const withRequestAttributes = <T>(\n attrs: AttributeMap,\n fn: () => T,\n options?: { append?: boolean },\n): T => {\n const store = requestAttributeStorage.getStore();\n if (!store) {\n return runWithRequestContext(() => fn(), attrs);\n }\n setRequestAttributes(attrs, options);\n return fn();\n};\n\nexport const runWithRequestContext = <T>(fn: () => T, initialAttributes?: AttributeMap): T => {\n return requestAttributeStorage.run(\n {\n requestAttributes: clone(initialAttributes),\n },\n fn,\n );\n};\n","import pino, { Logger } from 'pino';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nconst levelMethods = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'] as const;\n\nconst wrapWithDynamicAttributes = (logger: Logger): Logger => {\n const buildAttrs = () => ({ ...getGlobalAttributes(), ...getRequestAttributes() });\n\n return new Proxy(logger, {\n get(target, prop, receiver) {\n const original = Reflect.get(target, prop, receiver);\n if (typeof prop === 'string' && levelMethods.includes(prop as any) && typeof original === 'function') {\n return (firstArg?: any, ...rest: any[]) => {\n const attrs = buildAttrs();\n if (firstArg && typeof firstArg === 'object' && !Array.isArray(firstArg)) {\n return (original as any).call(target, { ...attrs, ...firstArg }, ...rest);\n }\n return (original as any).call(target, { ...attrs }, firstArg, ...rest);\n };\n }\n return original;\n },\n });\n};\n\nexport function createLogger() {\n const mainEnv = process.env.MAIN_ENV || 'development';\n const mainApp = process.env.MAIN_APP || 'app';\n const mainModule = process.env.MAIN_MODULE || 'unknown-module';\n\n const logger = pino({\n transport: {\n targets: [\n {\n target: 'pino-opentelemetry-transport',\n level: 'info',\n options: {\n resourceAttributes: {\n 'service.name': mainApp,\n 'service.namespace': mainEnv,\n 'deployment.environment': mainEnv,\n 'module.name': mainModule,\n 'host.name': require('os').hostname(),\n },\n },\n },\n {\n target: 'pino-pretty',\n level: 'debug',\n options: {\n colorize: true,\n translateTime: 'HH:MM:ss Z',\n ignore: 'pid,hostname',\n },\n },\n ],\n },\n });\n\n const base = logger.child({\n env: mainEnv,\n app: mainApp,\n module: mainModule,\n });\n\n return wrapWithDynamicAttributes(base);\n}\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\nimport type { Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\n\nexport const errorMiddleware =\n (logger?: Logger) =>\n (err: Error, req: Request, res: Response, next: NextFunction) => {\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n\n if (logger) {\n logger.error(\n {\n ...dynamicAttributes,\n error: err.message,\n stack: err.stack,\n path: req.path,\n },\n 'Unhandled error',\n );\n }\n\n const span = trace.getActiveSpan();\n if (span) {\n span.recordException(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n }\n\n if (res.headersSent) {\n return next(err);\n }\n\n res.status(500).json({\n error: err.message,\n attributes: dynamicAttributes,\n module: process.env.MAIN_MODULE || 'unknown-module',\n });\n };\n","import { context, propagation } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nexport interface HttpCallContext {\n [key: string]: any;\n}\n\nexport interface HttpCallOptions extends RequestInit {\n body?: any;\n}\n\nexport async function httpCall(\n url: string,\n options: HttpCallOptions = {},\n logger?: { info: Function; error: Function },\n logContext: HttpCallContext = {},\n) {\n const fetchOptions: RequestInit = { ...options };\n const method = (fetchOptions.method || 'GET').toString().toUpperCase();\n\n if (\n fetchOptions.body &&\n typeof fetchOptions.body !== 'string' &&\n !(fetchOptions.body instanceof Buffer) &&\n !(fetchOptions.body instanceof ArrayBuffer)\n ) {\n fetchOptions.body = JSON.stringify(fetchOptions.body);\n fetchOptions.headers = {\n 'Content-Type': 'application/json',\n ...(fetchOptions.headers || {}),\n };\n }\n\n const dynamicContext = { ...getGlobalAttributes(), ...getRequestAttributes(), ...logContext };\n\n // Inject trace context + baggage, and forward standard IDs as headers for downstream services\n const headerEntries = Object.entries({\n ...(fetchOptions.headers as any),\n 'organization-id':\n (dynamicContext['organization-id'] as string) || (dynamicContext['organization.id'] as string),\n 'session-id': (dynamicContext['session-id'] as string) || (dynamicContext['session.id'] as string),\n 'execution-id':\n (dynamicContext['execution-id'] as string) || (dynamicContext['execution.id'] as string),\n 'user-id': (dynamicContext['user-id'] as string) || (dynamicContext['user.id'] as string),\n 'request-id': (dynamicContext['request-id'] as string) || (dynamicContext['request.id'] as string),\n 'x-onelog-attr': JSON.stringify(dynamicContext),\n })\n .filter(([, v]) => v !== undefined && v !== null)\n .map(([k, v]) => [k, String(v)]) as [string, string][];\n\n const headers: Record<string, string> = Object.fromEntries(headerEntries);\n\n const carrier: Record<string, any> = { ...headers };\n\n // Build baggage from all attributes to propagate custom keys\n const baggageEntries: Record<string, { value: string }> = {};\n for (const [key, value] of Object.entries(dynamicContext)) {\n if (value === undefined || value === null) continue;\n try {\n baggageEntries[key] = { value: typeof value === 'string' ? value : JSON.stringify(value) };\n } catch {\n // skip values that can't be stringified\n }\n }\n const baggage = propagation.createBaggage(baggageEntries);\n const ctxWithBaggage = propagation.setBaggage(context.active(), baggage);\n propagation.inject(ctxWithBaggage, carrier);\n\n fetchOptions.headers = carrier;\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method }, 'HTTP call start');\n }\n\n try {\n const res = await fetch(url, fetchOptions);\n const contentType = res.headers.get('content-type') || '';\n const isJson = contentType.includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : await res.text().catch(() => null);\n\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status} ${res.statusText || ''}`.trim());\n (error as any).status = res.status;\n (error as any).data = data;\n if (logger) {\n logger.error({ ...dynamicContext, url, method, status: res.status, data }, 'HTTP call failed');\n }\n throw error;\n }\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method, status: res.status }, 'HTTP call success');\n }\n\n return data;\n } catch (err: any) {\n if (logger) {\n logger.error({ ...dynamicContext, url, method, error: err.message }, 'HTTP call error');\n }\n throw err;\n }\n}\n","import { context as otContext, metrics as otMetrics, type Attributes, type MetricOptions } from '@opentelemetry/api';\nimport { Resource } from '@opentelemetry/resources';\nimport { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';\nimport { HostMetrics } from '@opentelemetry/host-metrics';\nimport { RuntimeNodeInstrumentation } from '@opentelemetry/instrumentation-runtime-node';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nconst serviceName = process.env.OTEL_SERVICE_NAME || process.env.MAIN_MODULE || 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE || process.env.OTEL_SERVICE_NAMESPACE || process.env.MAIN_APP || 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\nconst hostMetricsEnabled = (process.env.ONELOG_HOST_METRICS || 'true').toLowerCase() === 'true';\nconst runtimeMetricsEnabled = (process.env.ONELOG_RUNTIME_METRICS || 'false').toLowerCase() === 'true';\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleName,\n }),\n);\n\nlet meterProvider: MeterProvider | undefined;\nlet shutdownRegistered = false;\nlet hostMetricsStarted = false;\nlet runtimeMetricsStarted = false;\n\nconst registerShutdown = () => {\n if (shutdownRegistered) return;\n shutdownRegistered = true;\n const shutdown = async () => {\n if (!meterProvider) return;\n try {\n await meterProvider.shutdown();\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Error shutting down metrics provider', (error as Error).message);\n }\n };\n process.on('SIGTERM', shutdown);\n process.on('SIGINT', shutdown);\n};\n\nconst ensureMeterProvider = () => {\n if (meterProvider) return meterProvider;\n\n const exporter = new OTLPMetricExporter({\n url: `${otlpEndpoint}/v1/metrics`,\n });\n\n meterProvider = new MeterProvider({\n resource,\n readers: [\n new PeriodicExportingMetricReader({\n exporter,\n }),\n ],\n });\n\n otMetrics.setGlobalMeterProvider(meterProvider);\n startHostMetrics(meterProvider);\n startRuntimeMetrics(meterProvider);\n registerShutdown();\n return meterProvider;\n};\n\nconst startHostMetrics = (provider: MeterProvider) => {\n if (!hostMetricsEnabled || hostMetricsStarted) return;\n try {\n const hostMetrics = new HostMetrics({\n meterProvider: provider,\n name: 'onelog-host-metrics',\n });\n hostMetrics.start();\n hostMetricsStarted = true;\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to start host metrics instrumentation', (error as Error).message);\n }\n};\n\nconst startRuntimeMetrics = (provider: MeterProvider) => {\n if (!runtimeMetricsEnabled || runtimeMetricsStarted) return;\n try {\n const runtimeInstrumentation = new RuntimeNodeInstrumentation();\n runtimeInstrumentation.setMeterProvider(provider);\n runtimeInstrumentation.enable();\n runtimeMetricsStarted = true;\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to start runtime metrics instrumentation', (error as Error).message);\n }\n};\n\nexport const metricsStartPromise = Promise.resolve().then(() => ensureMeterProvider());\n\nexport const getMeter = (name = 'onelog-metrics') => ensureMeterProvider().getMeter(name);\n\nconst buildAttributes = (attrs?: Attributes): Attributes => ({\n ...getGlobalAttributes(),\n ...getRequestAttributes(),\n ...(attrs || {}),\n});\n\nexport const createCounter = (name: string, options?: MetricOptions) => {\n const counter = getMeter().createCounter(name, options);\n return {\n add: (value: number, attributes?: Attributes) => {\n counter.add(value, buildAttributes(attributes), otContext.active());\n },\n instrument: counter,\n };\n};\n\nexport const createHistogram = (name: string, options?: MetricOptions) => {\n const histogram = getMeter().createHistogram(name, options);\n return {\n record: (value: number, attributes?: Attributes) => {\n histogram.record(value, buildAttributes(attributes), otContext.active());\n },\n instrument: histogram,\n };\n};\n"],"mappings":"0kBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,mBAAAE,GAAA,oBAAAC,GAAA,iBAAAC,GAAA,oBAAAC,GAAA,wBAAAC,EAAA,aAAAC,EAAA,yBAAAC,EAAA,aAAAC,GAAA,kBAAAC,GAAA,0BAAAC,GAAA,2BAAAC,GAAA,wBAAAC,GAAA,0BAAAC,EAAA,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EACvB,OAASI,EAAO,CAEd,QAAQ,MAAM,wDAA0DA,EAAgB,OAAO,CACjG,CACF,EAEMK,GAAuBC,GAA4B,CACvD,GAAI,GAACd,IAAyBK,IAC9B,GAAI,CACF,IAAMU,EAAyB,IAAI,8BACnCA,EAAuB,iBAAiBD,CAAQ,EAChDC,EAAuB,OAAO,EAC9BV,GAAwB,EAC1B,OAASG,EAAO,CAEd,QAAQ,MAAM,2DAA6DA,EAAgB,OAAO,CACpG,CACF,EAEaQ,GAAsB,QAAQ,QAAQ,EAAE,KAAK,IAAMP,GAAoB,CAAC,EAExEQ,EAAW,CAACC,EAAO,mBAAqBT,GAAoB,EAAE,SAASS,CAAI,EAElFC,GAAmBC,IAAoC,CAC3D,GAAGC,EAAoB,EACvB,GAAGC,EAAqB,EACxB,GAAIF,GAAS,CAAC,CAChB,GAEaG,GAAgB,CAACL,EAAcM,IAA4B,CACtE,IAAMC,EAAUR,EAAS,EAAE,cAAcC,EAAMM,CAAO,EACtD,MAAO,CACL,IAAK,CAACE,EAAeC,IAA4B,CAC/CF,EAAQ,IAAIC,EAAOP,GAAgBQ,CAAU,EAAG,EAAAC,QAAU,OAAO,CAAC,CACpE,EACA,WAAYH,CACd,CACF,EAEaI,GAAkB,CAACX,EAAcM,IAA4B,CACxE,IAAMM,EAAYb,EAAS,EAAE,gBAAgBC,EAAMM,CAAO,EAC1D,MAAO,CACL,OAAQ,CAACE,EAAeC,IAA4B,CAClDG,EAAU,OAAOJ,EAAOP,GAAgBQ,CAAU,EAAG,EAAAC,QAAU,OAAO,CAAC,CACzE,EACA,WAAYE,CACd,CACF","names":["index_exports","__export","createCounter","createHistogram","createLogger","errorMiddleware","getGlobalAttributes","getMeter","getRequestAttributes","httpCall","instrumentApp","mergeGlobalAttributes","mergeRequestAttributes","metricsStartPromise","runWithRequestContext","sdkStartPromise","setGlobalAttributes","setRequestAttributes","withRequestAttributes","__toCommonJS","import_api","import_sdk_node","import_api","SUPPRESS_TRACING_KEY","suppressTracing","context","import_api","loggingErrorHandler","ex","stringifyException","flattenException","result","current","propertyName","value","delegateHandler","loggingErrorHandler","globalErrorHandler","ex","delegateHandler","import_api","TracesSamplerValues","DEFAULT_LIST_SEPARATOR","ENVIRONMENT_BOOLEAN_KEYS","isEnvVarABoolean","key","ENVIRONMENT_NUMBERS_KEYS","isEnvVarANumber","ENVIRONMENT_LISTS_KEYS","isEnvVarAList","DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT","DEFAULT_ATTRIBUTE_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","DEFAULT_ENVIRONMENT","TracesSamplerValues","parseBoolean","environment","values","value","parseNumber","name","min","max","parseStringList","output","input","separator","givenValue","v","logLevelMap","setLogLevelFromEnv","theLevel","parseEnvironment","env","getEnv","processEnv","parseEnvironment","DEFAULT_ENVIRONMENT","unrefTimer","timer","ExportResultCode","Deferred","_this","resolve","reject","val","err","BindOnceFuture","_callback","_that","Deferred","_this","args","_i","_a","__spreadArray","__read","val","err","import_api","BatchSpanProcessorBase","_exporter","config","env","getEnv","BindOnceFuture","_span","_parentContext","span","_this","resolve","reject","promises","count","j","timer","suppressTracing","spans","doExport","result","ExportResultCode","_a","pendingResources","i","len","err","globalErrorHandler","flush","e","unrefTimer","BatchSpanProcessor","_super","__extends","BatchSpanProcessorBase","import_resources","import_exporter_trace_otlp_http","import_auto_instrumentations_node","import_undici","import_node_async_hooks","requestAttributeStorage","globalAttributes","clone","attrs","getGlobalAttributes","setGlobalAttributes","mergeGlobalAttributes","getRequestAttributes","setRequestAttributes","options","store","nextAttributes","mergeRequestAttributes","withRequestAttributes","fn","runWithRequestContext","initialAttributes","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","expressLayersEnabled","moduleLabel","proxyUrl","v","err","resource","ModuleNameSpanProcessor","span","currentName","dynamicAttributes","getGlobalAttributes","getRequestAttributes","key","value","_span","CombinedSpanProcessor","processors","ctx","p","instrumentations","exporter","spanProcessor","BatchSpanProcessor","sdk","sdkStartPromise","error","shutdown","instrumentApp","app","logger","customModuleName","req","_res","next","runWithRequestContext","baggage","otContext","baggageAttrs","entry","orgId","sessionId","executionId","userId","requestId","rawOnelogAttr","parsedOnelogAttrs","parsed","setRequestAttributes","requestAttributes","import_pino","levelMethods","wrapWithDynamicAttributes","logger","buildAttrs","getGlobalAttributes","getRequestAttributes","target","prop","receiver","original","firstArg","rest","attrs","createLogger","mainEnv","mainApp","mainModule","base","pino","import_api","errorMiddleware","logger","err","req","res","next","dynamicAttributes","getGlobalAttributes","getRequestAttributes","span","import_api","httpCall","url","options","logger","logContext","fetchOptions","method","dynamicContext","getGlobalAttributes","getRequestAttributes","headerEntries","v","k","carrier","baggageEntries","key","value","baggage","ctxWithBaggage","res","data","error","err","import_api","import_resources","import_sdk_metrics","import_exporter_metrics_otlp_http","import_host_metrics","import_instrumentation_runtime_node","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","hostMetricsEnabled","runtimeMetricsEnabled","resource","meterProvider","shutdownRegistered","hostMetricsStarted","runtimeMetricsStarted","registerShutdown","shutdown","error","ensureMeterProvider","exporter","otMetrics","startHostMetrics","startRuntimeMetrics","provider","runtimeInstrumentation","metricsStartPromise","getMeter","name","buildAttributes","attrs","getGlobalAttributes","getRequestAttributes","createCounter","options","counter","value","attributes","otContext","createHistogram","histogram"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { Application, Request, Response, NextFunction } from 'express';
|
|
2
2
|
import pino, { Logger } from 'pino';
|
|
3
|
+
import * as _opentelemetry_api from '@opentelemetry/api';
|
|
4
|
+
import { MetricOptions, Attributes } from '@opentelemetry/api';
|
|
5
|
+
import { MeterProvider } from '@opentelemetry/sdk-metrics';
|
|
3
6
|
|
|
4
7
|
declare const sdkStartPromise: Promise<void>;
|
|
5
8
|
declare const instrumentApp: (app: Application, logger?: Logger, customModuleName?: string) => void;
|
|
@@ -19,6 +22,17 @@ declare function httpCall(url: string, options?: HttpCallOptions, logger?: {
|
|
|
19
22
|
error: Function;
|
|
20
23
|
}, logContext?: HttpCallContext): Promise<any>;
|
|
21
24
|
|
|
25
|
+
declare const metricsStartPromise: Promise<MeterProvider>;
|
|
26
|
+
declare const getMeter: (name?: string) => _opentelemetry_api.Meter;
|
|
27
|
+
declare const createCounter: (name: string, options?: MetricOptions) => {
|
|
28
|
+
add: (value: number, attributes?: Attributes) => void;
|
|
29
|
+
instrument: _opentelemetry_api.Counter<Attributes>;
|
|
30
|
+
};
|
|
31
|
+
declare const createHistogram: (name: string, options?: MetricOptions) => {
|
|
32
|
+
record: (value: number, attributes?: Attributes) => void;
|
|
33
|
+
instrument: _opentelemetry_api.Histogram<Attributes>;
|
|
34
|
+
};
|
|
35
|
+
|
|
22
36
|
type AttributeMap = Record<string, any>;
|
|
23
37
|
declare const getGlobalAttributes: () => AttributeMap;
|
|
24
38
|
declare const setGlobalAttributes: (attrs: AttributeMap) => void;
|
|
@@ -33,4 +47,4 @@ declare const withRequestAttributes: <T>(attrs: AttributeMap, fn: () => T, optio
|
|
|
33
47
|
}) => T;
|
|
34
48
|
declare const runWithRequestContext: <T>(fn: () => T, initialAttributes?: AttributeMap) => T;
|
|
35
49
|
|
|
36
|
-
export { createLogger, errorMiddleware, getGlobalAttributes, getRequestAttributes, httpCall, instrumentApp, mergeGlobalAttributes, mergeRequestAttributes, runWithRequestContext, sdkStartPromise, setGlobalAttributes, setRequestAttributes, withRequestAttributes };
|
|
50
|
+
export { createCounter, createHistogram, createLogger, errorMiddleware, getGlobalAttributes, getMeter, getRequestAttributes, httpCall, instrumentApp, mergeGlobalAttributes, mergeRequestAttributes, metricsStartPromise, runWithRequestContext, sdkStartPromise, setGlobalAttributes, setRequestAttributes, withRequestAttributes };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { Application, Request, Response, NextFunction } from 'express';
|
|
2
2
|
import pino, { Logger } from 'pino';
|
|
3
|
+
import * as _opentelemetry_api from '@opentelemetry/api';
|
|
4
|
+
import { MetricOptions, Attributes } from '@opentelemetry/api';
|
|
5
|
+
import { MeterProvider } from '@opentelemetry/sdk-metrics';
|
|
3
6
|
|
|
4
7
|
declare const sdkStartPromise: Promise<void>;
|
|
5
8
|
declare const instrumentApp: (app: Application, logger?: Logger, customModuleName?: string) => void;
|
|
@@ -19,6 +22,17 @@ declare function httpCall(url: string, options?: HttpCallOptions, logger?: {
|
|
|
19
22
|
error: Function;
|
|
20
23
|
}, logContext?: HttpCallContext): Promise<any>;
|
|
21
24
|
|
|
25
|
+
declare const metricsStartPromise: Promise<MeterProvider>;
|
|
26
|
+
declare const getMeter: (name?: string) => _opentelemetry_api.Meter;
|
|
27
|
+
declare const createCounter: (name: string, options?: MetricOptions) => {
|
|
28
|
+
add: (value: number, attributes?: Attributes) => void;
|
|
29
|
+
instrument: _opentelemetry_api.Counter<Attributes>;
|
|
30
|
+
};
|
|
31
|
+
declare const createHistogram: (name: string, options?: MetricOptions) => {
|
|
32
|
+
record: (value: number, attributes?: Attributes) => void;
|
|
33
|
+
instrument: _opentelemetry_api.Histogram<Attributes>;
|
|
34
|
+
};
|
|
35
|
+
|
|
22
36
|
type AttributeMap = Record<string, any>;
|
|
23
37
|
declare const getGlobalAttributes: () => AttributeMap;
|
|
24
38
|
declare const setGlobalAttributes: (attrs: AttributeMap) => void;
|
|
@@ -33,4 +47,4 @@ declare const withRequestAttributes: <T>(attrs: AttributeMap, fn: () => T, optio
|
|
|
33
47
|
}) => T;
|
|
34
48
|
declare const runWithRequestContext: <T>(fn: () => T, initialAttributes?: AttributeMap) => T;
|
|
35
49
|
|
|
36
|
-
export { createLogger, errorMiddleware, getGlobalAttributes, getRequestAttributes, httpCall, instrumentApp, mergeGlobalAttributes, mergeRequestAttributes, runWithRequestContext, sdkStartPromise, setGlobalAttributes, setRequestAttributes, withRequestAttributes };
|
|
50
|
+
export { createCounter, createHistogram, createLogger, errorMiddleware, getGlobalAttributes, getMeter, getRequestAttributes, httpCall, instrumentApp, mergeGlobalAttributes, mergeRequestAttributes, metricsStartPromise, runWithRequestContext, sdkStartPromise, setGlobalAttributes, setRequestAttributes, withRequestAttributes };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var k=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{diag as Be,DiagConsoleLogger as De,DiagLogLevel as we,trace as Xe,context as Ge,propagation as He}from"@opentelemetry/api";import{NodeSDK as Fe}from"@opentelemetry/sdk-node";import{createContextKey as ee}from"@opentelemetry/api";var te=ee("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function b(e){return e.setValue(te,!0)}import{diag as re}from"@opentelemetry/api";function V(){return function(e){re.error(oe(e))}}function oe(e){return typeof e=="string"?e:JSON.stringify(ne(e))}function ne(e){for(var t={},r=e;r!==null;)Object.getOwnPropertyNames(r).forEach(function(o){if(!t[o]){var n=r[o];n&&(t[o]=String(n))}}),r=Object.getPrototypeOf(r);return t}var se=V();function x(e){try{se(e)}catch{}}import{DiagLogLevel as f}from"@opentelemetry/api";var N;(function(e){e.AlwaysOff="always_off",e.AlwaysOn="always_on",e.ParentBasedAlwaysOff="parentbased_always_off",e.ParentBasedAlwaysOn="parentbased_always_on",e.ParentBasedTraceIdRatio="parentbased_traceidratio",e.TraceIdRatio="traceidratio"})(N||(N={}));var ie=",",ae=["OTEL_SDK_DISABLED"];function Ee(e){return ae.indexOf(e)>-1}var _e=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function Te(e){return _e.indexOf(e)>-1}var ue=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function pe(e){return ue.indexOf(e)>-1}var M=1/0,U=128,ce=128,le=128,B={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:f.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:M,OTEL_ATTRIBUTE_COUNT_LIMIT:U,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:M,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:U,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:M,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:U,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:ce,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:le,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:N.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative",OTEL_SEMCONV_STABILITY_OPT_IN:[]};function Oe(e,t,r){if(!(typeof r[e]>"u")){var o=String(r[e]);t[e]=o.toLowerCase()==="true"}}function fe(e,t,r,o,n){if(o===void 0&&(o=-1/0),n===void 0&&(n=1/0),typeof r[e]<"u"){var s=Number(r[e]);isNaN(s)||(s<o?t[e]=o:s>n?t[e]=n:t[e]=s)}}function de(e,t,r,o){o===void 0&&(o=ie);var n=r[e];typeof n=="string"&&(t[e]=n.split(o).map(function(s){return s.trim()}))}var me={ALL:f.ALL,VERBOSE:f.VERBOSE,DEBUG:f.DEBUG,INFO:f.INFO,WARN:f.WARN,ERROR:f.ERROR,NONE:f.NONE};function Re(e,t,r){var o=r[e];if(typeof o=="string"){var n=me[o.toUpperCase()];n!=null&&(t[e]=n)}}function K(e){var t={};for(var r in B){var o=r;switch(o){case"OTEL_LOG_LEVEL":Re(o,t,e);break;default:if(Ee(o))Oe(o,t,e);else if(Te(o))fe(o,t,e);else if(pe(o))de(o,t,e);else{var n=e[o];typeof n<"u"&&n!==null&&(t[o]=String(n))}}}return t}function h(){var e=K(process.env);return Object.assign({},B,e)}function A(e){e.unref()}var S;(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"})(S||(S={}));var q=(function(){function e(){var t=this;this._promise=new Promise(function(r,o){t._resolve=r,t._reject=o})}return Object.defineProperty(e.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),e.prototype.resolve=function(t){this._resolve(t)},e.prototype.reject=function(t){this._reject(t)},e})();var Ie=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,s=[],i;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(E){i={error:E}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},ge=function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,s;o<n;o++)(s||!(o in t))&&(s||(s=Array.prototype.slice.call(t,0,o)),s[o]=t[o]);return e.concat(s||Array.prototype.slice.call(t))},D=(function(){function e(t,r){this._callback=t,this._that=r,this._isCalled=!1,this._deferred=new q}return Object.defineProperty(e.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),e.prototype.call=function(){for(var t,r=this,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((t=this._callback).call.apply(t,ge([this._that],Ie(o),!1))).then(function(s){return r._deferred.resolve(s)},function(s){return r._deferred.reject(s)})}catch(s){this._deferred.reject(s)}}return this._deferred.promise},e})();import{context as j,diag as w,TraceFlags as xe}from"@opentelemetry/api";var Y=(function(){function e(t,r){this._exporter=t,this._isExporting=!1,this._finishedSpans=[],this._droppedSpansCount=0;var o=h();this._maxExportBatchSize=typeof r?.maxExportBatchSize=="number"?r.maxExportBatchSize:o.OTEL_BSP_MAX_EXPORT_BATCH_SIZE,this._maxQueueSize=typeof r?.maxQueueSize=="number"?r.maxQueueSize:o.OTEL_BSP_MAX_QUEUE_SIZE,this._scheduledDelayMillis=typeof r?.scheduledDelayMillis=="number"?r.scheduledDelayMillis:o.OTEL_BSP_SCHEDULE_DELAY,this._exportTimeoutMillis=typeof r?.exportTimeoutMillis=="number"?r.exportTimeoutMillis:o.OTEL_BSP_EXPORT_TIMEOUT,this._shutdownOnce=new D(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(w.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}return e.prototype.forceFlush=function(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()},e.prototype.onStart=function(t,r){},e.prototype.onEnd=function(t){this._shutdownOnce.isCalled||(t.spanContext().traceFlags&xe.SAMPLED)!==0&&this._addToBuffer(t)},e.prototype.shutdown=function(){return this._shutdownOnce.call()},e.prototype._shutdown=function(){var t=this;return Promise.resolve().then(function(){return t.onShutdown()}).then(function(){return t._flushAll()}).then(function(){return t._exporter.shutdown()})},e.prototype._addToBuffer=function(t){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&w.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(w.warn("Dropped "+this._droppedSpansCount+" spans because maxQueueSize reached"),this._droppedSpansCount=0),this._finishedSpans.push(t),this._maybeStartTimer()},e.prototype._flushAll=function(){var t=this;return new Promise(function(r,o){for(var n=[],s=Math.ceil(t._finishedSpans.length/t._maxExportBatchSize),i=0,E=s;i<E;i++)n.push(t._flushOneBatch());Promise.all(n).then(function(){r()}).catch(o)})},e.prototype._flushOneBatch=function(){var t=this;return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise(function(r,o){var n=setTimeout(function(){o(new Error("Timeout"))},t._exportTimeoutMillis);j.with(b(j.active()),function(){var s;t._finishedSpans.length<=t._maxExportBatchSize?(s=t._finishedSpans,t._finishedSpans=[]):s=t._finishedSpans.splice(0,t._maxExportBatchSize);for(var i=function(){return t._exporter.export(s,function(u){var O;clearTimeout(n),u.code===S.SUCCESS?r():o((O=u.error)!==null&&O!==void 0?O:new Error("BatchSpanProcessor: span export failed"))})},E=null,_=0,d=s.length;_<d;_++){var l=s[_];l.resource.asyncAttributesPending&&l.resource.waitForAsyncAttributes&&(E??(E=[]),E.push(l.resource.waitForAsyncAttributes()))}E===null?i():Promise.all(E).then(i,function(u){x(u),o(u)})})})},e.prototype._maybeStartTimer=function(){var t=this;if(!this._isExporting){var r=function(){t._isExporting=!0,t._flushOneBatch().finally(function(){t._isExporting=!1,t._finishedSpans.length>0&&(t._clearTimer(),t._maybeStartTimer())}).catch(function(o){t._isExporting=!1,x(o)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return r();this._timer===void 0&&(this._timer=setTimeout(function(){return r()},this._scheduledDelayMillis),A(this._timer))}},e.prototype._clearTimer=function(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)},e})();var Ne=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function o(){this.constructor=t}t.prototype=r===null?Object.create(r):(o.prototype=r.prototype,new o)}})(),P=(function(e){Ne(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onShutdown=function(){},t})(Y);import{Resource as W}from"@opentelemetry/resources";import{OTLPTraceExporter as Ve}from"@opentelemetry/exporter-trace-otlp-http";import{getNodeAutoInstrumentations as Ke}from"@opentelemetry/auto-instrumentations-node";import{ProxyAgent as ze,setGlobalDispatcher as qe}from"undici";import{AsyncLocalStorage as Ce}from"async_hooks";var C=new Ce,y={},L=e=>({...e||{}}),p=()=>L(y),ve=e=>{y=L(e)},be=e=>{y={...y,...L(e)}},c=()=>C.getStore()?.requestAttributes||{},I=(e,t)=>{let r=C.getStore();if(!r)return;let o=t?.append===!1?L(e):{...r.requestAttributes,...L(e)};r.requestAttributes=o},Me=e=>I(e),Ue=(e,t,r)=>C.getStore()?(I(e,r),t()):v(()=>t(),e),v=(e,t)=>C.run({requestAttributes:L(t)},e);Be.setLogger(new De,we.WARN);var je=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",Ye=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",We=process.env.MAIN_ENV||process.env.NODE_ENV||"development",Q=process.env.MAIN_MODULE||"unknown-module",Qe=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),Ze=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",Z=process.env.MAIN_MODULE||Q,X=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0);if(X)try{qe(new ze(X)),console.log(`[onelog] Proxy enabled for outbound traffic: ${X}`)}catch(e){console.error("[onelog] Failed to configure proxy agent:",e.message)}var Je=W.default().merge(new W({"service.name":je,"service.namespace":Ye,"deployment.environment":We,"module.name":Z})),G=class{constructor(t){this.moduleName=t}onStart(t){if(!t)return;let r=t.name||t._name||"";this.moduleName&&!r.startsWith(`[${this.moduleName}] `)&&t.updateName(`[${this.moduleName}] ${r}`),this.moduleName&&t.setAttribute("module.name",this.moduleName);let o={...p(),...c()};for(let[n,s]of Object.entries(o))s!==void 0&&t.setAttribute(n,s)}onEnd(t){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}},H=class{constructor(t){this.processors=t}onStart(t,r){for(let o of this.processors)o.onStart(t,r)}onEnd(t){for(let r of this.processors)r.onEnd(t)}shutdown(){return Promise.all(this.processors.map(t=>t.shutdown())).then(()=>{})}forceFlush(){return Promise.all(this.processors.map(t=>t.forceFlush())).then(()=>{})}},$e=Ke({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:Ze?[]:["middleware","request_handler"]},"@opentelemetry/instrumentation-undici":{enabled:!0},"@opentelemetry/instrumentation-ioredis":{enabled:!1},"@opentelemetry/instrumentation-redis":{enabled:!1},"@opentelemetry/instrumentation-fs":{enabled:!1},"@opentelemetry/instrumentation-dns":{enabled:!1},"@opentelemetry/instrumentation-net":{enabled:!1}}),ke=new Ve({url:`${Qe}/v1/traces`}),et=new H([new G(Z),new P(ke)]),J=new Fe({resource:Je,instrumentations:[$e],spanProcessor:et}),tt=Promise.resolve(J.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),$=async()=>{try{await J.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",$);process.on("SIGINT",$);var rt=(e,t,r)=>{let o=r||process.env.MAIN_MODULE||Q;e.use((n,s,i)=>{v(()=>{let E=He.getBaggage(Ge.active()),_=E?Object.fromEntries((E.getAllEntries?.()||[]).map(([g,m])=>[g,m.value])):{},d=n.headers["organization-id"]||n.headers.activeorgid||n.headers["active-org-id"]||n.headers.activeOrgID||_["organization-id"],l=n.headers["session-id"]||_["session-id"],u=n.headers["execution-id"]||n.headers.executionid||n.headers.execution_id||_["execution-id"],O=n.headers["user-id"]||_["user-id"],a=n.headers["request-id"]||_["request-id"];I({"module.name":o,"http.method":n.method,"http.target":n.path,"organization.id":d,"organization-id":d,"session.id":l,"session-id":l,"execution.id":u,"execution-id":u,"user.id":O,"user-id":O,"request.id":a,"request-id":a,..._});let T=Xe.getActiveSpan();if(T){T.setAttribute("module.name",o),T.updateName(`[${o}] ${n.method} ${n.path}`);let g={...p(),...c()};for(let[m,R]of Object.entries(g))R!==void 0&&T.setAttribute(m,R)}t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),i()})})};import ot from"pino";var nt=["fatal","error","warn","info","debug","trace"],st=e=>{let t=()=>({...p(),...c()});return new Proxy(e,{get(r,o,n){let s=Reflect.get(r,o,n);return typeof o=="string"&&nt.includes(o)&&typeof s=="function"?(i,...E)=>{let _=t();return i&&typeof i=="object"&&!Array.isArray(i)?s.call(r,{..._,...i},...E):s.call(r,{..._},i,...E)}:s}})};function it(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",r=process.env.MAIN_MODULE||"unknown-module",n=ot({transport:{targets:[{target:"pino-opentelemetry-transport",level:"info",options:{resourceAttributes:{"service.name":t,"service.namespace":e,"deployment.environment":e,"module.name":r,"host.name":k("os").hostname()}}},{target:"pino-pretty",level:"debug",options:{colorize:!0,translateTime:"HH:MM:ss Z",ignore:"pid,hostname"}}]}}).child({env:e,app:t,module:r});return st(n)}import{trace as at,SpanStatusCode as Et}from"@opentelemetry/api";var _t=e=>(t,r,o,n)=>{let s={...p(),...c()};e&&e.error({...s,error:t.message,stack:t.stack,path:r.path},"Unhandled error");let i=at.getActiveSpan();if(i&&(i.recordException(t),i.setStatus({code:Et.ERROR,message:t.message})),o.headersSent)return n(t);o.status(500).json({error:t.message,attributes:s,module:process.env.MAIN_MODULE||"unknown-module"})};import{context as Tt,propagation as F}from"@opentelemetry/api";async function ut(e,t={},r,o={}){let n={...t},s=(n.method||"GET").toString().toUpperCase();n.body&&typeof n.body!="string"&&!(n.body instanceof Buffer)&&!(n.body instanceof ArrayBuffer)&&(n.body=JSON.stringify(n.body),n.headers={"Content-Type":"application/json",...n.headers||{}});let i={...p(),...c(),...o},E=Object.entries({...n.headers,"organization-id":i["organization-id"]||i["organization.id"],"session-id":i["session-id"]||i["session.id"],"execution-id":i["execution-id"]||i["execution.id"],"user-id":i["user-id"]||i["user.id"],"request-id":i["request-id"]||i["request.id"]}).filter(([,a])=>a!=null).map(([a,T])=>[a,String(T)]),d={...Object.fromEntries(E)},l={};for(let[a,T]of Object.entries(i))if(T!=null)try{l[a]={value:typeof T=="string"?T:JSON.stringify(T)}}catch{}let u=F.createBaggage(l),O=F.setBaggage(Tt.active(),u);F.inject(O,d),n.headers=d,r&&r.info({...i,url:e,method:s},"HTTP call start");try{let a=await fetch(e,n),m=(a.headers.get("content-type")||"").includes("application/json")?await a.json().catch(()=>null):await a.text().catch(()=>null);if(!a.ok){let R=new Error(`HTTP ${a.status} ${a.statusText||""}`.trim());throw R.status=a.status,R.data=m,r&&r.error({...i,url:e,method:s,status:a.status,data:m},"HTTP call failed"),R}return r&&r.info({...i,url:e,method:s,status:a.status},"HTTP call success"),m}catch(a){throw r&&r.error({...i,url:e,method:s,error:a.message},"HTTP call error"),a}}export{it as createLogger,_t as errorMiddleware,p as getGlobalAttributes,c as getRequestAttributes,ut as httpCall,rt as instrumentApp,be as mergeGlobalAttributes,Me as mergeRequestAttributes,v as runWithRequestContext,tt as sdkStartPromise,ve as setGlobalAttributes,I as setRequestAttributes,Ue as withRequestAttributes};
|
|
1
|
+
var Te=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{diag as je,DiagConsoleLogger as Ye,DiagLogLevel as We,trace as Qe,context as Je,propagation as $e}from"@opentelemetry/api";import{NodeSDK as Ze}from"@opentelemetry/sdk-node";import{createContextKey as ue}from"@opentelemetry/api";var pe=ue("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function U(e){return e.setValue(pe,!0)}import{diag as ce}from"@opentelemetry/api";function j(){return function(e){ce.error(le(e))}}function le(e){return typeof e=="string"?e:JSON.stringify(Oe(e))}function Oe(e){for(var t={},r=e;r!==null;)Object.getOwnPropertyNames(r).forEach(function(o){if(!t[o]){var n=r[o];n&&(t[o]=String(n))}}),r=Object.getPrototypeOf(r);return t}var de=j();function x(e){try{de(e)}catch{}}import{DiagLogLevel as R}from"@opentelemetry/api";var N;(function(e){e.AlwaysOff="always_off",e.AlwaysOn="always_on",e.ParentBasedAlwaysOff="parentbased_always_off",e.ParentBasedAlwaysOn="parentbased_always_on",e.ParentBasedTraceIdRatio="parentbased_traceidratio",e.TraceIdRatio="traceidratio"})(N||(N={}));var me=",",fe=["OTEL_SDK_DISABLED"];function Re(e){return fe.indexOf(e)>-1}var Le=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function he(e){return Le.indexOf(e)>-1}var Ae=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function Pe(e){return Ae.indexOf(e)>-1}var B=1/0,w=128,Se=128,ge=128,D={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:R.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:B,OTEL_ATTRIBUTE_COUNT_LIMIT:w,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:B,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:w,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:B,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:w,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:Se,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:ge,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:N.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative",OTEL_SEMCONV_STABILITY_OPT_IN:[]};function Ie(e,t,r){if(!(typeof r[e]>"u")){var o=String(r[e]);t[e]=o.toLowerCase()==="true"}}function xe(e,t,r,o,n){if(o===void 0&&(o=-1/0),n===void 0&&(n=1/0),typeof r[e]<"u"){var s=Number(r[e]);isNaN(s)||(s<o?t[e]=o:s>n?t[e]=n:t[e]=s)}}function Ne(e,t,r,o){o===void 0&&(o=me);var n=r[e];typeof n=="string"&&(t[e]=n.split(o).map(function(s){return s.trim()}))}var ve={ALL:R.ALL,VERBOSE:R.VERBOSE,DEBUG:R.DEBUG,INFO:R.INFO,WARN:R.WARN,ERROR:R.ERROR,NONE:R.NONE};function ye(e,t,r){var o=r[e];if(typeof o=="string"){var n=ve[o.toUpperCase()];n!=null&&(t[e]=n)}}function Y(e){var t={};for(var r in D){var o=r;switch(o){case"OTEL_LOG_LEVEL":ye(o,t,e);break;default:if(Re(o))Ie(o,t,e);else if(he(o))xe(o,t,e);else if(Pe(o))Ne(o,t,e);else{var n=e[o];typeof n<"u"&&n!==null&&(t[o]=String(n))}}}return t}function A(){var e=Y(process.env);return Object.assign({},D,e)}function P(e){e.unref()}var S;(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"})(S||(S={}));var Q=(function(){function e(){var t=this;this._promise=new Promise(function(r,o){t._resolve=r,t._reject=o})}return Object.defineProperty(e.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),e.prototype.resolve=function(t){this._resolve(t)},e.prototype.reject=function(t){this._reject(t)},e})();var we=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,s=[],i;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(E){i={error:E}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},De=function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,s;o<n;o++)(s||!(o in t))&&(s||(s=Array.prototype.slice.call(t,0,o)),s[o]=t[o]);return e.concat(s||Array.prototype.slice.call(t))},X=(function(){function e(t,r){this._callback=t,this._that=r,this._isCalled=!1,this._deferred=new Q}return Object.defineProperty(e.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),e.prototype.call=function(){for(var t,r=this,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((t=this._callback).call.apply(t,De([this._that],we(o),!1))).then(function(s){return r._deferred.resolve(s)},function(s){return r._deferred.reject(s)})}catch(s){this._deferred.reject(s)}}return this._deferred.promise},e})();import{context as J,diag as G,TraceFlags as Xe}from"@opentelemetry/api";var $=(function(){function e(t,r){this._exporter=t,this._isExporting=!1,this._finishedSpans=[],this._droppedSpansCount=0;var o=A();this._maxExportBatchSize=typeof r?.maxExportBatchSize=="number"?r.maxExportBatchSize:o.OTEL_BSP_MAX_EXPORT_BATCH_SIZE,this._maxQueueSize=typeof r?.maxQueueSize=="number"?r.maxQueueSize:o.OTEL_BSP_MAX_QUEUE_SIZE,this._scheduledDelayMillis=typeof r?.scheduledDelayMillis=="number"?r.scheduledDelayMillis:o.OTEL_BSP_SCHEDULE_DELAY,this._exportTimeoutMillis=typeof r?.exportTimeoutMillis=="number"?r.exportTimeoutMillis:o.OTEL_BSP_EXPORT_TIMEOUT,this._shutdownOnce=new X(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(G.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}return e.prototype.forceFlush=function(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()},e.prototype.onStart=function(t,r){},e.prototype.onEnd=function(t){this._shutdownOnce.isCalled||(t.spanContext().traceFlags&Xe.SAMPLED)!==0&&this._addToBuffer(t)},e.prototype.shutdown=function(){return this._shutdownOnce.call()},e.prototype._shutdown=function(){var t=this;return Promise.resolve().then(function(){return t.onShutdown()}).then(function(){return t._flushAll()}).then(function(){return t._exporter.shutdown()})},e.prototype._addToBuffer=function(t){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&G.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(G.warn("Dropped "+this._droppedSpansCount+" spans because maxQueueSize reached"),this._droppedSpansCount=0),this._finishedSpans.push(t),this._maybeStartTimer()},e.prototype._flushAll=function(){var t=this;return new Promise(function(r,o){for(var n=[],s=Math.ceil(t._finishedSpans.length/t._maxExportBatchSize),i=0,E=s;i<E;i++)n.push(t._flushOneBatch());Promise.all(n).then(function(){r()}).catch(o)})},e.prototype._flushOneBatch=function(){var t=this;return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise(function(r,o){var n=setTimeout(function(){o(new Error("Timeout"))},t._exportTimeoutMillis);J.with(U(J.active()),function(){var s;t._finishedSpans.length<=t._maxExportBatchSize?(s=t._finishedSpans,t._finishedSpans=[]):s=t._finishedSpans.splice(0,t._maxExportBatchSize);for(var i=function(){return t._exporter.export(s,function(l){var m;clearTimeout(n),l.code===S.SUCCESS?r():o((m=l.error)!==null&&m!==void 0?m:new Error("BatchSpanProcessor: span export failed"))})},E=null,_=0,L=s.length;_<L;_++){var O=s[_];O.resource.asyncAttributesPending&&O.resource.waitForAsyncAttributes&&(E??(E=[]),E.push(O.resource.waitForAsyncAttributes()))}E===null?i():Promise.all(E).then(i,function(l){x(l),o(l)})})})},e.prototype._maybeStartTimer=function(){var t=this;if(!this._isExporting){var r=function(){t._isExporting=!0,t._flushOneBatch().finally(function(){t._isExporting=!1,t._finishedSpans.length>0&&(t._clearTimer(),t._maybeStartTimer())}).catch(function(o){t._isExporting=!1,x(o)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return r();this._timer===void 0&&(this._timer=setTimeout(function(){return r()},this._scheduledDelayMillis),P(this._timer))}},e.prototype._clearTimer=function(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)},e})();var Ge=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function o(){this.constructor=t}t.prototype=r===null?Object.create(r):(o.prototype=r.prototype,new o)}})(),g=(function(e){Ge(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onShutdown=function(){},t})($);import{Resource as Z}from"@opentelemetry/resources";import{OTLPTraceExporter as ke}from"@opentelemetry/exporter-trace-otlp-http";import{getNodeAutoInstrumentations as et}from"@opentelemetry/auto-instrumentations-node";import{ProxyAgent as tt,setGlobalDispatcher as rt}from"undici";import{AsyncLocalStorage as Fe}from"async_hooks";var y=new Fe,v={},h=e=>({...e||{}}),u=()=>h(v),Ve=e=>{v=h(e)},Ke=e=>{v={...v,...h(e)}},p=()=>y.getStore()?.requestAttributes||{},I=(e,t)=>{let r=y.getStore();if(!r)return;let o=t?.append===!1?h(e):{...r.requestAttributes,...h(e)};r.requestAttributes=o},ze=e=>I(e),qe=(e,t,r)=>y.getStore()?(I(e,r),t()):C(()=>t(),e),C=(e,t)=>y.run({requestAttributes:h(t)},e);je.setLogger(new Ye,We.WARN);var ot=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",nt=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",st=process.env.MAIN_ENV||process.env.NODE_ENV||"development",k=process.env.MAIN_MODULE||"unknown-module",it=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),at=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",ee=process.env.MAIN_MODULE||k,H=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0);if(H)try{rt(new tt(H)),console.log(`[onelog] Proxy enabled for outbound traffic: ${H}`)}catch(e){console.error("[onelog] Failed to configure proxy agent:",e.message)}var Et=Z.default().merge(new Z({"service.name":ot,"service.namespace":nt,"deployment.environment":st,"module.name":ee})),F=class{constructor(t){this.moduleName=t}onStart(t){if(!t)return;let r=t.name||t._name||"";this.moduleName&&!r.startsWith(`[${this.moduleName}] `)&&t.updateName(`[${this.moduleName}] ${r}`),this.moduleName&&t.setAttribute("module.name",this.moduleName);let o={...u(),...p()};for(let[n,s]of Object.entries(o))s!==void 0&&t.setAttribute(n,s)}onEnd(t){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}},V=class{constructor(t){this.processors=t}onStart(t,r){for(let o of this.processors)o.onStart(t,r)}onEnd(t){for(let r of this.processors)r.onEnd(t)}shutdown(){return Promise.all(this.processors.map(t=>t.shutdown())).then(()=>{})}forceFlush(){return Promise.all(this.processors.map(t=>t.forceFlush())).then(()=>{})}},_t=et({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:at?[]:["middleware","request_handler"]},"@opentelemetry/instrumentation-undici":{enabled:!0},"@opentelemetry/instrumentation-ioredis":{enabled:!1},"@opentelemetry/instrumentation-redis":{enabled:!1},"@opentelemetry/instrumentation-fs":{enabled:!1},"@opentelemetry/instrumentation-dns":{enabled:!1},"@opentelemetry/instrumentation-net":{enabled:!1}}),Tt=new ke({url:`${it}/v1/traces`}),ut=new V([new F(ee),new g(Tt)]),te=new Ze({resource:Et,instrumentations:[_t],spanProcessor:ut}),pt=Promise.resolve(te.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),re=async()=>{try{await te.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",re);process.on("SIGINT",re);var ct=(e,t,r)=>{let o=r||process.env.MAIN_MODULE||k;e.use((n,s,i)=>{C(()=>{let E=$e.getBaggage(Je.active()),_=E?Object.fromEntries((E.getAllEntries?.()||[]).map(([c,b])=>[c,b.value])):{},L=n.headers["organization-id"]||n.headers.activeorgid||n.headers["active-org-id"]||n.headers.activeOrgID||_["organization-id"],O=n.headers["session-id"]||_["session-id"],l=n.headers["execution-id"]||n.headers.executionid||n.headers.execution_id||_["execution-id"],m=n.headers["user-id"]||_["user-id"],a=n.headers["request-id"]||_["request-id"],T=n.headers["x-onelog-attr"]||n.headers["x-onelog-attrs"]||_["x-onelog-attr"],M={};if(T)try{let c=typeof T=="string"?JSON.parse(T):T;c&&typeof c=="object"&&(M=c)}catch{}I({"module.name":o,"http.method":n.method,"http.target":n.path,"organization.id":L,"organization-id":L,"session.id":O,"session-id":O,"execution.id":l,"execution-id":l,"user.id":m,"user-id":m,"request.id":a,"request-id":a,..._,...M});let f=Qe.getActiveSpan();if(f){f.setAttribute("module.name",o),f.updateName(`[${o}] ${n.method} ${n.path}`);let c={...u(),...p()};for(let[b,q]of Object.entries(c))q!==void 0&&f.setAttribute(b,q)}t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),i()})})};import lt from"pino";var Ot=["fatal","error","warn","info","debug","trace"],dt=e=>{let t=()=>({...u(),...p()});return new Proxy(e,{get(r,o,n){let s=Reflect.get(r,o,n);return typeof o=="string"&&Ot.includes(o)&&typeof s=="function"?(i,...E)=>{let _=t();return i&&typeof i=="object"&&!Array.isArray(i)?s.call(r,{..._,...i},...E):s.call(r,{..._},i,...E)}:s}})};function mt(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",r=process.env.MAIN_MODULE||"unknown-module",n=lt({transport:{targets:[{target:"pino-opentelemetry-transport",level:"info",options:{resourceAttributes:{"service.name":t,"service.namespace":e,"deployment.environment":e,"module.name":r,"host.name":Te("os").hostname()}}},{target:"pino-pretty",level:"debug",options:{colorize:!0,translateTime:"HH:MM:ss Z",ignore:"pid,hostname"}}]}}).child({env:e,app:t,module:r});return dt(n)}import{trace as ft,SpanStatusCode as Rt}from"@opentelemetry/api";var Lt=e=>(t,r,o,n)=>{let s={...u(),...p()};e&&e.error({...s,error:t.message,stack:t.stack,path:r.path},"Unhandled error");let i=ft.getActiveSpan();if(i&&(i.recordException(t),i.setStatus({code:Rt.ERROR,message:t.message})),o.headersSent)return n(t);o.status(500).json({error:t.message,attributes:s,module:process.env.MAIN_MODULE||"unknown-module"})};import{context as ht,propagation as K}from"@opentelemetry/api";async function At(e,t={},r,o={}){let n={...t},s=(n.method||"GET").toString().toUpperCase();n.body&&typeof n.body!="string"&&!(n.body instanceof Buffer)&&!(n.body instanceof ArrayBuffer)&&(n.body=JSON.stringify(n.body),n.headers={"Content-Type":"application/json",...n.headers||{}});let i={...u(),...p(),...o},E=Object.entries({...n.headers,"organization-id":i["organization-id"]||i["organization.id"],"session-id":i["session-id"]||i["session.id"],"execution-id":i["execution-id"]||i["execution.id"],"user-id":i["user-id"]||i["user.id"],"request-id":i["request-id"]||i["request.id"],"x-onelog-attr":JSON.stringify(i)}).filter(([,a])=>a!=null).map(([a,T])=>[a,String(T)]),L={...Object.fromEntries(E)},O={};for(let[a,T]of Object.entries(i))if(T!=null)try{O[a]={value:typeof T=="string"?T:JSON.stringify(T)}}catch{}let l=K.createBaggage(O),m=K.setBaggage(ht.active(),l);K.inject(m,L),n.headers=L,r&&r.info({...i,url:e,method:s},"HTTP call start");try{let a=await fetch(e,n),f=(a.headers.get("content-type")||"").includes("application/json")?await a.json().catch(()=>null):await a.text().catch(()=>null);if(!a.ok){let c=new Error(`HTTP ${a.status} ${a.statusText||""}`.trim());throw c.status=a.status,c.data=f,r&&r.error({...i,url:e,method:s,status:a.status,data:f},"HTTP call failed"),c}return r&&r.info({...i,url:e,method:s,status:a.status},"HTTP call success"),f}catch(a){throw r&&r.error({...i,url:e,method:s,error:a.message},"HTTP call error"),a}}import{context as ae,metrics as Pt}from"@opentelemetry/api";import{Resource as oe}from"@opentelemetry/resources";import{MeterProvider as St,PeriodicExportingMetricReader as gt}from"@opentelemetry/sdk-metrics";import{OTLPMetricExporter as It}from"@opentelemetry/exporter-metrics-otlp-http";import{HostMetrics as xt}from"@opentelemetry/host-metrics";import{RuntimeNodeInstrumentation as Nt}from"@opentelemetry/instrumentation-runtime-node";var vt=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",yt=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",Ct=process.env.MAIN_ENV||process.env.NODE_ENV||"development",Mt=process.env.MAIN_MODULE||"unknown-module",bt=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),Ut=(process.env.ONELOG_HOST_METRICS||"true").toLowerCase()==="true",Bt=(process.env.ONELOG_RUNTIME_METRICS||"false").toLowerCase()==="true",wt=oe.default().merge(new oe({"service.name":vt,"service.namespace":yt,"deployment.environment":Ct,"module.name":Mt})),d,ne=!1,se=!1,ie=!1,Dt=()=>{if(ne)return;ne=!0;let e=async()=>{if(d)try{await d.shutdown()}catch(t){console.error("[onelog] Error shutting down metrics provider",t.message)}};process.on("SIGTERM",e),process.on("SIGINT",e)},Ee=()=>{if(d)return d;let e=new It({url:`${bt}/v1/metrics`});return d=new St({resource:wt,readers:[new gt({exporter:e})]}),Pt.setGlobalMeterProvider(d),Xt(d),Gt(d),Dt(),d},Xt=e=>{if(!(!Ut||se))try{new xt({meterProvider:e,name:"onelog-host-metrics"}).start(),se=!0}catch(t){console.error("[onelog] Failed to start host metrics instrumentation",t.message)}},Gt=e=>{if(!(!Bt||ie))try{let t=new Nt;t.setMeterProvider(e),t.enable(),ie=!0}catch(t){console.error("[onelog] Failed to start runtime metrics instrumentation",t.message)}},Ht=Promise.resolve().then(()=>Ee()),z=(e="onelog-metrics")=>Ee().getMeter(e),_e=e=>({...u(),...p(),...e||{}}),Ft=(e,t)=>{let r=z().createCounter(e,t);return{add:(o,n)=>{r.add(o,_e(n),ae.active())},instrument:r}},Vt=(e,t)=>{let r=z().createHistogram(e,t);return{record:(o,n)=>{r.record(o,_e(n),ae.active())},instrument:r}};export{Ft as createCounter,Vt as createHistogram,mt as createLogger,Lt as errorMiddleware,u as getGlobalAttributes,z as getMeter,p as getRequestAttributes,At as httpCall,ct as instrumentApp,Ke as mergeGlobalAttributes,ze as mergeRequestAttributes,Ht as metricsStartPromise,C as runWithRequestContext,pt as sdkStartPromise,Ve as setGlobalAttributes,I as setRequestAttributes,qe as withRequestAttributes};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/sampling.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/timer-util.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/ExportResult.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/promise.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/callback.ts","../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../src/attributes.ts","../src/logger.ts","../src/exceptions.ts","../src/http-caller.ts"],"sourcesContent":["import { diag, DiagConsoleLogger, DiagLogLevel, trace, context as otContext, propagation } from '@opentelemetry/api';\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { SpanProcessor, ReadableSpan, BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { Resource } from '@opentelemetry/resources';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { ProxyAgent, setGlobalDispatcher } from 'undici';\nimport type { Application, Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\nimport {\n getGlobalAttributes,\n getRequestAttributes,\n runWithRequestContext,\n setRequestAttributes,\n} from './attributes.js';\n\ndiag.setLogger(new DiagConsoleLogger(), DiagLogLevel.WARN);\n\nconst serviceName =\n process.env.OTEL_SERVICE_NAME ||\n process.env.MAIN_MODULE ||\n 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE ||\n process.env.OTEL_SERVICE_NAMESPACE ||\n process.env.MAIN_APP ||\n 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\nconst expressLayersEnabled = (process.env.ONELOG_EXPRESS_LAYERS || '').toLowerCase() === 'true';\nconst moduleLabel = process.env.MAIN_MODULE || moduleName;\n\n// Optional proxy support for environments with HTTP(S)_PROXY set\nconst proxyUrl = [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy]\n .find((v) => v && v.trim().length > 0);\n\nif (proxyUrl) {\n try {\n setGlobalDispatcher(new ProxyAgent(proxyUrl));\n // eslint-disable-next-line no-console\n console.log(`[onelog] Proxy enabled for outbound traffic: ${proxyUrl}`);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure proxy agent:', (err as Error).message);\n }\n}\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleLabel,\n }),\n);\n\nclass ModuleNameSpanProcessor implements SpanProcessor {\n constructor(private readonly moduleName: string) {}\n onStart(span: any): void {\n if (!span) return;\n const currentName = (span as any).name || (span as any)._name || '';\n if (this.moduleName && !currentName.startsWith(`[${this.moduleName}] `)) {\n span.updateName(`[${this.moduleName}] ${currentName}`);\n }\n if (this.moduleName) {\n span.setAttribute('module.name', this.moduleName);\n }\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(dynamicAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n onEnd(_span: ReadableSpan): void {\n // no-op\n }\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nclass CombinedSpanProcessor implements SpanProcessor {\n constructor(private readonly processors: SpanProcessor[]) {}\n onStart(span: any, ctx?: any): void {\n for (const p of this.processors) p.onStart(span as any, ctx);\n }\n onEnd(span: ReadableSpan): void {\n for (const p of this.processors) p.onEnd(span);\n }\n shutdown(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.shutdown())).then(() => undefined);\n }\n forceFlush(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.forceFlush())).then(() => undefined);\n }\n}\n\nconst instrumentations = getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-http': {\n enabled: true,\n },\n '@opentelemetry/instrumentation-express': {\n enabled: true,\n ignoreLayersType: expressLayersEnabled ? [] : (['middleware', 'request_handler'] as any),\n },\n '@opentelemetry/instrumentation-undici': {\n enabled: true,\n },\n // Redis instrumentation is noisy in our workloads; keep it off by default\n '@opentelemetry/instrumentation-ioredis': { enabled: false },\n '@opentelemetry/instrumentation-redis': { enabled: false },\n '@opentelemetry/instrumentation-fs': { enabled: false },\n '@opentelemetry/instrumentation-dns': { enabled: false },\n '@opentelemetry/instrumentation-net': { enabled: false },\n});\n\nconst exporter = new OTLPTraceExporter({\n url: `${otlpEndpoint}/v1/traces`,\n});\n\nconst spanProcessor = new CombinedSpanProcessor([\n new ModuleNameSpanProcessor(moduleLabel),\n new BatchSpanProcessor(exporter),\n]);\n\nconst sdk = new NodeSDK({\n resource,\n instrumentations: [instrumentations],\n spanProcessor,\n});\n\nexport const sdkStartPromise = Promise.resolve(sdk.start()).catch((error) => {\n console.error('Failed to start OpenTelemetry SDK', error);\n return Promise.resolve();\n});\n\nconst shutdown = async () => {\n try {\n await sdk.shutdown();\n } catch (error) {\n console.error('Error shutting down OpenTelemetry SDK', error);\n }\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nexport const instrumentApp = (app: Application, logger?: Logger, customModuleName?: string) => {\n const moduleLabel = customModuleName || process.env.MAIN_MODULE || moduleName;\n app.use((req: Request, _res: Response, next: NextFunction) => {\n runWithRequestContext(() => {\n const baggage = propagation.getBaggage(otContext.active());\n const baggageAttrs = baggage\n ? Object.fromEntries(\n (baggage.getAllEntries?.() || []).map(([key, entry]) => [key, entry.value]),\n )\n : {};\n\n const orgId =\n (req.headers['organization-id'] as string) ||\n (req.headers['activeorgid'] as string) ||\n (req.headers['active-org-id'] as string) ||\n (req.headers['activeOrgID'] as string) ||\n (baggageAttrs['organization-id'] as string);\n const sessionId = (req.headers['session-id'] as string) || (baggageAttrs['session-id'] as string);\n const executionId =\n (req.headers['execution-id'] as string) ||\n (req.headers['executionid'] as string) ||\n (req.headers['execution_id'] as string) ||\n (baggageAttrs['execution-id'] as string);\n const userId = (req.headers['user-id'] as string) || (baggageAttrs['user-id'] as string);\n const requestId = (req.headers['request-id'] as string) || (baggageAttrs['request-id'] as string);\n\n setRequestAttributes({\n 'module.name': moduleLabel,\n 'http.method': req.method,\n 'http.target': req.path,\n 'organization.id': orgId,\n 'organization-id': orgId,\n 'session.id': sessionId,\n 'session-id': sessionId,\n 'execution.id': executionId,\n 'execution-id': executionId,\n 'user.id': userId,\n 'user-id': userId,\n 'request.id': requestId,\n 'request-id': requestId,\n ...baggageAttrs,\n });\n\n const span = trace.getActiveSpan();\n if (span) {\n span.setAttribute('module.name', moduleLabel);\n span.updateName(`[${moduleLabel}] ${req.method} ${req.path}`);\n const requestAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(requestAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n if (logger) {\n logger.info(\n {\n method: req.method,\n path: req.path,\n ip: req.ip,\n },\n 'Incoming request',\n );\n }\n next();\n });\n });\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, Exception } from '@opentelemetry/api';\nimport { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n 'OTEL_SEMCONV_STABILITY_OPT_IN',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required<ENVIRONMENT> = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n OTEL_SEMCONV_STABILITY_OPT_IN: [],\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_ENVIRONMENT,\n ENVIRONMENT,\n RAW_ENVIRONMENT,\n parseEnvironment,\n} from '../../utils/environment';\n\n/**\n * Gets the environment variables\n */\nexport function getEnv(): Required<ENVIRONMENT> {\n const processEnv = parseEnvironment(process.env as RAW_ENVIRONMENT);\n return Object.assign({}, DEFAULT_ENVIRONMENT, processEnv);\n}\n\nexport function getEnvWithoutDefaults(): ENVIRONMENT {\n return parseEnvironment(process.env as RAW_ENVIRONMENT);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function unrefTimer(timer: NodeJS.Timer): void {\n timer.unref();\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context, Context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getEnv,\n globalErrorHandler,\n suppressTracing,\n unrefTimer,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { BufferConfig } from '../types';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(\n private readonly _exporter: SpanExporter,\n config?: T\n ) {\n const env = getEnv();\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : env.OTEL_BSP_MAX_QUEUE_SIZE;\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : env.OTEL_BSP_SCHEDULE_DELAY;\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : env.OTEL_BSP_EXPORT_TIMEOUT;\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n unrefTimer(this._timer);\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport type AttributeMap = Record<string, any>;\n\ntype RequestAttributeContext = {\n requestAttributes: AttributeMap;\n};\n\nconst requestAttributeStorage = new AsyncLocalStorage<RequestAttributeContext>();\n\nlet globalAttributes: AttributeMap = {};\n\nconst clone = (attrs?: AttributeMap) => ({ ...(attrs || {}) });\n\nexport const getGlobalAttributes = (): AttributeMap => clone(globalAttributes);\n\nexport const setGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = clone(attrs);\n};\n\nexport const mergeGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = { ...globalAttributes, ...clone(attrs) };\n};\n\nexport const getRequestAttributes = (): AttributeMap => {\n const store = requestAttributeStorage.getStore();\n return store?.requestAttributes || {};\n};\n\nexport const setRequestAttributes = (attrs: AttributeMap, options?: { append?: boolean }) => {\n const store = requestAttributeStorage.getStore();\n if (!store) return;\n\n const nextAttributes =\n options?.append === false ? clone(attrs) : { ...store.requestAttributes, ...clone(attrs) };\n store.requestAttributes = nextAttributes;\n};\n\nexport const mergeRequestAttributes = (attrs: AttributeMap) => setRequestAttributes(attrs);\n\nexport const withRequestAttributes = <T>(\n attrs: AttributeMap,\n fn: () => T,\n options?: { append?: boolean },\n): T => {\n const store = requestAttributeStorage.getStore();\n if (!store) {\n return runWithRequestContext(() => fn(), attrs);\n }\n setRequestAttributes(attrs, options);\n return fn();\n};\n\nexport const runWithRequestContext = <T>(fn: () => T, initialAttributes?: AttributeMap): T => {\n return requestAttributeStorage.run(\n {\n requestAttributes: clone(initialAttributes),\n },\n fn,\n );\n};\n","import pino, { Logger } from 'pino';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nconst levelMethods = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'] as const;\n\nconst wrapWithDynamicAttributes = (logger: Logger): Logger => {\n const buildAttrs = () => ({ ...getGlobalAttributes(), ...getRequestAttributes() });\n\n return new Proxy(logger, {\n get(target, prop, receiver) {\n const original = Reflect.get(target, prop, receiver);\n if (typeof prop === 'string' && levelMethods.includes(prop as any) && typeof original === 'function') {\n return (firstArg?: any, ...rest: any[]) => {\n const attrs = buildAttrs();\n if (firstArg && typeof firstArg === 'object' && !Array.isArray(firstArg)) {\n return (original as any).call(target, { ...attrs, ...firstArg }, ...rest);\n }\n return (original as any).call(target, { ...attrs }, firstArg, ...rest);\n };\n }\n return original;\n },\n });\n};\n\nexport function createLogger() {\n const mainEnv = process.env.MAIN_ENV || 'development';\n const mainApp = process.env.MAIN_APP || 'app';\n const mainModule = process.env.MAIN_MODULE || 'unknown-module';\n\n const logger = pino({\n transport: {\n targets: [\n {\n target: 'pino-opentelemetry-transport',\n level: 'info',\n options: {\n resourceAttributes: {\n 'service.name': mainApp,\n 'service.namespace': mainEnv,\n 'deployment.environment': mainEnv,\n 'module.name': mainModule,\n 'host.name': require('os').hostname(),\n },\n },\n },\n {\n target: 'pino-pretty',\n level: 'debug',\n options: {\n colorize: true,\n translateTime: 'HH:MM:ss Z',\n ignore: 'pid,hostname',\n },\n },\n ],\n },\n });\n\n const base = logger.child({\n env: mainEnv,\n app: mainApp,\n module: mainModule,\n });\n\n return wrapWithDynamicAttributes(base);\n}\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\nimport type { Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\n\nexport const errorMiddleware =\n (logger?: Logger) =>\n (err: Error, req: Request, res: Response, next: NextFunction) => {\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n\n if (logger) {\n logger.error(\n {\n ...dynamicAttributes,\n error: err.message,\n stack: err.stack,\n path: req.path,\n },\n 'Unhandled error',\n );\n }\n\n const span = trace.getActiveSpan();\n if (span) {\n span.recordException(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n }\n\n if (res.headersSent) {\n return next(err);\n }\n\n res.status(500).json({\n error: err.message,\n attributes: dynamicAttributes,\n module: process.env.MAIN_MODULE || 'unknown-module',\n });\n };\n","import { context, propagation } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nexport interface HttpCallContext {\n [key: string]: any;\n}\n\nexport interface HttpCallOptions extends RequestInit {\n body?: any;\n}\n\nexport async function httpCall(\n url: string,\n options: HttpCallOptions = {},\n logger?: { info: Function; error: Function },\n logContext: HttpCallContext = {},\n) {\n const fetchOptions: RequestInit = { ...options };\n const method = (fetchOptions.method || 'GET').toString().toUpperCase();\n\n if (\n fetchOptions.body &&\n typeof fetchOptions.body !== 'string' &&\n !(fetchOptions.body instanceof Buffer) &&\n !(fetchOptions.body instanceof ArrayBuffer)\n ) {\n fetchOptions.body = JSON.stringify(fetchOptions.body);\n fetchOptions.headers = {\n 'Content-Type': 'application/json',\n ...(fetchOptions.headers || {}),\n };\n }\n\n const dynamicContext = { ...getGlobalAttributes(), ...getRequestAttributes(), ...logContext };\n\n // Inject trace context + baggage, and forward standard IDs as headers for downstream services\n const headerEntries = Object.entries({\n ...(fetchOptions.headers as any),\n 'organization-id':\n (dynamicContext['organization-id'] as string) || (dynamicContext['organization.id'] as string),\n 'session-id': (dynamicContext['session-id'] as string) || (dynamicContext['session.id'] as string),\n 'execution-id':\n (dynamicContext['execution-id'] as string) || (dynamicContext['execution.id'] as string),\n 'user-id': (dynamicContext['user-id'] as string) || (dynamicContext['user.id'] as string),\n 'request-id': (dynamicContext['request-id'] as string) || (dynamicContext['request.id'] as string),\n })\n .filter(([, v]) => v !== undefined && v !== null)\n .map(([k, v]) => [k, String(v)]) as [string, string][];\n\n const headers: Record<string, string> = Object.fromEntries(headerEntries);\n\n const carrier: Record<string, any> = { ...headers };\n\n // Build baggage from all attributes to propagate custom keys\n const baggageEntries: Record<string, { value: string }> = {};\n for (const [key, value] of Object.entries(dynamicContext)) {\n if (value === undefined || value === null) continue;\n try {\n baggageEntries[key] = { value: typeof value === 'string' ? value : JSON.stringify(value) };\n } catch {\n // skip values that can't be stringified\n }\n }\n const baggage = propagation.createBaggage(baggageEntries);\n const ctxWithBaggage = propagation.setBaggage(context.active(), baggage);\n propagation.inject(ctxWithBaggage, carrier);\n\n fetchOptions.headers = carrier;\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method }, 'HTTP call start');\n }\n\n try {\n const res = await fetch(url, fetchOptions);\n const contentType = res.headers.get('content-type') || '';\n const isJson = contentType.includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : await res.text().catch(() => null);\n\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status} ${res.statusText || ''}`.trim());\n (error as any).status = res.status;\n (error as any).data = data;\n if (logger) {\n logger.error({ ...dynamicContext, url, method, status: res.status, data }, 'HTTP call failed');\n }\n throw error;\n }\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method, status: res.status }, 'HTTP call success');\n }\n\n return data;\n } catch (err: any) {\n if (logger) {\n logger.error({ ...dynamicContext, url, method, error: err.message }, 'HTTP call error');\n }\n throw err;\n }\n}\n"],"mappings":"yPAAA,OAAS,QAAAA,GAAM,qBAAAC,GAAmB,gBAAAC,GAAc,SAAAC,GAAO,WAAWC,GAAW,eAAAC,OAAmB,qBAChG,OAAS,W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nE,GAAI,CACF,IAAMe,EAAM,MAAM,MAAMpB,EAAKI,CAAY,EAGnCiB,GAFcD,EAAI,QAAQ,IAAI,cAAc,GAAK,IAC5B,SAAS,kBAAkB,EAChC,MAAMA,EAAI,KAAK,EAAE,MAAM,IAAM,IAAI,EAAI,MAAMA,EAAI,KAAK,EAAE,MAAM,IAAM,IAAI,EAE5F,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQ,IAAI,MAAM,QAAQF,EAAI,MAAM,IAAIA,EAAI,YAAc,EAAE,GAAG,KAAK,CAAC,EAC3E,MAACE,EAAc,OAASF,EAAI,OAC3BE,EAAc,KAAOD,EAClBnB,GACFA,EAAO,MAAM,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,OAAQe,EAAI,OAAQ,KAAAC,CAAK,EAAG,kBAAkB,EAEzFC,CACR,CAEA,OAAIpB,GACFA,EAAO,KAAK,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,OAAQe,EAAI,MAAO,EAAG,mBAAmB,EAGlFC,CACT,OAASE,EAAU,CACjB,MAAIrB,GACFA,EAAO,MAAM,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,MAAOkB,EAAI,OAAQ,EAAG,iBAAiB,EAElFA,CACR,CACF","names":["diag","DiagConsoleLogger","DiagLogLevel","trace","otContext","propagation","NodeSDK","createContextKey","SUPPRESS_TRACING_KEY","suppressTracing","context","diag","loggingErrorHandler","ex","stringifyException","flattenException","result","current","propertyName","value","delegateHandler","loggingErrorHandler","globalErrorHandler","ex","delegateHandler","DiagLogLevel","TracesSamplerValues","DEFAULT_LIST_SEPARATOR","ENVIRONMENT_BOOLEAN_KEYS","isEnvVarABoolean","key","ENVIRONMENT_NUMBERS_KEYS","isEnvVarANumber","ENVIRONMENT_LISTS_KEYS","isEnvVarAList","DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT","DEFAULT_ATTRIBUTE_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","DEFAULT_ENVIRONMENT","DiagLogLevel","TracesSamplerValues","parseBoolean","environment","values","value","parseNumber","name","min","max","parseStringList","output","input","separator","givenValue","v","logLevelMap","setLogLevelFromEnv","theLevel","parseEnvironment","env","getEnv","processEnv","parseEnvironment","DEFAULT_ENVIRONMENT","unrefTimer","timer","ExportResultCode","Deferred","_this","resolve","reject","val","err","BindOnceFuture","_callback","_that","Deferred","_this","args","_i","_a","__spreadArray","__read","val","err","context","diag","TraceFlags","BatchSpanProcessorBase","_exporter","config","env","getEnv","BindOnceFuture","diag","_span","_parentContext","span","TraceFlags","_this","resolve","reject","promises","count","j","timer","context","suppressTracing","spans","doExport","result","ExportResultCode","_a","pendingResources","i","len","err","globalErrorHandler","flush","e","unrefTimer","BatchSpanProcessor","_super","__extends","BatchSpanProcessorBase","Resource","OTLPTraceExporter","getNodeAutoInstrumentations","ProxyAgent","setGlobalDispatcher","AsyncLocalStorage","requestAttributeStorage","globalAttributes","clone","attrs","getGlobalAttributes","setGlobalAttributes","mergeGlobalAttributes","getRequestAttributes","setRequestAttributes","options","store","nextAttributes","mergeRequestAttributes","withRequestAttributes","fn","runWithRequestContext","initialAttributes","diag","DiagConsoleLogger","DiagLogLevel","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","expressLayersEnabled","moduleLabel","proxyUrl","v","setGlobalDispatcher","ProxyAgent","err","resource","Resource","ModuleNameSpanProcessor","span","currentName","dynamicAttributes","getGlobalAttributes","getRequestAttributes","key","value","_span","CombinedSpanProcessor","processors","ctx","p","instrumentations","getNodeAutoInstrumentations","exporter","OTLPTraceExporter","spanProcessor","BatchSpanProcessor","sdk","NodeSDK","sdkStartPromise","error","shutdown","instrumentApp","app","logger","customModuleName","req","_res","next","runWithRequestContext","baggage","propagation","otContext","baggageAttrs","entry","orgId","sessionId","executionId","userId","requestId","setRequestAttributes","trace","requestAttributes","pino","levelMethods","wrapWithDynamicAttributes","logger","buildAttrs","getGlobalAttributes","getRequestAttributes","target","prop","receiver","original","firstArg","rest","attrs","createLogger","mainEnv","mainApp","mainModule","base","pino","trace","SpanStatusCode","errorMiddleware","logger","err","req","res","next","dynamicAttributes","getGlobalAttributes","getRequestAttributes","span","trace","SpanStatusCode","context","propagation","httpCall","url","options","logger","logContext","fetchOptions","method","dynamicContext","getGlobalAttributes","getRequestAttributes","headerEntries","v","k","carrier","baggageEntries","key","value","baggage","propagation","ctxWithBaggage","context","res","data","error","err"]}
|
|
1
|
+
{"version":3,"sources":["../src/tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/sampling.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/timer-util.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/ExportResult.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/promise.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/callback.ts","../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../src/attributes.ts","../src/logger.ts","../src/exceptions.ts","../src/http-caller.ts","../src/metrics.ts"],"sourcesContent":["import { diag, DiagConsoleLogger, DiagLogLevel, trace, context as otContext, propagation } from '@opentelemetry/api';\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { SpanProcessor, ReadableSpan, BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { Resource } from '@opentelemetry/resources';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { ProxyAgent, setGlobalDispatcher } from 'undici';\nimport type { Application, Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\nimport {\n getGlobalAttributes,\n getRequestAttributes,\n runWithRequestContext,\n setRequestAttributes,\n} from './attributes.js';\n\ndiag.setLogger(new DiagConsoleLogger(), DiagLogLevel.WARN);\n\nconst serviceName =\n process.env.OTEL_SERVICE_NAME ||\n process.env.MAIN_MODULE ||\n 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE ||\n process.env.OTEL_SERVICE_NAMESPACE ||\n process.env.MAIN_APP ||\n 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\nconst expressLayersEnabled = (process.env.ONELOG_EXPRESS_LAYERS || '').toLowerCase() === 'true';\nconst moduleLabel = process.env.MAIN_MODULE || moduleName;\n\n// Optional proxy support for environments with HTTP(S)_PROXY set\nconst proxyUrl = [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy]\n .find((v) => v && v.trim().length > 0);\n\nif (proxyUrl) {\n try {\n setGlobalDispatcher(new ProxyAgent(proxyUrl));\n // eslint-disable-next-line no-console\n console.log(`[onelog] Proxy enabled for outbound traffic: ${proxyUrl}`);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure proxy agent:', (err as Error).message);\n }\n}\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleLabel,\n }),\n);\n\nclass ModuleNameSpanProcessor implements SpanProcessor {\n constructor(private readonly moduleName: string) {}\n onStart(span: any): void {\n if (!span) return;\n const currentName = (span as any).name || (span as any)._name || '';\n if (this.moduleName && !currentName.startsWith(`[${this.moduleName}] `)) {\n span.updateName(`[${this.moduleName}] ${currentName}`);\n }\n if (this.moduleName) {\n span.setAttribute('module.name', this.moduleName);\n }\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(dynamicAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n onEnd(_span: ReadableSpan): void {\n // no-op\n }\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nclass CombinedSpanProcessor implements SpanProcessor {\n constructor(private readonly processors: SpanProcessor[]) {}\n onStart(span: any, ctx?: any): void {\n for (const p of this.processors) p.onStart(span as any, ctx);\n }\n onEnd(span: ReadableSpan): void {\n for (const p of this.processors) p.onEnd(span);\n }\n shutdown(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.shutdown())).then(() => undefined);\n }\n forceFlush(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.forceFlush())).then(() => undefined);\n }\n}\n\nconst instrumentations = getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-http': {\n enabled: true,\n },\n '@opentelemetry/instrumentation-express': {\n enabled: true,\n ignoreLayersType: expressLayersEnabled ? [] : (['middleware', 'request_handler'] as any),\n },\n '@opentelemetry/instrumentation-undici': {\n enabled: true,\n },\n // Redis instrumentation is noisy in our workloads; keep it off by default\n '@opentelemetry/instrumentation-ioredis': { enabled: false },\n '@opentelemetry/instrumentation-redis': { enabled: false },\n '@opentelemetry/instrumentation-fs': { enabled: false },\n '@opentelemetry/instrumentation-dns': { enabled: false },\n '@opentelemetry/instrumentation-net': { enabled: false },\n});\n\nconst exporter = new OTLPTraceExporter({\n url: `${otlpEndpoint}/v1/traces`,\n});\n\nconst spanProcessor = new CombinedSpanProcessor([\n new ModuleNameSpanProcessor(moduleLabel),\n new BatchSpanProcessor(exporter),\n]);\n\nconst sdk = new NodeSDK({\n resource,\n instrumentations: [instrumentations],\n spanProcessor,\n});\n\nexport const sdkStartPromise = Promise.resolve(sdk.start()).catch((error) => {\n console.error('Failed to start OpenTelemetry SDK', error);\n return Promise.resolve();\n});\n\nconst shutdown = async () => {\n try {\n await sdk.shutdown();\n } catch (error) {\n console.error('Error shutting down OpenTelemetry SDK', error);\n }\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nexport const instrumentApp = (app: Application, logger?: Logger, customModuleName?: string) => {\n const moduleLabel = customModuleName || process.env.MAIN_MODULE || moduleName;\n app.use((req: Request, _res: Response, next: NextFunction) => {\n runWithRequestContext(() => {\n const baggage = propagation.getBaggage(otContext.active());\n const baggageAttrs = baggage\n ? Object.fromEntries(\n (baggage.getAllEntries?.() || []).map(([key, entry]) => [key, entry.value]),\n )\n : {};\n\n const orgId =\n (req.headers['organization-id'] as string) ||\n (req.headers['activeorgid'] as string) ||\n (req.headers['active-org-id'] as string) ||\n (req.headers['activeOrgID'] as string) ||\n (baggageAttrs['organization-id'] as string);\n const sessionId = (req.headers['session-id'] as string) || (baggageAttrs['session-id'] as string);\n const executionId =\n (req.headers['execution-id'] as string) ||\n (req.headers['executionid'] as string) ||\n (req.headers['execution_id'] as string) ||\n (baggageAttrs['execution-id'] as string);\n const userId = (req.headers['user-id'] as string) || (baggageAttrs['user-id'] as string);\n const requestId = (req.headers['request-id'] as string) || (baggageAttrs['request-id'] as string);\n const rawOnelogAttr =\n (req.headers['x-onelog-attr'] as string) ||\n (req.headers['x-onelog-attrs'] as string) ||\n (baggageAttrs['x-onelog-attr'] as string);\n let parsedOnelogAttrs: Record<string, any> = {};\n if (rawOnelogAttr) {\n try {\n const parsed = typeof rawOnelogAttr === 'string' ? JSON.parse(rawOnelogAttr) : rawOnelogAttr;\n if (parsed && typeof parsed === 'object') parsedOnelogAttrs = parsed;\n } catch {\n // ignore malformed\n }\n }\n\n setRequestAttributes({\n 'module.name': moduleLabel,\n 'http.method': req.method,\n 'http.target': req.path,\n 'organization.id': orgId,\n 'organization-id': orgId,\n 'session.id': sessionId,\n 'session-id': sessionId,\n 'execution.id': executionId,\n 'execution-id': executionId,\n 'user.id': userId,\n 'user-id': userId,\n 'request.id': requestId,\n 'request-id': requestId,\n ...baggageAttrs,\n ...parsedOnelogAttrs,\n });\n\n const span = trace.getActiveSpan();\n if (span) {\n span.setAttribute('module.name', moduleLabel);\n span.updateName(`[${moduleLabel}] ${req.method} ${req.path}`);\n const requestAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(requestAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n if (logger) {\n logger.info(\n {\n method: req.method,\n path: req.path,\n ip: req.ip,\n },\n 'Incoming request',\n );\n }\n next();\n });\n });\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, Exception } from '@opentelemetry/api';\nimport { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n 'OTEL_SEMCONV_STABILITY_OPT_IN',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required<ENVIRONMENT> = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n OTEL_SEMCONV_STABILITY_OPT_IN: [],\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_ENVIRONMENT,\n ENVIRONMENT,\n RAW_ENVIRONMENT,\n parseEnvironment,\n} from '../../utils/environment';\n\n/**\n * Gets the environment variables\n */\nexport function getEnv(): Required<ENVIRONMENT> {\n const processEnv = parseEnvironment(process.env as RAW_ENVIRONMENT);\n return Object.assign({}, DEFAULT_ENVIRONMENT, processEnv);\n}\n\nexport function getEnvWithoutDefaults(): ENVIRONMENT {\n return parseEnvironment(process.env as RAW_ENVIRONMENT);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function unrefTimer(timer: NodeJS.Timer): void {\n timer.unref();\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context, Context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getEnv,\n globalErrorHandler,\n suppressTracing,\n unrefTimer,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { BufferConfig } from '../types';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(\n private readonly _exporter: SpanExporter,\n config?: T\n ) {\n const env = getEnv();\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : env.OTEL_BSP_MAX_QUEUE_SIZE;\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : env.OTEL_BSP_SCHEDULE_DELAY;\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : env.OTEL_BSP_EXPORT_TIMEOUT;\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n unrefTimer(this._timer);\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport type AttributeMap = Record<string, any>;\n\ntype RequestAttributeContext = {\n requestAttributes: AttributeMap;\n};\n\nconst requestAttributeStorage = new AsyncLocalStorage<RequestAttributeContext>();\n\nlet globalAttributes: AttributeMap = {};\n\nconst clone = (attrs?: AttributeMap) => ({ ...(attrs || {}) });\n\nexport const getGlobalAttributes = (): AttributeMap => clone(globalAttributes);\n\nexport const setGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = clone(attrs);\n};\n\nexport const mergeGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = { ...globalAttributes, ...clone(attrs) };\n};\n\nexport const getRequestAttributes = (): AttributeMap => {\n const store = requestAttributeStorage.getStore();\n return store?.requestAttributes || {};\n};\n\nexport const setRequestAttributes = (attrs: AttributeMap, options?: { append?: boolean }) => {\n const store = requestAttributeStorage.getStore();\n if (!store) return;\n\n const nextAttributes =\n options?.append === false ? clone(attrs) : { ...store.requestAttributes, ...clone(attrs) };\n store.requestAttributes = nextAttributes;\n};\n\nexport const mergeRequestAttributes = (attrs: AttributeMap) => setRequestAttributes(attrs);\n\nexport const withRequestAttributes = <T>(\n attrs: AttributeMap,\n fn: () => T,\n options?: { append?: boolean },\n): T => {\n const store = requestAttributeStorage.getStore();\n if (!store) {\n return runWithRequestContext(() => fn(), attrs);\n }\n setRequestAttributes(attrs, options);\n return fn();\n};\n\nexport const runWithRequestContext = <T>(fn: () => T, initialAttributes?: AttributeMap): T => {\n return requestAttributeStorage.run(\n {\n requestAttributes: clone(initialAttributes),\n },\n fn,\n );\n};\n","import pino, { Logger } from 'pino';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nconst levelMethods = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'] as const;\n\nconst wrapWithDynamicAttributes = (logger: Logger): Logger => {\n const buildAttrs = () => ({ ...getGlobalAttributes(), ...getRequestAttributes() });\n\n return new Proxy(logger, {\n get(target, prop, receiver) {\n const original = Reflect.get(target, prop, receiver);\n if (typeof prop === 'string' && levelMethods.includes(prop as any) && typeof original === 'function') {\n return (firstArg?: any, ...rest: any[]) => {\n const attrs = buildAttrs();\n if (firstArg && typeof firstArg === 'object' && !Array.isArray(firstArg)) {\n return (original as any).call(target, { ...attrs, ...firstArg }, ...rest);\n }\n return (original as any).call(target, { ...attrs }, firstArg, ...rest);\n };\n }\n return original;\n },\n });\n};\n\nexport function createLogger() {\n const mainEnv = process.env.MAIN_ENV || 'development';\n const mainApp = process.env.MAIN_APP || 'app';\n const mainModule = process.env.MAIN_MODULE || 'unknown-module';\n\n const logger = pino({\n transport: {\n targets: [\n {\n target: 'pino-opentelemetry-transport',\n level: 'info',\n options: {\n resourceAttributes: {\n 'service.name': mainApp,\n 'service.namespace': mainEnv,\n 'deployment.environment': mainEnv,\n 'module.name': mainModule,\n 'host.name': require('os').hostname(),\n },\n },\n },\n {\n target: 'pino-pretty',\n level: 'debug',\n options: {\n colorize: true,\n translateTime: 'HH:MM:ss Z',\n ignore: 'pid,hostname',\n },\n },\n ],\n },\n });\n\n const base = logger.child({\n env: mainEnv,\n app: mainApp,\n module: mainModule,\n });\n\n return wrapWithDynamicAttributes(base);\n}\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\nimport type { Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\n\nexport const errorMiddleware =\n (logger?: Logger) =>\n (err: Error, req: Request, res: Response, next: NextFunction) => {\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n\n if (logger) {\n logger.error(\n {\n ...dynamicAttributes,\n error: err.message,\n stack: err.stack,\n path: req.path,\n },\n 'Unhandled error',\n );\n }\n\n const span = trace.getActiveSpan();\n if (span) {\n span.recordException(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n }\n\n if (res.headersSent) {\n return next(err);\n }\n\n res.status(500).json({\n error: err.message,\n attributes: dynamicAttributes,\n module: process.env.MAIN_MODULE || 'unknown-module',\n });\n };\n","import { context, propagation } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nexport interface HttpCallContext {\n [key: string]: any;\n}\n\nexport interface HttpCallOptions extends RequestInit {\n body?: any;\n}\n\nexport async function httpCall(\n url: string,\n options: HttpCallOptions = {},\n logger?: { info: Function; error: Function },\n logContext: HttpCallContext = {},\n) {\n const fetchOptions: RequestInit = { ...options };\n const method = (fetchOptions.method || 'GET').toString().toUpperCase();\n\n if (\n fetchOptions.body &&\n typeof fetchOptions.body !== 'string' &&\n !(fetchOptions.body instanceof Buffer) &&\n !(fetchOptions.body instanceof ArrayBuffer)\n ) {\n fetchOptions.body = JSON.stringify(fetchOptions.body);\n fetchOptions.headers = {\n 'Content-Type': 'application/json',\n ...(fetchOptions.headers || {}),\n };\n }\n\n const dynamicContext = { ...getGlobalAttributes(), ...getRequestAttributes(), ...logContext };\n\n // Inject trace context + baggage, and forward standard IDs as headers for downstream services\n const headerEntries = Object.entries({\n ...(fetchOptions.headers as any),\n 'organization-id':\n (dynamicContext['organization-id'] as string) || (dynamicContext['organization.id'] as string),\n 'session-id': (dynamicContext['session-id'] as string) || (dynamicContext['session.id'] as string),\n 'execution-id':\n (dynamicContext['execution-id'] as string) || (dynamicContext['execution.id'] as string),\n 'user-id': (dynamicContext['user-id'] as string) || (dynamicContext['user.id'] as string),\n 'request-id': (dynamicContext['request-id'] as string) || (dynamicContext['request.id'] as string),\n 'x-onelog-attr': JSON.stringify(dynamicContext),\n })\n .filter(([, v]) => v !== undefined && v !== null)\n .map(([k, v]) => [k, String(v)]) as [string, string][];\n\n const headers: Record<string, string> = Object.fromEntries(headerEntries);\n\n const carrier: Record<string, any> = { ...headers };\n\n // Build baggage from all attributes to propagate custom keys\n const baggageEntries: Record<string, { value: string }> = {};\n for (const [key, value] of Object.entries(dynamicContext)) {\n if (value === undefined || value === null) continue;\n try {\n baggageEntries[key] = { value: typeof value === 'string' ? value : JSON.stringify(value) };\n } catch {\n // skip values that can't be stringified\n }\n }\n const baggage = propagation.createBaggage(baggageEntries);\n const ctxWithBaggage = propagation.setBaggage(context.active(), baggage);\n propagation.inject(ctxWithBaggage, carrier);\n\n fetchOptions.headers = carrier;\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method }, 'HTTP call start');\n }\n\n try {\n const res = await fetch(url, fetchOptions);\n const contentType = res.headers.get('content-type') || '';\n const isJson = contentType.includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : await res.text().catch(() => null);\n\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status} ${res.statusText || ''}`.trim());\n (error as any).status = res.status;\n (error as any).data = data;\n if (logger) {\n logger.error({ ...dynamicContext, url, method, status: res.status, data }, 'HTTP call failed');\n }\n throw error;\n }\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method, status: res.status }, 'HTTP call success');\n }\n\n return data;\n } catch (err: any) {\n if (logger) {\n logger.error({ ...dynamicContext, url, method, error: err.message }, 'HTTP call error');\n }\n throw err;\n }\n}\n","import { context as otContext, metrics as otMetrics, type Attributes, type MetricOptions } from '@opentelemetry/api';\nimport { Resource } from '@opentelemetry/resources';\nimport { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';\nimport { HostMetrics } from '@opentelemetry/host-metrics';\nimport { RuntimeNodeInstrumentation } from '@opentelemetry/instrumentation-runtime-node';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nconst serviceName = process.env.OTEL_SERVICE_NAME || process.env.MAIN_MODULE || 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE || process.env.OTEL_SERVICE_NAMESPACE || process.env.MAIN_APP || 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\nconst hostMetricsEnabled = (process.env.ONELOG_HOST_METRICS || 'true').toLowerCase() === 'true';\nconst runtimeMetricsEnabled = (process.env.ONELOG_RUNTIME_METRICS || 'false').toLowerCase() === 'true';\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleName,\n }),\n);\n\nlet meterProvider: MeterProvider | undefined;\nlet shutdownRegistered = false;\nlet hostMetricsStarted = false;\nlet runtimeMetricsStarted = false;\n\nconst registerShutdown = () => {\n if (shutdownRegistered) return;\n shutdownRegistered = true;\n const shutdown = async () => {\n if (!meterProvider) return;\n try {\n await meterProvider.shutdown();\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Error shutting down metrics provider', (error as Error).message);\n }\n };\n process.on('SIGTERM', shutdown);\n process.on('SIGINT', shutdown);\n};\n\nconst ensureMeterProvider = () => {\n if (meterProvider) return meterProvider;\n\n const exporter = new OTLPMetricExporter({\n url: `${otlpEndpoint}/v1/metrics`,\n });\n\n meterProvider = new MeterProvider({\n resource,\n readers: [\n new PeriodicExportingMetricReader({\n exporter,\n }),\n ],\n });\n\n otMetrics.setGlobalMeterProvider(meterProvider);\n startHostMetrics(meterProvider);\n startRuntimeMetrics(meterProvider);\n registerShutdown();\n return meterProvider;\n};\n\nconst startHostMetrics = (provider: MeterProvider) => {\n if (!hostMetricsEnabled || hostMetricsStarted) return;\n try {\n const hostMetrics = new HostMetrics({\n meterProvider: provider,\n name: 'onelog-host-metrics',\n });\n hostMetrics.start();\n hostMetricsStarted = true;\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to start host metrics instrumentation', (error as Error).message);\n }\n};\n\nconst startRuntimeMetrics = (provider: MeterProvider) => {\n if (!runtimeMetricsEnabled || runtimeMetricsStarted) return;\n try {\n const runtimeInstrumentation = new RuntimeNodeInstrumentation();\n runtimeInstrumentation.setMeterProvider(provider);\n runtimeInstrumentation.enable();\n runtimeMetricsStarted = true;\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to start runtime metrics instrumentation', (error as Error).message);\n }\n};\n\nexport const metricsStartPromise = Promise.resolve().then(() => ensureMeterProvider());\n\nexport const getMeter = (name = 'onelog-metrics') => ensureMeterProvider().getMeter(name);\n\nconst buildAttributes = (attrs?: Attributes): Attributes => ({\n ...getGlobalAttributes(),\n ...getRequestAttributes(),\n ...(attrs || {}),\n});\n\nexport const createCounter = (name: string, options?: MetricOptions) => {\n const counter = getMeter().createCounter(name, options);\n return {\n add: (value: number, attributes?: Attributes) => {\n counter.add(value, buildAttributes(attributes), otContext.active());\n },\n instrument: counter,\n };\n};\n\nexport const createHistogram = (name: string, options?: MetricOptions) => {\n const histogram = getMeter().createHistogram(name, options);\n return {\n record: (value: number, attributes?: Attributes) => {\n histogram.record(value, buildAttributes(attributes), otContext.active());\n },\n instrument: histogram,\n };\n};\n"],"mappings":"0PAAA,OAAS,QAAAA,GAAM,qBAAAC,GAAmB,gBAAAC,GAAc,SAAAC,GAAO,WAAWC,GAAW,eAAAC,OAAmB,qBAChG,OAAS,WAAAC,OAAe,0BCexB,OAAkB,oBAAAC,OAAwB,qBAE1C,IAAMC,GAAuBD,GAC3B,gDAAgD,EAG5C,SAAUE,EAAgBC,EAAgB,CAC9C,OAAOA,EAAQ,SAASF,GAAsB,EAAI,CACpD,CCRA,OAAS,QAAAG,OAAuB,qBAO1B,SAAUC,GAAmB,CACjC,OAAO,SAACC,EAAa,CACnBF,GAAK,MAAMG,GAAmBD,CAAE,CAAC,CACnC,CACF,CAMA,SAASC,GAAmBD,EAAsB,CAChD,OAAI,OAAOA,GAAO,SACTA,EAEA,KAAK,UAAUE,GAAiBF,CAAE,CAAC,CAE9C,CAOA,SAASE,GAAiBF,EAAa,CAIrC,QAHMG,EAAS,CAAA,EACXC,EAAUJ,EAEPI,IAAY,MACjB,OAAO,oBAAoBA,CAAO,EAAE,QAAQ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sB,QAAQ,QAAQ,EAAE,KAAK,IAAMZ,GAAoB,CAAC,EAExEa,EAAW,CAACC,EAAO,mBAAqBd,GAAoB,EAAE,SAASc,CAAI,EAElFC,GAAmBC,IAAoC,CAC3D,GAAGC,EAAoB,EACvB,GAAGC,EAAqB,EACxB,GAAIF,GAAS,CAAC,CAChB,GAEaG,GAAgB,CAACL,EAAcM,IAA4B,CACtE,IAAMC,EAAUR,EAAS,EAAE,cAAcC,EAAMM,CAAO,EACtD,MAAO,CACL,IAAK,CAACE,EAAeC,IAA4B,CAC/CF,EAAQ,IAAIC,EAAOP,GAAgBQ,CAAU,EAAGC,GAAU,OAAO,CAAC,CACpE,EACA,WAAYH,CACd,CACF,EAEaI,GAAkB,CAACX,EAAcM,IAA4B,CACxE,IAAMM,EAAYb,EAAS,EAAE,gBAAgBC,EAAMM,CAAO,EAC1D,MAAO,CACL,OAAQ,CAACE,EAAeC,IAA4B,CAClDG,EAAU,OAAOJ,EAAOP,GAAgBQ,CAAU,EAAGC,GAAU,OAAO,CAAC,CACzE,EACA,WAAYE,CACd,CACF","names":["diag","DiagConsoleLogger","DiagLogLevel","trace","otContext","propagation","NodeSDK","createContextKey","SUPPRESS_TRACING_KEY","suppressTracing","context","diag","loggingErrorHandler","ex","stringifyException","flattenException","result","current","propertyName","value","delegateHandler","loggingErrorHandler","globalErrorHandler","ex","delegateHandler","DiagLogLevel","TracesSamplerValues","DEFAULT_LIST_SEPARATOR","ENVIRONMENT_BOOLEAN_KEYS","isEnvVarABoolean","key","ENVIRONMENT_NUMBERS_KEYS","isEnvVarANumber","ENVIRONMENT_LISTS_KEYS","isEnvVarAList","DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT","DEFAULT_ATTRIBUTE_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","DEFAULT_ENVIRONMENT","DiagLogLevel","TracesSamplerValues","parseBoolean","environment","values","value","parseNumber","name","min","max","parseStringList","output","input","separator","givenValue","v","logLevelMap","setLogLevelFromEnv","theLevel","parseEnvironment","env","getEnv","processEnv","parseEnvironment","DEFAULT_ENVIRONMENT","unrefTimer","timer","ExportResultCode","Deferred","_this","resolve","reject","val","err","BindOnceFuture","_callback","_that","Deferred","_this","args","_i","_a","__spreadArray","__read","val","err","context","diag","TraceFlags","BatchSpanProcessorBase","_exporter","config","env","getEnv","BindOnceFuture","diag","_span","_parentContext","span","TraceFlags","_this","resolve","reject","promises","count","j","timer","context","suppressTracing","spans","doExport","result","ExportResultCode","_a","pendingResources","i","len","err","globalErrorHandler","flush","e","unrefTimer","BatchSpanProcessor","_super","__extends","BatchSpanProcessorBase","Resource","OTLPTraceExporter","getNodeAutoInstrumentations","ProxyAgent","setGlobalDispatcher","AsyncLocalStorage","requestAttributeStorage","globalAttributes","clone","attrs","getGlobalAttributes","setGlobalAttributes","mergeGlobalAttributes","getRequestAttributes","setRequestAttributes","options","store","nextAttributes","mergeRequestAttributes","withRequestAttributes","fn","runWithRequestContext","initialAttributes","diag","DiagConsoleLogger","DiagLogLevel","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","expressLayersEnabled","moduleLabel","proxyUrl","v","setGlobalDispatcher","ProxyAgent","err","resource","Resource","ModuleNameSpanProcessor","span","currentName","dynamicAttributes","getGlobalAttributes","getRequestAttributes","key","value","_span","CombinedSpanProcessor","processors","ctx","p","instrumentations","getNodeAutoInstrumentations","exporter","OTLPTraceExporter","spanProcessor","BatchSpanProcessor","sdk","NodeSDK","sdkStartPromise","error","shutdown","instrumentApp","app","logger","customModuleName","req","_res","next","runWithRequestContext","baggage","propagation","otContext","baggageAttrs","entry","orgId","sessionId","executionId","userId","requestId","rawOnelogAttr","parsedOnelogAttrs","parsed","setRequestAttributes","trace","requestAttributes","pino","levelMethods","wrapWithDynamicAttributes","logger","buildAttrs","getGlobalAttributes","getRequestAttributes","target","prop","receiver","original","firstArg","rest","attrs","createLogger","mainEnv","mainApp","mainModule","base","pino","trace","SpanStatusCode","errorMiddleware","logger","err","req","res","next","dynamicAttributes","getGlobalAttributes","getRequestAttributes","span","trace","SpanStatusCode","context","propagation","httpCall","url","options","logger","logContext","fetchOptions","method","dynamicContext","getGlobalAttributes","getRequestAttributes","headerEntries","v","k","carrier","baggageEntries","key","value","baggage","propagation","ctxWithBaggage","context","res","data","error","err","otContext","otMetrics","Resource","MeterProvider","PeriodicExportingMetricReader","OTLPMetricExporter","HostMetrics","RuntimeNodeInstrumentation","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","hostMetricsEnabled","runtimeMetricsEnabled","resource","Resource","meterProvider","shutdownRegistered","hostMetricsStarted","runtimeMetricsStarted","registerShutdown","shutdown","error","ensureMeterProvider","exporter","OTLPMetricExporter","MeterProvider","PeriodicExportingMetricReader","otMetrics","startHostMetrics","startRuntimeMetrics","provider","HostMetrics","runtimeInstrumentation","RuntimeNodeInstrumentation","metricsStartPromise","getMeter","name","buildAttributes","attrs","getGlobalAttributes","getRequestAttributes","createCounter","options","counter","value","attributes","otContext","createHistogram","histogram"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@onelog-sdk/node",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.7",
|
|
4
4
|
"description": "OneLog Node SDK for unified tracing, logging, and error handling.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -31,9 +31,14 @@
|
|
|
31
31
|
"dependencies": {
|
|
32
32
|
"@opentelemetry/api": "^1.9.0",
|
|
33
33
|
"@opentelemetry/auto-instrumentations-node": "^0.67.3",
|
|
34
|
+
"@opentelemetry/exporter-metrics-otlp-http": "^0.55.0",
|
|
35
|
+
"@opentelemetry/host-metrics": "^0.35.0",
|
|
36
|
+
"@opentelemetry/instrumentation": "^0.49.0",
|
|
37
|
+
"@opentelemetry/instrumentation-runtime-node": "^0.22.0",
|
|
34
38
|
"@opentelemetry/exporter-trace-otlp-http": "^0.55.0",
|
|
35
39
|
"@opentelemetry/resources": "^1.24.1",
|
|
36
40
|
"@opentelemetry/sdk-node": "^0.55.0",
|
|
41
|
+
"@opentelemetry/sdk-metrics": "^1.24.1",
|
|
37
42
|
"pino": "^10.1.0",
|
|
38
43
|
"pino-opentelemetry-transport": "^2.0.0",
|
|
39
44
|
"pino-pretty": "^13.1.3",
|