🚀 Big News:Socket Has Acquired Secure Annex.Learn More
Socket
Book a DemoSign in
Socket

@opentelemetry/sdk-trace-base

Package Overview
Dependencies
Maintainers
3
Versions
74
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@opentelemetry/sdk-trace-base - npm Package Compare versions

Comparing version
1.22.0
to
1.23.0
+19
-6
build/esm/export/BatchSpanProcessorBase.js

@@ -139,3 +139,10 @@ /*

// outside the execution of this callback.
var spans = _this._finishedSpans.splice(0, _this._maxExportBatchSize);
var spans;
if (_this._finishedSpans.length <= _this._maxExportBatchSize) {
spans = _this._finishedSpans;
_this._finishedSpans = [];
}
else {
spans = _this._finishedSpans.splice(0, _this._maxExportBatchSize);
}
var doExport = function () {

@@ -153,11 +160,17 @@ return _this._exporter.export(spans, function (result) {

};
var pendingResources = spans
.map(function (span) { return span.resource; })
.filter(function (resource) { return resource.asyncAttributesPending; });
var pendingResources = null;
for (var i = 0, len = spans.length; i < len; i++) {
var span = spans[i];
if (span.resource.asyncAttributesPending &&
span.resource.waitForAsyncAttributes) {
pendingResources !== null && pendingResources !== void 0 ? pendingResources : (pendingResources = []);
pendingResources.push(span.resource.waitForAsyncAttributes());
}
}
// Avoid scheduling a promise to make the behavior more predictable and easier to test
if (pendingResources.length === 0) {
if (pendingResources === null) {
doExport();
}
else {
Promise.all(pendingResources.map(function (resource) { var _a; return (_a = resource.waitForAsyncAttributes) === null || _a === void 0 ? void 0 : _a.call(resource); })).then(doExport, function (err) {
Promise.all(pendingResources).then(doExport, function (err) {
globalErrorHandler(err);

@@ -164,0 +177,0 @@ reject(err);

@@ -1,1 +0,1 @@

{"version":3,"file":"BatchSpanProcessorBase.js","sourceRoot":"","sources":["../../../src/export/BatchSpanProcessorBase.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,OAAO,EAAW,IAAI,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EACL,cA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B,CAAC;IAEO,4CAAW,GAAnB;QACE,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE;YAC7B,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC1B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;SACzB;IACH,CAAC;IAGH,6BAAC;AAAD,CAAC,AAzND,IAyNC","sourcesContent":["/*\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 const spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\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 const pendingResources = spans\n .map(span => span.resource)\n .filter(resource => resource.asyncAttributesPending);\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources.length === 0) {\n doExport();\n } else {\n Promise.all(\n pendingResources.map(\n resource => resource.waitForAsyncAttributes?.()\n )\n ).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"]}
{"version":3,"file":"BatchSpanProcessorBase.js","sourceRoot":"","sources":["../../../src/export/BatchSpanProcessorBase.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,OAAO,EAAW,IAAI,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,MAAM,EACN,kBAAkB,EAClB,eAAe,EACf,UAAU,GACX,MAAM,qBAAqB,CAAC;AAO7B;;;GAGG;AACH;IAcE,gCACmB,SAAuB,EACxC,MAAU;QADO,cAAS,GAAT,SAAS,CAAc;QAPlC,iBAAY,GAAG,KAAK,CAAC;QACrB,mBAAc,GAAmB,EAAE,CAAC;QAGpC,uBAAkB,GAAW,CAAC,CAAC;QAMrC,IAAM,GAAG,GAAG,MAAM,EAAE,CAAC;QACrB,IAAI,CAAC,mBAAmB;YACtB,OAAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,kBAAkB,CAAA,KAAK,QAAQ;gBAC5C,CAAC,CAAC,MAAM,CAAC,kBAAkB;gBAC3B,CAAC,CAAC,GAAG,CAAC,8BAA8B,CAAC;QACzC,IAAI,CAAC,aAAa;YAChB,OAAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,YAAY,CAAA,KAAK,QAAQ;gBACtC,CAAC,CAAC,MAAM,CAAC,YAAY;gBACrB,CAAC,CAAC,GAAG,CAAC,uBAAuB,CAAC;QAClC,IAAI,CAAC,qBAAqB;YACxB,OAAO,CAA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,IAAI,CAAC,YAAY;YAAE,OAAO;QAC9B,IAAM,KAAK,GAAG;YACZ,KAAI,CAAC,YAAY,GAAG,IAAI,CAAC;YACzB,KAAI,CAAC,cAAc,EAAE;iBAClB,OAAO,CAAC;gBACP,KAAI,CAAC,YAAY,GAAG,KAAK,CAAC;gBAC1B,IAAI,KAAI,CAAC,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE;oBAClC,KAAI,CAAC,WAAW,EAAE,CAAC;oBACnB,KAAI,CAAC,gBAAgB,EAAE,CAAC;iBACzB;YACH,CAAC,CAAC;iBACD,KAAK,CAAC,UAAA,CAAC;gBACN,KAAI,CAAC,YAAY,GAAG,KAAK,CAAC;gBAC1B,kBAAkB,CAAC,CAAC,CAAC,CAAC;YACxB,CAAC,CAAC,CAAC;QACP,CAAC,CAAC;QACF,6DAA6D;QAC7D,IAAI,IAAI,CAAC,cAAc,CAAC,MAAM,IAAI,IAAI,CAAC,mBAAmB,EAAE;YAC1D,OAAO,KAAK,EAAE,CAAC;SAChB;QACD,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YAAE,OAAO;QACtC,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC,cAAM,OAAA,KAAK,EAAE,EAAP,CAAO,EAAE,IAAI,CAAC,qBAAqB,CAAC,CAAC;QACpE,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1B,CAAC;IAEO,4CAAW,GAAnB;QACE,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE;YAC7B,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC1B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;SACzB;IACH,CAAC;IAGH,6BAAC;AAAD,CAAC,AApOD,IAoOC","sourcesContent":["/*\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"]}

@@ -67,3 +67,3 @@ import { Context, Exception, HrTime, Link, Span as APISpan, SpanAttributes, SpanAttributeValue, SpanContext, SpanKind, SpanStatus, TimeInput } from '@opentelemetry/api';

* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with trucated to {@code attributeValueLengthLimit} characters
* return string with truncated to {@code attributeValueLengthLimit} characters
*

@@ -70,0 +70,0 @@ * If the given attribute value is array of strings then

@@ -307,3 +307,3 @@ /*

* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with trucated to {@code attributeValueLengthLimit} characters
* return string with truncated to {@code attributeValueLengthLimit} characters
*

@@ -310,0 +310,0 @@ * If the given attribute value is array of strings then

@@ -1,1 +0,1 @@

{"version":3,"file":"Span.js","sourceRoot":"","sources":["../../src/Span.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,EAEL,IAAI,EAUJ,cAAc,GAEf,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,UAAU,EACV,cAAc,EACd,aAAa,EACb,MAAM,EACN,cAAc,EAEd,gBAAgB,EAChB,WAAW,EACX,iBAAiB,EACjB,aAAa,EACb,kBAAkB,GACnB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAO7C;;GAEG;AACH;IAgCE;;;;SAIK;IACL,cACE,YAAoB,EACpB,OAAgB,EAChB,QAAgB,EAChB,WAAwB,EACxB,IAAc,EACd,YAAqB,EACrB,KAAkB,EAClB,SAAqB,EACrB,gBAA0B,EAAE,mFAAmF;IAC/G,UAA2B;QAH3B,sBAAA,EAAA,UAAkB;QAtCX,eAAU,GAAmB,EAAE,CAAC;QACh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a,IAAI,CAAC,YAAY,CAAC,MAAM,MAAG,CAC3H,CAAC;SACH;QACD,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,uDAAuD;IACvD,yDAAyD;IACzD,iDAAiD;IACzC,mCAAoB,GAA5B,UAA6B,KAAa,EAAE,KAAa;QACvD,IAAI,KAAK,CAAC,MAAM,IAAI,KAAK,EAAE;YACzB,OAAO,KAAK,CAAC;SACd;QACD,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;IAChC,CAAC;IAED;;;;;;;;;;;OAWG;IACK,8BAAe,GAAvB,UAAwB,KAAyB;QAAjD,iBAuBC;QAtBC,IAAM,KAAK,GAAG,IAAI,CAAC,0BAA0B,CAAC;QAC9C,cAAc;QACd,IAAI,KAAK,IAAI,CAAC,EAAE;YACd,kDAAkD;YAClD,IAAI,CAAC,IAAI,CAAC,iDAA+C,KAAO,CAAC,CAAC;YAClE,OAAO,KAAK,CAAC;SACd;QAED,SAAS;QACT,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC7B,OAAO,IAAI,CAAC,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;SAChD;QAED,mBAAmB;QACnB,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;YACxB,OAAQ,KAAY,CAAC,GAAG,CAAC,UAAA,GAAG;gBAC1B,OAAA,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAI,CAAC,oBAAoB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG;YAArE,CAAqE,CACtE,CAAC;SACH;QAED,mDAAmD;QACnD,OAAO,KAAK,CAAC;IACf,CAAC;IACH,WAAC;AAAD,CAAC,AAjVD,IAiVC","sourcesContent":["/*\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 Context,\n diag,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanAttributes,\n SpanAttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n SpanStatusCode,\n TimeInput,\n} from '@opentelemetry/api';\nimport {\n addHrTimes,\n millisToHrTime,\n getTimeOrigin,\n hrTime,\n hrTimeDuration,\n InstrumentationLibrary,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport { IResource } from '@opentelemetry/resources';\nimport { SemanticAttributes } from '@opentelemetry/semantic-conventions';\nimport { ExceptionEventName } from './enums';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { SpanProcessor } from './SpanProcessor';\nimport { TimedEvent } from './TimedEvent';\nimport { Tracer } from './Tracer';\nimport { SpanLimits } from './types';\n\n/**\n * This class represents a span.\n */\nexport class Span implements APISpan, ReadableSpan {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanId?: string;\n readonly attributes: SpanAttributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: IResource;\n readonly instrumentationLibrary: InstrumentationLibrary;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new Span instance.\n *\n * @deprecated calling Span constructor directly is not supported. Please use tracer.startSpan.\n * */\n constructor(\n parentTracer: Tracer,\n context: Context,\n spanName: string,\n spanContext: SpanContext,\n kind: SpanKind,\n parentSpanId?: string,\n links: Link[] = [],\n startTime?: TimeInput,\n _deprecatedClock?: unknown, // keeping this argument even though it is unused to ensure backwards compatibility\n attributes?: SpanAttributes\n ) {\n this.name = spanName;\n this._spanContext = spanContext;\n this.parentSpanId = parentSpanId;\n this.kind = kind;\n this.links = links;\n\n const now = Date.now();\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + getTimeOrigin());\n this._startTimeProvided = startTime != null;\n\n this.startTime = this._getTime(startTime ?? now);\n\n this.resource = parentTracer.resource;\n this.instrumentationLibrary = parentTracer.instrumentationLibrary;\n this._spanLimits = parentTracer.getSpanLimits();\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit || 0;\n\n if (attributes != null) {\n this.setAttributes(attributes);\n }\n\n this._spanProcessor = parentTracer.getActiveSpanProcessor();\n this._spanProcessor.onStart(this, context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: SpanAttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n if (\n Object.keys(this.attributes).length >=\n this._spanLimits.attributeCountLimit! &&\n !Object.prototype.hasOwnProperty.call(this.attributes, key)\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n this.attributes[key] = this._truncateToSize(value);\n return this;\n }\n\n setAttributes(attributes: SpanAttributes): this {\n for (const [k, v] of Object.entries(attributes)) {\n this.setAttribute(k, v);\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: SpanAttributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n if (this._spanLimits.eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n if (this.events.length >= this._spanLimits.eventCountLimit!) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const attributes = sanitizeAttributes(attributesOrStartTime);\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount: 0,\n });\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n this.status = status;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this._ended = true;\n\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp < otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: SpanAttributes = {};\n if (typeof exception === 'string') {\n attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[SemanticAttributes.EXCEPTION_TYPE] =\n exception.code.toString();\n } else if (exception.name) {\n attributes[SemanticAttributes.EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[SemanticAttributes.EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (\n attributes[SemanticAttributes.EXCEPTION_TYPE] ||\n attributes[SemanticAttributes.EXCEPTION_MESSAGE]\n ) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n diag.warn(\n `Can not execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substr(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with trucated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: SpanAttributeValue): SpanAttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n}\n"]}
{"version":3,"file":"Span.js","sourceRoot":"","sources":["../../src/Span.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,EAEL,IAAI,EAUJ,cAAc,GAEf,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,UAAU,EACV,cAAc,EACd,aAAa,EACb,MAAM,EACN,cAAc,EAEd,gBAAgB,EAChB,WAAW,EACX,iBAAiB,EACjB,aAAa,EACb,kBAAkB,GACnB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAO7C;;GAEG;AACH;IAgCE;;;;SAIK;IACL,cACE,YAAoB,EACpB,OAAgB,EAChB,QAAgB,EAChB,WAAwB,EACxB,IAAc,EACd,YA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C,AAjVD,IAiVC","sourcesContent":["/*\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 Context,\n diag,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanAttributes,\n SpanAttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n SpanStatusCode,\n TimeInput,\n} from '@opentelemetry/api';\nimport {\n addHrTimes,\n millisToHrTime,\n getTimeOrigin,\n hrTime,\n hrTimeDuration,\n InstrumentationLibrary,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport { IResource } from '@opentelemetry/resources';\nimport { SemanticAttributes } from '@opentelemetry/semantic-conventions';\nimport { ExceptionEventName } from './enums';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { SpanProcessor } from './SpanProcessor';\nimport { TimedEvent } from './TimedEvent';\nimport { Tracer } from './Tracer';\nimport { SpanLimits } from './types';\n\n/**\n * This class represents a span.\n */\nexport class Span implements APISpan, ReadableSpan {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanId?: string;\n readonly attributes: SpanAttributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: IResource;\n readonly instrumentationLibrary: InstrumentationLibrary;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new Span instance.\n *\n * @deprecated calling Span constructor directly is not supported. Please use tracer.startSpan.\n * */\n constructor(\n parentTracer: Tracer,\n context: Context,\n spanName: string,\n spanContext: SpanContext,\n kind: SpanKind,\n parentSpanId?: string,\n links: Link[] = [],\n startTime?: TimeInput,\n _deprecatedClock?: unknown, // keeping this argument even though it is unused to ensure backwards compatibility\n attributes?: SpanAttributes\n ) {\n this.name = spanName;\n this._spanContext = spanContext;\n this.parentSpanId = parentSpanId;\n this.kind = kind;\n this.links = links;\n\n const now = Date.now();\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + getTimeOrigin());\n this._startTimeProvided = startTime != null;\n\n this.startTime = this._getTime(startTime ?? now);\n\n this.resource = parentTracer.resource;\n this.instrumentationLibrary = parentTracer.instrumentationLibrary;\n this._spanLimits = parentTracer.getSpanLimits();\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit || 0;\n\n if (attributes != null) {\n this.setAttributes(attributes);\n }\n\n this._spanProcessor = parentTracer.getActiveSpanProcessor();\n this._spanProcessor.onStart(this, context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: SpanAttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n if (\n Object.keys(this.attributes).length >=\n this._spanLimits.attributeCountLimit! &&\n !Object.prototype.hasOwnProperty.call(this.attributes, key)\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n this.attributes[key] = this._truncateToSize(value);\n return this;\n }\n\n setAttributes(attributes: SpanAttributes): this {\n for (const [k, v] of Object.entries(attributes)) {\n this.setAttribute(k, v);\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: SpanAttributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n if (this._spanLimits.eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n if (this.events.length >= this._spanLimits.eventCountLimit!) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const attributes = sanitizeAttributes(attributesOrStartTime);\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount: 0,\n });\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n this.status = status;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this._ended = true;\n\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp < otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: SpanAttributes = {};\n if (typeof exception === 'string') {\n attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[SemanticAttributes.EXCEPTION_TYPE] =\n exception.code.toString();\n } else if (exception.name) {\n attributes[SemanticAttributes.EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[SemanticAttributes.EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (\n attributes[SemanticAttributes.EXCEPTION_TYPE] ||\n attributes[SemanticAttributes.EXCEPTION_MESSAGE]\n ) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n diag.warn(\n `Can not execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substr(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with truncated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: SpanAttributeValue): SpanAttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n}\n"]}

@@ -1,2 +0,2 @@

export declare const VERSION = "1.22.0";
export declare const VERSION = "1.23.0";
//# sourceMappingURL=version.d.ts.map

@@ -17,3 +17,3 @@ /*

// this is autogenerated file, see scripts/version-update.js
export var VERSION = '1.22.0';
export var VERSION = '1.23.0';
//# sourceMappingURL=version.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,IAAM,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["/*\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\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.22.0';\n"]}
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,IAAM,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["/*\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\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.23.0';\n"]}

@@ -136,3 +136,10 @@ /*

// outside the execution of this callback.
const spans = this._finishedSpans.splice(0, this._maxExportBatchSize);
let spans;
if (this._finishedSpans.length <= this._maxExportBatchSize) {
spans = this._finishedSpans;
this._finishedSpans = [];
}
else {
spans = this._finishedSpans.splice(0, this._maxExportBatchSize);
}
const doExport = () => this._exporter.export(spans, result => {

@@ -148,11 +155,17 @@ var _a;

});
const pendingResources = spans
.map(span => span.resource)
.filter(resource => resource.asyncAttributesPending);
let pendingResources = null;
for (let i = 0, len = spans.length; i < len; i++) {
const span = spans[i];
if (span.resource.asyncAttributesPending &&
span.resource.waitForAsyncAttributes) {
pendingResources !== null && pendingResources !== void 0 ? pendingResources : (pendingResources = []);
pendingResources.push(span.resource.waitForAsyncAttributes());
}
}
// Avoid scheduling a promise to make the behavior more predictable and easier to test
if (pendingResources.length === 0) {
if (pendingResources === null) {
doExport();
}
else {
Promise.all(pendingResources.map(resource => { var _a; return (_a = resource.waitForAsyncAttributes) === null || _a === void 0 ? void 0 : _a.call(resource); })).then(doExport, err => {
Promise.all(pendingResources).then(doExport, err => {
globalErrorHandler(err);

@@ -159,0 +172,0 @@ reject(err);

@@ -1,1 +0,1 @@

{"version":3,"file":"BatchSpanProcessorBase.js","sourceRoot":"","sources":["../../../src/export/BatchSpanProcessorBase.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,OAAO,EAAW,IAAI,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,MAAM,EACN,kBAAkB,EAClB,eAAe,EACf,UAAU,GACX,MAAM,qBAAqB,CAAC;AAO7B;;;GAGG;AACH,MAAM,OAAgB,sBAAsB;IAc1C,YACmB,SAAuB,EACxC,MAAU;QADO,cAAS,GAAT,SAAS,CAAc;QAPlC,iBAAY,GAAG,KAAK,CAAC;QACrB,mBAAc,GAAmB,EAAE,CAAC;QAGpC,uBAAkB,GAAW,CAAC,CAAC;QAMrC,MAAM,GAAG,GAAG,MAAM,EAAE,CAAC;QACrB,IAAI,CAAC,mBAAmB;YACtB,OAAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,kBAAkB,CAAA,KAAK,QAAQ;gBAC5C,CAAC,CAAC,MAAM,CAAC,kBAAkB;gBAC3B,CAAC,CAAC,GAAG,CAAC,8BAA8B,CAAC;QACzC,IAAI,CAAC,aAAa;YAChB,OAAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,YAAY,CAAA,KAAK,QAAQ;gBACtC,CAAC,CAAC,MAAM,CAAC,YAAY;gBACrB,CAAC,CAAC,GAAG,CAAC,uBAAuB,CAAC;QAClC,IAAI,C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AC,CAAC,CAAC,EAAE;gBACT,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;gBAC1B,kBAAkB,CAAC,CAAC,CAAC,CAAC;YACxB,CAAC,CAAC,CAAC;QACP,CAAC,CAAC;QACF,6DAA6D;QAC7D,IAAI,IAAI,CAAC,cAAc,CAAC,MAAM,IAAI,IAAI,CAAC,mBAAmB,EAAE;YAC1D,OAAO,KAAK,EAAE,CAAC;SAChB;QACD,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YAAE,OAAO;QACtC,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,qBAAqB,CAAC,CAAC;QACpE,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1B,CAAC;IAEO,WAAW;QACjB,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE;YAC7B,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC1B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;SACzB;IACH,CAAC;CAGF","sourcesContent":["/*\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 const spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\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 const pendingResources = spans\n .map(span => span.resource)\n .filter(resource => resource.asyncAttributesPending);\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources.length === 0) {\n doExport();\n } else {\n Promise.all(\n pendingResources.map(\n resource => resource.waitForAsyncAttributes?.()\n )\n ).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"]}
{"version":3,"file":"BatchSpanProcessorBase.js","sourceRoot":"","sources":["../../../src/export/BatchSpanProcessorBase.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,OAAO,EAAW,IAAI,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,MAAM,EACN,kBAAkB,EAClB,eAAe,EACf,UAAU,GACX,MAAM,qBAAqB,CAAC;AAO7B;;;GAGG;AACH,MAAM,OAAgB,sBAAsB;IAc1C,YACmB,SAAuB,EACxC,MAAU;QADO,cAAS,GAAT,SAAS,CAAc;QAPlC,iBAAY,GAAG,KAAK,CAAC;QACrB,mBAAc,GAAmB,EAAE,CAAC;QAGpC,uBAAkB,GAAW,CAAC,CAAC;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AI,CAAC,qBAAqB,CAAC,CAAC;QACpE,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1B,CAAC;IAEO,WAAW;QACjB,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE;YAC7B,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC1B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;SACzB;IACH,CAAC;CAGF","sourcesContent":["/*\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"]}

@@ -67,3 +67,3 @@ import { Context, Exception, HrTime, Link, Span as APISpan, SpanAttributes, SpanAttributeValue, SpanContext, SpanKind, SpanStatus, TimeInput } from '@opentelemetry/api';

* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with trucated to {@code attributeValueLengthLimit} characters
* return string with truncated to {@code attributeValueLengthLimit} characters
*

@@ -70,0 +70,0 @@ * If the given attribute value is array of strings then

@@ -248,3 +248,3 @@ /*

* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with trucated to {@code attributeValueLengthLimit} characters
* return string with truncated to {@code attributeValueLengthLimit} characters
*

@@ -251,0 +251,0 @@ * If the given attribute value is array of strings then

@@ -1,1 +0,1 @@

{"version":3,"file":"Span.js","sourceRoot":"","sources":["../../src/Span.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAEL,IAAI,EAUJ,cAAc,GAEf,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,UAAU,EACV,cAAc,EACd,aAAa,EACb,MAAM,EACN,cAAc,EAEd,gBAAgB,EAChB,WAAW,EACX,iBAAiB,EACjB,aAAa,EACb,kBA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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 Context,\n diag,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanAttributes,\n SpanAttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n SpanStatusCode,\n TimeInput,\n} from '@opentelemetry/api';\nimport {\n addHrTimes,\n millisToHrTime,\n getTimeOrigin,\n hrTime,\n hrTimeDuration,\n InstrumentationLibrary,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport { IResource } from '@opentelemetry/resources';\nimport { SemanticAttributes } from '@opentelemetry/semantic-conventions';\nimport { ExceptionEventName } from './enums';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { SpanProcessor } from './SpanProcessor';\nimport { TimedEvent } from './TimedEvent';\nimport { Tracer } from './Tracer';\nimport { SpanLimits } from './types';\n\n/**\n * This class represents a span.\n */\nexport class Span implements APISpan, ReadableSpan {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanId?: string;\n readonly attributes: SpanAttributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: IResource;\n readonly instrumentationLibrary: InstrumentationLibrary;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new Span instance.\n *\n * @deprecated calling Span constructor directly is not supported. Please use tracer.startSpan.\n * */\n constructor(\n parentTracer: Tracer,\n context: Context,\n spanName: string,\n spanContext: SpanContext,\n kind: SpanKind,\n parentSpanId?: string,\n links: Link[] = [],\n startTime?: TimeInput,\n _deprecatedClock?: unknown, // keeping this argument even though it is unused to ensure backwards compatibility\n attributes?: SpanAttributes\n ) {\n this.name = spanName;\n this._spanContext = spanContext;\n this.parentSpanId = parentSpanId;\n this.kind = kind;\n this.links = links;\n\n const now = Date.now();\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + getTimeOrigin());\n this._startTimeProvided = startTime != null;\n\n this.startTime = this._getTime(startTime ?? now);\n\n this.resource = parentTracer.resource;\n this.instrumentationLibrary = parentTracer.instrumentationLibrary;\n this._spanLimits = parentTracer.getSpanLimits();\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit || 0;\n\n if (attributes != null) {\n this.setAttributes(attributes);\n }\n\n this._spanProcessor = parentTracer.getActiveSpanProcessor();\n this._spanProcessor.onStart(this, context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: SpanAttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n if (\n Object.keys(this.attributes).length >=\n this._spanLimits.attributeCountLimit! &&\n !Object.prototype.hasOwnProperty.call(this.attributes, key)\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n this.attributes[key] = this._truncateToSize(value);\n return this;\n }\n\n setAttributes(attributes: SpanAttributes): this {\n for (const [k, v] of Object.entries(attributes)) {\n this.setAttribute(k, v);\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: SpanAttributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n if (this._spanLimits.eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n if (this.events.length >= this._spanLimits.eventCountLimit!) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const attributes = sanitizeAttributes(attributesOrStartTime);\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount: 0,\n });\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n this.status = status;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this._ended = true;\n\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp < otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: SpanAttributes = {};\n if (typeof exception === 'string') {\n attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[SemanticAttributes.EXCEPTION_TYPE] =\n exception.code.toString();\n } else if (exception.name) {\n attributes[SemanticAttributes.EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[SemanticAttributes.EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (\n attributes[SemanticAttributes.EXCEPTION_TYPE] ||\n attributes[SemanticAttributes.EXCEPTION_MESSAGE]\n ) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n diag.warn(\n `Can not execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substr(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with trucated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: SpanAttributeValue): SpanAttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n}\n"]}
{"version":3,"file":"Span.js","sourceRoot":"","sources":["../../src/Span.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAEL,IAAI,EAUJ,cAAc,GAEf,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,UAAU,EACV,cAAc,EACd,aAAa,EACb,MAAM,EACN,cAAc,EAEd,gBAAgB,EAChB,WAAW,EACX,iBAAiB,EACjB,aAAa,EACb,kBAAkB,GACnB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAO7C;;GAEG;AACH,MAAM,OAAO,IAAI;IAgCf;;;;SAIK;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,MAAM,GAAG,CAC3H,CAAC;SACH;QACD,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,uDAAuD;IACvD,yDAAyD;IACzD,iDAAiD;IACzC,oBAAoB,CAAC,KAAa,EAAE,KAAa;QACvD,IAAI,KAAK,CAAC,MAAM,IAAI,KAAK,EAAE;YACzB,OAAO,KAAK,CAAC;SACd;QACD,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;IAChC,CAAC;IAED;;;;;;;;;;;OAWG;IACK,eAAe,CAAC,KAAyB;QAC/C,MAAM,KAAK,GAAG,IAAI,CAAC,0BAA0B,CAAC;QAC9C,cAAc;QACd,IAAI,KAAK,IAAI,CAAC,EAAE;YACd,kDAAkD;YAClD,IAAI,CAAC,IAAI,CAAC,+CAA+C,KAAK,EAAE,CAAC,CAAC;YAClE,OAAO,KAAK,CAAC;SACd;QAED,SAAS;QACT,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC7B,OAAO,IAAI,CAAC,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;SAChD;QAED,mBAAmB;QACnB,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;YACxB,OAAQ,KAAY,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAC7B,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CACtE,CAAC;SACH;QAED,mDAAmD;QACnD,OAAO,KAAK,CAAC;IACf,CAAC;CACF","sourcesContent":["/*\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 Context,\n diag,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanAttributes,\n SpanAttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n SpanStatusCode,\n TimeInput,\n} from '@opentelemetry/api';\nimport {\n addHrTimes,\n millisToHrTime,\n getTimeOrigin,\n hrTime,\n hrTimeDuration,\n InstrumentationLibrary,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport { IResource } from '@opentelemetry/resources';\nimport { SemanticAttributes } from '@opentelemetry/semantic-conventions';\nimport { ExceptionEventName } from './enums';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { SpanProcessor } from './SpanProcessor';\nimport { TimedEvent } from './TimedEvent';\nimport { Tracer } from './Tracer';\nimport { SpanLimits } from './types';\n\n/**\n * This class represents a span.\n */\nexport class Span implements APISpan, ReadableSpan {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanId?: string;\n readonly attributes: SpanAttributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: IResource;\n readonly instrumentationLibrary: InstrumentationLibrary;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new Span instance.\n *\n * @deprecated calling Span constructor directly is not supported. Please use tracer.startSpan.\n * */\n constructor(\n parentTracer: Tracer,\n context: Context,\n spanName: string,\n spanContext: SpanContext,\n kind: SpanKind,\n parentSpanId?: string,\n links: Link[] = [],\n startTime?: TimeInput,\n _deprecatedClock?: unknown, // keeping this argument even though it is unused to ensure backwards compatibility\n attributes?: SpanAttributes\n ) {\n this.name = spanName;\n this._spanContext = spanContext;\n this.parentSpanId = parentSpanId;\n this.kind = kind;\n this.links = links;\n\n const now = Date.now();\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + getTimeOrigin());\n this._startTimeProvided = startTime != null;\n\n this.startTime = this._getTime(startTime ?? now);\n\n this.resource = parentTracer.resource;\n this.instrumentationLibrary = parentTracer.instrumentationLibrary;\n this._spanLimits = parentTracer.getSpanLimits();\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit || 0;\n\n if (attributes != null) {\n this.setAttributes(attributes);\n }\n\n this._spanProcessor = parentTracer.getActiveSpanProcessor();\n this._spanProcessor.onStart(this, context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: SpanAttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n if (\n Object.keys(this.attributes).length >=\n this._spanLimits.attributeCountLimit! &&\n !Object.prototype.hasOwnProperty.call(this.attributes, key)\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n this.attributes[key] = this._truncateToSize(value);\n return this;\n }\n\n setAttributes(attributes: SpanAttributes): this {\n for (const [k, v] of Object.entries(attributes)) {\n this.setAttribute(k, v);\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: SpanAttributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n if (this._spanLimits.eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n if (this.events.length >= this._spanLimits.eventCountLimit!) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const attributes = sanitizeAttributes(attributesOrStartTime);\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount: 0,\n });\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n this.status = status;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this._ended = true;\n\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp < otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: SpanAttributes = {};\n if (typeof exception === 'string') {\n attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[SemanticAttributes.EXCEPTION_TYPE] =\n exception.code.toString();\n } else if (exception.name) {\n attributes[SemanticAttributes.EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[SemanticAttributes.EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (\n attributes[SemanticAttributes.EXCEPTION_TYPE] ||\n attributes[SemanticAttributes.EXCEPTION_MESSAGE]\n ) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n diag.warn(\n `Can not execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substr(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with truncated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: SpanAttributeValue): SpanAttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n}\n"]}

@@ -1,2 +0,2 @@

export declare const VERSION = "1.22.0";
export declare const VERSION = "1.23.0";
//# sourceMappingURL=version.d.ts.map

@@ -17,3 +17,3 @@ /*

// this is autogenerated file, see scripts/version-update.js
export const VERSION = '1.22.0';
export const VERSION = '1.23.0';
//# sourceMappingURL=version.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["/*\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\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.22.0';\n"]}
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["/*\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\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.23.0';\n"]}

@@ -139,3 +139,10 @@ "use strict";

// outside the execution of this callback.
const spans = this._finishedSpans.splice(0, this._maxExportBatchSize);
let spans;
if (this._finishedSpans.length <= this._maxExportBatchSize) {
spans = this._finishedSpans;
this._finishedSpans = [];
}
else {
spans = this._finishedSpans.splice(0, this._maxExportBatchSize);
}
const doExport = () => this._exporter.export(spans, result => {

@@ -151,11 +158,17 @@ var _a;

});
const pendingResources = spans
.map(span => span.resource)
.filter(resource => resource.asyncAttributesPending);
let pendingResources = null;
for (let i = 0, len = spans.length; i < len; i++) {
const span = spans[i];
if (span.resource.asyncAttributesPending &&
span.resource.waitForAsyncAttributes) {
pendingResources !== null && pendingResources !== void 0 ? pendingResources : (pendingResources = []);
pendingResources.push(span.resource.waitForAsyncAttributes());
}
}
// Avoid scheduling a promise to make the behavior more predictable and easier to test
if (pendingResources.length === 0) {
if (pendingResources === null) {
doExport();
}
else {
Promise.all(pendingResources.map(resource => { var _a; return (_a = resource.waitForAsyncAttributes) === null || _a === void 0 ? void 0 : _a.call(resource); })).then(doExport, err => {
Promise.all(pendingResources).then(doExport, err => {
(0, core_1.globalErrorHandler)(err);

@@ -162,0 +175,0 @@ reject(err);

@@ -1,1 +0,1 @@

{"version":3,"file":"BatchSpanProcessorBase.js","sourceRoot":"","sources":["../../../src/export/BatchSpanProcessorBase.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4CAAwE;AACxE,8CAO6B;AAO7B;;;GAGG;AACH,MAAsB,sBAAsB;IAc1C,YACmB,SAAuB,EACxC,MAAU;QADO,cAAS,GAAT,SAAS,CAAc;QAPlC,iBAAY,GAAG,KAAK,CAAC;QACrB,mBAAc,GAAmB,EAAE,CAAC;QAGpC,uBAAkB,GAAW,CAAC,CAAC;QAMrC,MAAM,GAAG,GAAG,IAAA,aAAM,GAAE,CAAC;QACrB,IAAI,CAAC,mBAAmB;YACtB,OAAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,kBAAkB,CAAA,KAAK,QAAQ;gBAC5C,CAAC,CAAC,MAAM,CAAC,kBAAkB;gBAC3B,CAAC,CAAC,GAAG,CAAC,8BAA8B,CAAC;QACzC,IAAI,CAAC,aAAa;YAChB,OAAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,YAAY,CAAA,KAAK,QAAQ;gBACtC,CAAC,CAAC,MAAM,CAAC,YAAY;gBACrB,CAAC,CAAC,GAAG,CAAC,uBAAuB,CAAC;QAClC,IAAI,CAAC,qBAAqB;YACxB,OAAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,oBAAoB,CAAA,KAAK,QAAQ;gBAC9C,CAAC,CAAC,MAAM,CAAC,oBAAoB;gBAC7B,CAAC,CAAC,GAAG,CAAC,uBAAuB,CAAC;QAClC,IAAI,CAAC,oBAAoB;YACvB,OAAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,mBAAmB,CAAA,KAAK,QAAQ;gBAC7C,CAAC,CAAC,MAAM,CAAC,mBAAmB;gBAC5B,CAAC,CAAC,GAAG,CAAC,uBAAuB,CA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AAU,CAAC,GAAG,EAAE,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,qBAAqB,CAAC,CAAC;QACpE,IAAA,iBAAU,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1B,CAAC;IAEO,WAAW;QACjB,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE;YAC7B,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC1B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;SACzB;IACH,CAAC;CAGF;AAzND,wDAyNC","sourcesContent":["/*\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 const spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\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 const pendingResources = spans\n .map(span => span.resource)\n .filter(resource => resource.asyncAttributesPending);\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources.length === 0) {\n doExport();\n } else {\n Promise.all(\n pendingResources.map(\n resource => resource.waitForAsyncAttributes?.()\n )\n ).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"]}
{"version":3,"file":"BatchSpanProcessorBase.js","sourceRoot":"","sources":["../../../src/export/BatchSpanProcessorBase.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4CAAwE;AACxE,8CAO6B;AAO7B;;;GAGG;AACH,MAAsB,sBAAsB;IAc1C,YACmB,SAAuB,EACxC,MAAU;QADO,cAAS,GAAT,SAAS,CAAc;QAPlC,iBAAY,GAAG,KAAK,CAAC;QACrB,mBAAc,GAAmB,EAAE,CAAC;QAGpC,uBAAkB,GAAW,CAAC,CAAC;QAMrC,MAAM,GAAG,GAAG,IAAA,aAAM,GAAE,CAAC;QACrB,IAAI,CAAC,mBAAmB;YACtB,OAAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,kBAAkB,CAAA,KAAK,QAAQ;gBAC5C,CAAC,CAAC,MAAM,CAAC,kBAAkB;gBAC3B,CAAC,CAAC,GAAG,CAAC,8BAA8B,CAAC;QACzC,IAAI,CAAC,aAAa;YAChB,OAAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,YAAY,CAAA,KAAK,QAAQ;gBACtC,CAAC,CAAC,MAAM,CAAC,YAAY;gBACrB,CAAC,CAAC,GAAG,CAAC,uBAAuB,CAAC;QAClC,IAAI,CAAC,qBAAqB;YACxB,OAAO,CAAA,MAAM,aAAN,MA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MAAM,KAAK,GAAG,GAAG,EAAE;YACjB,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;YACzB,IAAI,CAAC,cAAc,EAAE;iBAClB,OAAO,CAAC,GAAG,EAAE;gBACZ,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;gBAC1B,IAAI,IAAI,CAAC,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE;oBAClC,IAAI,CAAC,WAAW,EAAE,CAAC;oBACnB,IAAI,CAAC,gBAAgB,EAAE,CAAC;iBACzB;YACH,CAAC,CAAC;iBACD,KAAK,CAAC,CAAC,CAAC,EAAE;gBACT,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;gBAC1B,IAAA,yBAAkB,EAAC,CAAC,CAAC,CAAC;YACxB,CAAC,CAAC,CAAC;QACP,CAAC,CAAC;QACF,6DAA6D;QAC7D,IAAI,IAAI,CAAC,cAAc,CAAC,MAAM,IAAI,IAAI,CAAC,mBAAmB,EAAE;YAC1D,OAAO,KAAK,EAAE,CAAC;SAChB;QACD,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YAAE,OAAO;QACtC,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,qBAAqB,CAAC,CAAC;QACpE,IAAA,iBAAU,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1B,CAAC;IAEO,WAAW;QACjB,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE;YAC7B,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC1B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;SACzB;IACH,CAAC;CAGF;AApOD,wDAoOC","sourcesContent":["/*\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"]}

@@ -67,3 +67,3 @@ import { Context, Exception, HrTime, Link, Span as APISpan, SpanAttributes, SpanAttributeValue, SpanContext, SpanKind, SpanStatus, TimeInput } from '@opentelemetry/api';

* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with trucated to {@code attributeValueLengthLimit} characters
* return string with truncated to {@code attributeValueLengthLimit} characters
*

@@ -70,0 +70,0 @@ * If the given attribute value is array of strings then

@@ -251,3 +251,3 @@ "use strict";

* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with trucated to {@code attributeValueLengthLimit} characters
* return string with truncated to {@code attributeValueLengthLimit} characters
*

@@ -254,0 +254,0 @@ * If the given attribute value is array of strings then

@@ -1,1 +0,1 @@

{"version":3,"file":"Span.js","sourceRoot":"","sources":["../../src/Span.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4CAc4B;AAC5B,8CAY6B;AAE7B,8EAAyE;AACzE,mCAA6C;AAO7C;;GAEG;AACH,MAAa,IAAI;IAgCf;;;;SAIK;IACL,YACE,YAAoB,EACpB,OAAgB,EAChB,QAAgB,EAChB,WAAwB,EACxB,IAAc,EACd,YAAqB,EACrB,QAAgB,EAAE,EAClB,SAAqB,EACrB,gBAA0B,EAAE,mFAAmF;IAC/G,UAA2B;QAzCpB,eAAU,GAAmB,EAAE,CAAC;QAChC,UAAK,GAAW,EAAE,CAAC;QACnB,WAAM,GAAiB,EAAE,CAAC;QAK3B,4BAAuB,GAAG,CAAC,CAAC;QAC5B,wBAAmB,GAAW,CAAC,CAAC;QAChC,uBAAkB,GAAW,CAAC,CAAC;QAGvC,WAAM,GAAe;YACnB,IAAI,EAAE,oBAAc,CAAC,KAAK;SAC3B,CAAC;QACF,YAAO,GAAW,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACjB,WAAM,GAAG,KAAK,CAAC;QACf,cAAS,GAAW,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d,IAAI,KAAK,IAAI,CAAC,EAAE;YACd,kDAAkD;YAClD,UAAI,CAAC,IAAI,CAAC,+CAA+C,KAAK,EAAE,CAAC,CAAC;YAClE,OAAO,KAAK,CAAC;SACd;QAED,SAAS;QACT,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC7B,OAAO,IAAI,CAAC,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;SAChD;QAED,mBAAmB;QACnB,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;YACxB,OAAQ,KAAY,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAC7B,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CACtE,CAAC;SACH;QAED,mDAAmD;QACnD,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAjVD,oBAiVC","sourcesContent":["/*\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 Context,\n diag,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanAttributes,\n SpanAttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n SpanStatusCode,\n TimeInput,\n} from '@opentelemetry/api';\nimport {\n addHrTimes,\n millisToHrTime,\n getTimeOrigin,\n hrTime,\n hrTimeDuration,\n InstrumentationLibrary,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport { IResource } from '@opentelemetry/resources';\nimport { SemanticAttributes } from '@opentelemetry/semantic-conventions';\nimport { ExceptionEventName } from './enums';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { SpanProcessor } from './SpanProcessor';\nimport { TimedEvent } from './TimedEvent';\nimport { Tracer } from './Tracer';\nimport { SpanLimits } from './types';\n\n/**\n * This class represents a span.\n */\nexport class Span implements APISpan, ReadableSpan {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanId?: string;\n readonly attributes: SpanAttributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: IResource;\n readonly instrumentationLibrary: InstrumentationLibrary;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new Span instance.\n *\n * @deprecated calling Span constructor directly is not supported. Please use tracer.startSpan.\n * */\n constructor(\n parentTracer: Tracer,\n context: Context,\n spanName: string,\n spanContext: SpanContext,\n kind: SpanKind,\n parentSpanId?: string,\n links: Link[] = [],\n startTime?: TimeInput,\n _deprecatedClock?: unknown, // keeping this argument even though it is unused to ensure backwards compatibility\n attributes?: SpanAttributes\n ) {\n this.name = spanName;\n this._spanContext = spanContext;\n this.parentSpanId = parentSpanId;\n this.kind = kind;\n this.links = links;\n\n const now = Date.now();\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + getTimeOrigin());\n this._startTimeProvided = startTime != null;\n\n this.startTime = this._getTime(startTime ?? now);\n\n this.resource = parentTracer.resource;\n this.instrumentationLibrary = parentTracer.instrumentationLibrary;\n this._spanLimits = parentTracer.getSpanLimits();\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit || 0;\n\n if (attributes != null) {\n this.setAttributes(attributes);\n }\n\n this._spanProcessor = parentTracer.getActiveSpanProcessor();\n this._spanProcessor.onStart(this, context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: SpanAttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n if (\n Object.keys(this.attributes).length >=\n this._spanLimits.attributeCountLimit! &&\n !Object.prototype.hasOwnProperty.call(this.attributes, key)\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n this.attributes[key] = this._truncateToSize(value);\n return this;\n }\n\n setAttributes(attributes: SpanAttributes): this {\n for (const [k, v] of Object.entries(attributes)) {\n this.setAttribute(k, v);\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: SpanAttributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n if (this._spanLimits.eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n if (this.events.length >= this._spanLimits.eventCountLimit!) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const attributes = sanitizeAttributes(attributesOrStartTime);\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount: 0,\n });\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n this.status = status;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this._ended = true;\n\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp < otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: SpanAttributes = {};\n if (typeof exception === 'string') {\n attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[SemanticAttributes.EXCEPTION_TYPE] =\n exception.code.toString();\n } else if (exception.name) {\n attributes[SemanticAttributes.EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[SemanticAttributes.EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (\n attributes[SemanticAttributes.EXCEPTION_TYPE] ||\n attributes[SemanticAttributes.EXCEPTION_MESSAGE]\n ) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n diag.warn(\n `Can not execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substr(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with trucated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: SpanAttributeValue): SpanAttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n}\n"]}
{"version":3,"file":"Span.js","sourceRoot":"","sources":["../../src/Span.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4CAc4B;AAC5B,8CAY6B;AAE7B,8EAAyE;AACzE,mCAA6C;AAO7C;;GAEG;AACH,MAAa,IAAI;IAgCf;;;;SAIK;IACL,YACE,YAAoB,EACpB,OAAgB,EAChB,QAAgB,EAChB,WAAwB,EACxB,IAAc,EACd,YAAqB,EACrB,QAAgB,EAAE,EAClB,SAAqB,EACrB,gBAA0B,EAAE,mFAAmF;IAC/G,UAA2B;QAzCpB,eAAU,GAAmB,EAAE,CAAC;QAChC,UAAK,GAAW,EAAE,CAAC;QACnB,WAAM,GAAiB,EAAE,CAAC;QAK3B,4BAAuB,GAAG,CAAC,CAAC;QAC5B,wBAAmB,GAAW,CAAC,CAAC;QAChC,uBAAkB,GAAW,CAAC,CAAC;QAGvC,WAAM,GAAe;YACnB,IAAI,EAAE,oBAAc,CAAC,KAAK;SAC3B,CAAC;QACF,YAAO,GAAW,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACjB,WAAM,GAAG,KAAK,CAAC;QACf,cAAS,GAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QA0BnC,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC;QACrB,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;QAChC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QAEnB,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,IAAI,CAAC,qBAAqB,GAAG,o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,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAC7B,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CACtE,CAAC;SACH;QAED,mDAAmD;QACnD,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAjVD,oBAiVC","sourcesContent":["/*\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 Context,\n diag,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanAttributes,\n SpanAttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n SpanStatusCode,\n TimeInput,\n} from '@opentelemetry/api';\nimport {\n addHrTimes,\n millisToHrTime,\n getTimeOrigin,\n hrTime,\n hrTimeDuration,\n InstrumentationLibrary,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport { IResource } from '@opentelemetry/resources';\nimport { SemanticAttributes } from '@opentelemetry/semantic-conventions';\nimport { ExceptionEventName } from './enums';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { SpanProcessor } from './SpanProcessor';\nimport { TimedEvent } from './TimedEvent';\nimport { Tracer } from './Tracer';\nimport { SpanLimits } from './types';\n\n/**\n * This class represents a span.\n */\nexport class Span implements APISpan, ReadableSpan {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanId?: string;\n readonly attributes: SpanAttributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: IResource;\n readonly instrumentationLibrary: InstrumentationLibrary;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new Span instance.\n *\n * @deprecated calling Span constructor directly is not supported. Please use tracer.startSpan.\n * */\n constructor(\n parentTracer: Tracer,\n context: Context,\n spanName: string,\n spanContext: SpanContext,\n kind: SpanKind,\n parentSpanId?: string,\n links: Link[] = [],\n startTime?: TimeInput,\n _deprecatedClock?: unknown, // keeping this argument even though it is unused to ensure backwards compatibility\n attributes?: SpanAttributes\n ) {\n this.name = spanName;\n this._spanContext = spanContext;\n this.parentSpanId = parentSpanId;\n this.kind = kind;\n this.links = links;\n\n const now = Date.now();\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + getTimeOrigin());\n this._startTimeProvided = startTime != null;\n\n this.startTime = this._getTime(startTime ?? now);\n\n this.resource = parentTracer.resource;\n this.instrumentationLibrary = parentTracer.instrumentationLibrary;\n this._spanLimits = parentTracer.getSpanLimits();\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit || 0;\n\n if (attributes != null) {\n this.setAttributes(attributes);\n }\n\n this._spanProcessor = parentTracer.getActiveSpanProcessor();\n this._spanProcessor.onStart(this, context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: SpanAttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n if (\n Object.keys(this.attributes).length >=\n this._spanLimits.attributeCountLimit! &&\n !Object.prototype.hasOwnProperty.call(this.attributes, key)\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n this.attributes[key] = this._truncateToSize(value);\n return this;\n }\n\n setAttributes(attributes: SpanAttributes): this {\n for (const [k, v] of Object.entries(attributes)) {\n this.setAttribute(k, v);\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: SpanAttributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n if (this._spanLimits.eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n if (this.events.length >= this._spanLimits.eventCountLimit!) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const attributes = sanitizeAttributes(attributesOrStartTime);\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount: 0,\n });\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n this.status = status;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this._ended = true;\n\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp < otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: SpanAttributes = {};\n if (typeof exception === 'string') {\n attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[SemanticAttributes.EXCEPTION_TYPE] =\n exception.code.toString();\n } else if (exception.name) {\n attributes[SemanticAttributes.EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[SemanticAttributes.EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (\n attributes[SemanticAttributes.EXCEPTION_TYPE] ||\n attributes[SemanticAttributes.EXCEPTION_MESSAGE]\n ) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n diag.warn(\n `Can not execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substr(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with truncated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: SpanAttributeValue): SpanAttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n}\n"]}

@@ -1,2 +0,2 @@

export declare const VERSION = "1.22.0";
export declare const VERSION = "1.23.0";
//# sourceMappingURL=version.d.ts.map

@@ -20,3 +20,3 @@ "use strict";

// this is autogenerated file, see scripts/version-update.js
exports.VERSION = '1.22.0';
exports.VERSION = '1.23.0';
//# sourceMappingURL=version.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["/*\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\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.22.0';\n"]}
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["/*\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\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.23.0';\n"]}
{
"name": "@opentelemetry/sdk-trace-base",
"version": "1.22.0",
"version": "1.23.0",
"description": "OpenTelemetry Tracing",

@@ -96,9 +96,9 @@ "main": "build/src/index.js",

"dependencies": {
"@opentelemetry/core": "1.22.0",
"@opentelemetry/resources": "1.22.0",
"@opentelemetry/semantic-conventions": "1.22.0"
"@opentelemetry/core": "1.23.0",
"@opentelemetry/resources": "1.23.0",
"@opentelemetry/semantic-conventions": "1.23.0"
},
"homepage": "https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-sdk-trace-base",
"sideEffects": false,
"gitHead": "7be35c7845e206b27b682e8ce1cee850b09cec04"
"gitHead": "5231aa255047fbc6ee3d6a299f4423ab2f8a5fbc"
}