Update test framework: fix run_tests.py to support all test files, add auto-import-check for test files

This commit is contained in:
qiaoxinjiu
2026-05-09 15:11:30 +08:00
parent eb053a347f
commit eaba8328da
21739 changed files with 2236758 additions and 719 deletions

201
node_modules/@opentelemetry/exporter-zipkin/LICENSE generated vendored Normal file
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.

80
node_modules/@opentelemetry/exporter-zipkin/README.md generated vendored Normal file
View File

@@ -0,0 +1,80 @@
# OpenTelemetry Zipkin Trace Exporter
[![NPM Published Version][npm-img]][npm-url]
[![Apache License][license-image]][license-image]
OpenTelemetry Zipkin Trace Exporter allows the user to send collected traces to Zipkin.
[Zipkin](https://zipkin.io/) is a distributed tracing system. It helps gather timing data needed to troubleshoot latency problems in microservice architectures. It manages both the collection and lookup of this data.
## Installation
```bash
npm install --save @opentelemetry/exporter-zipkin
```
## Usage in Node and Browser
Install the exporter on your application and pass the options. `serviceName` is an optional string. If omitted, the exporter will first try to get the service name from the Resource. If no service name can be detected on the Resource, a fallback name of "OpenTelemetry Service" will be used.
```js
const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin');
// Add your zipkin url (`http://localhost:9411/api/v2/spans` is used as
// default) and application name to the Zipkin options.
// You can also define your custom headers which will be added automatically.
const options = {
headers: {
'my-header': 'header-value',
},
url: 'your-zipkin-url',
// optional interceptor
getExportRequestHeaders: () => {
return {
'my-header': 'header-value',
}
}
}
const exporter = new ZipkinExporter(options);
```
Now, register the exporter and start tracing.
```js
const tracerProvider = new NodeTracerProvider({
spanProcessors: [new BatchSpanProcessor(exporter)]
})
const tracer = traceProvider.getTracer('my-tracer')
```
You can use built-in `SimpleSpanProcessor` or `BatchSpanProcessor` or write your own.
- [SimpleSpanProcessor](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/sdk.md#simple-processor): The implementation of `SpanProcessor` that passes ended span directly to the configured `SpanExporter`.
- [BatchSpanProcessor](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/sdk.md#batching-processor): The implementation of the `SpanProcessor` that batches ended spans and pushes them to the configured `SpanExporter`. It is recommended to use this `SpanProcessor` for better performance and optimization.
### Options
- **getExportRequestHeaders** - optional interceptor that allows adding new headers every time time the exporter is going to send spans.
This is optional and can be used if headers are changing over time. This is a sync callback.
## Viewing your traces
Please visit the Zipkin UI endpoint <http://localhost:9411>
## Useful links
- For more information on OpenTelemetry, visit: <https://opentelemetry.io/>
- For more about OpenTelemetry JavaScript: <https://github.com/open-telemetry/opentelemetry-js>
- For Zipkin project at <https://zipkin.io/>
- 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/exporter-zipkin
[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fexporter-zipkin.svg

View File

@@ -0,0 +1,4 @@
export { prepareSend } from './platform';
export { ExporterConfig } from './types';
export { ZipkinExporter } from './zipkin';
//# 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 { prepareSend } from './platform';
export { ZipkinExporter } from './zipkin';
//# 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,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzC,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,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 { prepareSend } from './platform';\nexport { ExporterConfig } from './types';\nexport { ZipkinExporter } from './zipkin';\n"]}

View File

@@ -0,0 +1,2 @@
export { prepareSend } from './util';
//# 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 { prepareSend } from './util';
//# 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,WAAW,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 { prepareSend } from './util';\n"]}

View File

@@ -0,0 +1,9 @@
import * as zipkinTypes from '../../types';
/**
* Prepares send function that will send spans to the remote Zipkin service.
* @param urlStr - url to send spans
* @param headers - headers
* send
*/
export declare function prepareSend(urlStr: string, headers?: Record<string, string>): zipkinTypes.SendFn;
//# sourceMappingURL=util.d.ts.map

View File

@@ -0,0 +1,105 @@
/*
* 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 { ExportResultCode, globalErrorHandler, } from '@opentelemetry/core';
/**
* Prepares send function that will send spans to the remote Zipkin service.
* @param urlStr - url to send spans
* @param headers - headers
* send
*/
export function prepareSend(urlStr, headers) {
let xhrHeaders;
const useBeacon = typeof navigator.sendBeacon === 'function' && !headers;
if (headers) {
xhrHeaders = {
Accept: 'application/json',
'Content-Type': 'application/json',
...headers,
};
}
/**
* Send spans to the remote Zipkin service.
*/
return function send(zipkinSpans, done) {
if (zipkinSpans.length === 0) {
diag.debug('Zipkin send with empty spans');
return done({ code: ExportResultCode.SUCCESS });
}
const payload = JSON.stringify(zipkinSpans);
if (useBeacon) {
sendWithBeacon(payload, done, urlStr);
}
else {
sendWithXhr(payload, done, urlStr, xhrHeaders);
}
};
}
/**
* Sends data using beacon
* @param data
* @param done
* @param urlStr
*/
function sendWithBeacon(data, done, urlStr) {
if (navigator.sendBeacon(urlStr, data)) {
diag.debug('sendBeacon - can send', data);
done({ code: ExportResultCode.SUCCESS });
}
else {
done({
code: ExportResultCode.FAILED,
error: new Error(`sendBeacon - cannot send ${data}`),
});
}
}
/**
* Sends data using XMLHttpRequest
* @param data
* @param done
* @param urlStr
* @param xhrHeaders
*/
function sendWithXhr(data, done, urlStr, xhrHeaders = {}) {
const xhr = new XMLHttpRequest();
xhr.open('POST', urlStr);
Object.entries(xhrHeaders).forEach(([k, v]) => {
xhr.setRequestHeader(k, v);
});
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
const statusCode = xhr.status || 0;
diag.debug(`Zipkin response status code: ${statusCode}, body: ${data}`);
if (xhr.status >= 200 && xhr.status < 400) {
return done({ code: ExportResultCode.SUCCESS });
}
else {
return done({
code: ExportResultCode.FAILED,
error: new Error(`Got unexpected status code from zipkin: ${xhr.status}`),
});
}
}
};
xhr.onerror = msg => {
globalErrorHandler(new Error(`Zipkin request error: ${msg}`));
return done({ code: ExportResultCode.FAILED });
};
// Issue request to remote service
diag.debug(`Zipkin request payload: ${data}`);
xhr.send(data);
}
//# sourceMappingURL=util.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export { prepareSend } 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 { prepareSend } 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,WAAW,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 { prepareSend } from './node';\n"]}

View File

@@ -0,0 +1,2 @@
export { prepareSend } from './util';
//# 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 { prepareSend } from './util';
//# 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,WAAW,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 { prepareSend } from './util';\n"]}

View File

@@ -0,0 +1,9 @@
import * as zipkinTypes from '../../types';
/**
* Prepares send function that will send spans to the remote Zipkin service.
* @param urlStr - url to send spans
* @param headers - headers
* send
*/
export declare function prepareSend(urlStr: string, headers?: Record<string, string>): zipkinTypes.SendFn;
//# sourceMappingURL=util.d.ts.map

View File

@@ -0,0 +1,78 @@
/*
* 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 { ExportResultCode } from '@opentelemetry/core';
import * as http from 'http';
import * as https from 'https';
/**
* Prepares send function that will send spans to the remote Zipkin service.
* @param urlStr - url to send spans
* @param headers - headers
* send
*/
export function prepareSend(urlStr, headers) {
const url = new URL(urlStr);
const reqOpts = Object.assign({
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers,
},
});
/**
* Send spans to the remote Zipkin service.
*/
return function send(zipkinSpans, done) {
if (zipkinSpans.length === 0) {
diag.debug('Zipkin send with empty spans');
return done({ code: ExportResultCode.SUCCESS });
}
const { request } = url.protocol === 'http:' ? http : https;
const req = request(url, reqOpts, (res) => {
let rawData = '';
res.on('data', chunk => {
rawData += chunk;
});
res.on('end', () => {
const statusCode = res.statusCode || 0;
diag.debug(`Zipkin response status code: ${statusCode}, body: ${rawData}`);
// Consider 2xx and 3xx as success.
if (statusCode < 400) {
return done({ code: ExportResultCode.SUCCESS });
// Consider 4xx as failed non-retryable.
}
else {
return done({
code: ExportResultCode.FAILED,
error: new Error(`Got unexpected status code from zipkin: ${statusCode}`),
});
}
});
});
req.on('error', error => {
return done({
code: ExportResultCode.FAILED,
error,
});
});
// Issue request to remote service
const payload = JSON.stringify(zipkinSpans);
diag.debug(`Zipkin request payload: ${payload}`);
req.write(payload, 'utf8');
req.end();
};
}
//# sourceMappingURL=util.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"util.js","sourceRoot":"","sources":["../../../../src/platform/node/util.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAgB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAG/B;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CACzB,MAAc,EACd,OAAgC;IAEhC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;IAE5B,MAAM,OAAO,GAAwB,MAAM,CAAC,MAAM,CAAC;QACjD,MAAM,EAAE,MAAM;QACd,OAAO,EAAE;YACP,cAAc,EAAE,kBAAkB;YAClC,GAAG,OAAO;SACX;KACF,CAAC,CAAC;IAEH;;OAEG;IACH,OAAO,SAAS,IAAI,CAClB,WAA+B,EAC/B,IAAoC;QAEpC,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;YAC5B,IAAI,CAAC,KAAK,CAAC,8BAA8B,CAAC,CAAC;YAC3C,OAAO,IAAI,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;SACjD;QAED,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;QAC5D,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,OAAO,EAAE,CAAC,GAAyB,EAAE,EAAE;YAC9D,IAAI,OAAO,GAAG,EAAE,CAAC;YACjB,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE;gBACrB,OAAO,IAAI,KAAK,CAAC;YACnB,CAAC,CAAC,CAAC;YACH,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;gBACjB,MAAM,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,CAAC,CAAC;gBACvC,IAAI,CAAC,KAAK,CACR,gCAAgC,UAAU,WAAW,OAAO,EAAE,CAC/D,CAAC;gBAEF,mCAAmC;gBACnC,IAAI,UAAU,GAAG,GAAG,EAAE;oBACpB,OAAO,IAAI,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;oBAChD,wCAAwC;iBACzC;qBAAM;oBACL,OAAO,IAAI,CAAC;wBACV,IAAI,EAAE,gBAAgB,CAAC,MAAM;wBAC7B,KAAK,EAAE,IAAI,KAAK,CACd,2CAA2C,UAAU,EAAE,CACxD;qBACF,CAAC,CAAC;iBACJ;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE;YACtB,OAAO,IAAI,CAAC;gBACV,IAAI,EAAE,gBAAgB,CAAC,MAAM;gBAC7B,KAAK;aACN,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,kCAAkC;QAClC,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QAC5C,IAAI,CAAC,KAAK,CAAC,2BAA2B,OAAO,EAAE,CAAC,CAAC;QACjD,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC3B,GAAG,CAAC,GAAG,EAAE,CAAC;IACZ,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 { diag } from '@opentelemetry/api';\nimport { ExportResult, ExportResultCode } from '@opentelemetry/core';\nimport * as http from 'http';\nimport * as https from 'https';\nimport * as zipkinTypes from '../../types';\n\n/**\n * Prepares send function that will send spans to the remote Zipkin service.\n * @param urlStr - url to send spans\n * @param headers - headers\n * send\n */\nexport function prepareSend(\n urlStr: string,\n headers?: Record<string, string>\n): zipkinTypes.SendFn {\n const url = new URL(urlStr);\n\n const reqOpts: http.RequestOptions = Object.assign({\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n /**\n * Send spans to the remote Zipkin service.\n */\n return function send(\n zipkinSpans: zipkinTypes.Span[],\n done: (result: ExportResult) => void\n ) {\n if (zipkinSpans.length === 0) {\n diag.debug('Zipkin send with empty spans');\n return done({ code: ExportResultCode.SUCCESS });\n }\n\n const { request } = url.protocol === 'http:' ? http : https;\n const req = request(url, reqOpts, (res: http.IncomingMessage) => {\n let rawData = '';\n res.on('data', chunk => {\n rawData += chunk;\n });\n res.on('end', () => {\n const statusCode = res.statusCode || 0;\n diag.debug(\n `Zipkin response status code: ${statusCode}, body: ${rawData}`\n );\n\n // Consider 2xx and 3xx as success.\n if (statusCode < 400) {\n return done({ code: ExportResultCode.SUCCESS });\n // Consider 4xx as failed non-retryable.\n } else {\n return done({\n code: ExportResultCode.FAILED,\n error: new Error(\n `Got unexpected status code from zipkin: ${statusCode}`\n ),\n });\n }\n });\n });\n\n req.on('error', error => {\n return done({\n code: ExportResultCode.FAILED,\n error,\n });\n });\n\n // Issue request to remote service\n const payload = JSON.stringify(zipkinSpans);\n diag.debug(`Zipkin request payload: ${payload}`);\n req.write(payload, 'utf8');\n req.end();\n };\n}\n"]}

View File

@@ -0,0 +1,16 @@
import { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base';
import * as zipkinTypes from './types';
export declare const defaultStatusCodeTagName = "otel.status_code";
export declare const defaultStatusErrorTagName = "error";
/**
* Translate OpenTelemetry ReadableSpan to ZipkinSpan format
* @param span Span to be translated
*/
export declare function toZipkinSpan(span: ReadableSpan, serviceName: string, statusCodeTagName: string, statusErrorTagName: string): zipkinTypes.Span;
/** Converts OpenTelemetry Span properties to Zipkin Tags format. */
export declare function _toZipkinTags({ attributes, resource, status, droppedAttributesCount, droppedEventsCount, droppedLinksCount, }: ReadableSpan, statusCodeTagName: string, statusErrorTagName: string): zipkinTypes.Tags;
/**
* Converts OpenTelemetry Events to Zipkin Annotations format.
*/
export declare function _toZipkinAnnotations(events: TimedEvent[]): zipkinTypes.Annotation[];
//# sourceMappingURL=transform.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.
*/
import * as api from '@opentelemetry/api';
import { hrTimeToMicroseconds } from '@opentelemetry/core';
import * as zipkinTypes from './types';
const ZIPKIN_SPAN_KIND_MAPPING = {
[api.SpanKind.CLIENT]: zipkinTypes.SpanKind.CLIENT,
[api.SpanKind.SERVER]: zipkinTypes.SpanKind.SERVER,
[api.SpanKind.CONSUMER]: zipkinTypes.SpanKind.CONSUMER,
[api.SpanKind.PRODUCER]: zipkinTypes.SpanKind.PRODUCER,
// When absent, the span is local.
[api.SpanKind.INTERNAL]: undefined,
};
export const defaultStatusCodeTagName = 'otel.status_code';
export const defaultStatusErrorTagName = 'error';
/**
* Translate OpenTelemetry ReadableSpan to ZipkinSpan format
* @param span Span to be translated
*/
export function toZipkinSpan(span, serviceName, statusCodeTagName, statusErrorTagName) {
const zipkinSpan = {
traceId: span.spanContext().traceId,
parentId: span.parentSpanContext?.spanId,
name: span.name,
id: span.spanContext().spanId,
kind: ZIPKIN_SPAN_KIND_MAPPING[span.kind],
timestamp: hrTimeToMicroseconds(span.startTime),
duration: Math.round(hrTimeToMicroseconds(span.duration)),
localEndpoint: { serviceName },
tags: _toZipkinTags(span, statusCodeTagName, statusErrorTagName),
annotations: span.events.length
? _toZipkinAnnotations(span.events)
: undefined,
};
return zipkinSpan;
}
/** Converts OpenTelemetry Span properties to Zipkin Tags format. */
export function _toZipkinTags({ attributes, resource, status, droppedAttributesCount, droppedEventsCount, droppedLinksCount, }, statusCodeTagName, statusErrorTagName) {
const tags = {};
for (const key of Object.keys(attributes)) {
tags[key] = String(attributes[key]);
}
if (status.code !== api.SpanStatusCode.UNSET) {
tags[statusCodeTagName] = String(api.SpanStatusCode[status.code]);
}
if (status.code === api.SpanStatusCode.ERROR && status.message) {
tags[statusErrorTagName] = status.message;
}
/* Add droppedAttributesCount as a tag */
if (droppedAttributesCount) {
tags['otel.dropped_attributes_count'] = String(droppedAttributesCount);
}
/* Add droppedEventsCount as a tag */
if (droppedEventsCount) {
tags['otel.dropped_events_count'] = String(droppedEventsCount);
}
/* Add droppedLinksCount as a tag */
if (droppedLinksCount) {
tags['otel.dropped_links_count'] = String(droppedLinksCount);
}
Object.keys(resource.attributes).forEach(name => (tags[name] = String(resource.attributes[name])));
return tags;
}
/**
* Converts OpenTelemetry Events to Zipkin Annotations format.
*/
export function _toZipkinAnnotations(events) {
return events.map(event => ({
timestamp: Math.round(hrTimeToMicroseconds(event.time)),
value: event.name,
}));
}
//# sourceMappingURL=transform.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,158 @@
import { ExportResult } from '@opentelemetry/core';
/**
* Exporter config
*/
export interface ExporterConfig {
headers?: Record<string, string>;
serviceName?: string;
url?: string;
statusCodeTagName?: string;
statusDescriptionTagName?: string;
getExportRequestHeaders?: () => Record<string, string> | undefined;
}
/**
* Zipkin Span
* @see https://github.com/openzipkin/zipkin-api/blob/master/zipkin2-api.yaml
*/
export interface Span {
/**
* Trace identifier, set on all spans within it.
*/
traceId: string;
/**
* The logical operation this span represents in lowercase (e.g. rpc method).
* Leave absent if unknown.
*/
name: string;
/**
* The parent span ID or absent if this the root span in a trace.
*/
parentId?: string;
/**
* Unique 64bit identifier for this operation within the trace.
*/
id: string;
/**
* When present, kind clarifies timestamp, duration and remoteEndpoint.
* When absent, the span is local or incomplete.
*/
kind?: SpanKind;
/**
* Epoch microseconds of the start of this span, possibly absent if
* incomplete.
*/
timestamp: number;
/**
* Duration in microseconds of the critical path, if known.
*/
duration: number;
/**
* True is a request to store this span even if it overrides sampling policy.
* This is true when the `X-B3-Flags` header has a value of 1.
*/
debug?: boolean;
/**
* True if we are contributing to a span started by another tracer (ex on a
* different host).
*/
shared?: boolean;
/**
* The host that recorded this span, primarily for query by service name.
*/
localEndpoint: Endpoint;
/**
* Associates events that explain latency with the time they happened.
*/
annotations?: Annotation[];
/**
* Tags give your span context for search, viewing and analysis.
*/
tags: Tags;
}
/**
* Associates an event that explains latency with a timestamp.
* Unlike log statements, annotations are often codes. Ex. "ws" for WireSend
* Zipkin v1 core annotations such as "cs" and "sr" have been replaced with
* Span.Kind, which interprets timestamp and duration.
*/
export interface Annotation {
/**
* Epoch microseconds of this event.
* For example, 1502787600000000 corresponds to 2017-08-15 09:00 UTC
*/
timestamp: number;
/**
* Usually a short tag indicating an event, like "error"
* While possible to add larger data, such as garbage collection details, low
* cardinality event names both keep the size of spans down and also are easy
* to search against.
*/
value: string;
}
/**
* The network context of a node in the service graph.
*/
export interface Endpoint {
/**
* Lower-case label of this node in the service graph, such as "favstar".
* Leave absent if unknown.
* This is a primary label for trace lookup and aggregation, so it should be
* intuitive and consistent. Many use a name from service discovery.
*/
serviceName?: string;
/**
* The text representation of the primary IPv4 address associated with this
* connection. Ex. 192.168.99.100 Absent if unknown.
*/
ipv4?: string;
/**
* The text representation of the primary IPv6 address associated with a
* connection. Ex. 2001:db8::c001 Absent if unknown.
* Prefer using the ipv4 field for mapped addresses.
*/
port?: number;
}
/**
* Adds context to a span, for search, viewing and analysis.
* For example, a key "your_app.version" would let you lookup traces by version.
* A tag "sql.query" isn't searchable, but it can help in debugging when viewing
* a trace.
*/
export interface Tags {
[tagKey: string]: unknown;
}
/**
* When present, kind clarifies timestamp, duration and remoteEndpoint. When
* absent, the span is local or incomplete. Unlike client and server, there
* is no direct critical path latency relationship between producer and
* consumer spans.
* `CLIENT`
* timestamp is the moment a request was sent to the server.
* duration is the delay until a response or an error was received.
* remoteEndpoint is the server.
* `SERVER`
* timestamp is the moment a client request was received.
* duration is the delay until a response was sent or an error.
* remoteEndpoint is the client.
* `PRODUCER`
* timestamp is the moment a message was sent to a destination.
* duration is the delay sending the message, such as batching.
* remoteEndpoint is the broker.
* `CONSUMER`
* timestamp is the moment a message was received from an origin.
* duration is the delay consuming the message, such as from backlog.
* remoteEndpoint - Represents the broker. Leave serviceName absent if unknown.
*/
export declare enum SpanKind {
CLIENT = "CLIENT",
SERVER = "SERVER",
CONSUMER = "CONSUMER",
PRODUCER = "PRODUCER"
}
/**
* interface for function that will send zipkin spans
*/
export type SendFunction = (zipkinSpans: Span[], done: (result: ExportResult) => void) => void;
export type GetHeaders = () => Record<string, string> | undefined;
export type SendFn = (zipkinSpans: Span[], done: (result: ExportResult) => void) => void;
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1,45 @@
/*
* 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.
*/
/**
* When present, kind clarifies timestamp, duration and remoteEndpoint. When
* absent, the span is local or incomplete. Unlike client and server, there
* is no direct critical path latency relationship between producer and
* consumer spans.
* `CLIENT`
* timestamp is the moment a request was sent to the server.
* duration is the delay until a response or an error was received.
* remoteEndpoint is the server.
* `SERVER`
* timestamp is the moment a client request was received.
* duration is the delay until a response was sent or an error.
* remoteEndpoint is the client.
* `PRODUCER`
* timestamp is the moment a message was sent to a destination.
* duration is the delay sending the message, such as batching.
* remoteEndpoint is the broker.
* `CONSUMER`
* timestamp is the moment a message was received from an origin.
* duration is the delay consuming the message, such as from backlog.
* remoteEndpoint - Represents the broker. Leave serviceName absent if unknown.
*/
export var SpanKind;
(function (SpanKind) {
SpanKind["CLIENT"] = "CLIENT";
SpanKind["SERVER"] = "SERVER";
SpanKind["CONSUMER"] = "CONSUMER";
SpanKind["PRODUCER"] = "PRODUCER";
})(SpanKind || (SpanKind = {}));
//# sourceMappingURL=types.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
import { GetHeaders } from './types';
export declare function prepareGetHeaders(getExportRequestHeaders: GetHeaders): () => Record<string, string> | undefined;
//# sourceMappingURL=utils.d.ts.map

View File

@@ -0,0 +1,6 @@
export function prepareGetHeaders(getExportRequestHeaders) {
return function () {
return getExportRequestHeaders();
};
}
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAiBA,MAAM,UAAU,iBAAiB,CAC/B,uBAAmC;IAEnC,OAAO;QACL,OAAO,uBAAuB,EAAE,CAAC;IACnC,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 */\nimport { GetHeaders } from './types';\n\nexport function prepareGetHeaders(\n getExportRequestHeaders: GetHeaders\n): () => Record<string, string> | undefined {\n return function () {\n return getExportRequestHeaders();\n };\n}\n"]}

View File

@@ -0,0 +1,2 @@
export declare const VERSION = "2.0.0";
//# 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 const VERSION = '2.0.0';
//# 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,MAAM,OAAO,GAAG,OAAO,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 = '2.0.0';\n"]}

View File

@@ -0,0 +1,42 @@
import { ExportResult } from '@opentelemetry/core';
import { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base';
import * as zipkinTypes from './types';
/**
* Zipkin Exporter
*/
export declare class ZipkinExporter implements SpanExporter {
private readonly DEFAULT_SERVICE_NAME;
private readonly _statusCodeTagName;
private readonly _statusDescriptionTagName;
private _urlStr;
private _send;
private _getHeaders;
private _serviceName?;
private _isShutdown;
private _sendingPromises;
constructor(config?: zipkinTypes.ExporterConfig);
/**
* Export spans.
*/
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
/**
* Shutdown exporter. Noop operation in this exporter.
*/
shutdown(): Promise<void>;
/**
* Exports any pending spans in exporter
*/
forceFlush(): Promise<void>;
/**
* if user defines getExportRequestHeaders in config then this will be called
* every time before send, otherwise it will be replaced with noop in
* constructor
* @default noop
*/
private _beforeSend;
/**
* Transform spans and sends to Zipkin service.
*/
private _sendSpans;
}
//# sourceMappingURL=zipkin.d.ts.map

View File

@@ -0,0 +1,127 @@
/*
* 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 { ExportResultCode, getStringFromEnv, } from '@opentelemetry/core';
import { prepareSend } from './platform/index';
import { toZipkinSpan, defaultStatusCodeTagName, defaultStatusErrorTagName, } from './transform';
import { SEMRESATTRS_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
import { prepareGetHeaders } from './utils';
/**
* Zipkin Exporter
*/
export class ZipkinExporter {
DEFAULT_SERVICE_NAME = 'OpenTelemetry Service';
_statusCodeTagName;
_statusDescriptionTagName;
_urlStr;
_send;
_getHeaders;
_serviceName;
_isShutdown;
_sendingPromises = [];
constructor(config = {}) {
this._urlStr =
config.url ||
(getStringFromEnv('OTEL_EXPORTER_ZIPKIN_ENDPOINT') ??
'http://localhost:9411/api/v2/spans');
this._send = prepareSend(this._urlStr, config.headers);
this._serviceName = config.serviceName;
this._statusCodeTagName =
config.statusCodeTagName || defaultStatusCodeTagName;
this._statusDescriptionTagName =
config.statusDescriptionTagName || defaultStatusErrorTagName;
this._isShutdown = false;
if (typeof config.getExportRequestHeaders === 'function') {
this._getHeaders = prepareGetHeaders(config.getExportRequestHeaders);
}
else {
// noop
this._beforeSend = function () { };
}
}
/**
* Export spans.
*/
export(spans, resultCallback) {
const serviceName = String(this._serviceName ||
spans[0].resource.attributes[SEMRESATTRS_SERVICE_NAME] ||
this.DEFAULT_SERVICE_NAME);
diag.debug('Zipkin exporter export');
if (this._isShutdown) {
setTimeout(() => resultCallback({
code: ExportResultCode.FAILED,
error: new Error('Exporter has been shutdown'),
}));
return;
}
const promise = new Promise(resolve => {
this._sendSpans(spans, serviceName, result => {
resolve();
resultCallback(result);
});
});
this._sendingPromises.push(promise);
const popPromise = () => {
const index = this._sendingPromises.indexOf(promise);
this._sendingPromises.splice(index, 1);
};
promise.then(popPromise, popPromise);
}
/**
* Shutdown exporter. Noop operation in this exporter.
*/
shutdown() {
diag.debug('Zipkin exporter shutdown');
this._isShutdown = true;
return this.forceFlush();
}
/**
* Exports any pending spans in exporter
*/
forceFlush() {
return new Promise((resolve, reject) => {
Promise.all(this._sendingPromises).then(() => {
resolve();
}, reject);
});
}
/**
* if user defines getExportRequestHeaders in config then this will be called
* every time before send, otherwise it will be replaced with noop in
* constructor
* @default noop
*/
_beforeSend() {
if (this._getHeaders) {
this._send = prepareSend(this._urlStr, this._getHeaders());
}
}
/**
* Transform spans and sends to Zipkin service.
*/
_sendSpans(spans, serviceName, done) {
const zipkinSpans = spans.map(span => toZipkinSpan(span, String(span.attributes[SEMRESATTRS_SERVICE_NAME] ||
span.resource.attributes[SEMRESATTRS_SERVICE_NAME] ||
serviceName), this._statusCodeTagName, this._statusDescriptionTagName));
this._beforeSend();
return this._send(zipkinSpans, (result) => {
if (done) {
return done(result);
}
});
}
}
//# sourceMappingURL=zipkin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
export { prepareSend } from './platform';
export { ExporterConfig } from './types';
export { ZipkinExporter } from './zipkin';
//# 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 { prepareSend } from './platform';
export { ZipkinExporter } from './zipkin';
//# 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,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzC,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,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 { prepareSend } from './platform';\nexport { ExporterConfig } from './types';\nexport { ZipkinExporter } from './zipkin';\n"]}

View File

@@ -0,0 +1,2 @@
export { prepareSend } from './util';
//# 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 { prepareSend } from './util';
//# 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,WAAW,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 { prepareSend } from './util';\n"]}

View File

@@ -0,0 +1,9 @@
import * as zipkinTypes from '../../types';
/**
* Prepares send function that will send spans to the remote Zipkin service.
* @param urlStr - url to send spans
* @param headers - headers
* send
*/
export declare function prepareSend(urlStr: string, headers?: Record<string, string>): zipkinTypes.SendFn;
//# sourceMappingURL=util.d.ts.map

View File

@@ -0,0 +1,105 @@
/*
* 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 { ExportResultCode, globalErrorHandler, } from '@opentelemetry/core';
/**
* Prepares send function that will send spans to the remote Zipkin service.
* @param urlStr - url to send spans
* @param headers - headers
* send
*/
export function prepareSend(urlStr, headers) {
let xhrHeaders;
const useBeacon = typeof navigator.sendBeacon === 'function' && !headers;
if (headers) {
xhrHeaders = {
Accept: 'application/json',
'Content-Type': 'application/json',
...headers,
};
}
/**
* Send spans to the remote Zipkin service.
*/
return function send(zipkinSpans, done) {
if (zipkinSpans.length === 0) {
diag.debug('Zipkin send with empty spans');
return done({ code: ExportResultCode.SUCCESS });
}
const payload = JSON.stringify(zipkinSpans);
if (useBeacon) {
sendWithBeacon(payload, done, urlStr);
}
else {
sendWithXhr(payload, done, urlStr, xhrHeaders);
}
};
}
/**
* Sends data using beacon
* @param data
* @param done
* @param urlStr
*/
function sendWithBeacon(data, done, urlStr) {
if (navigator.sendBeacon(urlStr, data)) {
diag.debug('sendBeacon - can send', data);
done({ code: ExportResultCode.SUCCESS });
}
else {
done({
code: ExportResultCode.FAILED,
error: new Error(`sendBeacon - cannot send ${data}`),
});
}
}
/**
* Sends data using XMLHttpRequest
* @param data
* @param done
* @param urlStr
* @param xhrHeaders
*/
function sendWithXhr(data, done, urlStr, xhrHeaders = {}) {
const xhr = new XMLHttpRequest();
xhr.open('POST', urlStr);
Object.entries(xhrHeaders).forEach(([k, v]) => {
xhr.setRequestHeader(k, v);
});
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
const statusCode = xhr.status || 0;
diag.debug(`Zipkin response status code: ${statusCode}, body: ${data}`);
if (xhr.status >= 200 && xhr.status < 400) {
return done({ code: ExportResultCode.SUCCESS });
}
else {
return done({
code: ExportResultCode.FAILED,
error: new Error(`Got unexpected status code from zipkin: ${xhr.status}`),
});
}
}
};
xhr.onerror = msg => {
globalErrorHandler(new Error(`Zipkin request error: ${msg}`));
return done({ code: ExportResultCode.FAILED });
};
// Issue request to remote service
diag.debug(`Zipkin request payload: ${data}`);
xhr.send(data);
}
//# sourceMappingURL=util.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export { prepareSend } 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 { prepareSend } 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,WAAW,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 { prepareSend } from './node';\n"]}

View File

@@ -0,0 +1,2 @@
export { prepareSend } from './util';
//# 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 { prepareSend } from './util';
//# 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,WAAW,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 { prepareSend } from './util';\n"]}

View File

@@ -0,0 +1,9 @@
import * as zipkinTypes from '../../types';
/**
* Prepares send function that will send spans to the remote Zipkin service.
* @param urlStr - url to send spans
* @param headers - headers
* send
*/
export declare function prepareSend(urlStr: string, headers?: Record<string, string>): zipkinTypes.SendFn;
//# sourceMappingURL=util.d.ts.map

View File

@@ -0,0 +1,78 @@
/*
* 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 { ExportResultCode } from '@opentelemetry/core';
import * as http from 'http';
import * as https from 'https';
/**
* Prepares send function that will send spans to the remote Zipkin service.
* @param urlStr - url to send spans
* @param headers - headers
* send
*/
export function prepareSend(urlStr, headers) {
const url = new URL(urlStr);
const reqOpts = Object.assign({
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers,
},
});
/**
* Send spans to the remote Zipkin service.
*/
return function send(zipkinSpans, done) {
if (zipkinSpans.length === 0) {
diag.debug('Zipkin send with empty spans');
return done({ code: ExportResultCode.SUCCESS });
}
const { request } = url.protocol === 'http:' ? http : https;
const req = request(url, reqOpts, (res) => {
let rawData = '';
res.on('data', chunk => {
rawData += chunk;
});
res.on('end', () => {
const statusCode = res.statusCode || 0;
diag.debug(`Zipkin response status code: ${statusCode}, body: ${rawData}`);
// Consider 2xx and 3xx as success.
if (statusCode < 400) {
return done({ code: ExportResultCode.SUCCESS });
// Consider 4xx as failed non-retryable.
}
else {
return done({
code: ExportResultCode.FAILED,
error: new Error(`Got unexpected status code from zipkin: ${statusCode}`),
});
}
});
});
req.on('error', error => {
return done({
code: ExportResultCode.FAILED,
error,
});
});
// Issue request to remote service
const payload = JSON.stringify(zipkinSpans);
diag.debug(`Zipkin request payload: ${payload}`);
req.write(payload, 'utf8');
req.end();
};
}
//# sourceMappingURL=util.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"util.js","sourceRoot":"","sources":["../../../../src/platform/node/util.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAgB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAG/B;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CACzB,MAAc,EACd,OAAgC;IAEhC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;IAE5B,MAAM,OAAO,GAAwB,MAAM,CAAC,MAAM,CAAC;QACjD,MAAM,EAAE,MAAM;QACd,OAAO,EAAE;YACP,cAAc,EAAE,kBAAkB;YAClC,GAAG,OAAO;SACX;KACF,CAAC,CAAC;IAEH;;OAEG;IACH,OAAO,SAAS,IAAI,CAClB,WAA+B,EAC/B,IAAoC;QAEpC,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;YAC5B,IAAI,CAAC,KAAK,CAAC,8BAA8B,CAAC,CAAC;YAC3C,OAAO,IAAI,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;SACjD;QAED,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;QAC5D,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,OAAO,EAAE,CAAC,GAAyB,EAAE,EAAE;YAC9D,IAAI,OAAO,GAAG,EAAE,CAAC;YACjB,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE;gBACrB,OAAO,IAAI,KAAK,CAAC;YACnB,CAAC,CAAC,CAAC;YACH,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;gBACjB,MAAM,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,CAAC,CAAC;gBACvC,IAAI,CAAC,KAAK,CACR,gCAAgC,UAAU,WAAW,OAAO,EAAE,CAC/D,CAAC;gBAEF,mCAAmC;gBACnC,IAAI,UAAU,GAAG,GAAG,EAAE;oBACpB,OAAO,IAAI,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;oBAChD,wCAAwC;iBACzC;qBAAM;oBACL,OAAO,IAAI,CAAC;wBACV,IAAI,EAAE,gBAAgB,CAAC,MAAM;wBAC7B,KAAK,EAAE,IAAI,KAAK,CACd,2CAA2C,UAAU,EAAE,CACxD;qBACF,CAAC,CAAC;iBACJ;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE;YACtB,OAAO,IAAI,CAAC;gBACV,IAAI,EAAE,gBAAgB,CAAC,MAAM;gBAC7B,KAAK;aACN,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,kCAAkC;QAClC,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QAC5C,IAAI,CAAC,KAAK,CAAC,2BAA2B,OAAO,EAAE,CAAC,CAAC;QACjD,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC3B,GAAG,CAAC,GAAG,EAAE,CAAC;IACZ,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 { diag } from '@opentelemetry/api';\nimport { ExportResult, ExportResultCode } from '@opentelemetry/core';\nimport * as http from 'http';\nimport * as https from 'https';\nimport * as zipkinTypes from '../../types';\n\n/**\n * Prepares send function that will send spans to the remote Zipkin service.\n * @param urlStr - url to send spans\n * @param headers - headers\n * send\n */\nexport function prepareSend(\n urlStr: string,\n headers?: Record<string, string>\n): zipkinTypes.SendFn {\n const url = new URL(urlStr);\n\n const reqOpts: http.RequestOptions = Object.assign({\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n /**\n * Send spans to the remote Zipkin service.\n */\n return function send(\n zipkinSpans: zipkinTypes.Span[],\n done: (result: ExportResult) => void\n ) {\n if (zipkinSpans.length === 0) {\n diag.debug('Zipkin send with empty spans');\n return done({ code: ExportResultCode.SUCCESS });\n }\n\n const { request } = url.protocol === 'http:' ? http : https;\n const req = request(url, reqOpts, (res: http.IncomingMessage) => {\n let rawData = '';\n res.on('data', chunk => {\n rawData += chunk;\n });\n res.on('end', () => {\n const statusCode = res.statusCode || 0;\n diag.debug(\n `Zipkin response status code: ${statusCode}, body: ${rawData}`\n );\n\n // Consider 2xx and 3xx as success.\n if (statusCode < 400) {\n return done({ code: ExportResultCode.SUCCESS });\n // Consider 4xx as failed non-retryable.\n } else {\n return done({\n code: ExportResultCode.FAILED,\n error: new Error(\n `Got unexpected status code from zipkin: ${statusCode}`\n ),\n });\n }\n });\n });\n\n req.on('error', error => {\n return done({\n code: ExportResultCode.FAILED,\n error,\n });\n });\n\n // Issue request to remote service\n const payload = JSON.stringify(zipkinSpans);\n diag.debug(`Zipkin request payload: ${payload}`);\n req.write(payload, 'utf8');\n req.end();\n };\n}\n"]}

View File

@@ -0,0 +1,16 @@
import { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base';
import * as zipkinTypes from './types';
export declare const defaultStatusCodeTagName = "otel.status_code";
export declare const defaultStatusErrorTagName = "error";
/**
* Translate OpenTelemetry ReadableSpan to ZipkinSpan format
* @param span Span to be translated
*/
export declare function toZipkinSpan(span: ReadableSpan, serviceName: string, statusCodeTagName: string, statusErrorTagName: string): zipkinTypes.Span;
/** Converts OpenTelemetry Span properties to Zipkin Tags format. */
export declare function _toZipkinTags({ attributes, resource, status, droppedAttributesCount, droppedEventsCount, droppedLinksCount, }: ReadableSpan, statusCodeTagName: string, statusErrorTagName: string): zipkinTypes.Tags;
/**
* Converts OpenTelemetry Events to Zipkin Annotations format.
*/
export declare function _toZipkinAnnotations(events: TimedEvent[]): zipkinTypes.Annotation[];
//# sourceMappingURL=transform.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.
*/
import * as api from '@opentelemetry/api';
import { hrTimeToMicroseconds } from '@opentelemetry/core';
import * as zipkinTypes from './types';
const ZIPKIN_SPAN_KIND_MAPPING = {
[api.SpanKind.CLIENT]: zipkinTypes.SpanKind.CLIENT,
[api.SpanKind.SERVER]: zipkinTypes.SpanKind.SERVER,
[api.SpanKind.CONSUMER]: zipkinTypes.SpanKind.CONSUMER,
[api.SpanKind.PRODUCER]: zipkinTypes.SpanKind.PRODUCER,
// When absent, the span is local.
[api.SpanKind.INTERNAL]: undefined,
};
export const defaultStatusCodeTagName = 'otel.status_code';
export const defaultStatusErrorTagName = 'error';
/**
* Translate OpenTelemetry ReadableSpan to ZipkinSpan format
* @param span Span to be translated
*/
export function toZipkinSpan(span, serviceName, statusCodeTagName, statusErrorTagName) {
const zipkinSpan = {
traceId: span.spanContext().traceId,
parentId: span.parentSpanContext?.spanId,
name: span.name,
id: span.spanContext().spanId,
kind: ZIPKIN_SPAN_KIND_MAPPING[span.kind],
timestamp: hrTimeToMicroseconds(span.startTime),
duration: Math.round(hrTimeToMicroseconds(span.duration)),
localEndpoint: { serviceName },
tags: _toZipkinTags(span, statusCodeTagName, statusErrorTagName),
annotations: span.events.length
? _toZipkinAnnotations(span.events)
: undefined,
};
return zipkinSpan;
}
/** Converts OpenTelemetry Span properties to Zipkin Tags format. */
export function _toZipkinTags({ attributes, resource, status, droppedAttributesCount, droppedEventsCount, droppedLinksCount, }, statusCodeTagName, statusErrorTagName) {
const tags = {};
for (const key of Object.keys(attributes)) {
tags[key] = String(attributes[key]);
}
if (status.code !== api.SpanStatusCode.UNSET) {
tags[statusCodeTagName] = String(api.SpanStatusCode[status.code]);
}
if (status.code === api.SpanStatusCode.ERROR && status.message) {
tags[statusErrorTagName] = status.message;
}
/* Add droppedAttributesCount as a tag */
if (droppedAttributesCount) {
tags['otel.dropped_attributes_count'] = String(droppedAttributesCount);
}
/* Add droppedEventsCount as a tag */
if (droppedEventsCount) {
tags['otel.dropped_events_count'] = String(droppedEventsCount);
}
/* Add droppedLinksCount as a tag */
if (droppedLinksCount) {
tags['otel.dropped_links_count'] = String(droppedLinksCount);
}
Object.keys(resource.attributes).forEach(name => (tags[name] = String(resource.attributes[name])));
return tags;
}
/**
* Converts OpenTelemetry Events to Zipkin Annotations format.
*/
export function _toZipkinAnnotations(events) {
return events.map(event => ({
timestamp: Math.round(hrTimeToMicroseconds(event.time)),
value: event.name,
}));
}
//# sourceMappingURL=transform.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,158 @@
import { ExportResult } from '@opentelemetry/core';
/**
* Exporter config
*/
export interface ExporterConfig {
headers?: Record<string, string>;
serviceName?: string;
url?: string;
statusCodeTagName?: string;
statusDescriptionTagName?: string;
getExportRequestHeaders?: () => Record<string, string> | undefined;
}
/**
* Zipkin Span
* @see https://github.com/openzipkin/zipkin-api/blob/master/zipkin2-api.yaml
*/
export interface Span {
/**
* Trace identifier, set on all spans within it.
*/
traceId: string;
/**
* The logical operation this span represents in lowercase (e.g. rpc method).
* Leave absent if unknown.
*/
name: string;
/**
* The parent span ID or absent if this the root span in a trace.
*/
parentId?: string;
/**
* Unique 64bit identifier for this operation within the trace.
*/
id: string;
/**
* When present, kind clarifies timestamp, duration and remoteEndpoint.
* When absent, the span is local or incomplete.
*/
kind?: SpanKind;
/**
* Epoch microseconds of the start of this span, possibly absent if
* incomplete.
*/
timestamp: number;
/**
* Duration in microseconds of the critical path, if known.
*/
duration: number;
/**
* True is a request to store this span even if it overrides sampling policy.
* This is true when the `X-B3-Flags` header has a value of 1.
*/
debug?: boolean;
/**
* True if we are contributing to a span started by another tracer (ex on a
* different host).
*/
shared?: boolean;
/**
* The host that recorded this span, primarily for query by service name.
*/
localEndpoint: Endpoint;
/**
* Associates events that explain latency with the time they happened.
*/
annotations?: Annotation[];
/**
* Tags give your span context for search, viewing and analysis.
*/
tags: Tags;
}
/**
* Associates an event that explains latency with a timestamp.
* Unlike log statements, annotations are often codes. Ex. "ws" for WireSend
* Zipkin v1 core annotations such as "cs" and "sr" have been replaced with
* Span.Kind, which interprets timestamp and duration.
*/
export interface Annotation {
/**
* Epoch microseconds of this event.
* For example, 1502787600000000 corresponds to 2017-08-15 09:00 UTC
*/
timestamp: number;
/**
* Usually a short tag indicating an event, like "error"
* While possible to add larger data, such as garbage collection details, low
* cardinality event names both keep the size of spans down and also are easy
* to search against.
*/
value: string;
}
/**
* The network context of a node in the service graph.
*/
export interface Endpoint {
/**
* Lower-case label of this node in the service graph, such as "favstar".
* Leave absent if unknown.
* This is a primary label for trace lookup and aggregation, so it should be
* intuitive and consistent. Many use a name from service discovery.
*/
serviceName?: string;
/**
* The text representation of the primary IPv4 address associated with this
* connection. Ex. 192.168.99.100 Absent if unknown.
*/
ipv4?: string;
/**
* The text representation of the primary IPv6 address associated with a
* connection. Ex. 2001:db8::c001 Absent if unknown.
* Prefer using the ipv4 field for mapped addresses.
*/
port?: number;
}
/**
* Adds context to a span, for search, viewing and analysis.
* For example, a key "your_app.version" would let you lookup traces by version.
* A tag "sql.query" isn't searchable, but it can help in debugging when viewing
* a trace.
*/
export interface Tags {
[tagKey: string]: unknown;
}
/**
* When present, kind clarifies timestamp, duration and remoteEndpoint. When
* absent, the span is local or incomplete. Unlike client and server, there
* is no direct critical path latency relationship between producer and
* consumer spans.
* `CLIENT`
* timestamp is the moment a request was sent to the server.
* duration is the delay until a response or an error was received.
* remoteEndpoint is the server.
* `SERVER`
* timestamp is the moment a client request was received.
* duration is the delay until a response was sent or an error.
* remoteEndpoint is the client.
* `PRODUCER`
* timestamp is the moment a message was sent to a destination.
* duration is the delay sending the message, such as batching.
* remoteEndpoint is the broker.
* `CONSUMER`
* timestamp is the moment a message was received from an origin.
* duration is the delay consuming the message, such as from backlog.
* remoteEndpoint - Represents the broker. Leave serviceName absent if unknown.
*/
export declare enum SpanKind {
CLIENT = "CLIENT",
SERVER = "SERVER",
CONSUMER = "CONSUMER",
PRODUCER = "PRODUCER"
}
/**
* interface for function that will send zipkin spans
*/
export type SendFunction = (zipkinSpans: Span[], done: (result: ExportResult) => void) => void;
export type GetHeaders = () => Record<string, string> | undefined;
export type SendFn = (zipkinSpans: Span[], done: (result: ExportResult) => void) => void;
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1,45 @@
/*
* 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.
*/
/**
* When present, kind clarifies timestamp, duration and remoteEndpoint. When
* absent, the span is local or incomplete. Unlike client and server, there
* is no direct critical path latency relationship between producer and
* consumer spans.
* `CLIENT`
* timestamp is the moment a request was sent to the server.
* duration is the delay until a response or an error was received.
* remoteEndpoint is the server.
* `SERVER`
* timestamp is the moment a client request was received.
* duration is the delay until a response was sent or an error.
* remoteEndpoint is the client.
* `PRODUCER`
* timestamp is the moment a message was sent to a destination.
* duration is the delay sending the message, such as batching.
* remoteEndpoint is the broker.
* `CONSUMER`
* timestamp is the moment a message was received from an origin.
* duration is the delay consuming the message, such as from backlog.
* remoteEndpoint - Represents the broker. Leave serviceName absent if unknown.
*/
export var SpanKind;
(function (SpanKind) {
SpanKind["CLIENT"] = "CLIENT";
SpanKind["SERVER"] = "SERVER";
SpanKind["CONSUMER"] = "CONSUMER";
SpanKind["PRODUCER"] = "PRODUCER";
})(SpanKind || (SpanKind = {}));
//# sourceMappingURL=types.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
import { GetHeaders } from './types';
export declare function prepareGetHeaders(getExportRequestHeaders: GetHeaders): () => Record<string, string> | undefined;
//# sourceMappingURL=utils.d.ts.map

View File

@@ -0,0 +1,6 @@
export function prepareGetHeaders(getExportRequestHeaders) {
return function () {
return getExportRequestHeaders();
};
}
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAiBA,MAAM,UAAU,iBAAiB,CAC/B,uBAAmC;IAEnC,OAAO;QACL,OAAO,uBAAuB,EAAE,CAAC;IACnC,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 */\nimport { GetHeaders } from './types';\n\nexport function prepareGetHeaders(\n getExportRequestHeaders: GetHeaders\n): () => Record<string, string> | undefined {\n return function () {\n return getExportRequestHeaders();\n };\n}\n"]}

View File

@@ -0,0 +1,2 @@
export declare const VERSION = "2.0.0";
//# 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 const VERSION = '2.0.0';
//# 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,MAAM,OAAO,GAAG,OAAO,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 = '2.0.0';\n"]}

View File

@@ -0,0 +1,42 @@
import { ExportResult } from '@opentelemetry/core';
import { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base';
import * as zipkinTypes from './types';
/**
* Zipkin Exporter
*/
export declare class ZipkinExporter implements SpanExporter {
private readonly DEFAULT_SERVICE_NAME;
private readonly _statusCodeTagName;
private readonly _statusDescriptionTagName;
private _urlStr;
private _send;
private _getHeaders;
private _serviceName?;
private _isShutdown;
private _sendingPromises;
constructor(config?: zipkinTypes.ExporterConfig);
/**
* Export spans.
*/
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
/**
* Shutdown exporter. Noop operation in this exporter.
*/
shutdown(): Promise<void>;
/**
* Exports any pending spans in exporter
*/
forceFlush(): Promise<void>;
/**
* if user defines getExportRequestHeaders in config then this will be called
* every time before send, otherwise it will be replaced with noop in
* constructor
* @default noop
*/
private _beforeSend;
/**
* Transform spans and sends to Zipkin service.
*/
private _sendSpans;
}
//# sourceMappingURL=zipkin.d.ts.map

View File

@@ -0,0 +1,127 @@
/*
* 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 { ExportResultCode, getStringFromEnv, } from '@opentelemetry/core';
import { prepareSend } from './platform/index';
import { toZipkinSpan, defaultStatusCodeTagName, defaultStatusErrorTagName, } from './transform';
import { SEMRESATTRS_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
import { prepareGetHeaders } from './utils';
/**
* Zipkin Exporter
*/
export class ZipkinExporter {
DEFAULT_SERVICE_NAME = 'OpenTelemetry Service';
_statusCodeTagName;
_statusDescriptionTagName;
_urlStr;
_send;
_getHeaders;
_serviceName;
_isShutdown;
_sendingPromises = [];
constructor(config = {}) {
this._urlStr =
config.url ||
(getStringFromEnv('OTEL_EXPORTER_ZIPKIN_ENDPOINT') ??
'http://localhost:9411/api/v2/spans');
this._send = prepareSend(this._urlStr, config.headers);
this._serviceName = config.serviceName;
this._statusCodeTagName =
config.statusCodeTagName || defaultStatusCodeTagName;
this._statusDescriptionTagName =
config.statusDescriptionTagName || defaultStatusErrorTagName;
this._isShutdown = false;
if (typeof config.getExportRequestHeaders === 'function') {
this._getHeaders = prepareGetHeaders(config.getExportRequestHeaders);
}
else {
// noop
this._beforeSend = function () { };
}
}
/**
* Export spans.
*/
export(spans, resultCallback) {
const serviceName = String(this._serviceName ||
spans[0].resource.attributes[SEMRESATTRS_SERVICE_NAME] ||
this.DEFAULT_SERVICE_NAME);
diag.debug('Zipkin exporter export');
if (this._isShutdown) {
setTimeout(() => resultCallback({
code: ExportResultCode.FAILED,
error: new Error('Exporter has been shutdown'),
}));
return;
}
const promise = new Promise(resolve => {
this._sendSpans(spans, serviceName, result => {
resolve();
resultCallback(result);
});
});
this._sendingPromises.push(promise);
const popPromise = () => {
const index = this._sendingPromises.indexOf(promise);
this._sendingPromises.splice(index, 1);
};
promise.then(popPromise, popPromise);
}
/**
* Shutdown exporter. Noop operation in this exporter.
*/
shutdown() {
diag.debug('Zipkin exporter shutdown');
this._isShutdown = true;
return this.forceFlush();
}
/**
* Exports any pending spans in exporter
*/
forceFlush() {
return new Promise((resolve, reject) => {
Promise.all(this._sendingPromises).then(() => {
resolve();
}, reject);
});
}
/**
* if user defines getExportRequestHeaders in config then this will be called
* every time before send, otherwise it will be replaced with noop in
* constructor
* @default noop
*/
_beforeSend() {
if (this._getHeaders) {
this._send = prepareSend(this._urlStr, this._getHeaders());
}
}
/**
* Transform spans and sends to Zipkin service.
*/
_sendSpans(spans, serviceName, done) {
const zipkinSpans = spans.map(span => toZipkinSpan(span, String(span.attributes[SEMRESATTRS_SERVICE_NAME] ||
span.resource.attributes[SEMRESATTRS_SERVICE_NAME] ||
serviceName), this._statusCodeTagName, this._statusDescriptionTagName));
this._beforeSend();
return this._send(zipkinSpans, (result) => {
if (done) {
return done(result);
}
});
}
}
//# sourceMappingURL=zipkin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
export { prepareSend } from './platform';
export { ExporterConfig } from './types';
export { ZipkinExporter } from './zipkin';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,23 @@
"use strict";
/*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZipkinExporter = exports.prepareSend = void 0;
var platform_1 = require("./platform");
Object.defineProperty(exports, "prepareSend", { enumerable: true, get: function () { return platform_1.prepareSend; } });
var zipkin_1 = require("./zipkin");
Object.defineProperty(exports, "ZipkinExporter", { enumerable: true, get: function () { return zipkin_1.ZipkinExporter; } });
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,uCAAyC;AAAhC,uGAAA,WAAW,OAAA;AAEpB,mCAA0C;AAAjC,wGAAA,cAAc,OAAA","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 { prepareSend } from './platform';\nexport { ExporterConfig } from './types';\nexport { ZipkinExporter } from './zipkin';\n"]}

View File

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

View File

@@ -0,0 +1,21 @@
"use strict";
/*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareSend = void 0;
var util_1 = require("./util");
Object.defineProperty(exports, "prepareSend", { enumerable: true, get: function () { return util_1.prepareSend; } });
//# 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,+BAAqC;AAA5B,mGAAA,WAAW,OAAA","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 { prepareSend } from './util';\n"]}

View File

@@ -0,0 +1,9 @@
import * as zipkinTypes from '../../types';
/**
* Prepares send function that will send spans to the remote Zipkin service.
* @param urlStr - url to send spans
* @param headers - headers
* send
*/
export declare function prepareSend(urlStr: string, headers?: Record<string, string>): zipkinTypes.SendFn;
//# sourceMappingURL=util.d.ts.map

View File

@@ -0,0 +1,109 @@
"use strict";
/*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareSend = void 0;
const api_1 = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
/**
* Prepares send function that will send spans to the remote Zipkin service.
* @param urlStr - url to send spans
* @param headers - headers
* send
*/
function prepareSend(urlStr, headers) {
let xhrHeaders;
const useBeacon = typeof navigator.sendBeacon === 'function' && !headers;
if (headers) {
xhrHeaders = {
Accept: 'application/json',
'Content-Type': 'application/json',
...headers,
};
}
/**
* Send spans to the remote Zipkin service.
*/
return function send(zipkinSpans, done) {
if (zipkinSpans.length === 0) {
api_1.diag.debug('Zipkin send with empty spans');
return done({ code: core_1.ExportResultCode.SUCCESS });
}
const payload = JSON.stringify(zipkinSpans);
if (useBeacon) {
sendWithBeacon(payload, done, urlStr);
}
else {
sendWithXhr(payload, done, urlStr, xhrHeaders);
}
};
}
exports.prepareSend = prepareSend;
/**
* Sends data using beacon
* @param data
* @param done
* @param urlStr
*/
function sendWithBeacon(data, done, urlStr) {
if (navigator.sendBeacon(urlStr, data)) {
api_1.diag.debug('sendBeacon - can send', data);
done({ code: core_1.ExportResultCode.SUCCESS });
}
else {
done({
code: core_1.ExportResultCode.FAILED,
error: new Error(`sendBeacon - cannot send ${data}`),
});
}
}
/**
* Sends data using XMLHttpRequest
* @param data
* @param done
* @param urlStr
* @param xhrHeaders
*/
function sendWithXhr(data, done, urlStr, xhrHeaders = {}) {
const xhr = new XMLHttpRequest();
xhr.open('POST', urlStr);
Object.entries(xhrHeaders).forEach(([k, v]) => {
xhr.setRequestHeader(k, v);
});
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
const statusCode = xhr.status || 0;
api_1.diag.debug(`Zipkin response status code: ${statusCode}, body: ${data}`);
if (xhr.status >= 200 && xhr.status < 400) {
return done({ code: core_1.ExportResultCode.SUCCESS });
}
else {
return done({
code: core_1.ExportResultCode.FAILED,
error: new Error(`Got unexpected status code from zipkin: ${xhr.status}`),
});
}
}
};
xhr.onerror = msg => {
(0, core_1.globalErrorHandler)(new Error(`Zipkin request error: ${msg}`));
return done({ code: core_1.ExportResultCode.FAILED });
};
// Issue request to remote service
api_1.diag.debug(`Zipkin request payload: ${data}`);
xhr.send(data);
}
//# sourceMappingURL=util.js.map

File diff suppressed because one or more lines are too long

View File

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

View File

@@ -0,0 +1,21 @@
"use strict";
/*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareSend = void 0;
var node_1 = require("./node");
Object.defineProperty(exports, "prepareSend", { enumerable: true, get: function () { return node_1.prepareSend; } });
//# 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,+BAAqC;AAA5B,mGAAA,WAAW,OAAA","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 { prepareSend } from './node';\n"]}

View File

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

View File

@@ -0,0 +1,21 @@
"use strict";
/*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareSend = void 0;
var util_1 = require("./util");
Object.defineProperty(exports, "prepareSend", { enumerable: true, get: function () { return util_1.prepareSend; } });
//# 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,+BAAqC;AAA5B,mGAAA,WAAW,OAAA","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 { prepareSend } from './util';\n"]}

View File

@@ -0,0 +1,9 @@
import * as zipkinTypes from '../../types';
/**
* Prepares send function that will send spans to the remote Zipkin service.
* @param urlStr - url to send spans
* @param headers - headers
* send
*/
export declare function prepareSend(urlStr: string, headers?: Record<string, string>): zipkinTypes.SendFn;
//# sourceMappingURL=util.d.ts.map

View File

@@ -0,0 +1,82 @@
"use strict";
/*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareSend = void 0;
const api_1 = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
const http = require("http");
const https = require("https");
/**
* Prepares send function that will send spans to the remote Zipkin service.
* @param urlStr - url to send spans
* @param headers - headers
* send
*/
function prepareSend(urlStr, headers) {
const url = new URL(urlStr);
const reqOpts = Object.assign({
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers,
},
});
/**
* Send spans to the remote Zipkin service.
*/
return function send(zipkinSpans, done) {
if (zipkinSpans.length === 0) {
api_1.diag.debug('Zipkin send with empty spans');
return done({ code: core_1.ExportResultCode.SUCCESS });
}
const { request } = url.protocol === 'http:' ? http : https;
const req = request(url, reqOpts, (res) => {
let rawData = '';
res.on('data', chunk => {
rawData += chunk;
});
res.on('end', () => {
const statusCode = res.statusCode || 0;
api_1.diag.debug(`Zipkin response status code: ${statusCode}, body: ${rawData}`);
// Consider 2xx and 3xx as success.
if (statusCode < 400) {
return done({ code: core_1.ExportResultCode.SUCCESS });
// Consider 4xx as failed non-retryable.
}
else {
return done({
code: core_1.ExportResultCode.FAILED,
error: new Error(`Got unexpected status code from zipkin: ${statusCode}`),
});
}
});
});
req.on('error', error => {
return done({
code: core_1.ExportResultCode.FAILED,
error,
});
});
// Issue request to remote service
const payload = JSON.stringify(zipkinSpans);
api_1.diag.debug(`Zipkin request payload: ${payload}`);
req.write(payload, 'utf8');
req.end();
};
}
exports.prepareSend = prepareSend;
//# sourceMappingURL=util.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"util.js","sourceRoot":"","sources":["../../../../src/platform/node/util.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4CAA0C;AAC1C,8CAAqE;AACrE,6BAA6B;AAC7B,+BAA+B;AAG/B;;;;;GAKG;AACH,SAAgB,WAAW,CACzB,MAAc,EACd,OAAgC;IAEhC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;IAE5B,MAAM,OAAO,GAAwB,MAAM,CAAC,MAAM,CAAC;QACjD,MAAM,EAAE,MAAM;QACd,OAAO,EAAE;YACP,cAAc,EAAE,kBAAkB;YAClC,GAAG,OAAO;SACX;KACF,CAAC,CAAC;IAEH;;OAEG;IACH,OAAO,SAAS,IAAI,CAClB,WAA+B,EAC/B,IAAoC;QAEpC,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;YAC5B,UAAI,CAAC,KAAK,CAAC,8BAA8B,CAAC,CAAC;YAC3C,OAAO,IAAI,CAAC,EAAE,IAAI,EAAE,uBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;SACjD;QAED,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;QAC5D,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,OAAO,EAAE,CAAC,GAAyB,EAAE,EAAE;YAC9D,IAAI,OAAO,GAAG,EAAE,CAAC;YACjB,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE;gBACrB,OAAO,IAAI,KAAK,CAAC;YACnB,CAAC,CAAC,CAAC;YACH,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;gBACjB,MAAM,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,CAAC,CAAC;gBACvC,UAAI,CAAC,KAAK,CACR,gCAAgC,UAAU,WAAW,OAAO,EAAE,CAC/D,CAAC;gBAEF,mCAAmC;gBACnC,IAAI,UAAU,GAAG,GAAG,EAAE;oBACpB,OAAO,IAAI,CAAC,EAAE,IAAI,EAAE,uBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;oBAChD,wCAAwC;iBACzC;qBAAM;oBACL,OAAO,IAAI,CAAC;wBACV,IAAI,EAAE,uBAAgB,CAAC,MAAM;wBAC7B,KAAK,EAAE,IAAI,KAAK,CACd,2CAA2C,UAAU,EAAE,CACxD;qBACF,CAAC,CAAC;iBACJ;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE;YACtB,OAAO,IAAI,CAAC;gBACV,IAAI,EAAE,uBAAgB,CAAC,MAAM;gBAC7B,KAAK;aACN,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,kCAAkC;QAClC,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QAC5C,UAAI,CAAC,KAAK,CAAC,2BAA2B,OAAO,EAAE,CAAC,CAAC;QACjD,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC3B,GAAG,CAAC,GAAG,EAAE,CAAC;IACZ,CAAC,CAAC;AACJ,CAAC;AAlED,kCAkEC","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 { diag } from '@opentelemetry/api';\nimport { ExportResult, ExportResultCode } from '@opentelemetry/core';\nimport * as http from 'http';\nimport * as https from 'https';\nimport * as zipkinTypes from '../../types';\n\n/**\n * Prepares send function that will send spans to the remote Zipkin service.\n * @param urlStr - url to send spans\n * @param headers - headers\n * send\n */\nexport function prepareSend(\n urlStr: string,\n headers?: Record<string, string>\n): zipkinTypes.SendFn {\n const url = new URL(urlStr);\n\n const reqOpts: http.RequestOptions = Object.assign({\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n /**\n * Send spans to the remote Zipkin service.\n */\n return function send(\n zipkinSpans: zipkinTypes.Span[],\n done: (result: ExportResult) => void\n ) {\n if (zipkinSpans.length === 0) {\n diag.debug('Zipkin send with empty spans');\n return done({ code: ExportResultCode.SUCCESS });\n }\n\n const { request } = url.protocol === 'http:' ? http : https;\n const req = request(url, reqOpts, (res: http.IncomingMessage) => {\n let rawData = '';\n res.on('data', chunk => {\n rawData += chunk;\n });\n res.on('end', () => {\n const statusCode = res.statusCode || 0;\n diag.debug(\n `Zipkin response status code: ${statusCode}, body: ${rawData}`\n );\n\n // Consider 2xx and 3xx as success.\n if (statusCode < 400) {\n return done({ code: ExportResultCode.SUCCESS });\n // Consider 4xx as failed non-retryable.\n } else {\n return done({\n code: ExportResultCode.FAILED,\n error: new Error(\n `Got unexpected status code from zipkin: ${statusCode}`\n ),\n });\n }\n });\n });\n\n req.on('error', error => {\n return done({\n code: ExportResultCode.FAILED,\n error,\n });\n });\n\n // Issue request to remote service\n const payload = JSON.stringify(zipkinSpans);\n diag.debug(`Zipkin request payload: ${payload}`);\n req.write(payload, 'utf8');\n req.end();\n };\n}\n"]}

View File

@@ -0,0 +1,16 @@
import { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base';
import * as zipkinTypes from './types';
export declare const defaultStatusCodeTagName = "otel.status_code";
export declare const defaultStatusErrorTagName = "error";
/**
* Translate OpenTelemetry ReadableSpan to ZipkinSpan format
* @param span Span to be translated
*/
export declare function toZipkinSpan(span: ReadableSpan, serviceName: string, statusCodeTagName: string, statusErrorTagName: string): zipkinTypes.Span;
/** Converts OpenTelemetry Span properties to Zipkin Tags format. */
export declare function _toZipkinTags({ attributes, resource, status, droppedAttributesCount, droppedEventsCount, droppedLinksCount, }: ReadableSpan, statusCodeTagName: string, statusErrorTagName: string): zipkinTypes.Tags;
/**
* Converts OpenTelemetry Events to Zipkin Annotations format.
*/
export declare function _toZipkinAnnotations(events: TimedEvent[]): zipkinTypes.Annotation[];
//# sourceMappingURL=transform.d.ts.map

View File

@@ -0,0 +1,92 @@
"use strict";
/*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports._toZipkinAnnotations = exports._toZipkinTags = exports.toZipkinSpan = exports.defaultStatusErrorTagName = exports.defaultStatusCodeTagName = void 0;
const api = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
const zipkinTypes = require("./types");
const ZIPKIN_SPAN_KIND_MAPPING = {
[api.SpanKind.CLIENT]: zipkinTypes.SpanKind.CLIENT,
[api.SpanKind.SERVER]: zipkinTypes.SpanKind.SERVER,
[api.SpanKind.CONSUMER]: zipkinTypes.SpanKind.CONSUMER,
[api.SpanKind.PRODUCER]: zipkinTypes.SpanKind.PRODUCER,
// When absent, the span is local.
[api.SpanKind.INTERNAL]: undefined,
};
exports.defaultStatusCodeTagName = 'otel.status_code';
exports.defaultStatusErrorTagName = 'error';
/**
* Translate OpenTelemetry ReadableSpan to ZipkinSpan format
* @param span Span to be translated
*/
function toZipkinSpan(span, serviceName, statusCodeTagName, statusErrorTagName) {
const zipkinSpan = {
traceId: span.spanContext().traceId,
parentId: span.parentSpanContext?.spanId,
name: span.name,
id: span.spanContext().spanId,
kind: ZIPKIN_SPAN_KIND_MAPPING[span.kind],
timestamp: (0, core_1.hrTimeToMicroseconds)(span.startTime),
duration: Math.round((0, core_1.hrTimeToMicroseconds)(span.duration)),
localEndpoint: { serviceName },
tags: _toZipkinTags(span, statusCodeTagName, statusErrorTagName),
annotations: span.events.length
? _toZipkinAnnotations(span.events)
: undefined,
};
return zipkinSpan;
}
exports.toZipkinSpan = toZipkinSpan;
/** Converts OpenTelemetry Span properties to Zipkin Tags format. */
function _toZipkinTags({ attributes, resource, status, droppedAttributesCount, droppedEventsCount, droppedLinksCount, }, statusCodeTagName, statusErrorTagName) {
const tags = {};
for (const key of Object.keys(attributes)) {
tags[key] = String(attributes[key]);
}
if (status.code !== api.SpanStatusCode.UNSET) {
tags[statusCodeTagName] = String(api.SpanStatusCode[status.code]);
}
if (status.code === api.SpanStatusCode.ERROR && status.message) {
tags[statusErrorTagName] = status.message;
}
/* Add droppedAttributesCount as a tag */
if (droppedAttributesCount) {
tags['otel.dropped_attributes_count'] = String(droppedAttributesCount);
}
/* Add droppedEventsCount as a tag */
if (droppedEventsCount) {
tags['otel.dropped_events_count'] = String(droppedEventsCount);
}
/* Add droppedLinksCount as a tag */
if (droppedLinksCount) {
tags['otel.dropped_links_count'] = String(droppedLinksCount);
}
Object.keys(resource.attributes).forEach(name => (tags[name] = String(resource.attributes[name])));
return tags;
}
exports._toZipkinTags = _toZipkinTags;
/**
* Converts OpenTelemetry Events to Zipkin Annotations format.
*/
function _toZipkinAnnotations(events) {
return events.map(event => ({
timestamp: Math.round((0, core_1.hrTimeToMicroseconds)(event.time)),
value: event.name,
}));
}
exports._toZipkinAnnotations = _toZipkinAnnotations;
//# sourceMappingURL=transform.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,158 @@
import { ExportResult } from '@opentelemetry/core';
/**
* Exporter config
*/
export interface ExporterConfig {
headers?: Record<string, string>;
serviceName?: string;
url?: string;
statusCodeTagName?: string;
statusDescriptionTagName?: string;
getExportRequestHeaders?: () => Record<string, string> | undefined;
}
/**
* Zipkin Span
* @see https://github.com/openzipkin/zipkin-api/blob/master/zipkin2-api.yaml
*/
export interface Span {
/**
* Trace identifier, set on all spans within it.
*/
traceId: string;
/**
* The logical operation this span represents in lowercase (e.g. rpc method).
* Leave absent if unknown.
*/
name: string;
/**
* The parent span ID or absent if this the root span in a trace.
*/
parentId?: string;
/**
* Unique 64bit identifier for this operation within the trace.
*/
id: string;
/**
* When present, kind clarifies timestamp, duration and remoteEndpoint.
* When absent, the span is local or incomplete.
*/
kind?: SpanKind;
/**
* Epoch microseconds of the start of this span, possibly absent if
* incomplete.
*/
timestamp: number;
/**
* Duration in microseconds of the critical path, if known.
*/
duration: number;
/**
* True is a request to store this span even if it overrides sampling policy.
* This is true when the `X-B3-Flags` header has a value of 1.
*/
debug?: boolean;
/**
* True if we are contributing to a span started by another tracer (ex on a
* different host).
*/
shared?: boolean;
/**
* The host that recorded this span, primarily for query by service name.
*/
localEndpoint: Endpoint;
/**
* Associates events that explain latency with the time they happened.
*/
annotations?: Annotation[];
/**
* Tags give your span context for search, viewing and analysis.
*/
tags: Tags;
}
/**
* Associates an event that explains latency with a timestamp.
* Unlike log statements, annotations are often codes. Ex. "ws" for WireSend
* Zipkin v1 core annotations such as "cs" and "sr" have been replaced with
* Span.Kind, which interprets timestamp and duration.
*/
export interface Annotation {
/**
* Epoch microseconds of this event.
* For example, 1502787600000000 corresponds to 2017-08-15 09:00 UTC
*/
timestamp: number;
/**
* Usually a short tag indicating an event, like "error"
* While possible to add larger data, such as garbage collection details, low
* cardinality event names both keep the size of spans down and also are easy
* to search against.
*/
value: string;
}
/**
* The network context of a node in the service graph.
*/
export interface Endpoint {
/**
* Lower-case label of this node in the service graph, such as "favstar".
* Leave absent if unknown.
* This is a primary label for trace lookup and aggregation, so it should be
* intuitive and consistent. Many use a name from service discovery.
*/
serviceName?: string;
/**
* The text representation of the primary IPv4 address associated with this
* connection. Ex. 192.168.99.100 Absent if unknown.
*/
ipv4?: string;
/**
* The text representation of the primary IPv6 address associated with a
* connection. Ex. 2001:db8::c001 Absent if unknown.
* Prefer using the ipv4 field for mapped addresses.
*/
port?: number;
}
/**
* Adds context to a span, for search, viewing and analysis.
* For example, a key "your_app.version" would let you lookup traces by version.
* A tag "sql.query" isn't searchable, but it can help in debugging when viewing
* a trace.
*/
export interface Tags {
[tagKey: string]: unknown;
}
/**
* When present, kind clarifies timestamp, duration and remoteEndpoint. When
* absent, the span is local or incomplete. Unlike client and server, there
* is no direct critical path latency relationship between producer and
* consumer spans.
* `CLIENT`
* timestamp is the moment a request was sent to the server.
* duration is the delay until a response or an error was received.
* remoteEndpoint is the server.
* `SERVER`
* timestamp is the moment a client request was received.
* duration is the delay until a response was sent or an error.
* remoteEndpoint is the client.
* `PRODUCER`
* timestamp is the moment a message was sent to a destination.
* duration is the delay sending the message, such as batching.
* remoteEndpoint is the broker.
* `CONSUMER`
* timestamp is the moment a message was received from an origin.
* duration is the delay consuming the message, such as from backlog.
* remoteEndpoint - Represents the broker. Leave serviceName absent if unknown.
*/
export declare enum SpanKind {
CLIENT = "CLIENT",
SERVER = "SERVER",
CONSUMER = "CONSUMER",
PRODUCER = "PRODUCER"
}
/**
* interface for function that will send zipkin spans
*/
export type SendFunction = (zipkinSpans: Span[], done: (result: ExportResult) => void) => void;
export type GetHeaders = () => Record<string, string> | undefined;
export type SendFn = (zipkinSpans: Span[], done: (result: ExportResult) => void) => void;
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1,48 @@
"use strict";
/*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpanKind = void 0;
/**
* When present, kind clarifies timestamp, duration and remoteEndpoint. When
* absent, the span is local or incomplete. Unlike client and server, there
* is no direct critical path latency relationship between producer and
* consumer spans.
* `CLIENT`
* timestamp is the moment a request was sent to the server.
* duration is the delay until a response or an error was received.
* remoteEndpoint is the server.
* `SERVER`
* timestamp is the moment a client request was received.
* duration is the delay until a response was sent or an error.
* remoteEndpoint is the client.
* `PRODUCER`
* timestamp is the moment a message was sent to a destination.
* duration is the delay sending the message, such as batching.
* remoteEndpoint is the broker.
* `CONSUMER`
* timestamp is the moment a message was received from an origin.
* duration is the delay consuming the message, such as from backlog.
* remoteEndpoint - Represents the broker. Leave serviceName absent if unknown.
*/
var SpanKind;
(function (SpanKind) {
SpanKind["CLIENT"] = "CLIENT";
SpanKind["SERVER"] = "SERVER";
SpanKind["CONSUMER"] = "CONSUMER";
SpanKind["PRODUCER"] = "PRODUCER";
})(SpanKind = exports.SpanKind || (exports.SpanKind = {}));
//# sourceMappingURL=types.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
import { GetHeaders } from './types';
export declare function prepareGetHeaders(getExportRequestHeaders: GetHeaders): () => Record<string, string> | undefined;
//# sourceMappingURL=utils.d.ts.map

View File

@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareGetHeaders = void 0;
function prepareGetHeaders(getExportRequestHeaders) {
return function () {
return getExportRequestHeaders();
};
}
exports.prepareGetHeaders = prepareGetHeaders;
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";;;AAiBA,SAAgB,iBAAiB,CAC/B,uBAAmC;IAEnC,OAAO;QACL,OAAO,uBAAuB,EAAE,CAAC;IACnC,CAAC,CAAC;AACJ,CAAC;AAND,8CAMC","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 */\nimport { GetHeaders } from './types';\n\nexport function prepareGetHeaders(\n getExportRequestHeaders: GetHeaders\n): () => Record<string, string> | undefined {\n return function () {\n return getExportRequestHeaders();\n };\n}\n"]}

View File

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

View File

@@ -0,0 +1,21 @@
"use strict";
/*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.VERSION = void 0;
// this is autogenerated file, see scripts/version-update.js
exports.VERSION = '2.0.0';
//# 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;AAC/C,QAAA,OAAO,GAAG,OAAO,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 = '2.0.0';\n"]}

View File

@@ -0,0 +1,42 @@
import { ExportResult } from '@opentelemetry/core';
import { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base';
import * as zipkinTypes from './types';
/**
* Zipkin Exporter
*/
export declare class ZipkinExporter implements SpanExporter {
private readonly DEFAULT_SERVICE_NAME;
private readonly _statusCodeTagName;
private readonly _statusDescriptionTagName;
private _urlStr;
private _send;
private _getHeaders;
private _serviceName?;
private _isShutdown;
private _sendingPromises;
constructor(config?: zipkinTypes.ExporterConfig);
/**
* Export spans.
*/
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
/**
* Shutdown exporter. Noop operation in this exporter.
*/
shutdown(): Promise<void>;
/**
* Exports any pending spans in exporter
*/
forceFlush(): Promise<void>;
/**
* if user defines getExportRequestHeaders in config then this will be called
* every time before send, otherwise it will be replaced with noop in
* constructor
* @default noop
*/
private _beforeSend;
/**
* Transform spans and sends to Zipkin service.
*/
private _sendSpans;
}
//# sourceMappingURL=zipkin.d.ts.map

View File

@@ -0,0 +1,131 @@
"use strict";
/*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZipkinExporter = void 0;
const api_1 = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
const index_1 = require("./platform/index");
const transform_1 = require("./transform");
const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
const utils_1 = require("./utils");
/**
* Zipkin Exporter
*/
class ZipkinExporter {
DEFAULT_SERVICE_NAME = 'OpenTelemetry Service';
_statusCodeTagName;
_statusDescriptionTagName;
_urlStr;
_send;
_getHeaders;
_serviceName;
_isShutdown;
_sendingPromises = [];
constructor(config = {}) {
this._urlStr =
config.url ||
((0, core_1.getStringFromEnv)('OTEL_EXPORTER_ZIPKIN_ENDPOINT') ??
'http://localhost:9411/api/v2/spans');
this._send = (0, index_1.prepareSend)(this._urlStr, config.headers);
this._serviceName = config.serviceName;
this._statusCodeTagName =
config.statusCodeTagName || transform_1.defaultStatusCodeTagName;
this._statusDescriptionTagName =
config.statusDescriptionTagName || transform_1.defaultStatusErrorTagName;
this._isShutdown = false;
if (typeof config.getExportRequestHeaders === 'function') {
this._getHeaders = (0, utils_1.prepareGetHeaders)(config.getExportRequestHeaders);
}
else {
// noop
this._beforeSend = function () { };
}
}
/**
* Export spans.
*/
export(spans, resultCallback) {
const serviceName = String(this._serviceName ||
spans[0].resource.attributes[semantic_conventions_1.SEMRESATTRS_SERVICE_NAME] ||
this.DEFAULT_SERVICE_NAME);
api_1.diag.debug('Zipkin exporter export');
if (this._isShutdown) {
setTimeout(() => resultCallback({
code: core_1.ExportResultCode.FAILED,
error: new Error('Exporter has been shutdown'),
}));
return;
}
const promise = new Promise(resolve => {
this._sendSpans(spans, serviceName, result => {
resolve();
resultCallback(result);
});
});
this._sendingPromises.push(promise);
const popPromise = () => {
const index = this._sendingPromises.indexOf(promise);
this._sendingPromises.splice(index, 1);
};
promise.then(popPromise, popPromise);
}
/**
* Shutdown exporter. Noop operation in this exporter.
*/
shutdown() {
api_1.diag.debug('Zipkin exporter shutdown');
this._isShutdown = true;
return this.forceFlush();
}
/**
* Exports any pending spans in exporter
*/
forceFlush() {
return new Promise((resolve, reject) => {
Promise.all(this._sendingPromises).then(() => {
resolve();
}, reject);
});
}
/**
* if user defines getExportRequestHeaders in config then this will be called
* every time before send, otherwise it will be replaced with noop in
* constructor
* @default noop
*/
_beforeSend() {
if (this._getHeaders) {
this._send = (0, index_1.prepareSend)(this._urlStr, this._getHeaders());
}
}
/**
* Transform spans and sends to Zipkin service.
*/
_sendSpans(spans, serviceName, done) {
const zipkinSpans = spans.map(span => (0, transform_1.toZipkinSpan)(span, String(span.attributes[semantic_conventions_1.SEMRESATTRS_SERVICE_NAME] ||
span.resource.attributes[semantic_conventions_1.SEMRESATTRS_SERVICE_NAME] ||
serviceName), this._statusCodeTagName, this._statusDescriptionTagName));
this._beforeSend();
return this._send(zipkinSpans, (result) => {
if (done) {
return done(result);
}
});
}
}
exports.ZipkinExporter = ZipkinExporter;
//# sourceMappingURL=zipkin.js.map

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