feat: Complete zCode CLI X with Telegram bot integration

- Add full Telegram bot functionality with Z.AI API integration
- Implement 4 tools: Bash, FileEdit, WebSearch, Git
- Add 3 agents: Code Reviewer, Architect, DevOps Engineer
- Add 6 skills for common coding tasks
- Add systemd service file for 24/7 operation
- Add nginx configuration for HTTPS webhook
- Add comprehensive documentation
- Implement WebSocket server for real-time updates
- Add logging system with Winston
- Add environment validation

🤖 zCode CLI X - Agentic coder with Z.AI + Telegram integration
This commit is contained in:
admin
2026-05-05 09:01:26 +00:00
Unverified
parent 4a7035dd92
commit 875c7f9b91
24688 changed files with 3224957 additions and 221 deletions

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,178 @@
# OpenTelemetry Tracing SDK
[![NPM Published Version][npm-img]][npm-url]
[![Apache License][license-image]][license-image]
The `tracing` module contains the foundation for all tracing SDKs of [opentelemetry-js](https://github.com/open-telemetry/opentelemetry-js).
Used standalone, this module provides methods for manual instrumentation of code, offering full control over span creation for client-side JavaScript (browser) and Node.js.
It does **not** provide automated instrumentation of known libraries, context propagation for asynchronous invocations or distributed-context out-of-the-box.
For automated instrumentation for Node.js, please see
[@opentelemetry/sdk-trace-node](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-sdk-trace-node).
## Installation
```bash
npm install --save @opentelemetry/api
npm install --save @opentelemetry/sdk-trace-base
```
## Usage
```js
const opentelemetry = require('@opentelemetry/api');
const { BasicTracerProvider } = require('@opentelemetry/sdk-trace-base');
// To start a trace, you first need to initialize the Tracer provider.
// NOTE: The default OpenTelemetry tracer provider does not record any tracing information.
// Registering a working tracer provider allows the API methods to record traces.
new BasicTracerProvider().register();
// To create a span in a trace, we used the global singleton tracer to start a new span.
const span = opentelemetry.trace.getTracer('default').startSpan('foo');
// Set a span attribute
span.setAttribute('key', 'value');
// We must end the spans so they become available for exporting.
span.end();
```
## Config
Tracing configuration is a merge of user supplied configuration with both the default
configuration as specified in [config.ts](./src/config.ts) and an
environmentally configurable sampling (via `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG`).
## Built-in Samplers
Sampler is used to make decisions on `Span` sampling.
### AlwaysOn Sampler
Samples every trace regardless of upstream sampling decisions.
> This is used as a default Sampler
```js
const {
AlwaysOnSampler,
BasicTracerProvider,
} = require("@opentelemetry/sdk-trace-base");
const tracerProvider = new BasicTracerProvider({
sampler: new AlwaysOnSampler()
});
```
### AlwaysOff Sampler
Doesn't sample any trace, regardless of upstream sampling decisions.
```js
const {
AlwaysOffSampler,
BasicTracerProvider,
} = require("@opentelemetry/sdk-trace-base");
const tracerProvider = new BasicTracerProvider({
sampler: new AlwaysOffSampler()
});
```
### TraceIdRatioBased Sampler
Samples some percentage of traces, calculated deterministically using the trace ID.
Any trace that would be sampled at a given percentage will also be sampled at any higher percentage.
The `TraceIDRatioSampler` may be used with the `ParentBasedSampler` to respect the sampled flag of an incoming trace.
```js
const {
BasicTracerProvider,
TraceIdRatioBasedSampler,
} = require("@opentelemetry/sdk-trace-base");
const tracerProvider = new BasicTracerProvider({
// See details of ParentBasedSampler below
sampler: new ParentBasedSampler({
// Trace ID Ratio Sampler accepts a positional argument
// which represents the percentage of traces which should
// be sampled.
root: new TraceIdRatioBasedSampler(0.5)
});
});
```
### ParentBased Sampler
- This is a composite sampler. `ParentBased` helps distinguished between the
following cases:
- No parent (root span).
- Remote parent with `sampled` flag `true`
- Remote parent with `sampled` flag `false`
- Local parent with `sampled` flag `true`
- Local parent with `sampled` flag `false`
Required parameters:
- `root(Sampler)` - Sampler called for spans with no parent (root spans)
Optional parameters:
- `remoteParentSampled(Sampler)` (default: `AlwaysOn`)
- `remoteParentNotSampled(Sampler)` (default: `AlwaysOff`)
- `localParentSampled(Sampler)` (default: `AlwaysOn`)
- `localParentNotSampled(Sampler)` (default: `AlwaysOff`)
|Parent| parent.isRemote() | parent.isSampled()| Invoke sampler|
|--|--|--|--|
|absent| n/a | n/a |`root()`|
|present|true|true|`remoteParentSampled()`|
|present|true|false|`remoteParentNotSampled()`|
|present|false|true|`localParentSampled()`|
|present|false|false|`localParentNotSampled()`|
```js
const {
AlwaysOffSampler,
BasicTracerProvider,
ParentBasedSampler,
TraceIdRatioBasedSampler,
} = require("@opentelemetry/sdk-trace-base");
const tracerProvider = new BasicTracerProvider({
sampler: new ParentBasedSampler({
// By default, the ParentBasedSampler will respect the parent span's sampling
// decision. This is configurable by providing a different sampler to use
// based on the situation. See configuration details above.
//
// This will delegate the sampling decision of all root traces (no parent)
// to the TraceIdRatioBasedSampler.
// See details of TraceIdRatioBasedSampler above.
root: new TraceIdRatioBasedSampler(0.5)
})
});
```
## Example
See [examples/basic-tracer-node](https://github.com/open-telemetry/opentelemetry-js/tree/main/examples/basic-tracer-node) for an end-to-end example, including exporting created spans.
## Useful links
- For more information on OpenTelemetry, visit: <https://opentelemetry.io/>
- For more about OpenTelemetry JavaScript: <https://github.com/open-telemetry/opentelemetry-js>
- For help or feedback on this project, join us in [GitHub Discussions][discussions-url]
## License
Apache 2.0 - See [LICENSE][license-url] for more information.
[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions
[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/main/LICENSE
[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat
[npm-url]: https://www.npmjs.com/package/@opentelemetry/sdk-trace-base
[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fsdk-trace-base.svg

View File

@@ -0,0 +1,59 @@
import { TextMapPropagator, TracerProvider } from '@opentelemetry/api';
import { IResource } from '@opentelemetry/resources';
import { SpanProcessor } from './SpanProcessor';
import { Tracer } from './Tracer';
import { SDKRegistrationConfig, TracerConfig } from './types';
import { SpanExporter } from './export/SpanExporter';
export declare type PROPAGATOR_FACTORY = () => TextMapPropagator;
export declare type EXPORTER_FACTORY = () => SpanExporter;
export declare enum ForceFlushState {
'resolved' = 0,
'timeout' = 1,
'error' = 2,
'unresolved' = 3
}
/**
* This class represents a basic tracer provider which platform libraries can extend
*/
export declare class BasicTracerProvider implements TracerProvider {
protected static readonly _registeredPropagators: Map<string, PROPAGATOR_FACTORY>;
protected static readonly _registeredExporters: Map<string, EXPORTER_FACTORY>;
private readonly _config;
private readonly _registeredSpanProcessors;
private readonly _tracers;
activeSpanProcessor: SpanProcessor;
readonly resource: IResource;
constructor(config?: TracerConfig);
getTracer(name: string, version?: string, options?: {
schemaUrl?: string;
}): Tracer;
/**
* @deprecated please use {@link TracerConfig} spanProcessors property
* Adds a new {@link SpanProcessor} to this tracer.
* @param spanProcessor the new SpanProcessor to be added.
*/
addSpanProcessor(spanProcessor: SpanProcessor): void;
getActiveSpanProcessor(): SpanProcessor;
/**
* Register this TracerProvider for use with the OpenTelemetry API.
* Undefined values may be replaced with defaults, and
* null values will be skipped.
*
* @param config Configuration object for SDK registration
*/
register(config?: SDKRegistrationConfig): void;
forceFlush(): Promise<void>;
shutdown(): Promise<void>;
/**
* TS cannot yet infer the type of this.constructor:
* https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146
* There is no need to override either of the getters in your child class.
* The type of the registered component maps should be the same across all
* classes in the inheritance tree.
*/
protected _getPropagator(name: string): TextMapPropagator | undefined;
protected _getSpanExporter(name: string): SpanExporter | undefined;
protected _buildPropagatorFromEnv(): TextMapPropagator | undefined;
protected _buildExporterFromEnv(): SpanExporter | undefined;
}
//# sourceMappingURL=BasicTracerProvider.d.ts.map

View File

@@ -0,0 +1,242 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
import { context, diag, propagation, trace, } from '@opentelemetry/api';
import { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator, getEnv, merge, } from '@opentelemetry/core';
import { Resource } from '@opentelemetry/resources';
import { Tracer } from './Tracer';
import { loadDefaultConfig } from './config';
import { MultiSpanProcessor } from './MultiSpanProcessor';
import { NoopSpanProcessor } from './export/NoopSpanProcessor';
import { BatchSpanProcessor } from './platform';
import { reconfigureLimits } from './utility';
export var ForceFlushState;
(function (ForceFlushState) {
ForceFlushState[ForceFlushState["resolved"] = 0] = "resolved";
ForceFlushState[ForceFlushState["timeout"] = 1] = "timeout";
ForceFlushState[ForceFlushState["error"] = 2] = "error";
ForceFlushState[ForceFlushState["unresolved"] = 3] = "unresolved";
})(ForceFlushState || (ForceFlushState = {}));
/**
* This class represents a basic tracer provider which platform libraries can extend
*/
var BasicTracerProvider = /** @class */ (function () {
function BasicTracerProvider(config) {
if (config === void 0) { config = {}; }
var _a, _b;
this._registeredSpanProcessors = [];
this._tracers = new Map();
var mergedConfig = merge({}, loadDefaultConfig(), reconfigureLimits(config));
this.resource = (_a = mergedConfig.resource) !== null && _a !== void 0 ? _a : Resource.empty();
if (mergedConfig.mergeResourceWithDefaults) {
this.resource = Resource.default().merge(this.resource);
}
this._config = Object.assign({}, mergedConfig, {
resource: this.resource,
});
if ((_b = config.spanProcessors) === null || _b === void 0 ? void 0 : _b.length) {
this._registeredSpanProcessors = __spreadArray([], __read(config.spanProcessors), false);
this.activeSpanProcessor = new MultiSpanProcessor(this._registeredSpanProcessors);
}
else {
var defaultExporter = this._buildExporterFromEnv();
if (defaultExporter !== undefined) {
var batchProcessor = new BatchSpanProcessor(defaultExporter);
this.activeSpanProcessor = batchProcessor;
}
else {
this.activeSpanProcessor = new NoopSpanProcessor();
}
}
}
BasicTracerProvider.prototype.getTracer = function (name, version, options) {
var key = name + "@" + (version || '') + ":" + ((options === null || options === void 0 ? void 0 : options.schemaUrl) || '');
if (!this._tracers.has(key)) {
this._tracers.set(key, new Tracer({ name: name, version: version, schemaUrl: options === null || options === void 0 ? void 0 : options.schemaUrl }, this._config, this));
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this._tracers.get(key);
};
/**
* @deprecated please use {@link TracerConfig} spanProcessors property
* Adds a new {@link SpanProcessor} to this tracer.
* @param spanProcessor the new SpanProcessor to be added.
*/
BasicTracerProvider.prototype.addSpanProcessor = function (spanProcessor) {
if (this._registeredSpanProcessors.length === 0) {
// since we might have enabled by default a batchProcessor, we disable it
// before adding the new one
this.activeSpanProcessor
.shutdown()
.catch(function (err) {
return diag.error('Error while trying to shutdown current span processor', err);
});
}
this._registeredSpanProcessors.push(spanProcessor);
this.activeSpanProcessor = new MultiSpanProcessor(this._registeredSpanProcessors);
};
BasicTracerProvider.prototype.getActiveSpanProcessor = function () {
return this.activeSpanProcessor;
};
/**
* Register this TracerProvider for use with the OpenTelemetry API.
* Undefined values may be replaced with defaults, and
* null values will be skipped.
*
* @param config Configuration object for SDK registration
*/
BasicTracerProvider.prototype.register = function (config) {
if (config === void 0) { config = {}; }
trace.setGlobalTracerProvider(this);
if (config.propagator === undefined) {
config.propagator = this._buildPropagatorFromEnv();
}
if (config.contextManager) {
context.setGlobalContextManager(config.contextManager);
}
if (config.propagator) {
propagation.setGlobalPropagator(config.propagator);
}
};
BasicTracerProvider.prototype.forceFlush = function () {
var timeout = this._config.forceFlushTimeoutMillis;
var promises = this._registeredSpanProcessors.map(function (spanProcessor) {
return new Promise(function (resolve) {
var state;
var timeoutInterval = setTimeout(function () {
resolve(new Error("Span processor did not completed within timeout period of " + timeout + " ms"));
state = ForceFlushState.timeout;
}, timeout);
spanProcessor
.forceFlush()
.then(function () {
clearTimeout(timeoutInterval);
if (state !== ForceFlushState.timeout) {
state = ForceFlushState.resolved;
resolve(state);
}
})
.catch(function (error) {
clearTimeout(timeoutInterval);
state = ForceFlushState.error;
resolve(error);
});
});
});
return new Promise(function (resolve, reject) {
Promise.all(promises)
.then(function (results) {
var errors = results.filter(function (result) { return result !== ForceFlushState.resolved; });
if (errors.length > 0) {
reject(errors);
}
else {
resolve();
}
})
.catch(function (error) { return reject([error]); });
});
};
BasicTracerProvider.prototype.shutdown = function () {
return this.activeSpanProcessor.shutdown();
};
/**
* TS cannot yet infer the type of this.constructor:
* https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146
* There is no need to override either of the getters in your child class.
* The type of the registered component maps should be the same across all
* classes in the inheritance tree.
*/
BasicTracerProvider.prototype._getPropagator = function (name) {
var _a;
return (_a = this.constructor._registeredPropagators.get(name)) === null || _a === void 0 ? void 0 : _a();
};
BasicTracerProvider.prototype._getSpanExporter = function (name) {
var _a;
return (_a = this.constructor._registeredExporters.get(name)) === null || _a === void 0 ? void 0 : _a();
};
BasicTracerProvider.prototype._buildPropagatorFromEnv = function () {
var _this = this;
// per spec, propagators from env must be deduplicated
var uniquePropagatorNames = Array.from(new Set(getEnv().OTEL_PROPAGATORS));
var propagators = uniquePropagatorNames.map(function (name) {
var propagator = _this._getPropagator(name);
if (!propagator) {
diag.warn("Propagator \"" + name + "\" requested through environment variable is unavailable.");
}
return propagator;
});
var validPropagators = propagators.reduce(function (list, item) {
if (item) {
list.push(item);
}
return list;
}, []);
if (validPropagators.length === 0) {
return;
}
else if (uniquePropagatorNames.length === 1) {
return validPropagators[0];
}
else {
return new CompositePropagator({
propagators: validPropagators,
});
}
};
BasicTracerProvider.prototype._buildExporterFromEnv = function () {
var exporterName = getEnv().OTEL_TRACES_EXPORTER;
if (exporterName === 'none' || exporterName === '')
return;
var exporter = this._getSpanExporter(exporterName);
if (!exporter) {
diag.error("Exporter \"" + exporterName + "\" requested through environment variable is unavailable.");
}
return exporter;
};
BasicTracerProvider._registeredPropagators = new Map([
['tracecontext', function () { return new W3CTraceContextPropagator(); }],
['baggage', function () { return new W3CBaggagePropagator(); }],
]);
BasicTracerProvider._registeredExporters = new Map();
return BasicTracerProvider;
}());
export { BasicTracerProvider };
//# sourceMappingURL=BasicTracerProvider.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
/** IdGenerator provides an interface for generating Trace Id and Span Id */
export interface IdGenerator {
/** Returns a trace ID composed of 32 lowercase hex characters. */
generateTraceId(): string;
/** Returns a span ID composed of 16 lowercase hex characters. */
generateSpanId(): string;
}
//# sourceMappingURL=IdGenerator.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {};
//# sourceMappingURL=IdGenerator.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"IdGenerator.js","sourceRoot":"","sources":["../../src/IdGenerator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","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/** IdGenerator provides an interface for generating Trace Id and Span Id */\nexport interface IdGenerator {\n /** Returns a trace ID composed of 32 lowercase hex characters. */\n generateTraceId(): string;\n /** Returns a span ID composed of 16 lowercase hex characters. */\n generateSpanId(): string;\n}\n"]}

View File

@@ -0,0 +1,17 @@
import { Context } from '@opentelemetry/api';
import { ReadableSpan } from './export/ReadableSpan';
import { Span } from './Span';
import { SpanProcessor } from './SpanProcessor';
/**
* Implementation of the {@link SpanProcessor} that simply forwards all
* received events to a list of {@link SpanProcessor}s.
*/
export declare class MultiSpanProcessor implements SpanProcessor {
private readonly _spanProcessors;
constructor(_spanProcessors: SpanProcessor[]);
forceFlush(): Promise<void>;
onStart(span: Span, context: Context): void;
onEnd(span: ReadableSpan): void;
shutdown(): Promise<void>;
}
//# sourceMappingURL=MultiSpanProcessor.d.ts.map

View File

@@ -0,0 +1,120 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
import { globalErrorHandler } from '@opentelemetry/core';
/**
* Implementation of the {@link SpanProcessor} that simply forwards all
* received events to a list of {@link SpanProcessor}s.
*/
var MultiSpanProcessor = /** @class */ (function () {
function MultiSpanProcessor(_spanProcessors) {
this._spanProcessors = _spanProcessors;
}
MultiSpanProcessor.prototype.forceFlush = function () {
var e_1, _a;
var promises = [];
try {
for (var _b = __values(this._spanProcessors), _c = _b.next(); !_c.done; _c = _b.next()) {
var spanProcessor = _c.value;
promises.push(spanProcessor.forceFlush());
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
return new Promise(function (resolve) {
Promise.all(promises)
.then(function () {
resolve();
})
.catch(function (error) {
globalErrorHandler(error || new Error('MultiSpanProcessor: forceFlush failed'));
resolve();
});
});
};
MultiSpanProcessor.prototype.onStart = function (span, context) {
var e_2, _a;
try {
for (var _b = __values(this._spanProcessors), _c = _b.next(); !_c.done; _c = _b.next()) {
var spanProcessor = _c.value;
spanProcessor.onStart(span, context);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_2) throw e_2.error; }
}
};
MultiSpanProcessor.prototype.onEnd = function (span) {
var e_3, _a;
try {
for (var _b = __values(this._spanProcessors), _c = _b.next(); !_c.done; _c = _b.next()) {
var spanProcessor = _c.value;
spanProcessor.onEnd(span);
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_3) throw e_3.error; }
}
};
MultiSpanProcessor.prototype.shutdown = function () {
var e_4, _a;
var promises = [];
try {
for (var _b = __values(this._spanProcessors), _c = _b.next(); !_c.done; _c = _b.next()) {
var spanProcessor = _c.value;
promises.push(spanProcessor.shutdown());
}
}
catch (e_4_1) { e_4 = { error: e_4_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_4) throw e_4.error; }
}
return new Promise(function (resolve, reject) {
Promise.all(promises).then(function () {
resolve();
}, reject);
});
};
return MultiSpanProcessor;
}());
export { MultiSpanProcessor };
//# sourceMappingURL=MultiSpanProcessor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"MultiSpanProcessor.js","sourceRoot":"","sources":["../../src/MultiSpanProcessor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;AAGH,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAKzD;;;GAGG;AACH;IACE,4BAA6B,eAAgC;QAAhC,oBAAe,GAAf,eAAe,CAAiB;IAAG,CAAC;IAEjE,uCAAU,GAAV;;QACE,IAAM,QAAQ,GAAoB,EAAE,CAAC;;YAErC,KAA4B,IAAA,KAAA,SAAA,IAAI,CAAC,eAAe,CAAA,gBAAA,4BAAE;gBAA7C,IAAM,aAAa,WAAA;gBACtB,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,UAAU,EAAE,CAAC,CAAC;aAC3C;;;;;;;;;QACD,OAAO,IAAI,OAAO,CAAC,UAAA,OAAO;YACxB,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;iBAClB,IAAI,CAAC;gBACJ,OAAO,EAAE,CAAC;YACZ,CAAC,CAAC;iBACD,KAAK,CAAC,UAAA,KAAK;gBACV,kBAAkB,CAChB,KAAK,IAAI,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAC5D,CAAC;gBACF,OAAO,EAAE,CAAC;YACZ,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACL,CAAC;IAED,oCAAO,GAAP,UAAQ,IAAU,EAAE,OAAgB;;;YAClC,KAA4B,IAAA,KAAA,SAAA,IAAI,CAAC,eAAe,CAAA,gBAAA,4BAAE;gBAA7C,IAAM,aAAa,WAAA;gBACtB,aAAa,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;aACtC;;;;;;;;;IACH,CAAC;IAED,kCAAK,GAAL,UAAM,IAAkB;;;YACtB,KAA4B,IAAA,KAAA,SAAA,IAAI,CAAC,eAAe,CAAA,gBAAA,4BAAE;gBAA7C,IAAM,aAAa,WAAA;gBACtB,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;aAC3B;;;;;;;;;IACH,CAAC;IAED,qCAAQ,GAAR;;QACE,IAAM,QAAQ,GAAoB,EAAE,CAAC;;YAErC,KAA4B,IAAA,KAAA,SAAA,IAAI,CAAC,eAAe,CAAA,gBAAA,4BAAE;gBAA7C,IAAM,aAAa,WAAA;gBACtB,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC,CAAC;aACzC;;;;;;;;;QACD,OAAO,IAAI,OAAO,CAAC,UAAC,OAAO,EAAE,MAAM;YACjC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC;gBACzB,OAAO,EAAE,CAAC;YACZ,CAAC,EAAE,MAAM,CAAC,CAAC;QACb,CAAC,CAAC,CAAC;IACL,CAAC;IACH,yBAAC;AAAD,CAAC,AA/CD,IA+CC","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 } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { Span } from './Span';\nimport { SpanProcessor } from './SpanProcessor';\n\n/**\n * Implementation of the {@link SpanProcessor} that simply forwards all\n * received events to a list of {@link SpanProcessor}s.\n */\nexport class MultiSpanProcessor implements SpanProcessor {\n constructor(private readonly _spanProcessors: SpanProcessor[]) {}\n\n forceFlush(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.forceFlush());\n }\n return new Promise(resolve => {\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(error => {\n globalErrorHandler(\n error || new Error('MultiSpanProcessor: forceFlush failed')\n );\n resolve();\n });\n });\n }\n\n onStart(span: Span, context: Context): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onStart(span, context);\n }\n }\n\n onEnd(span: ReadableSpan): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onEnd(span);\n }\n }\n\n shutdown(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.shutdown());\n }\n return new Promise((resolve, reject) => {\n Promise.all(promises).then(() => {\n resolve();\n }, reject);\n });\n }\n}\n"]}

View File

@@ -0,0 +1,70 @@
import { Context, Link, SpanAttributes, SpanKind, TraceState } from '@opentelemetry/api';
/**
* A sampling decision that determines how a {@link Span} will be recorded
* and collected.
*/
export declare enum SamplingDecision {
/**
* `Span.isRecording() === false`, span will not be recorded and all events
* and attributes will be dropped.
*/
NOT_RECORD = 0,
/**
* `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}
* MUST NOT be set.
*/
RECORD = 1,
/**
* `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}
* MUST be set.
*/
RECORD_AND_SAMPLED = 2
}
/**
* A sampling result contains a decision for a {@link Span} and additional
* attributes the sampler would like to added to the Span.
*/
export interface SamplingResult {
/**
* A sampling decision, refer to {@link SamplingDecision} for details.
*/
decision: SamplingDecision;
/**
* The list of attributes returned by SamplingResult MUST be immutable.
* Caller may call {@link Sampler}.shouldSample any number of times and
* can safely cache the returned value.
*/
attributes?: Readonly<SpanAttributes>;
/**
* A {@link TraceState} that will be associated with the {@link Span} through
* the new {@link SpanContext}. Samplers SHOULD return the TraceState from
* the passed-in {@link Context} if they do not intend to change it. Leaving
* the value undefined will also leave the TraceState unchanged.
*/
traceState?: TraceState;
}
/**
* This interface represent a sampler. Sampling is a mechanism to control the
* noise and overhead introduced by OpenTelemetry by reducing the number of
* samples of traces collected and sent to the backend.
*/
export interface Sampler {
/**
* Checks whether span needs to be created and tracked.
*
* @param context Parent Context which may contain a span.
* @param traceId of the span to be created. It can be different from the
* traceId in the {@link SpanContext}. Typically in situations when the
* span to be created starts a new trace.
* @param spanName of the span to be created.
* @param spanKind of the span to be created.
* @param attributes Initial set of SpanAttributes for the Span being constructed.
* @param links Collection of links that will be associated with the Span to
* be created. Typically useful for batch operations.
* @returns a {@link SamplingResult}.
*/
shouldSample(context: Context, traceId: string, spanName: string, spanKind: SpanKind, attributes: SpanAttributes, links: Link[]): SamplingResult;
/** Returns the sampler name or short description with the configuration. */
toString(): string;
}
//# sourceMappingURL=Sampler.d.ts.map

View File

@@ -0,0 +1,38 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A sampling decision that determines how a {@link Span} will be recorded
* and collected.
*/
export var SamplingDecision;
(function (SamplingDecision) {
/**
* `Span.isRecording() === false`, span will not be recorded and all events
* and attributes will be dropped.
*/
SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD";
/**
* `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}
* MUST NOT be set.
*/
SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD";
/**
* `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}
* MUST be set.
*/
SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
})(SamplingDecision || (SamplingDecision = {}));
//# sourceMappingURL=Sampler.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Sampler.js","sourceRoot":"","sources":["../../src/Sampler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAUH;;;GAGG;AACH,MAAM,CAAN,IAAY,gBAgBX;AAhBD,WAAY,gBAAgB;IAC1B;;;OAGG;IACH,mEAAU,CAAA;IACV;;;OAGG;IACH,2DAAM,CAAA;IACN;;;OAGG;IACH,mFAAkB,CAAA;AACpB,CAAC,EAhBW,gBAAgB,KAAhB,gBAAgB,QAgB3B","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 Link,\n SpanAttributes,\n SpanKind,\n TraceState,\n} from '@opentelemetry/api';\n\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly<SpanAttributes>;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n\n/**\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of SpanAttributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: SpanAttributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n"]}

View File

@@ -0,0 +1,81 @@
import { Context, Exception, HrTime, Link, Span as APISpan, SpanAttributes, SpanAttributeValue, SpanContext, SpanKind, SpanStatus, TimeInput } from '@opentelemetry/api';
import { InstrumentationLibrary } from '@opentelemetry/core';
import { IResource } from '@opentelemetry/resources';
import { ReadableSpan } from './export/ReadableSpan';
import { TimedEvent } from './TimedEvent';
import { Tracer } from './Tracer';
/**
* This class represents a span.
*/
export declare class Span implements APISpan, ReadableSpan {
private readonly _spanContext;
readonly kind: SpanKind;
readonly parentSpanId?: string;
readonly attributes: SpanAttributes;
readonly links: Link[];
readonly events: TimedEvent[];
readonly startTime: HrTime;
readonly resource: IResource;
readonly instrumentationLibrary: InstrumentationLibrary;
private _droppedAttributesCount;
private _droppedEventsCount;
private _droppedLinksCount;
name: string;
status: SpanStatus;
endTime: HrTime;
private _ended;
private _duration;
private readonly _spanProcessor;
private readonly _spanLimits;
private readonly _attributeValueLengthLimit;
private readonly _performanceStartTime;
private readonly _performanceOffset;
private readonly _startTimeProvided;
/**
* Constructs a new Span instance.
*
* @deprecated calling Span constructor directly is not supported. Please use tracer.startSpan.
* */
constructor(parentTracer: Tracer, context: Context, spanName: string, spanContext: SpanContext, kind: SpanKind, parentSpanId?: string, links?: Link[], startTime?: TimeInput, _deprecatedClock?: unknown, // keeping this argument even though it is unused to ensure backwards compatibility
attributes?: SpanAttributes);
spanContext(): SpanContext;
setAttribute(key: string, value?: SpanAttributeValue): this;
setAttributes(attributes: SpanAttributes): this;
/**
*
* @param name Span Name
* @param [attributesOrStartTime] Span attributes or start time
* if type is {@type TimeInput} and 3rd param is undefined
* @param [timeStamp] Specified time stamp for the event
*/
addEvent(name: string, attributesOrStartTime?: SpanAttributes | TimeInput, timeStamp?: TimeInput): this;
addLink(link: Link): this;
addLinks(links: Link[]): this;
setStatus(status: SpanStatus): this;
updateName(name: string): this;
end(endTime?: TimeInput): void;
private _getTime;
isRecording(): boolean;
recordException(exception: Exception, time?: TimeInput): void;
get duration(): HrTime;
get ended(): boolean;
get droppedAttributesCount(): number;
get droppedEventsCount(): number;
get droppedLinksCount(): number;
private _isSpanEnded;
private _truncateToLimitUtil;
/**
* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with truncated to {@code attributeValueLengthLimit} characters
*
* If the given attribute value is array of strings then
* return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
*
* Otherwise return same Attribute {@code value}
*
* @param value Attribute value
* @returns truncated attribute value if required, otherwise same value
*/
private _truncateToSize;
}
//# sourceMappingURL=Span.d.ts.map

View File

@@ -0,0 +1,378 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
import { diag, SpanStatusCode, } from '@opentelemetry/api';
import { addHrTimes, millisToHrTime, getTimeOrigin, hrTime, hrTimeDuration, isAttributeValue, isTimeInput, isTimeInputHrTime, otperformance, sanitizeAttributes, } from '@opentelemetry/core';
import { SEMATTRS_EXCEPTION_MESSAGE, SEMATTRS_EXCEPTION_STACKTRACE, SEMATTRS_EXCEPTION_TYPE, } from '@opentelemetry/semantic-conventions';
import { ExceptionEventName } from './enums';
/**
* This class represents a span.
*/
var Span = /** @class */ (function () {
/**
* Constructs a new Span instance.
*
* @deprecated calling Span constructor directly is not supported. Please use tracer.startSpan.
* */
function Span(parentTracer, context, spanName, spanContext, kind, parentSpanId, links, startTime, _deprecatedClock, // keeping this argument even though it is unused to ensure backwards compatibility
attributes) {
if (links === void 0) { links = []; }
this.attributes = {};
this.links = [];
this.events = [];
this._droppedAttributesCount = 0;
this._droppedEventsCount = 0;
this._droppedLinksCount = 0;
this.status = {
code: SpanStatusCode.UNSET,
};
this.endTime = [0, 0];
this._ended = false;
this._duration = [-1, -1];
this.name = spanName;
this._spanContext = spanContext;
this.parentSpanId = parentSpanId;
this.kind = kind;
this.links = links;
var now = Date.now();
this._performanceStartTime = otperformance.now();
this._performanceOffset =
now - (this._performanceStartTime + getTimeOrigin());
this._startTimeProvided = startTime != null;
this.startTime = this._getTime(startTime !== null && startTime !== void 0 ? startTime : now);
this.resource = parentTracer.resource;
this.instrumentationLibrary = parentTracer.instrumentationLibrary;
this._spanLimits = parentTracer.getSpanLimits();
this._attributeValueLengthLimit =
this._spanLimits.attributeValueLengthLimit || 0;
if (attributes != null) {
this.setAttributes(attributes);
}
this._spanProcessor = parentTracer.getActiveSpanProcessor();
this._spanProcessor.onStart(this, context);
}
Span.prototype.spanContext = function () {
return this._spanContext;
};
Span.prototype.setAttribute = function (key, value) {
if (value == null || this._isSpanEnded())
return this;
if (key.length === 0) {
diag.warn("Invalid attribute key: " + key);
return this;
}
if (!isAttributeValue(value)) {
diag.warn("Invalid attribute value set for key: " + key);
return this;
}
if (Object.keys(this.attributes).length >=
this._spanLimits.attributeCountLimit &&
!Object.prototype.hasOwnProperty.call(this.attributes, key)) {
this._droppedAttributesCount++;
return this;
}
this.attributes[key] = this._truncateToSize(value);
return this;
};
Span.prototype.setAttributes = function (attributes) {
var e_1, _a;
try {
for (var _b = __values(Object.entries(attributes)), _c = _b.next(); !_c.done; _c = _b.next()) {
var _d = __read(_c.value, 2), k = _d[0], v = _d[1];
this.setAttribute(k, v);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
return this;
};
/**
*
* @param name Span Name
* @param [attributesOrStartTime] Span attributes or start time
* if type is {@type TimeInput} and 3rd param is undefined
* @param [timeStamp] Specified time stamp for the event
*/
Span.prototype.addEvent = function (name, attributesOrStartTime, timeStamp) {
if (this._isSpanEnded())
return this;
if (this._spanLimits.eventCountLimit === 0) {
diag.warn('No events allowed.');
this._droppedEventsCount++;
return this;
}
if (this.events.length >= this._spanLimits.eventCountLimit) {
if (this._droppedEventsCount === 0) {
diag.debug('Dropping extra events.');
}
this.events.shift();
this._droppedEventsCount++;
}
if (isTimeInput(attributesOrStartTime)) {
if (!isTimeInput(timeStamp)) {
timeStamp = attributesOrStartTime;
}
attributesOrStartTime = undefined;
}
var attributes = sanitizeAttributes(attributesOrStartTime);
this.events.push({
name: name,
attributes: attributes,
time: this._getTime(timeStamp),
droppedAttributesCount: 0,
});
return this;
};
Span.prototype.addLink = function (link) {
this.links.push(link);
return this;
};
Span.prototype.addLinks = function (links) {
var _a;
(_a = this.links).push.apply(_a, __spreadArray([], __read(links), false));
return this;
};
Span.prototype.setStatus = function (status) {
if (this._isSpanEnded())
return this;
this.status = __assign({}, status);
// When using try-catch, the caught "error" is of type `any`. When then assigning `any` to `status.message`,
// TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()
// as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or
// undefined to avoid an incorrect type causing issues downstream.
if (this.status.message != null && typeof status.message !== 'string') {
diag.warn("Dropping invalid status.message of type '" + typeof status.message + "', expected 'string'");
delete this.status.message;
}
return this;
};
Span.prototype.updateName = function (name) {
if (this._isSpanEnded())
return this;
this.name = name;
return this;
};
Span.prototype.end = function (endTime) {
if (this._isSpanEnded()) {
diag.error(this.name + " " + this._spanContext.traceId + "-" + this._spanContext.spanId + " - You can only call end() on a span once.");
return;
}
this._ended = true;
this.endTime = this._getTime(endTime);
this._duration = hrTimeDuration(this.startTime, this.endTime);
if (this._duration[0] < 0) {
diag.warn('Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.', this.startTime, this.endTime);
this.endTime = this.startTime.slice();
this._duration = [0, 0];
}
if (this._droppedEventsCount > 0) {
diag.warn("Dropped " + this._droppedEventsCount + " events because eventCountLimit reached");
}
this._spanProcessor.onEnd(this);
};
Span.prototype._getTime = function (inp) {
if (typeof inp === 'number' && inp <= otperformance.now()) {
// must be a performance timestamp
// apply correction and convert to hrtime
return hrTime(inp + this._performanceOffset);
}
if (typeof inp === 'number') {
return millisToHrTime(inp);
}
if (inp instanceof Date) {
return millisToHrTime(inp.getTime());
}
if (isTimeInputHrTime(inp)) {
return inp;
}
if (this._startTimeProvided) {
// if user provided a time for the start manually
// we can't use duration to calculate event/end times
return millisToHrTime(Date.now());
}
var msDuration = otperformance.now() - this._performanceStartTime;
return addHrTimes(this.startTime, millisToHrTime(msDuration));
};
Span.prototype.isRecording = function () {
return this._ended === false;
};
Span.prototype.recordException = function (exception, time) {
var attributes = {};
if (typeof exception === 'string') {
attributes[SEMATTRS_EXCEPTION_MESSAGE] = exception;
}
else if (exception) {
if (exception.code) {
attributes[SEMATTRS_EXCEPTION_TYPE] = exception.code.toString();
}
else if (exception.name) {
attributes[SEMATTRS_EXCEPTION_TYPE] = exception.name;
}
if (exception.message) {
attributes[SEMATTRS_EXCEPTION_MESSAGE] = exception.message;
}
if (exception.stack) {
attributes[SEMATTRS_EXCEPTION_STACKTRACE] = exception.stack;
}
}
// these are minimum requirements from spec
if (attributes[SEMATTRS_EXCEPTION_TYPE] ||
attributes[SEMATTRS_EXCEPTION_MESSAGE]) {
this.addEvent(ExceptionEventName, attributes, time);
}
else {
diag.warn("Failed to record an exception " + exception);
}
};
Object.defineProperty(Span.prototype, "duration", {
get: function () {
return this._duration;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Span.prototype, "ended", {
get: function () {
return this._ended;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Span.prototype, "droppedAttributesCount", {
get: function () {
return this._droppedAttributesCount;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Span.prototype, "droppedEventsCount", {
get: function () {
return this._droppedEventsCount;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Span.prototype, "droppedLinksCount", {
get: function () {
return this._droppedLinksCount;
},
enumerable: false,
configurable: true
});
Span.prototype._isSpanEnded = function () {
if (this._ended) {
diag.warn("Can not execute the operation on ended Span {traceId: " + this._spanContext.traceId + ", spanId: " + this._spanContext.spanId + "}");
}
return this._ended;
};
// Utility function to truncate given value within size
// for value type of string, will truncate to given limit
// for type of non-string, will return same value
Span.prototype._truncateToLimitUtil = function (value, limit) {
if (value.length <= limit) {
return value;
}
return value.substring(0, limit);
};
/**
* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with truncated to {@code attributeValueLengthLimit} characters
*
* If the given attribute value is array of strings then
* return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
*
* Otherwise return same Attribute {@code value}
*
* @param value Attribute value
* @returns truncated attribute value if required, otherwise same value
*/
Span.prototype._truncateToSize = function (value) {
var _this = this;
var limit = this._attributeValueLengthLimit;
// Check limit
if (limit <= 0) {
// Negative values are invalid, so do not truncate
diag.warn("Attribute value limit must be positive, got " + limit);
return value;
}
// String
if (typeof value === 'string') {
return this._truncateToLimitUtil(value, limit);
}
// Array of strings
if (Array.isArray(value)) {
return value.map(function (val) {
return typeof val === 'string' ? _this._truncateToLimitUtil(val, limit) : val;
});
}
// Other types, no need to apply value length limit
return value;
};
return Span;
}());
export { Span };
//# sourceMappingURL=Span.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,31 @@
import { Context } from '@opentelemetry/api';
import { ReadableSpan } from './export/ReadableSpan';
import { Span } from './Span';
/**
* SpanProcessor is the interface Tracer SDK uses to allow synchronous hooks
* for when a {@link Span} is started or when a {@link Span} is ended.
*/
export interface SpanProcessor {
/**
* Forces to export all finished spans
*/
forceFlush(): Promise<void>;
/**
* Called when a {@link Span} is started, if the `span.isRecording()`
* returns true.
* @param span the Span that just started.
*/
onStart(span: Span, parentContext: Context): void;
/**
* Called when a {@link ReadableSpan} is ended, if the `span.isRecording()`
* returns true.
* @param span the Span that just ended.
*/
onEnd(span: ReadableSpan): void;
/**
* Shuts down the processor. Called when SDK is shut down. This is an
* opportunity for processor to do any cleanup required.
*/
shutdown(): Promise<void>;
}
//# sourceMappingURL=SpanProcessor.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {};
//# sourceMappingURL=SpanProcessor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"SpanProcessor.js","sourceRoot":"","sources":["../../src/SpanProcessor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","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 } from '@opentelemetry/api';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { Span } from './Span';\n\n/**\n * SpanProcessor is the interface Tracer SDK uses to allow synchronous hooks\n * for when a {@link Span} is started or when a {@link Span} is ended.\n */\nexport interface SpanProcessor {\n /**\n * Forces to export all finished spans\n */\n forceFlush(): Promise<void>;\n\n /**\n * Called when a {@link Span} is started, if the `span.isRecording()`\n * returns true.\n * @param span the Span that just started.\n */\n onStart(span: Span, parentContext: Context): void;\n\n /**\n * Called when a {@link ReadableSpan} is ended, if the `span.isRecording()`\n * returns true.\n * @param span the Span that just ended.\n */\n onEnd(span: ReadableSpan): void;\n\n /**\n * Shuts down the processor. Called when SDK is shut down. This is an\n * opportunity for processor to do any cleanup required.\n */\n shutdown(): Promise<void>;\n}\n"]}

View File

@@ -0,0 +1,15 @@
import { HrTime, SpanAttributes } from '@opentelemetry/api';
/**
* Represents a timed event.
* A timed event is an event with a timestamp.
*/
export interface TimedEvent {
time: HrTime;
/** The name of the event. */
name: string;
/** The attributes of the event. */
attributes?: SpanAttributes;
/** Count of attributes of the event that were dropped due to collection limits */
droppedAttributesCount?: number;
}
//# sourceMappingURL=TimedEvent.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {};
//# sourceMappingURL=TimedEvent.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"TimedEvent.js","sourceRoot":"","sources":["../../src/TimedEvent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","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 { HrTime, SpanAttributes } from '@opentelemetry/api';\n\n/**\n * Represents a timed event.\n * A timed event is an event with a timestamp.\n */\nexport interface TimedEvent {\n time: HrTime;\n /** The name of the event. */\n name: string;\n /** The attributes of the event. */\n attributes?: SpanAttributes;\n /** Count of attributes of the event that were dropped due to collection limits */\n droppedAttributesCount?: number;\n}\n"]}

View File

@@ -0,0 +1,79 @@
import * as api from '@opentelemetry/api';
import { InstrumentationLibrary } from '@opentelemetry/core';
import { IResource } from '@opentelemetry/resources';
import { BasicTracerProvider } from './BasicTracerProvider';
import { GeneralLimits, SpanLimits, TracerConfig } from './types';
import { SpanProcessor } from './SpanProcessor';
/**
* This class represents a basic tracer.
*/
export declare class Tracer implements api.Tracer {
private _tracerProvider;
private readonly _sampler;
private readonly _generalLimits;
private readonly _spanLimits;
private readonly _idGenerator;
readonly resource: IResource;
readonly instrumentationLibrary: InstrumentationLibrary;
/**
* Constructs a new Tracer instance.
*/
constructor(instrumentationLibrary: InstrumentationLibrary, config: TracerConfig, _tracerProvider: BasicTracerProvider);
/**
* Starts a new Span or returns the default NoopSpan based on the sampling
* decision.
*/
startSpan(name: string, options?: api.SpanOptions, context?: api.Context): api.Span;
/**
* Starts a new {@link Span} and calls the given function passing it the
* created span as first argument.
* Additionally the new span gets set in context and this context is activated
* for the duration of the function call.
*
* @param name The name of the span
* @param [options] SpanOptions used for span creation
* @param [context] Context to use to extract parent
* @param fn function called in the context of the span and receives the newly created span as an argument
* @returns return value of fn
* @example
* const something = tracer.startActiveSpan('op', span => {
* try {
* do some work
* span.setStatus({code: SpanStatusCode.OK});
* return something;
* } catch (err) {
* span.setStatus({
* code: SpanStatusCode.ERROR,
* message: err.message,
* });
* throw err;
* } finally {
* span.end();
* }
* });
* @example
* const span = tracer.startActiveSpan('op', span => {
* try {
* do some work
* return span;
* } catch (err) {
* span.setStatus({
* code: SpanStatusCode.ERROR,
* message: err.message,
* });
* throw err;
* }
* });
* do some more work
* span.end();
*/
startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(name: string, fn: F): ReturnType<F>;
startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(name: string, opts: api.SpanOptions, fn: F): ReturnType<F>;
startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(name: string, opts: api.SpanOptions, ctx: api.Context, fn: F): ReturnType<F>;
/** Returns the active {@link GeneralLimits}. */
getGeneralLimits(): GeneralLimits;
/** Returns the active {@link SpanLimits}. */
getSpanLimits(): SpanLimits;
getActiveSpanProcessor(): SpanProcessor;
}
//# sourceMappingURL=Tracer.d.ts.map

View File

@@ -0,0 +1,136 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as api from '@opentelemetry/api';
import { sanitizeAttributes, isTracingSuppressed, } from '@opentelemetry/core';
import { Span } from './Span';
import { mergeConfig } from './utility';
import { RandomIdGenerator } from './platform';
/**
* This class represents a basic tracer.
*/
var Tracer = /** @class */ (function () {
/**
* Constructs a new Tracer instance.
*/
function Tracer(instrumentationLibrary, config, _tracerProvider) {
this._tracerProvider = _tracerProvider;
var localConfig = mergeConfig(config);
this._sampler = localConfig.sampler;
this._generalLimits = localConfig.generalLimits;
this._spanLimits = localConfig.spanLimits;
this._idGenerator = config.idGenerator || new RandomIdGenerator();
this.resource = _tracerProvider.resource;
this.instrumentationLibrary = instrumentationLibrary;
}
/**
* Starts a new Span or returns the default NoopSpan based on the sampling
* decision.
*/
Tracer.prototype.startSpan = function (name, options, context) {
var _a, _b, _c;
if (options === void 0) { options = {}; }
if (context === void 0) { context = api.context.active(); }
// remove span from context in case a root span is requested via options
if (options.root) {
context = api.trace.deleteSpan(context);
}
var parentSpan = api.trace.getSpan(context);
if (isTracingSuppressed(context)) {
api.diag.debug('Instrumentation suppressed, returning Noop Span');
var nonRecordingSpan = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT);
return nonRecordingSpan;
}
var parentSpanContext = parentSpan === null || parentSpan === void 0 ? void 0 : parentSpan.spanContext();
var spanId = this._idGenerator.generateSpanId();
var traceId;
var traceState;
var parentSpanId;
if (!parentSpanContext ||
!api.trace.isSpanContextValid(parentSpanContext)) {
// New root span.
traceId = this._idGenerator.generateTraceId();
}
else {
// New child span.
traceId = parentSpanContext.traceId;
traceState = parentSpanContext.traceState;
parentSpanId = parentSpanContext.spanId;
}
var spanKind = (_a = options.kind) !== null && _a !== void 0 ? _a : api.SpanKind.INTERNAL;
var links = ((_b = options.links) !== null && _b !== void 0 ? _b : []).map(function (link) {
return {
context: link.context,
attributes: sanitizeAttributes(link.attributes),
};
});
var attributes = sanitizeAttributes(options.attributes);
// make sampling decision
var samplingResult = this._sampler.shouldSample(context, traceId, name, spanKind, attributes, links);
traceState = (_c = samplingResult.traceState) !== null && _c !== void 0 ? _c : traceState;
var traceFlags = samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED
? api.TraceFlags.SAMPLED
: api.TraceFlags.NONE;
var spanContext = { traceId: traceId, spanId: spanId, traceFlags: traceFlags, traceState: traceState };
if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {
api.diag.debug('Recording is off, propagating context in a non-recording span');
var nonRecordingSpan = api.trace.wrapSpanContext(spanContext);
return nonRecordingSpan;
}
// Set initial span attributes. The attributes object may have been mutated
// by the sampler, so we sanitize the merged attributes before setting them.
var initAttributes = sanitizeAttributes(Object.assign(attributes, samplingResult.attributes));
var span = new Span(this, context, name, spanContext, spanKind, parentSpanId, links, options.startTime, undefined, initAttributes);
return span;
};
Tracer.prototype.startActiveSpan = function (name, arg2, arg3, arg4) {
var opts;
var ctx;
var fn;
if (arguments.length < 2) {
return;
}
else if (arguments.length === 2) {
fn = arg2;
}
else if (arguments.length === 3) {
opts = arg2;
fn = arg3;
}
else {
opts = arg2;
ctx = arg3;
fn = arg4;
}
var parentContext = ctx !== null && ctx !== void 0 ? ctx : api.context.active();
var span = this.startSpan(name, opts, parentContext);
var contextWithSpanSet = api.trace.setSpan(parentContext, span);
return api.context.with(contextWithSpanSet, fn, undefined, span);
};
/** Returns the active {@link GeneralLimits}. */
Tracer.prototype.getGeneralLimits = function () {
return this._generalLimits;
};
/** Returns the active {@link SpanLimits}. */
Tracer.prototype.getSpanLimits = function () {
return this._spanLimits;
};
Tracer.prototype.getActiveSpanProcessor = function () {
return this._tracerProvider.getActiveSpanProcessor();
};
return Tracer;
}());
export { Tracer };
//# sourceMappingURL=Tracer.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,31 @@
import { ENVIRONMENT } from '@opentelemetry/core';
import { Sampler } from './Sampler';
/**
* Load default configuration. For fields with primitive values, any user-provided
* value will override the corresponding default value. For fields with
* non-primitive values (like `spanLimits`), the user-provided value will be
* used to extend the default value.
*/
export declare function loadDefaultConfig(): {
sampler: Sampler;
forceFlushTimeoutMillis: number;
generalLimits: {
attributeValueLengthLimit: number;
attributeCountLimit: number;
};
spanLimits: {
attributeValueLengthLimit: number;
attributeCountLimit: number;
linkCountLimit: number;
eventCountLimit: number;
attributePerEventCountLimit: number;
attributePerLinkCountLimit: number;
};
mergeResourceWithDefaults: boolean;
};
/**
* Based on environment, builds a sampler, complies with specification.
* @param environment optional, by default uses getEnv(), but allows passing a value to reuse parsed environment
*/
export declare function buildSamplerFromEnv(environment?: Required<ENVIRONMENT>): Sampler;
//# sourceMappingURL=config.d.ts.map

View File

@@ -0,0 +1,99 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { diag } from '@opentelemetry/api';
import { getEnv, TracesSamplerValues } from '@opentelemetry/core';
import { AlwaysOffSampler } from './sampler/AlwaysOffSampler';
import { AlwaysOnSampler } from './sampler/AlwaysOnSampler';
import { ParentBasedSampler } from './sampler/ParentBasedSampler';
import { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';
var FALLBACK_OTEL_TRACES_SAMPLER = TracesSamplerValues.AlwaysOn;
var DEFAULT_RATIO = 1;
/**
* Load default configuration. For fields with primitive values, any user-provided
* value will override the corresponding default value. For fields with
* non-primitive values (like `spanLimits`), the user-provided value will be
* used to extend the default value.
*/
// object needs to be wrapped in this function and called when needed otherwise
// envs are parsed before tests are ran - causes tests using these envs to fail
export function loadDefaultConfig() {
var env = getEnv();
return {
sampler: buildSamplerFromEnv(env),
forceFlushTimeoutMillis: 30000,
generalLimits: {
attributeValueLengthLimit: env.OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT,
attributeCountLimit: env.OTEL_ATTRIBUTE_COUNT_LIMIT,
},
spanLimits: {
attributeValueLengthLimit: env.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,
attributeCountLimit: env.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
linkCountLimit: env.OTEL_SPAN_LINK_COUNT_LIMIT,
eventCountLimit: env.OTEL_SPAN_EVENT_COUNT_LIMIT,
attributePerEventCountLimit: env.OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,
attributePerLinkCountLimit: env.OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,
},
mergeResourceWithDefaults: true,
};
}
/**
* Based on environment, builds a sampler, complies with specification.
* @param environment optional, by default uses getEnv(), but allows passing a value to reuse parsed environment
*/
export function buildSamplerFromEnv(environment) {
if (environment === void 0) { environment = getEnv(); }
switch (environment.OTEL_TRACES_SAMPLER) {
case TracesSamplerValues.AlwaysOn:
return new AlwaysOnSampler();
case TracesSamplerValues.AlwaysOff:
return new AlwaysOffSampler();
case TracesSamplerValues.ParentBasedAlwaysOn:
return new ParentBasedSampler({
root: new AlwaysOnSampler(),
});
case TracesSamplerValues.ParentBasedAlwaysOff:
return new ParentBasedSampler({
root: new AlwaysOffSampler(),
});
case TracesSamplerValues.TraceIdRatio:
return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv(environment));
case TracesSamplerValues.ParentBasedTraceIdRatio:
return new ParentBasedSampler({
root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv(environment)),
});
default:
diag.error("OTEL_TRACES_SAMPLER value \"" + environment.OTEL_TRACES_SAMPLER + " invalid, defaulting to " + FALLBACK_OTEL_TRACES_SAMPLER + "\".");
return new AlwaysOnSampler();
}
}
function getSamplerProbabilityFromEnv(environment) {
if (environment.OTEL_TRACES_SAMPLER_ARG === undefined ||
environment.OTEL_TRACES_SAMPLER_ARG === '') {
diag.error("OTEL_TRACES_SAMPLER_ARG is blank, defaulting to " + DEFAULT_RATIO + ".");
return DEFAULT_RATIO;
}
var probability = Number(environment.OTEL_TRACES_SAMPLER_ARG);
if (isNaN(probability)) {
diag.error("OTEL_TRACES_SAMPLER_ARG=" + environment.OTEL_TRACES_SAMPLER_ARG + " was given, but it is invalid, defaulting to " + DEFAULT_RATIO + ".");
return DEFAULT_RATIO;
}
if (probability < 0 || probability > 1) {
diag.error("OTEL_TRACES_SAMPLER_ARG=" + environment.OTEL_TRACES_SAMPLER_ARG + " was given, but it is out of range ([0..1]), defaulting to " + DEFAULT_RATIO + ".");
return DEFAULT_RATIO;
}
return probability;
}
//# sourceMappingURL=config.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export declare const ExceptionEventName = "exception";
//# sourceMappingURL=enums.d.ts.map

View File

@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Event name definitions
export var ExceptionEventName = 'exception';
//# sourceMappingURL=enums.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"enums.js","sourceRoot":"","sources":["../../src/enums.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,yBAAyB;AACzB,MAAM,CAAC,IAAM,kBAAkB,GAAG,WAAW,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// Event name definitions\nexport const ExceptionEventName = 'exception';\n"]}

View File

@@ -0,0 +1,41 @@
import { Context } from '@opentelemetry/api';
import { Span } from '../Span';
import { SpanProcessor } from '../SpanProcessor';
import { BufferConfig } from '../types';
import { ReadableSpan } from './ReadableSpan';
import { SpanExporter } from './SpanExporter';
/**
* Implementation of the {@link SpanProcessor} that batches spans exported by
* the SDK then pushes them to the exporter pipeline.
*/
export declare abstract class BatchSpanProcessorBase<T extends BufferConfig> implements SpanProcessor {
private readonly _exporter;
private readonly _maxExportBatchSize;
private readonly _maxQueueSize;
private readonly _scheduledDelayMillis;
private readonly _exportTimeoutMillis;
private _isExporting;
private _finishedSpans;
private _timer;
private _shutdownOnce;
private _droppedSpansCount;
constructor(_exporter: SpanExporter, config?: T);
forceFlush(): Promise<void>;
onStart(_span: Span, _parentContext: Context): void;
onEnd(span: ReadableSpan): void;
shutdown(): Promise<void>;
private _shutdown;
/** Add a span in the buffer. */
private _addToBuffer;
/**
* Send all spans to the exporter respecting the batch size limit
* This function is used only on forceFlush or shutdown,
* for all other cases _flush should be used
* */
private _flushAll;
private _flushOneBatch;
private _maybeStartTimer;
private _clearTimer;
protected abstract onShutdown(): void;
}
//# sourceMappingURL=BatchSpanProcessorBase.d.ts.map

View File

@@ -0,0 +1,218 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { context, diag, TraceFlags } from '@opentelemetry/api';
import { BindOnceFuture, ExportResultCode, getEnv, globalErrorHandler, suppressTracing, unrefTimer, } from '@opentelemetry/core';
/**
* Implementation of the {@link SpanProcessor} that batches spans exported by
* the SDK then pushes them to the exporter pipeline.
*/
var BatchSpanProcessorBase = /** @class */ (function () {
function BatchSpanProcessorBase(_exporter, config) {
this._exporter = _exporter;
this._isExporting = false;
this._finishedSpans = [];
this._droppedSpansCount = 0;
var env = getEnv();
this._maxExportBatchSize =
typeof (config === null || config === void 0 ? void 0 : config.maxExportBatchSize) === 'number'
? config.maxExportBatchSize
: env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;
this._maxQueueSize =
typeof (config === null || config === void 0 ? void 0 : config.maxQueueSize) === 'number'
? config.maxQueueSize
: env.OTEL_BSP_MAX_QUEUE_SIZE;
this._scheduledDelayMillis =
typeof (config === null || config === void 0 ? void 0 : config.scheduledDelayMillis) === 'number'
? config.scheduledDelayMillis
: env.OTEL_BSP_SCHEDULE_DELAY;
this._exportTimeoutMillis =
typeof (config === null || config === void 0 ? void 0 : config.exportTimeoutMillis) === 'number'
? config.exportTimeoutMillis
: env.OTEL_BSP_EXPORT_TIMEOUT;
this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
if (this._maxExportBatchSize > this._maxQueueSize) {
diag.warn('BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize');
this._maxExportBatchSize = this._maxQueueSize;
}
}
BatchSpanProcessorBase.prototype.forceFlush = function () {
if (this._shutdownOnce.isCalled) {
return this._shutdownOnce.promise;
}
return this._flushAll();
};
// does nothing.
BatchSpanProcessorBase.prototype.onStart = function (_span, _parentContext) { };
BatchSpanProcessorBase.prototype.onEnd = function (span) {
if (this._shutdownOnce.isCalled) {
return;
}
if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {
return;
}
this._addToBuffer(span);
};
BatchSpanProcessorBase.prototype.shutdown = function () {
return this._shutdownOnce.call();
};
BatchSpanProcessorBase.prototype._shutdown = function () {
var _this = this;
return Promise.resolve()
.then(function () {
return _this.onShutdown();
})
.then(function () {
return _this._flushAll();
})
.then(function () {
return _this._exporter.shutdown();
});
};
/** Add a span in the buffer. */
BatchSpanProcessorBase.prototype._addToBuffer = function (span) {
if (this._finishedSpans.length >= this._maxQueueSize) {
// limit reached, drop span
if (this._droppedSpansCount === 0) {
diag.debug('maxQueueSize reached, dropping spans');
}
this._droppedSpansCount++;
return;
}
if (this._droppedSpansCount > 0) {
// some spans were dropped, log once with count of spans dropped
diag.warn("Dropped " + this._droppedSpansCount + " spans because maxQueueSize reached");
this._droppedSpansCount = 0;
}
this._finishedSpans.push(span);
this._maybeStartTimer();
};
/**
* Send all spans to the exporter respecting the batch size limit
* This function is used only on forceFlush or shutdown,
* for all other cases _flush should be used
* */
BatchSpanProcessorBase.prototype._flushAll = function () {
var _this = this;
return new Promise(function (resolve, reject) {
var promises = [];
// calculate number of batches
var count = Math.ceil(_this._finishedSpans.length / _this._maxExportBatchSize);
for (var i = 0, j = count; i < j; i++) {
promises.push(_this._flushOneBatch());
}
Promise.all(promises)
.then(function () {
resolve();
})
.catch(reject);
});
};
BatchSpanProcessorBase.prototype._flushOneBatch = function () {
var _this = this;
this._clearTimer();
if (this._finishedSpans.length === 0) {
return Promise.resolve();
}
return new Promise(function (resolve, reject) {
var timer = setTimeout(function () {
// don't wait anymore for export, this way the next batch can start
reject(new Error('Timeout'));
}, _this._exportTimeoutMillis);
// prevent downstream exporter calls from generating spans
context.with(suppressTracing(context.active()), function () {
// Reset the finished spans buffer here because the next invocations of the _flush method
// could pass the same finished spans to the exporter if the buffer is cleared
// outside the execution of this callback.
var spans;
if (_this._finishedSpans.length <= _this._maxExportBatchSize) {
spans = _this._finishedSpans;
_this._finishedSpans = [];
}
else {
spans = _this._finishedSpans.splice(0, _this._maxExportBatchSize);
}
var doExport = function () {
return _this._exporter.export(spans, function (result) {
var _a;
clearTimeout(timer);
if (result.code === ExportResultCode.SUCCESS) {
resolve();
}
else {
reject((_a = result.error) !== null && _a !== void 0 ? _a : new Error('BatchSpanProcessor: span export failed'));
}
});
};
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 === null) {
doExport();
}
else {
Promise.all(pendingResources).then(doExport, function (err) {
globalErrorHandler(err);
reject(err);
});
}
});
});
};
BatchSpanProcessorBase.prototype._maybeStartTimer = function () {
var _this = this;
if (this._isExporting)
return;
var flush = function () {
_this._isExporting = true;
_this._flushOneBatch()
.finally(function () {
_this._isExporting = false;
if (_this._finishedSpans.length > 0) {
_this._clearTimer();
_this._maybeStartTimer();
}
})
.catch(function (e) {
_this._isExporting = false;
globalErrorHandler(e);
});
};
// we only wait if the queue doesn't have enough elements yet
if (this._finishedSpans.length >= this._maxExportBatchSize) {
return flush();
}
if (this._timer !== undefined)
return;
this._timer = setTimeout(function () { return flush(); }, this._scheduledDelayMillis);
unrefTimer(this._timer);
};
BatchSpanProcessorBase.prototype._clearTimer = function () {
if (this._timer !== undefined) {
clearTimeout(this._timer);
this._timer = undefined;
}
};
return BatchSpanProcessorBase;
}());
export { BatchSpanProcessorBase };
//# sourceMappingURL=BatchSpanProcessorBase.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,37 @@
import { SpanExporter } from './SpanExporter';
import { ReadableSpan } from './ReadableSpan';
import { ExportResult } from '@opentelemetry/core';
/**
* This is implementation of {@link SpanExporter} that prints spans to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
export declare class ConsoleSpanExporter implements SpanExporter {
/**
* Export spans.
* @param spans
* @param resultCallback
*/
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
/**
* Shutdown the exporter.
*/
shutdown(): Promise<void>;
/**
* Exports any pending spans in exporter
*/
forceFlush(): Promise<void>;
/**
* converts span info into more readable format
* @param span
*/
private _exportInfo;
/**
* Showing spans in console
* @param spans
* @param done
*/
private _sendSpans;
}
//# sourceMappingURL=ConsoleSpanExporter.d.ts.map

View File

@@ -0,0 +1,111 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
import { ExportResultCode, hrTimeToMicroseconds, } from '@opentelemetry/core';
/**
* This is implementation of {@link SpanExporter} that prints spans to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
/* eslint-disable no-console */
var ConsoleSpanExporter = /** @class */ (function () {
function ConsoleSpanExporter() {
}
/**
* Export spans.
* @param spans
* @param resultCallback
*/
ConsoleSpanExporter.prototype.export = function (spans, resultCallback) {
return this._sendSpans(spans, resultCallback);
};
/**
* Shutdown the exporter.
*/
ConsoleSpanExporter.prototype.shutdown = function () {
this._sendSpans([]);
return this.forceFlush();
};
/**
* Exports any pending spans in exporter
*/
ConsoleSpanExporter.prototype.forceFlush = function () {
return Promise.resolve();
};
/**
* converts span info into more readable format
* @param span
*/
ConsoleSpanExporter.prototype._exportInfo = function (span) {
var _a;
return {
resource: {
attributes: span.resource.attributes,
},
instrumentationScope: span.instrumentationLibrary,
traceId: span.spanContext().traceId,
parentId: span.parentSpanId,
traceState: (_a = span.spanContext().traceState) === null || _a === void 0 ? void 0 : _a.serialize(),
name: span.name,
id: span.spanContext().spanId,
kind: span.kind,
timestamp: hrTimeToMicroseconds(span.startTime),
duration: hrTimeToMicroseconds(span.duration),
attributes: span.attributes,
status: span.status,
events: span.events,
links: span.links,
};
};
/**
* Showing spans in console
* @param spans
* @param done
*/
ConsoleSpanExporter.prototype._sendSpans = function (spans, done) {
var e_1, _a;
try {
for (var spans_1 = __values(spans), spans_1_1 = spans_1.next(); !spans_1_1.done; spans_1_1 = spans_1.next()) {
var span = spans_1_1.value;
console.dir(this._exportInfo(span), { depth: 3 });
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (spans_1_1 && !spans_1_1.done && (_a = spans_1.return)) _a.call(spans_1);
}
finally { if (e_1) throw e_1.error; }
}
if (done) {
return done({ code: ExportResultCode.SUCCESS });
}
};
return ConsoleSpanExporter;
}());
export { ConsoleSpanExporter };
//# sourceMappingURL=ConsoleSpanExporter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ConsoleSpanExporter.js","sourceRoot":"","sources":["../../../src/export/ConsoleSpanExporter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;AAIH,OAAO,EAEL,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAE7B;;;;;GAKG;AAEH,+BAA+B;AAC/B;IAAA;IAqEA,CAAC;IApEC;;;;OAIG;IACH,oCAAM,GAAN,UACE,KAAqB,EACrB,cAA8C;QAE9C,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,cAAc,CAAC,CAAC;IAChD,CAAC;IAED;;OAEG;IACH,sCAAQ,GAAR;QACE,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QACpB,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,wCAAU,GAAV;QACE,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED;;;OAGG;IACK,yCAAW,GAAnB,UAAoB,IAAkB;;QACpC,OAAO;YACL,QAAQ,EAAE;gBACR,UAAU,EAAE,IAAI,CAAC,QAAQ,CAAC,UAAU;aACrC;YACD,oBAAoB,EAAE,IAAI,CAAC,sBAAsB;YACjD,OAAO,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,OAAO;YACnC,QAAQ,EAAE,IAAI,CAAC,YAAY;YAC3B,UAAU,EAAE,MAAA,IAAI,CAAC,WAAW,EAAE,CAAC,UAAU,0CAAE,SAAS,EAAE;YACtD,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,EAAE,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,MAAM;YAC7B,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,SAAS,EAAE,oBAAoB,CAAC,IAAI,CAAC,SAAS,CAAC;YAC/C,QAAQ,EAAE,oBAAoB,CAAC,IAAI,CAAC,QAAQ,CAAC;YAC7C,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACK,wCAAU,GAAlB,UACE,KAAqB,EACrB,IAAqC;;;YAErC,KAAmB,IAAA,UAAA,SAAA,KAAK,CAAA,4BAAA,+CAAE;gBAArB,IAAM,IAAI,kBAAA;gBACb,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;aACnD;;;;;;;;;QACD,IAAI,IAAI,EAAE;YACR,OAAO,IAAI,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;SACjD;IACH,CAAC;IACH,0BAAC;AAAD,CAAC,AArED,IAqEC","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 { SpanExporter } from './SpanExporter';\nimport { ReadableSpan } from './ReadableSpan';\nimport {\n ExportResult,\n ExportResultCode,\n hrTimeToMicroseconds,\n} from '@opentelemetry/core';\n\n/**\n * This is implementation of {@link SpanExporter} that prints spans to the\n * console. This class can be used for diagnostic purposes.\n *\n * NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.\n */\n\n/* eslint-disable no-console */\nexport class ConsoleSpanExporter implements SpanExporter {\n /**\n * Export spans.\n * @param spans\n * @param resultCallback\n */\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void {\n return this._sendSpans(spans, resultCallback);\n }\n\n /**\n * Shutdown the exporter.\n */\n shutdown(): Promise<void> {\n this._sendSpans([]);\n return this.forceFlush();\n }\n\n /**\n * Exports any pending spans in exporter\n */\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * converts span info into more readable format\n * @param span\n */\n private _exportInfo(span: ReadableSpan) {\n return {\n resource: {\n attributes: span.resource.attributes,\n },\n instrumentationScope: span.instrumentationLibrary,\n traceId: span.spanContext().traceId,\n parentId: span.parentSpanId,\n traceState: span.spanContext().traceState?.serialize(),\n name: span.name,\n id: span.spanContext().spanId,\n kind: span.kind,\n timestamp: hrTimeToMicroseconds(span.startTime),\n duration: hrTimeToMicroseconds(span.duration),\n attributes: span.attributes,\n status: span.status,\n events: span.events,\n links: span.links,\n };\n }\n\n /**\n * Showing spans in console\n * @param spans\n * @param done\n */\n private _sendSpans(\n spans: ReadableSpan[],\n done?: (result: ExportResult) => void\n ): void {\n for (const span of spans) {\n console.dir(this._exportInfo(span), { depth: 3 });\n }\n if (done) {\n return done({ code: ExportResultCode.SUCCESS });\n }\n }\n}\n"]}

View File

@@ -0,0 +1,25 @@
import { SpanExporter } from './SpanExporter';
import { ReadableSpan } from './ReadableSpan';
import { ExportResult } from '@opentelemetry/core';
/**
* This class can be used for testing purposes. It stores the exported spans
* in a list in memory that can be retrieved using the `getFinishedSpans()`
* method.
*/
export declare class InMemorySpanExporter implements SpanExporter {
private _finishedSpans;
/**
* Indicates if the exporter has been "shutdown."
* When false, exported spans will not be stored in-memory.
*/
protected _stopped: boolean;
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
shutdown(): Promise<void>;
/**
* Exports any pending spans in the exporter
*/
forceFlush(): Promise<void>;
reset(): void;
getFinishedSpans(): ReadableSpan[];
}
//# sourceMappingURL=InMemorySpanExporter.d.ts.map

View File

@@ -0,0 +1,86 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
import { ExportResultCode } from '@opentelemetry/core';
/**
* This class can be used for testing purposes. It stores the exported spans
* in a list in memory that can be retrieved using the `getFinishedSpans()`
* method.
*/
var InMemorySpanExporter = /** @class */ (function () {
function InMemorySpanExporter() {
this._finishedSpans = [];
/**
* Indicates if the exporter has been "shutdown."
* When false, exported spans will not be stored in-memory.
*/
this._stopped = false;
}
InMemorySpanExporter.prototype.export = function (spans, resultCallback) {
var _a;
if (this._stopped)
return resultCallback({
code: ExportResultCode.FAILED,
error: new Error('Exporter has been stopped'),
});
(_a = this._finishedSpans).push.apply(_a, __spreadArray([], __read(spans), false));
setTimeout(function () { return resultCallback({ code: ExportResultCode.SUCCESS }); }, 0);
};
InMemorySpanExporter.prototype.shutdown = function () {
this._stopped = true;
this._finishedSpans = [];
return this.forceFlush();
};
/**
* Exports any pending spans in the exporter
*/
InMemorySpanExporter.prototype.forceFlush = function () {
return Promise.resolve();
};
InMemorySpanExporter.prototype.reset = function () {
this._finishedSpans = [];
};
InMemorySpanExporter.prototype.getFinishedSpans = function () {
return this._finishedSpans;
};
return InMemorySpanExporter;
}());
export { InMemorySpanExporter };
//# sourceMappingURL=InMemorySpanExporter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"InMemorySpanExporter.js","sourceRoot":"","sources":["../../../src/export/InMemorySpanExporter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;AAIH,OAAO,EAAgB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAErE;;;;GAIG;AACH;IAAA;QACU,mBAAc,GAAmB,EAAE,CAAC;QAC5C;;;WAGG;QACO,aAAQ,GAAG,KAAK,CAAC;IAoC7B,CAAC;IAlCC,qCAAM,GAAN,UACE,KAAqB,EACrB,cAA8C;;QAE9C,IAAI,IAAI,CAAC,QAAQ;YACf,OAAO,cAAc,CAAC;gBACpB,IAAI,EAAE,gBAAgB,CAAC,MAAM;gBAC7B,KAAK,EAAE,IAAI,KAAK,CAAC,2BAA2B,CAAC;aAC9C,CAAC,CAAC;QACL,CAAA,KAAA,IAAI,CAAC,cAAc,CAAA,CAAC,IAAI,oCAAI,KAAK,WAAE;QAEnC,UAAU,CAAC,cAAM,OAAA,cAAc,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,EAAlD,CAAkD,EAAE,CAAC,CAAC,CAAC;IAC1E,CAAC;IAED,uCAAQ,GAAR;QACE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,IAAI,CAAC,cAAc,GAAG,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,yCAAU,GAAV;QACE,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,oCAAK,GAAL;QACE,IAAI,CAAC,cAAc,GAAG,EAAE,CAAC;IAC3B,CAAC;IAED,+CAAgB,GAAhB;QACE,OAAO,IAAI,CAAC,cAAc,CAAC;IAC7B,CAAC;IACH,2BAAC;AAAD,CAAC,AA1CD,IA0CC","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 { SpanExporter } from './SpanExporter';\nimport { ReadableSpan } from './ReadableSpan';\nimport { ExportResult, ExportResultCode } from '@opentelemetry/core';\n\n/**\n * This class can be used for testing purposes. It stores the exported spans\n * in a list in memory that can be retrieved using the `getFinishedSpans()`\n * method.\n */\nexport class InMemorySpanExporter implements SpanExporter {\n private _finishedSpans: ReadableSpan[] = [];\n /**\n * Indicates if the exporter has been \"shutdown.\"\n * When false, exported spans will not be stored in-memory.\n */\n protected _stopped = false;\n\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void {\n if (this._stopped)\n return resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Exporter has been stopped'),\n });\n this._finishedSpans.push(...spans);\n\n setTimeout(() => resultCallback({ code: ExportResultCode.SUCCESS }), 0);\n }\n\n shutdown(): Promise<void> {\n this._stopped = true;\n this._finishedSpans = [];\n return this.forceFlush();\n }\n\n /**\n * Exports any pending spans in the exporter\n */\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n reset(): void {\n this._finishedSpans = [];\n }\n\n getFinishedSpans(): ReadableSpan[] {\n return this._finishedSpans;\n }\n}\n"]}

View File

@@ -0,0 +1,12 @@
import { Context } from '@opentelemetry/api';
import { ReadableSpan } from './ReadableSpan';
import { Span } from '../Span';
import { SpanProcessor } from '../SpanProcessor';
/** No-op implementation of SpanProcessor */
export declare class NoopSpanProcessor implements SpanProcessor {
onStart(_span: Span, _context: Context): void;
onEnd(_span: ReadableSpan): void;
shutdown(): Promise<void>;
forceFlush(): Promise<void>;
}
//# sourceMappingURL=NoopSpanProcessor.d.ts.map

View File

@@ -0,0 +1,31 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** No-op implementation of SpanProcessor */
var NoopSpanProcessor = /** @class */ (function () {
function NoopSpanProcessor() {
}
NoopSpanProcessor.prototype.onStart = function (_span, _context) { };
NoopSpanProcessor.prototype.onEnd = function (_span) { };
NoopSpanProcessor.prototype.shutdown = function () {
return Promise.resolve();
};
NoopSpanProcessor.prototype.forceFlush = function () {
return Promise.resolve();
};
return NoopSpanProcessor;
}());
export { NoopSpanProcessor };
//# sourceMappingURL=NoopSpanProcessor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"NoopSpanProcessor.js","sourceRoot":"","sources":["../../../src/export/NoopSpanProcessor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAOH,4CAA4C;AAC5C;IAAA;IASA,CAAC;IARC,mCAAO,GAAP,UAAQ,KAAW,EAAE,QAAiB,IAAS,CAAC;IAChD,iCAAK,GAAL,UAAM,KAAmB,IAAS,CAAC;IACnC,oCAAQ,GAAR;QACE,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IACD,sCAAU,GAAV;QACE,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IACH,wBAAC;AAAD,CAAC,AATD,IASC","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 } from '@opentelemetry/api';\nimport { ReadableSpan } from './ReadableSpan';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\n\n/** No-op implementation of SpanProcessor */\nexport class NoopSpanProcessor implements SpanProcessor {\n onStart(_span: Span, _context: Context): void {}\n onEnd(_span: ReadableSpan): void {}\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n"]}

View File

@@ -0,0 +1,24 @@
import { SpanKind, SpanStatus, SpanAttributes, HrTime, Link, SpanContext } from '@opentelemetry/api';
import { IResource } from '@opentelemetry/resources';
import { InstrumentationLibrary } from '@opentelemetry/core';
import { TimedEvent } from '../TimedEvent';
export interface ReadableSpan {
readonly name: string;
readonly kind: SpanKind;
readonly spanContext: () => SpanContext;
readonly parentSpanId?: string;
readonly startTime: HrTime;
readonly endTime: HrTime;
readonly status: SpanStatus;
readonly attributes: SpanAttributes;
readonly links: Link[];
readonly events: TimedEvent[];
readonly duration: HrTime;
readonly ended: boolean;
readonly resource: IResource;
readonly instrumentationLibrary: InstrumentationLibrary;
readonly droppedAttributesCount: number;
readonly droppedEventsCount: number;
readonly droppedLinksCount: number;
}
//# sourceMappingURL=ReadableSpan.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {};
//# sourceMappingURL=ReadableSpan.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ReadableSpan.js","sourceRoot":"","sources":["../../../src/export/ReadableSpan.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","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 SpanKind,\n SpanStatus,\n SpanAttributes,\n HrTime,\n Link,\n SpanContext,\n} from '@opentelemetry/api';\nimport { IResource } from '@opentelemetry/resources';\nimport { InstrumentationLibrary } from '@opentelemetry/core';\nimport { TimedEvent } from '../TimedEvent';\n\nexport interface ReadableSpan {\n readonly name: string;\n readonly kind: SpanKind;\n readonly spanContext: () => SpanContext;\n readonly parentSpanId?: string;\n readonly startTime: HrTime;\n readonly endTime: HrTime;\n readonly status: SpanStatus;\n readonly attributes: SpanAttributes;\n readonly links: Link[];\n readonly events: TimedEvent[];\n readonly duration: HrTime;\n readonly ended: boolean;\n readonly resource: IResource;\n readonly instrumentationLibrary: InstrumentationLibrary;\n readonly droppedAttributesCount: number;\n readonly droppedEventsCount: number;\n readonly droppedLinksCount: number;\n}\n"]}

View File

@@ -0,0 +1,25 @@
import { Context } from '@opentelemetry/api';
import { Span } from '../Span';
import { SpanProcessor } from '../SpanProcessor';
import { ReadableSpan } from './ReadableSpan';
import { SpanExporter } from './SpanExporter';
/**
* An implementation of the {@link SpanProcessor} that converts the {@link Span}
* to {@link ReadableSpan} and passes it to the configured exporter.
*
* Only spans that are sampled are converted.
*
* NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.
*/
export declare class SimpleSpanProcessor implements SpanProcessor {
private readonly _exporter;
private _shutdownOnce;
private _unresolvedExports;
constructor(_exporter: SpanExporter);
forceFlush(): Promise<void>;
onStart(_span: Span, _parentContext: Context): void;
onEnd(span: ReadableSpan): void;
shutdown(): Promise<void>;
private _shutdown;
}
//# sourceMappingURL=SimpleSpanProcessor.d.ts.map

View File

@@ -0,0 +1,137 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import { TraceFlags } from '@opentelemetry/api';
import { internal, ExportResultCode, globalErrorHandler, BindOnceFuture, } from '@opentelemetry/core';
/**
* An implementation of the {@link SpanProcessor} that converts the {@link Span}
* to {@link ReadableSpan} and passes it to the configured exporter.
*
* Only spans that are sampled are converted.
*
* NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.
*/
var SimpleSpanProcessor = /** @class */ (function () {
function SimpleSpanProcessor(_exporter) {
this._exporter = _exporter;
this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
this._unresolvedExports = new Set();
}
SimpleSpanProcessor.prototype.forceFlush = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// await unresolved resources before resolving
return [4 /*yield*/, Promise.all(Array.from(this._unresolvedExports))];
case 1:
// await unresolved resources before resolving
_a.sent();
if (!this._exporter.forceFlush) return [3 /*break*/, 3];
return [4 /*yield*/, this._exporter.forceFlush()];
case 2:
_a.sent();
_a.label = 3;
case 3: return [2 /*return*/];
}
});
});
};
SimpleSpanProcessor.prototype.onStart = function (_span, _parentContext) { };
SimpleSpanProcessor.prototype.onEnd = function (span) {
var _this = this;
var _a, _b;
if (this._shutdownOnce.isCalled) {
return;
}
if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {
return;
}
var doExport = function () {
return internal
._export(_this._exporter, [span])
.then(function (result) {
var _a;
if (result.code !== ExportResultCode.SUCCESS) {
globalErrorHandler((_a = result.error) !== null && _a !== void 0 ? _a : new Error("SimpleSpanProcessor: span export failed (status " + result + ")"));
}
})
.catch(function (error) {
globalErrorHandler(error);
});
};
// Avoid scheduling a promise to make the behavior more predictable and easier to test
if (span.resource.asyncAttributesPending) {
var exportPromise_1 = (_b = (_a = span.resource).waitForAsyncAttributes) === null || _b === void 0 ? void 0 : _b.call(_a).then(function () {
if (exportPromise_1 != null) {
_this._unresolvedExports.delete(exportPromise_1);
}
return doExport();
}, function (err) { return globalErrorHandler(err); });
// store the unresolved exports
if (exportPromise_1 != null) {
this._unresolvedExports.add(exportPromise_1);
}
}
else {
void doExport();
}
};
SimpleSpanProcessor.prototype.shutdown = function () {
return this._shutdownOnce.call();
};
SimpleSpanProcessor.prototype._shutdown = function () {
return this._exporter.shutdown();
};
return SimpleSpanProcessor;
}());
export { SimpleSpanProcessor };
//# sourceMappingURL=SimpleSpanProcessor.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,21 @@
import { ExportResult } from '@opentelemetry/core';
import { ReadableSpan } from './ReadableSpan';
/**
* An interface that allows different tracing services to export recorded data
* for sampled spans in their own format.
*
* To export data this MUST be register to the Tracer SDK using a optional
* config.
*/
export interface SpanExporter {
/**
* Called to export sampled {@link ReadableSpan}s.
* @param spans the list of sampled Spans to be exported.
*/
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
/** Stops the exporter. */
shutdown(): Promise<void>;
/** Immediately export all spans */
forceFlush?(): Promise<void>;
}
//# sourceMappingURL=SpanExporter.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {};
//# sourceMappingURL=SpanExporter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"SpanExporter.js","sourceRoot":"","sources":["../../../src/export/SpanExporter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","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 { ExportResult } from '@opentelemetry/core';\nimport { ReadableSpan } from './ReadableSpan';\n\n/**\n * An interface that allows different tracing services to export recorded data\n * for sampled spans in their own format.\n *\n * To export data this MUST be register to the Tracer SDK using a optional\n * config.\n */\nexport interface SpanExporter {\n /**\n * Called to export sampled {@link ReadableSpan}s.\n * @param spans the list of sampled Spans to be exported.\n */\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void;\n\n /** Stops the exporter. */\n shutdown(): Promise<void>;\n\n /** Immediately export all spans */\n forceFlush?(): Promise<void>;\n}\n"]}

View File

@@ -0,0 +1,20 @@
export { Tracer } from './Tracer';
export { BasicTracerProvider, EXPORTER_FACTORY, ForceFlushState, PROPAGATOR_FACTORY, } from './BasicTracerProvider';
export { BatchSpanProcessor, RandomIdGenerator } from './platform';
export { ConsoleSpanExporter } from './export/ConsoleSpanExporter';
export { InMemorySpanExporter } from './export/InMemorySpanExporter';
export { ReadableSpan } from './export/ReadableSpan';
export { SimpleSpanProcessor } from './export/SimpleSpanProcessor';
export { SpanExporter } from './export/SpanExporter';
export { NoopSpanProcessor } from './export/NoopSpanProcessor';
export { AlwaysOffSampler } from './sampler/AlwaysOffSampler';
export { AlwaysOnSampler } from './sampler/AlwaysOnSampler';
export { ParentBasedSampler } from './sampler/ParentBasedSampler';
export { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';
export { Sampler, SamplingDecision, SamplingResult } from './Sampler';
export { Span } from './Span';
export { SpanProcessor } from './SpanProcessor';
export { TimedEvent } from './TimedEvent';
export { BatchSpanProcessorBrowserConfig, BufferConfig, GeneralLimits, SDKRegistrationConfig, SpanLimits, TracerConfig, } from './types';
export { IdGenerator } from './IdGenerator';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,29 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { Tracer } from './Tracer';
export { BasicTracerProvider, ForceFlushState, } from './BasicTracerProvider';
export { BatchSpanProcessor, RandomIdGenerator } from './platform';
export { ConsoleSpanExporter } from './export/ConsoleSpanExporter';
export { InMemorySpanExporter } from './export/InMemorySpanExporter';
export { SimpleSpanProcessor } from './export/SimpleSpanProcessor';
export { NoopSpanProcessor } from './export/NoopSpanProcessor';
export { AlwaysOffSampler } from './sampler/AlwaysOffSampler';
export { AlwaysOnSampler } from './sampler/AlwaysOnSampler';
export { ParentBasedSampler } from './sampler/ParentBasedSampler';
export { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';
export { SamplingDecision } from './Sampler';
export { Span } from './Span';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EACL,mBAAmB,EAEnB,eAAe,GAEhB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAErE,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAEnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAC9E,OAAO,EAAW,gBAAgB,EAAkB,MAAM,WAAW,CAAC;AACtE,OAAO,EAAE,IAAI,EAAE,MAAM,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\nexport { Tracer } from './Tracer';\nexport {\n BasicTracerProvider,\n EXPORTER_FACTORY,\n ForceFlushState,\n PROPAGATOR_FACTORY,\n} from './BasicTracerProvider';\nexport { BatchSpanProcessor, RandomIdGenerator } from './platform';\nexport { ConsoleSpanExporter } from './export/ConsoleSpanExporter';\nexport { InMemorySpanExporter } from './export/InMemorySpanExporter';\nexport { ReadableSpan } from './export/ReadableSpan';\nexport { SimpleSpanProcessor } from './export/SimpleSpanProcessor';\nexport { SpanExporter } from './export/SpanExporter';\nexport { NoopSpanProcessor } from './export/NoopSpanProcessor';\nexport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nexport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nexport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nexport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\nexport { Sampler, SamplingDecision, SamplingResult } from './Sampler';\nexport { Span } from './Span';\nexport { SpanProcessor } from './SpanProcessor';\nexport { TimedEvent } from './TimedEvent';\nexport {\n BatchSpanProcessorBrowserConfig,\n BufferConfig,\n GeneralLimits,\n SDKRegistrationConfig,\n SpanLimits,\n TracerConfig,\n} from './types';\nexport { IdGenerator } from './IdGenerator';\n"]}

View File

@@ -0,0 +1,14 @@
import { IdGenerator } from '../../IdGenerator';
export declare class RandomIdGenerator implements IdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId: () => string;
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId: () => string;
}
//# sourceMappingURL=RandomIdGenerator.d.ts.map

View File

@@ -0,0 +1,47 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var SPAN_ID_BYTES = 8;
var TRACE_ID_BYTES = 16;
var RandomIdGenerator = /** @class */ (function () {
function RandomIdGenerator() {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
this.generateTraceId = getIdGenerator(TRACE_ID_BYTES);
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
this.generateSpanId = getIdGenerator(SPAN_ID_BYTES);
}
return RandomIdGenerator;
}());
export { RandomIdGenerator };
var SHARED_CHAR_CODES_ARRAY = Array(32);
function getIdGenerator(bytes) {
return function generateId() {
for (var i = 0; i < bytes * 2; i++) {
SHARED_CHAR_CODES_ARRAY[i] = Math.floor(Math.random() * 16) + 48;
// valid hex characters in the range 48-57 and 97-102
if (SHARED_CHAR_CODES_ARRAY[i] >= 58) {
SHARED_CHAR_CODES_ARRAY[i] += 39;
}
}
return String.fromCharCode.apply(null, SHARED_CHAR_CODES_ARRAY.slice(0, bytes * 2));
};
}
//# sourceMappingURL=RandomIdGenerator.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"RandomIdGenerator.js","sourceRoot":"","sources":["../../../../src/platform/browser/RandomIdGenerator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,IAAM,aAAa,GAAG,CAAC,CAAC;AACxB,IAAM,cAAc,GAAG,EAAE,CAAC;AAE1B;IAAA;QACE;;;WAGG;QACH,oBAAe,GAAG,cAAc,CAAC,cAAc,CAAC,CAAC;QAEjD;;;WAGG;QACH,mBAAc,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC;IACjD,CAAC;IAAD,wBAAC;AAAD,CAAC,AAZD,IAYC;;AAED,IAAM,uBAAuB,GAAG,KAAK,CAAC,EAAE,CAAC,CAAC;AAC1C,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,SAAS,UAAU;QACxB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;YAClC,uBAAuB,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC;YACjE,qDAAqD;YACrD,IAAI,uBAAuB,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE;gBACpC,uBAAuB,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;aAClC;SACF;QACD,OAAO,MAAM,CAAC,YAAY,CAAC,KAAK,CAC9B,IAAI,EACJ,uBAAuB,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAC5C,CAAC;IACJ,CAAC,CAAC;AACJ,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\nimport { IdGenerator } from '../../IdGenerator';\n\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_CHAR_CODES_ARRAY = Array(32);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes * 2; i++) {\n SHARED_CHAR_CODES_ARRAY[i] = Math.floor(Math.random() * 16) + 48;\n // valid hex characters in the range 48-57 and 97-102\n if (SHARED_CHAR_CODES_ARRAY[i] >= 58) {\n SHARED_CHAR_CODES_ARRAY[i] += 39;\n }\n }\n return String.fromCharCode.apply(\n null,\n SHARED_CHAR_CODES_ARRAY.slice(0, bytes * 2)\n );\n };\n}\n"]}

View File

@@ -0,0 +1,11 @@
import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';
import { SpanExporter } from '../../../export/SpanExporter';
import { BatchSpanProcessorBrowserConfig } from '../../../types';
export declare class BatchSpanProcessor extends BatchSpanProcessorBase<BatchSpanProcessorBrowserConfig> {
private _visibilityChangeListener?;
private _pageHideListener?;
constructor(_exporter: SpanExporter, config?: BatchSpanProcessorBrowserConfig);
private onInit;
protected onShutdown(): void;
}
//# sourceMappingURL=BatchSpanProcessor.d.ts.map

View File

@@ -0,0 +1,74 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';
import { globalErrorHandler } from '@opentelemetry/core';
var BatchSpanProcessor = /** @class */ (function (_super) {
__extends(BatchSpanProcessor, _super);
function BatchSpanProcessor(_exporter, config) {
var _this = _super.call(this, _exporter, config) || this;
_this.onInit(config);
return _this;
}
BatchSpanProcessor.prototype.onInit = function (config) {
var _this = this;
if ((config === null || config === void 0 ? void 0 : config.disableAutoFlushOnDocumentHide) !== true &&
typeof document !== 'undefined') {
this._visibilityChangeListener = function () {
if (document.visibilityState === 'hidden') {
_this.forceFlush().catch(function (error) {
globalErrorHandler(error);
});
}
};
this._pageHideListener = function () {
_this.forceFlush().catch(function (error) {
globalErrorHandler(error);
});
};
document.addEventListener('visibilitychange', this._visibilityChangeListener);
// use 'pagehide' event as a fallback for Safari; see https://bugs.webkit.org/show_bug.cgi?id=116769
document.addEventListener('pagehide', this._pageHideListener);
}
};
BatchSpanProcessor.prototype.onShutdown = function () {
if (typeof document !== 'undefined') {
if (this._visibilityChangeListener) {
document.removeEventListener('visibilitychange', this._visibilityChangeListener);
}
if (this._pageHideListener) {
document.removeEventListener('pagehide', this._pageHideListener);
}
}
};
return BatchSpanProcessor;
}(BatchSpanProcessorBase));
export { BatchSpanProcessor };
//# sourceMappingURL=BatchSpanProcessor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"BatchSpanProcessor.js","sourceRoot":"","sources":["../../../../../src/platform/browser/export/BatchSpanProcessor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;AAEH,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAGhF,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAEzD;IAAwC,sCAAuD;IAI7F,4BACE,SAAuB,EACvB,MAAwC;QAF1C,YAIE,kBAAM,SAAS,EAAE,MAAM,CAAC,SAEzB;QADC,KAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;;IACtB,CAAC;IAEO,mCAAM,GAAd,UAAe,MAAwC;QAAvD,iBAyBC;QAxBC,IACE,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,8BAA8B,MAAK,IAAI;YAC/C,OAAO,QAAQ,KAAK,WAAW,EAC/B;YACA,IAAI,CAAC,yBAAyB,GAAG;gBAC/B,IAAI,QAAQ,CAAC,eAAe,KAAK,QAAQ,EAAE;oBACzC,KAAI,CAAC,UAAU,EAAE,CAAC,KAAK,CAAC,UAAA,KAAK;wBAC3B,kBAAkB,CAAC,KAAK,CAAC,CAAC;oBAC5B,CAAC,CAAC,CAAC;iBACJ;YACH,CAAC,CAAC;YACF,IAAI,CAAC,iBAAiB,GAAG;gBACvB,KAAI,CAAC,UAAU,EAAE,CAAC,KAAK,CAAC,UAAA,KAAK;oBAC3B,kBAAkB,CAAC,KAAK,CAAC,CAAC;gBAC5B,CAAC,CAAC,CAAC;YACL,CAAC,CAAC;YACF,QAAQ,CAAC,gBAAgB,CACvB,kBAAkB,EAClB,IAAI,CAAC,yBAAyB,CAC/B,CAAC;YAEF,oGAAoG;YACpG,QAAQ,CAAC,gBAAgB,CAAC,UAAU,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC;SAC/D;IACH,CAAC;IAES,uCAAU,GAApB;QACE,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE;YACnC,IAAI,IAAI,CAAC,yBAAyB,EAAE;gBAClC,QAAQ,CAAC,mBAAmB,CAC1B,kBAAkB,EAClB,IAAI,CAAC,yBAAyB,CAC/B,CAAC;aACH;YACD,IAAI,IAAI,CAAC,iBAAiB,EAAE;gBAC1B,QAAQ,CAAC,mBAAmB,CAAC,UAAU,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC;aAClE;SACF;IACH,CAAC;IACH,yBAAC;AAAD,CAAC,AApDD,CAAwC,sBAAsB,GAoD7D","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 { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { SpanExporter } from '../../../export/SpanExporter';\nimport { BatchSpanProcessorBrowserConfig } from '../../../types';\nimport { globalErrorHandler } from '@opentelemetry/core';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BatchSpanProcessorBrowserConfig> {\n private _visibilityChangeListener?: () => void;\n private _pageHideListener?: () => void;\n\n constructor(\n _exporter: SpanExporter,\n config?: BatchSpanProcessorBrowserConfig\n ) {\n super(_exporter, config);\n this.onInit(config);\n }\n\n private onInit(config?: BatchSpanProcessorBrowserConfig): void {\n if (\n config?.disableAutoFlushOnDocumentHide !== true &&\n typeof document !== 'undefined'\n ) {\n this._visibilityChangeListener = () => {\n if (document.visibilityState === 'hidden') {\n this.forceFlush().catch(error => {\n globalErrorHandler(error);\n });\n }\n };\n this._pageHideListener = () => {\n this.forceFlush().catch(error => {\n globalErrorHandler(error);\n });\n };\n document.addEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n\n // use 'pagehide' event as a fallback for Safari; see https://bugs.webkit.org/show_bug.cgi?id=116769\n document.addEventListener('pagehide', this._pageHideListener);\n }\n }\n\n protected onShutdown(): void {\n if (typeof document !== 'undefined') {\n if (this._visibilityChangeListener) {\n document.removeEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n }\n if (this._pageHideListener) {\n document.removeEventListener('pagehide', this._pageHideListener);\n }\n }\n }\n}\n"]}

View File

@@ -0,0 +1,3 @@
export { BatchSpanProcessor } from './export/BatchSpanProcessor';
export { RandomIdGenerator } from './RandomIdGenerator';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { BatchSpanProcessor } from './export/BatchSpanProcessor';
export { RandomIdGenerator } from './RandomIdGenerator';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/browser/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,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\nexport { BatchSpanProcessor } from './export/BatchSpanProcessor';\nexport { RandomIdGenerator } from './RandomIdGenerator';\n"]}

View File

@@ -0,0 +1,2 @@
export { BatchSpanProcessor, RandomIdGenerator } from './node';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { BatchSpanProcessor, RandomIdGenerator } from './node';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/platform/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,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\nexport { BatchSpanProcessor, RandomIdGenerator } from './node';\n"]}

View File

@@ -0,0 +1,14 @@
import { IdGenerator } from '../../IdGenerator';
export declare class RandomIdGenerator implements IdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId: () => string;
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId: () => string;
}
//# sourceMappingURL=RandomIdGenerator.d.ts.map

View File

@@ -0,0 +1,54 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var SPAN_ID_BYTES = 8;
var TRACE_ID_BYTES = 16;
var RandomIdGenerator = /** @class */ (function () {
function RandomIdGenerator() {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
this.generateTraceId = getIdGenerator(TRACE_ID_BYTES);
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
this.generateSpanId = getIdGenerator(SPAN_ID_BYTES);
}
return RandomIdGenerator;
}());
export { RandomIdGenerator };
var SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);
function getIdGenerator(bytes) {
return function generateId() {
for (var i = 0; i < bytes / 4; i++) {
// unsigned right shift drops decimal part of the number
// it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE
SHARED_BUFFER.writeUInt32BE((Math.random() * Math.pow(2, 32)) >>> 0, i * 4);
}
// If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated
for (var i = 0; i < bytes; i++) {
if (SHARED_BUFFER[i] > 0) {
break;
}
else if (i === bytes - 1) {
SHARED_BUFFER[bytes - 1] = 1;
}
}
return SHARED_BUFFER.toString('hex', 0, bytes);
};
}
//# sourceMappingURL=RandomIdGenerator.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"RandomIdGenerator.js","sourceRoot":"","sources":["../../../../src/platform/node/RandomIdGenerator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,IAAM,aAAa,GAAG,CAAC,CAAC;AACxB,IAAM,cAAc,GAAG,EAAE,CAAC;AAE1B;IAAA;QACE;;;WAGG;QACH,oBAAe,GAAG,cAAc,CAAC,cAAc,CAAC,CAAC;QAEjD;;;WAGG;QACH,mBAAc,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC;IACjD,CAAC;IAAD,wBAAC;AAAD,CAAC,AAZD,IAYC;;AAED,IAAM,aAAa,GAAG,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;AACzD,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,SAAS,UAAU;QACxB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;YAClC,wDAAwD;YACxD,gIAAgI;YAChI,aAAa,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,SAAA,CAAC,EAAI,EAAE,CAAA,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;SACrE;QAED,sFAAsF;QACtF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;YAC9B,IAAI,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE;gBACxB,MAAM;aACP;iBAAM,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC,EAAE;gBAC1B,aAAa,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;aAC9B;SACF;QAED,OAAO,aAAa,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;IACjD,CAAC,CAAC;AACJ,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\nimport { IdGenerator } from '../../IdGenerator';\n\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n } else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n"]}

View File

@@ -0,0 +1,6 @@
import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';
import { BufferConfig } from '../../../types';
export declare class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {
protected onShutdown(): void;
}
//# sourceMappingURL=BatchSpanProcessor.d.ts.map

View File

@@ -0,0 +1,41 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';
var BatchSpanProcessor = /** @class */ (function (_super) {
__extends(BatchSpanProcessor, _super);
function BatchSpanProcessor() {
return _super !== null && _super.apply(this, arguments) || this;
}
BatchSpanProcessor.prototype.onShutdown = function () { };
return BatchSpanProcessor;
}(BatchSpanProcessorBase));
export { BatchSpanProcessor };
//# sourceMappingURL=BatchSpanProcessor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"BatchSpanProcessor.js","sourceRoot":"","sources":["../../../../../src/platform/node/export/BatchSpanProcessor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;AAEH,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAGhF;IAAwC,sCAAoC;IAA5E;;IAEA,CAAC;IADW,uCAAU,GAApB,cAA8B,CAAC;IACjC,yBAAC;AAAD,CAAC,AAFD,CAAwC,sBAAsB,GAE7D","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 { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n"]}

View File

@@ -0,0 +1,3 @@
export { BatchSpanProcessor } from './export/BatchSpanProcessor';
export { RandomIdGenerator } from './RandomIdGenerator';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { BatchSpanProcessor } from './export/BatchSpanProcessor';
export { RandomIdGenerator } from './RandomIdGenerator';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/node/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,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\nexport { BatchSpanProcessor } from './export/BatchSpanProcessor';\nexport { RandomIdGenerator } from './RandomIdGenerator';\n"]}

View File

@@ -0,0 +1,7 @@
import { Sampler, SamplingResult } from '../Sampler';
/** Sampler that samples no traces. */
export declare class AlwaysOffSampler implements Sampler {
shouldSample(): SamplingResult;
toString(): string;
}
//# sourceMappingURL=AlwaysOffSampler.d.ts.map

View File

@@ -0,0 +1,32 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { SamplingDecision } from '../Sampler';
/** Sampler that samples no traces. */
var AlwaysOffSampler = /** @class */ (function () {
function AlwaysOffSampler() {
}
AlwaysOffSampler.prototype.shouldSample = function () {
return {
decision: SamplingDecision.NOT_RECORD,
};
};
AlwaysOffSampler.prototype.toString = function () {
return 'AlwaysOffSampler';
};
return AlwaysOffSampler;
}());
export { AlwaysOffSampler };
//# sourceMappingURL=AlwaysOffSampler.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"AlwaysOffSampler.js","sourceRoot":"","sources":["../../../src/sampler/AlwaysOffSampler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAW,gBAAgB,EAAkB,MAAM,YAAY,CAAC;AAEvE,sCAAsC;AACtC;IAAA;IAUA,CAAC;IATC,uCAAY,GAAZ;QACE,OAAO;YACL,QAAQ,EAAE,gBAAgB,CAAC,UAAU;SACtC,CAAC;IACJ,CAAC;IAED,mCAAQ,GAAR;QACE,OAAO,kBAAkB,CAAC;IAC5B,CAAC;IACH,uBAAC;AAAD,CAAC,AAVD,IAUC","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 { Sampler, SamplingDecision, SamplingResult } from '../Sampler';\n\n/** Sampler that samples no traces. */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n"]}

View File

@@ -0,0 +1,7 @@
import { Sampler, SamplingResult } from '../Sampler';
/** Sampler that samples all traces. */
export declare class AlwaysOnSampler implements Sampler {
shouldSample(): SamplingResult;
toString(): string;
}
//# sourceMappingURL=AlwaysOnSampler.d.ts.map

View File

@@ -0,0 +1,32 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { SamplingDecision } from '../Sampler';
/** Sampler that samples all traces. */
var AlwaysOnSampler = /** @class */ (function () {
function AlwaysOnSampler() {
}
AlwaysOnSampler.prototype.shouldSample = function () {
return {
decision: SamplingDecision.RECORD_AND_SAMPLED,
};
};
AlwaysOnSampler.prototype.toString = function () {
return 'AlwaysOnSampler';
};
return AlwaysOnSampler;
}());
export { AlwaysOnSampler };
//# sourceMappingURL=AlwaysOnSampler.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"AlwaysOnSampler.js","sourceRoot":"","sources":["../../../src/sampler/AlwaysOnSampler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAW,gBAAgB,EAAkB,MAAM,YAAY,CAAC;AAEvE,uCAAuC;AACvC;IAAA;IAUA,CAAC;IATC,sCAAY,GAAZ;QACE,OAAO;YACL,QAAQ,EAAE,gBAAgB,CAAC,kBAAkB;SAC9C,CAAC;IACJ,CAAC;IAED,kCAAQ,GAAR;QACE,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IACH,sBAAC;AAAD,CAAC,AAVD,IAUC","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 { Sampler, SamplingDecision, SamplingResult } from '../Sampler';\n\n/** Sampler that samples all traces. */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n"]}

View File

@@ -0,0 +1,30 @@
import { Context, Link, SpanAttributes, SpanKind } from '@opentelemetry/api';
import { Sampler, SamplingResult } from '../Sampler';
/**
* A composite sampler that either respects the parent span's sampling decision
* or delegates to `delegateSampler` for root spans.
*/
export declare class ParentBasedSampler implements Sampler {
private _root;
private _remoteParentSampled;
private _remoteParentNotSampled;
private _localParentSampled;
private _localParentNotSampled;
constructor(config: ParentBasedSamplerConfig);
shouldSample(context: Context, traceId: string, spanName: string, spanKind: SpanKind, attributes: SpanAttributes, links: Link[]): SamplingResult;
toString(): string;
}
interface ParentBasedSamplerConfig {
/** Sampler called for spans with no parent */
root: Sampler;
/** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */
remoteParentSampled?: Sampler;
/** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */
remoteParentNotSampled?: Sampler;
/** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */
localParentSampled?: Sampler;
/** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */
localParentNotSampled?: Sampler;
}
export {};
//# sourceMappingURL=ParentBasedSampler.d.ts.map

View File

@@ -0,0 +1,63 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { isSpanContextValid, TraceFlags, trace, } from '@opentelemetry/api';
import { globalErrorHandler } from '@opentelemetry/core';
import { AlwaysOffSampler } from './AlwaysOffSampler';
import { AlwaysOnSampler } from './AlwaysOnSampler';
/**
* A composite sampler that either respects the parent span's sampling decision
* or delegates to `delegateSampler` for root spans.
*/
var ParentBasedSampler = /** @class */ (function () {
function ParentBasedSampler(config) {
var _a, _b, _c, _d;
this._root = config.root;
if (!this._root) {
globalErrorHandler(new Error('ParentBasedSampler must have a root sampler configured'));
this._root = new AlwaysOnSampler();
}
this._remoteParentSampled =
(_a = config.remoteParentSampled) !== null && _a !== void 0 ? _a : new AlwaysOnSampler();
this._remoteParentNotSampled =
(_b = config.remoteParentNotSampled) !== null && _b !== void 0 ? _b : new AlwaysOffSampler();
this._localParentSampled =
(_c = config.localParentSampled) !== null && _c !== void 0 ? _c : new AlwaysOnSampler();
this._localParentNotSampled =
(_d = config.localParentNotSampled) !== null && _d !== void 0 ? _d : new AlwaysOffSampler();
}
ParentBasedSampler.prototype.shouldSample = function (context, traceId, spanName, spanKind, attributes, links) {
var parentContext = trace.getSpanContext(context);
if (!parentContext || !isSpanContextValid(parentContext)) {
return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
if (parentContext.isRemote) {
if (parentContext.traceFlags & TraceFlags.SAMPLED) {
return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
if (parentContext.traceFlags & TraceFlags.SAMPLED) {
return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
};
ParentBasedSampler.prototype.toString = function () {
return "ParentBased{root=" + this._root.toString() + ", remoteParentSampled=" + this._remoteParentSampled.toString() + ", remoteParentNotSampled=" + this._remoteParentNotSampled.toString() + ", localParentSampled=" + this._localParentSampled.toString() + ", localParentNotSampled=" + this._localParentNotSampled.toString() + "}";
};
return ParentBasedSampler;
}());
export { ParentBasedSampler };
//# sourceMappingURL=ParentBasedSampler.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,12 @@
import { Sampler, SamplingResult } from '../Sampler';
/** Sampler that samples a given fraction of traces based of trace id deterministically. */
export declare class TraceIdRatioBasedSampler implements Sampler {
private readonly _ratio;
private _upperBound;
constructor(_ratio?: number);
shouldSample(context: unknown, traceId: string): SamplingResult;
toString(): string;
private _normalize;
private _accumulate;
}
//# sourceMappingURL=TraceIdRatioBasedSampler.d.ts.map

View File

@@ -0,0 +1,53 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { isValidTraceId } from '@opentelemetry/api';
import { SamplingDecision } from '../Sampler';
/** Sampler that samples a given fraction of traces based of trace id deterministically. */
var TraceIdRatioBasedSampler = /** @class */ (function () {
function TraceIdRatioBasedSampler(_ratio) {
if (_ratio === void 0) { _ratio = 0; }
this._ratio = _ratio;
this._ratio = this._normalize(_ratio);
this._upperBound = Math.floor(this._ratio * 0xffffffff);
}
TraceIdRatioBasedSampler.prototype.shouldSample = function (context, traceId) {
return {
decision: isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound
? SamplingDecision.RECORD_AND_SAMPLED
: SamplingDecision.NOT_RECORD,
};
};
TraceIdRatioBasedSampler.prototype.toString = function () {
return "TraceIdRatioBased{" + this._ratio + "}";
};
TraceIdRatioBasedSampler.prototype._normalize = function (ratio) {
if (typeof ratio !== 'number' || isNaN(ratio))
return 0;
return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;
};
TraceIdRatioBasedSampler.prototype._accumulate = function (traceId) {
var accumulation = 0;
for (var i = 0; i < traceId.length / 8; i++) {
var pos = i * 8;
var part = parseInt(traceId.slice(pos, pos + 8), 16);
accumulation = (accumulation ^ part) >>> 0;
}
return accumulation;
};
return TraceIdRatioBasedSampler;
}());
export { TraceIdRatioBasedSampler };
//# sourceMappingURL=TraceIdRatioBasedSampler.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"TraceIdRatioBasedSampler.js","sourceRoot":"","sources":["../../../src/sampler/TraceIdRatioBasedSampler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAW,gBAAgB,EAAkB,MAAM,YAAY,CAAC;AAEvE,2FAA2F;AAC3F;IAGE,kCAA6B,MAAkB;QAAlB,uBAAA,EAAA,UAAkB;QAAlB,WAAM,GAAN,MAAM,CAAY;QAC7C,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACtC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC,CAAC;IAC1D,CAAC;IAED,+CAAY,GAAZ,UAAa,OAAgB,EAAE,OAAe;QAC5C,OAAO;YACL,QAAQ,EACN,cAAc,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,WAAW;gBACrE,CAAC,CAAC,gBAAgB,CAAC,kBAAkB;gBACrC,CAAC,CAAC,gBAAgB,CAAC,UAAU;SAClC,CAAC;IACJ,CAAC;IAED,2CAAQ,GAAR;QACE,OAAO,uBAAqB,IAAI,CAAC,MAAM,MAAG,CAAC;IAC7C,CAAC;IAEO,6CAAU,GAAlB,UAAmB,KAAa;QAC9B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,KAAK,CAAC;YAAE,OAAO,CAAC,CAAC;QACxD,OAAO,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IACjD,CAAC;IAEO,8CAAW,GAAnB,UAAoB,OAAe;QACjC,IAAI,YAAY,GAAG,CAAC,CAAC;QACrB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;YAC3C,IAAM,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;YAClB,IAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YACvD,YAAY,GAAG,CAAC,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;SAC5C;QACD,OAAO,YAAY,CAAC;IACtB,CAAC;IACH,+BAAC;AAAD,CAAC,AAnCD,IAmCC","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 { isValidTraceId } from '@opentelemetry/api';\nimport { Sampler, SamplingDecision, SamplingResult } from '../Sampler';\n\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private _upperBound: number;\n\n constructor(private readonly _ratio: number = 0) {\n this._ratio = this._normalize(_ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < traceId.length / 8; i++) {\n const pos = i * 8;\n const part = parseInt(traceId.slice(pos, pos + 8), 16);\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n"]}

View File

@@ -0,0 +1,94 @@
import { ContextManager, TextMapPropagator } from '@opentelemetry/api';
import { IResource } from '@opentelemetry/resources';
import { IdGenerator } from './IdGenerator';
import { Sampler } from './Sampler';
import { SpanProcessor } from './SpanProcessor';
/**
* TracerConfig provides an interface for configuring a Basic Tracer.
*/
export interface TracerConfig {
/**
* Sampler determines if a span should be recorded or should be a NoopSpan.
*/
sampler?: Sampler;
/** General Limits */
generalLimits?: GeneralLimits;
/** Span Limits */
spanLimits?: SpanLimits;
/**
* Merge resource with {@link Resource.default()}?
* Default: {@code true}
**/
mergeResourceWithDefaults?: boolean;
/** Resource associated with trace telemetry */
resource?: IResource;
/**
* Generator of trace and span IDs
* The default idGenerator generates random ids
*/
idGenerator?: IdGenerator;
/**
* How long the forceFlush can run before it is cancelled.
* The default value is 30000ms
*/
forceFlushTimeoutMillis?: number;
/**
* List of SpanProcessor for the tracer
*/
spanProcessors?: SpanProcessor[];
}
/**
* Configuration options for registering the API with the SDK.
* Undefined values may be substituted for defaults, and null
* values will not be registered.
*/
export interface SDKRegistrationConfig {
/** Propagator to register as the global propagator */
propagator?: TextMapPropagator | null;
/** Context manager to register as the global context manager */
contextManager?: ContextManager | null;
}
/** Global configuration limits of trace service */
export interface GeneralLimits {
/** attributeValueLengthLimit is maximum allowed attribute value size */
attributeValueLengthLimit?: number;
/** attributeCountLimit is number of attributes per trace */
attributeCountLimit?: number;
}
/** Global configuration of trace service */
export interface SpanLimits {
/** attributeValueLengthLimit is maximum allowed attribute value size */
attributeValueLengthLimit?: number;
/** attributeCountLimit is number of attributes per span */
attributeCountLimit?: number;
/** linkCountLimit is number of links per span */
linkCountLimit?: number;
/** eventCountLimit is number of message events per span */
eventCountLimit?: number;
/** attributePerEventCountLimit is the maximum number of attributes allowed per span event */
attributePerEventCountLimit?: number;
/** attributePerLinkCountLimit is the maximum number of attributes allowed per span link */
attributePerLinkCountLimit?: number;
}
/** Interface configuration for a buffer. */
export interface BufferConfig {
/** The maximum batch size of every export. It must be smaller or equal to
* maxQueueSize. The default value is 512. */
maxExportBatchSize?: number;
/** The delay interval in milliseconds between two consecutive exports.
* The default value is 5000ms. */
scheduledDelayMillis?: number;
/** How long the export can run before it is cancelled.
* The default value is 30000ms */
exportTimeoutMillis?: number;
/** The maximum queue size. After the size is reached spans are dropped.
* The default value is 2048. */
maxQueueSize?: number;
}
/** Interface configuration for BatchSpanProcessor on browser */
export interface BatchSpanProcessorBrowserConfig extends BufferConfig {
/** Disable flush when a user navigates to a new page, closes the tab or the browser, or,
* on mobile, switches to a different app. Auto flush is enabled by default. */
disableAutoFlushOnDocumentHide?: boolean;
}
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {};
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","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 { ContextManager, TextMapPropagator } from '@opentelemetry/api';\nimport { IResource } from '@opentelemetry/resources';\nimport { IdGenerator } from './IdGenerator';\nimport { Sampler } from './Sampler';\nimport { SpanProcessor } from './SpanProcessor';\n\n/**\n * TracerConfig provides an interface for configuring a Basic Tracer.\n */\nexport interface TracerConfig {\n /**\n * Sampler determines if a span should be recorded or should be a NoopSpan.\n */\n sampler?: Sampler;\n\n /** General Limits */\n generalLimits?: GeneralLimits;\n\n /** Span Limits */\n spanLimits?: SpanLimits;\n\n /**\n * Merge resource with {@link Resource.default()}?\n * Default: {@code true}\n **/\n mergeResourceWithDefaults?: boolean;\n\n /** Resource associated with trace telemetry */\n resource?: IResource;\n\n /**\n * Generator of trace and span IDs\n * The default idGenerator generates random ids\n */\n idGenerator?: IdGenerator;\n\n /**\n * How long the forceFlush can run before it is cancelled.\n * The default value is 30000ms\n */\n forceFlushTimeoutMillis?: number;\n\n /**\n * List of SpanProcessor for the tracer\n */\n spanProcessors?: SpanProcessor[];\n}\n\n/**\n * Configuration options for registering the API with the SDK.\n * Undefined values may be substituted for defaults, and null\n * values will not be registered.\n */\nexport interface SDKRegistrationConfig {\n /** Propagator to register as the global propagator */\n propagator?: TextMapPropagator | null;\n\n /** Context manager to register as the global context manager */\n contextManager?: ContextManager | null;\n}\n\n/** Global configuration limits of trace service */\nexport interface GeneralLimits {\n /** attributeValueLengthLimit is maximum allowed attribute value size */\n attributeValueLengthLimit?: number;\n /** attributeCountLimit is number of attributes per trace */\n attributeCountLimit?: number;\n}\n\n/** Global configuration of trace service */\nexport interface SpanLimits {\n /** attributeValueLengthLimit is maximum allowed attribute value size */\n attributeValueLengthLimit?: number;\n /** attributeCountLimit is number of attributes per span */\n attributeCountLimit?: number;\n /** linkCountLimit is number of links per span */\n linkCountLimit?: number;\n /** eventCountLimit is number of message events per span */\n eventCountLimit?: number;\n /** attributePerEventCountLimit is the maximum number of attributes allowed per span event */\n attributePerEventCountLimit?: number;\n /** attributePerLinkCountLimit is the maximum number of attributes allowed per span link */\n attributePerLinkCountLimit?: number;\n}\n\n/** Interface configuration for a buffer. */\nexport interface BufferConfig {\n /** The maximum batch size of every export. It must be smaller or equal to\n * maxQueueSize. The default value is 512. */\n maxExportBatchSize?: number;\n\n /** The delay interval in milliseconds between two consecutive exports.\n * The default value is 5000ms. */\n scheduledDelayMillis?: number;\n\n /** How long the export can run before it is cancelled.\n * The default value is 30000ms */\n exportTimeoutMillis?: number;\n\n /** The maximum queue size. After the size is reached spans are dropped.\n * The default value is 2048. */\n maxQueueSize?: number;\n}\n\n/** Interface configuration for BatchSpanProcessor on browser */\nexport interface BatchSpanProcessorBrowserConfig extends BufferConfig {\n /** Disable flush when a user navigates to a new page, closes the tab or the browser, or,\n * on mobile, switches to a different app. Auto flush is enabled by default. */\n disableAutoFlushOnDocumentHide?: boolean;\n}\n"]}

View File

@@ -0,0 +1,18 @@
import { Sampler } from './Sampler';
import { SpanLimits, TracerConfig, GeneralLimits } from './types';
/**
* Function to merge Default configuration (as specified in './config') with
* user provided configurations.
*/
export declare function mergeConfig(userConfig: TracerConfig): TracerConfig & {
sampler: Sampler;
spanLimits: SpanLimits;
generalLimits: GeneralLimits;
};
/**
* When general limits are provided and model specific limits are not,
* configures the model specific limits by using the values from the general ones.
* @param userConfig User provided tracer configuration
*/
export declare function reconfigureLimits(userConfig: TracerConfig): TracerConfig;
//# sourceMappingURL=utility.d.ts.map

View File

@@ -0,0 +1,53 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { buildSamplerFromEnv, loadDefaultConfig } from './config';
import { DEFAULT_ATTRIBUTE_COUNT_LIMIT, DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT, getEnvWithoutDefaults, } from '@opentelemetry/core';
/**
* Function to merge Default configuration (as specified in './config') with
* user provided configurations.
*/
export function mergeConfig(userConfig) {
var perInstanceDefaults = {
sampler: buildSamplerFromEnv(),
};
var DEFAULT_CONFIG = loadDefaultConfig();
var target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig);
target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {});
target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {});
return target;
}
/**
* When general limits are provided and model specific limits are not,
* configures the model specific limits by using the values from the general ones.
* @param userConfig User provided tracer configuration
*/
export function reconfigureLimits(userConfig) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
var spanLimits = Object.assign({}, userConfig.spanLimits);
var parsedEnvConfig = getEnvWithoutDefaults();
/**
* Reassign span attribute count limit to use first non null value defined by user or use default value
*/
spanLimits.attributeCountLimit =
(_f = (_e = (_d = (_b = (_a = userConfig.spanLimits) === null || _a === void 0 ? void 0 : _a.attributeCountLimit) !== null && _b !== void 0 ? _b : (_c = userConfig.generalLimits) === null || _c === void 0 ? void 0 : _c.attributeCountLimit) !== null && _d !== void 0 ? _d : parsedEnvConfig.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) !== null && _e !== void 0 ? _e : parsedEnvConfig.OTEL_ATTRIBUTE_COUNT_LIMIT) !== null && _f !== void 0 ? _f : DEFAULT_ATTRIBUTE_COUNT_LIMIT;
/**
* Reassign span attribute value length limit to use first non null value defined by user or use default value
*/
spanLimits.attributeValueLengthLimit =
(_m = (_l = (_k = (_h = (_g = userConfig.spanLimits) === null || _g === void 0 ? void 0 : _g.attributeValueLengthLimit) !== null && _h !== void 0 ? _h : (_j = userConfig.generalLimits) === null || _j === void 0 ? void 0 : _j.attributeValueLengthLimit) !== null && _k !== void 0 ? _k : parsedEnvConfig.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) !== null && _l !== void 0 ? _l : parsedEnvConfig.OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT) !== null && _m !== void 0 ? _m : DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;
return Object.assign({}, userConfig, { spanLimits: spanLimits });
}
//# sourceMappingURL=utility.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"utility.js","sourceRoot":"","sources":["../../src/utility.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAGlE,OAAO,EACL,6BAA6B,EAC7B,oCAAoC,EACpC,qBAAqB,GACtB,MAAM,qBAAqB,CAAC;AAE7B;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,UAAwB;IAKlD,IAAM,mBAAmB,GAA0B;QACjD,OAAO,EAAE,mBAAmB,EAAE;KAC/B,CAAC;IAEF,IAAM,cAAc,GAAG,iBAAiB,EAAE,CAAC;IAE3C,IAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAC1B,EAAE,EACF,cAAc,EACd,mBAAmB,EACnB,UAAU,CACX,CAAC;IAEF,MAAM,CAAC,aAAa,GAAG,MAAM,CAAC,MAAM,CAClC,EAAE,EACF,cAAc,CAAC,aAAa,EAC5B,UAAU,CAAC,aAAa,IAAI,EAAE,CAC/B,CAAC;IAEF,MAAM,CAAC,UAAU,GAAG,MAAM,CAAC,MAAM,CAC/B,EAAE,EACF,cAAc,CAAC,UAAU,EACzB,UAAU,CAAC,UAAU,IAAI,EAAE,CAC5B,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,UAAwB;;IACxD,IAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;IAE5D,IAAM,eAAe,GAAG,qBAAqB,EAAE,CAAC;IAEhD;;OAEG;IACH,UAAU,CAAC,mBAAmB;QAC5B,MAAA,MAAA,MAAA,MAAA,MAAA,UAAU,CAAC,UAAU,0CAAE,mBAAmB,mCAC1C,MAAA,UAAU,CAAC,aAAa,0CAAE,mBAAmB,mCAC7C,eAAe,CAAC,+BAA+B,mCAC/C,eAAe,CAAC,0BAA0B,mCAC1C,6BAA6B,CAAC;IAEhC;;OAEG;IACH,UAAU,CAAC,yBAAyB;QAClC,MAAA,MAAA,MAAA,MAAA,MAAA,UAAU,CAAC,UAAU,0CAAE,yBAAyB,mCAChD,MAAA,UAAU,CAAC,aAAa,0CAAE,yBAAyB,mCACnD,eAAe,CAAC,sCAAsC,mCACtD,eAAe,CAAC,iCAAiC,mCACjD,oCAAoC,CAAC;IAEvC,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,EAAE,EAAE,UAAU,YAAA,EAAE,CAAC,CAAC;AACvD,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\nimport { buildSamplerFromEnv, loadDefaultConfig } from './config';\nimport { Sampler } from './Sampler';\nimport { SpanLimits, TracerConfig, GeneralLimits } from './types';\nimport {\n DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n getEnvWithoutDefaults,\n} from '@opentelemetry/core';\n\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nexport function mergeConfig(userConfig: TracerConfig): TracerConfig & {\n sampler: Sampler;\n spanLimits: SpanLimits;\n generalLimits: GeneralLimits;\n} {\n const perInstanceDefaults: Partial<TracerConfig> = {\n sampler: buildSamplerFromEnv(),\n };\n\n const DEFAULT_CONFIG = loadDefaultConfig();\n\n const target = Object.assign(\n {},\n DEFAULT_CONFIG,\n perInstanceDefaults,\n userConfig\n );\n\n target.generalLimits = Object.assign(\n {},\n DEFAULT_CONFIG.generalLimits,\n userConfig.generalLimits || {}\n );\n\n target.spanLimits = Object.assign(\n {},\n DEFAULT_CONFIG.spanLimits,\n userConfig.spanLimits || {}\n );\n\n return target;\n}\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n const parsedEnvConfig = getEnvWithoutDefaults();\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n parsedEnvConfig.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT ??\n parsedEnvConfig.OTEL_ATTRIBUTE_COUNT_LIMIT ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n parsedEnvConfig.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT ??\n parsedEnvConfig.OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n"]}

View File

@@ -0,0 +1,2 @@
export declare const VERSION = "1.30.1";
//# sourceMappingURL=version.d.ts.map

View File

@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// this is autogenerated file, see scripts/version-update.js
export var VERSION = '1.30.1';
//# sourceMappingURL=version.js.map

View File

@@ -0,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.30.1';\n"]}

View File

@@ -0,0 +1,59 @@
import { TextMapPropagator, TracerProvider } from '@opentelemetry/api';
import { IResource } from '@opentelemetry/resources';
import { SpanProcessor } from './SpanProcessor';
import { Tracer } from './Tracer';
import { SDKRegistrationConfig, TracerConfig } from './types';
import { SpanExporter } from './export/SpanExporter';
export declare type PROPAGATOR_FACTORY = () => TextMapPropagator;
export declare type EXPORTER_FACTORY = () => SpanExporter;
export declare enum ForceFlushState {
'resolved' = 0,
'timeout' = 1,
'error' = 2,
'unresolved' = 3
}
/**
* This class represents a basic tracer provider which platform libraries can extend
*/
export declare class BasicTracerProvider implements TracerProvider {
protected static readonly _registeredPropagators: Map<string, PROPAGATOR_FACTORY>;
protected static readonly _registeredExporters: Map<string, EXPORTER_FACTORY>;
private readonly _config;
private readonly _registeredSpanProcessors;
private readonly _tracers;
activeSpanProcessor: SpanProcessor;
readonly resource: IResource;
constructor(config?: TracerConfig);
getTracer(name: string, version?: string, options?: {
schemaUrl?: string;
}): Tracer;
/**
* @deprecated please use {@link TracerConfig} spanProcessors property
* Adds a new {@link SpanProcessor} to this tracer.
* @param spanProcessor the new SpanProcessor to be added.
*/
addSpanProcessor(spanProcessor: SpanProcessor): void;
getActiveSpanProcessor(): SpanProcessor;
/**
* Register this TracerProvider for use with the OpenTelemetry API.
* Undefined values may be replaced with defaults, and
* null values will be skipped.
*
* @param config Configuration object for SDK registration
*/
register(config?: SDKRegistrationConfig): void;
forceFlush(): Promise<void>;
shutdown(): Promise<void>;
/**
* TS cannot yet infer the type of this.constructor:
* https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146
* There is no need to override either of the getters in your child class.
* The type of the registered component maps should be the same across all
* classes in the inheritance tree.
*/
protected _getPropagator(name: string): TextMapPropagator | undefined;
protected _getSpanExporter(name: string): SpanExporter | undefined;
protected _buildPropagatorFromEnv(): TextMapPropagator | undefined;
protected _buildExporterFromEnv(): SpanExporter | undefined;
}
//# sourceMappingURL=BasicTracerProvider.d.ts.map

View File

@@ -0,0 +1,210 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { context, diag, propagation, trace, } from '@opentelemetry/api';
import { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator, getEnv, merge, } from '@opentelemetry/core';
import { Resource } from '@opentelemetry/resources';
import { Tracer } from './Tracer';
import { loadDefaultConfig } from './config';
import { MultiSpanProcessor } from './MultiSpanProcessor';
import { NoopSpanProcessor } from './export/NoopSpanProcessor';
import { BatchSpanProcessor } from './platform';
import { reconfigureLimits } from './utility';
export var ForceFlushState;
(function (ForceFlushState) {
ForceFlushState[ForceFlushState["resolved"] = 0] = "resolved";
ForceFlushState[ForceFlushState["timeout"] = 1] = "timeout";
ForceFlushState[ForceFlushState["error"] = 2] = "error";
ForceFlushState[ForceFlushState["unresolved"] = 3] = "unresolved";
})(ForceFlushState || (ForceFlushState = {}));
/**
* This class represents a basic tracer provider which platform libraries can extend
*/
export class BasicTracerProvider {
constructor(config = {}) {
var _a, _b;
this._registeredSpanProcessors = [];
this._tracers = new Map();
const mergedConfig = merge({}, loadDefaultConfig(), reconfigureLimits(config));
this.resource = (_a = mergedConfig.resource) !== null && _a !== void 0 ? _a : Resource.empty();
if (mergedConfig.mergeResourceWithDefaults) {
this.resource = Resource.default().merge(this.resource);
}
this._config = Object.assign({}, mergedConfig, {
resource: this.resource,
});
if ((_b = config.spanProcessors) === null || _b === void 0 ? void 0 : _b.length) {
this._registeredSpanProcessors = [...config.spanProcessors];
this.activeSpanProcessor = new MultiSpanProcessor(this._registeredSpanProcessors);
}
else {
const defaultExporter = this._buildExporterFromEnv();
if (defaultExporter !== undefined) {
const batchProcessor = new BatchSpanProcessor(defaultExporter);
this.activeSpanProcessor = batchProcessor;
}
else {
this.activeSpanProcessor = new NoopSpanProcessor();
}
}
}
getTracer(name, version, options) {
const key = `${name}@${version || ''}:${(options === null || options === void 0 ? void 0 : options.schemaUrl) || ''}`;
if (!this._tracers.has(key)) {
this._tracers.set(key, new Tracer({ name, version, schemaUrl: options === null || options === void 0 ? void 0 : options.schemaUrl }, this._config, this));
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this._tracers.get(key);
}
/**
* @deprecated please use {@link TracerConfig} spanProcessors property
* Adds a new {@link SpanProcessor} to this tracer.
* @param spanProcessor the new SpanProcessor to be added.
*/
addSpanProcessor(spanProcessor) {
if (this._registeredSpanProcessors.length === 0) {
// since we might have enabled by default a batchProcessor, we disable it
// before adding the new one
this.activeSpanProcessor
.shutdown()
.catch(err => diag.error('Error while trying to shutdown current span processor', err));
}
this._registeredSpanProcessors.push(spanProcessor);
this.activeSpanProcessor = new MultiSpanProcessor(this._registeredSpanProcessors);
}
getActiveSpanProcessor() {
return this.activeSpanProcessor;
}
/**
* Register this TracerProvider for use with the OpenTelemetry API.
* Undefined values may be replaced with defaults, and
* null values will be skipped.
*
* @param config Configuration object for SDK registration
*/
register(config = {}) {
trace.setGlobalTracerProvider(this);
if (config.propagator === undefined) {
config.propagator = this._buildPropagatorFromEnv();
}
if (config.contextManager) {
context.setGlobalContextManager(config.contextManager);
}
if (config.propagator) {
propagation.setGlobalPropagator(config.propagator);
}
}
forceFlush() {
const timeout = this._config.forceFlushTimeoutMillis;
const promises = this._registeredSpanProcessors.map((spanProcessor) => {
return new Promise(resolve => {
let state;
const timeoutInterval = setTimeout(() => {
resolve(new Error(`Span processor did not completed within timeout period of ${timeout} ms`));
state = ForceFlushState.timeout;
}, timeout);
spanProcessor
.forceFlush()
.then(() => {
clearTimeout(timeoutInterval);
if (state !== ForceFlushState.timeout) {
state = ForceFlushState.resolved;
resolve(state);
}
})
.catch(error => {
clearTimeout(timeoutInterval);
state = ForceFlushState.error;
resolve(error);
});
});
});
return new Promise((resolve, reject) => {
Promise.all(promises)
.then(results => {
const errors = results.filter(result => result !== ForceFlushState.resolved);
if (errors.length > 0) {
reject(errors);
}
else {
resolve();
}
})
.catch(error => reject([error]));
});
}
shutdown() {
return this.activeSpanProcessor.shutdown();
}
/**
* TS cannot yet infer the type of this.constructor:
* https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146
* There is no need to override either of the getters in your child class.
* The type of the registered component maps should be the same across all
* classes in the inheritance tree.
*/
_getPropagator(name) {
var _a;
return (_a = this.constructor._registeredPropagators.get(name)) === null || _a === void 0 ? void 0 : _a();
}
_getSpanExporter(name) {
var _a;
return (_a = this.constructor._registeredExporters.get(name)) === null || _a === void 0 ? void 0 : _a();
}
_buildPropagatorFromEnv() {
// per spec, propagators from env must be deduplicated
const uniquePropagatorNames = Array.from(new Set(getEnv().OTEL_PROPAGATORS));
const propagators = uniquePropagatorNames.map(name => {
const propagator = this._getPropagator(name);
if (!propagator) {
diag.warn(`Propagator "${name}" requested through environment variable is unavailable.`);
}
return propagator;
});
const validPropagators = propagators.reduce((list, item) => {
if (item) {
list.push(item);
}
return list;
}, []);
if (validPropagators.length === 0) {
return;
}
else if (uniquePropagatorNames.length === 1) {
return validPropagators[0];
}
else {
return new CompositePropagator({
propagators: validPropagators,
});
}
}
_buildExporterFromEnv() {
const exporterName = getEnv().OTEL_TRACES_EXPORTER;
if (exporterName === 'none' || exporterName === '')
return;
const exporter = this._getSpanExporter(exporterName);
if (!exporter) {
diag.error(`Exporter "${exporterName}" requested through environment variable is unavailable.`);
}
return exporter;
}
}
BasicTracerProvider._registeredPropagators = new Map([
['tracecontext', () => new W3CTraceContextPropagator()],
['baggage', () => new W3CBaggagePropagator()],
]);
BasicTracerProvider._registeredExporters = new Map();
//# sourceMappingURL=BasicTracerProvider.js.map

Some files were not shown because too many files have changed in this diff Show More