@uoa/lambda-tracing 2.0.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/uoaHttps.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import * as https from "https";
2
2
  import * as http from "http";
3
3
  import { URL } from "url";
4
- import {context, propagation, trace} from "@opentelemetry/api";
4
+ import {context, propagation} from "@opentelemetry/api";
5
5
  import {RequestOptions} from "https";
6
- import {getTracer} from "./tracing";
6
+ import {ClientRequest} from "http";
7
+ import {XMLParser} from "fast-xml-parser";
7
8
 
8
9
  function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
9
10
  function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
@@ -28,38 +29,8 @@ async function doGetRequest(hostname: string, path: string, headers: any, port:
28
29
  }
29
30
  propagation.inject(context.active(), options.headers);
30
31
 
31
- const req = https.request(options, function (response) {
32
- const chunks: any[] = [];
33
-
34
- response.on("data", function (chunk) {
35
- chunks.push(chunk);
36
- });
37
-
38
- response.on("end", function () {
39
- let body: any = Buffer.concat(chunks);
40
- if (options.headers['Content-Type'] === 'application/json') {
41
- body = JSON.parse(body.toString());
42
- } else {
43
- body = body.toString();
44
- }
45
- resolve(body);
46
- });
47
-
48
- response.on("error", function (e) {
49
- reject(e);
50
- })
51
- });
52
-
32
+ const req = doHttpsRequest(options, resolve, reject);
53
33
  req.end();
54
-
55
- });
56
- }
57
-
58
- async function doGetRequestExternal(hostname: string, path: string, headers: any, port: number | string = 443) {
59
- return getTracer().startActiveSpan(hostname+path, async (span) => {
60
- const result = await doGetRequest(hostname, path, headers, port);
61
- span.end();
62
- return result;
63
34
  });
64
35
  }
65
36
 
@@ -74,54 +45,12 @@ async function doPostRequest(hostname: string, path: string, headers: any, data:
74
45
  }
75
46
  propagation.inject(context.active(), options.headers);
76
47
 
77
- const req = https.request(options, function (response) {
78
- const chunks: any[] = [];
79
-
80
- response.on("data", function (chunk) {
81
- chunks.push(chunk);
82
- });
83
-
84
- response.on("end", function () {
85
- if (response.statusCode == 204) {
86
- //204 is no content, and most JSON parses blow up on an empty string
87
- resolve(null);
88
- } else {
89
- let body: any = Buffer.concat(chunks);
90
- if (!('Content-Type' in options.headers) || options.headers['Content-Type'] === 'application/json') {
91
- body = JSON.parse(body.toString());
92
- } else {
93
- body = body.toString();
94
- }
95
- resolve(body);
96
- }
97
- });
98
-
99
- response.on("error", function (e) {
100
- reject(e);
101
- })
102
- });
103
-
104
- if (data) {
105
- if (!('Content-Type' in options.headers) || options.headers['Content-Type'] === 'application/json') {
106
- //We serialize using JSON.stringify as a default, or if a JSON is specified
107
- req.write(JSON.stringify(data));
108
- } else {
109
- // If another content-type is specified however, we respect the serialization provided
110
- req.write(data);
111
- }
112
- }
48
+ const req = doHttpsRequest(options, resolve, reject);
49
+ setRequestBody(req, data);
113
50
  req.end();
114
51
  });
115
52
  }
116
53
 
117
- async function doPostRequestExternal(hostname: string, path: string, headers: any, data: any, port: number | string = 443) {
118
- return getTracer().startActiveSpan(hostname+path, async(span) => {
119
- const result = await doPostRequest(hostname, path, headers, port);
120
- span.end();
121
- return result;
122
- });
123
- }
124
-
125
54
  async function doPutRequest(hostname: string, path: string, headers: any, data: any, port: number | string = 443) {
126
55
  return new Promise(function (resolve, reject) {
127
56
  const options = {
@@ -133,54 +62,12 @@ async function doPutRequest(hostname: string, path: string, headers: any, data:
133
62
  }
134
63
  propagation.inject(context.active(), options.headers);
135
64
 
136
- const req = https.request(options, function (response) {
137
- const chunks: any[] = [];
138
-
139
- response.on("data", function (chunk) {
140
- chunks.push(chunk);
141
- });
142
-
143
- response.on("end", function () {
144
- if (response.statusCode == 204) {
145
- //204 is no content, and most JSON parses blow up on an empty string
146
- resolve(null);
147
- } else {
148
- let body: any = Buffer.concat(chunks);
149
- if (!('Content-Type' in options.headers) || options.headers['Content-Type'] === 'application/json') {
150
- body = JSON.parse(body.toString());
151
- } else {
152
- body = body.toString();
153
- }
154
- resolve(body);
155
- }
156
- });
157
-
158
- response.on("error", function (e) {
159
- reject(e);
160
- })
161
- });
162
-
163
- if (data) {
164
- if (!('Content-Type' in options.headers) || options.headers['Content-Type'] === 'application/json') {
165
- //We serialize using JSON.stringify as a default, or if a JSON is specified
166
- req.write(JSON.stringify(data));
167
- } else {
168
- // If another content-type is specified however, we respect the serialization provided
169
- req.write(data);
170
- }
171
- }
65
+ const req = doHttpsRequest(options, resolve, reject);
66
+ setRequestBody(req, data);
172
67
  req.end();
173
68
  });
174
69
  }
175
70
 
176
- async function doPutRequestExternal(hostname: string, path: string, headers: any, data: any, port: number | string = 443) {
177
- return getTracer().startActiveSpan(hostname+path, async(span) => {
178
- const result = await doPutRequest(hostname, path, headers, port);
179
- span.end();
180
- return result;
181
- });
182
- }
183
-
184
71
  async function doDeleteRequest(hostname: string, path: string, headers: any, port: number | string = 443) {
185
72
  return new Promise(function (resolve, reject) {
186
73
  const options = {
@@ -192,43 +79,70 @@ async function doDeleteRequest(hostname: string, path: string, headers: any, por
192
79
  }
193
80
  propagation.inject(context.active(), options.headers);
194
81
 
195
- const req = https.request(options, function (response) {
196
- const chunks: any[] = [];
197
-
198
- response.on("data", function (chunk) {
199
- chunks.push(chunk);
200
- });
201
-
202
- response.on("end", function () {
203
- if (response.statusCode == 204) {
204
- //204 is no content, and most JSON parses blow up on an empty string
205
- resolve(null);
206
- } else {
207
- let body: any = Buffer.concat(chunks);
208
- if (!('Content-Type' in options.headers) || options.headers['Content-Type'] === 'application/json') {
209
- body = JSON.parse(body.toString());
82
+ const req = doHttpsRequest(options, resolve, reject);
83
+ req.end();
84
+ });
85
+ }
86
+
87
+ function doHttpsRequest(options: RequestOptions, resolve: any, reject: any): ClientRequest {
88
+ return https.request(options, function (response) {
89
+ const chunks: any[] = [];
90
+
91
+ response.on("data", function (chunk) {
92
+ chunks.push(chunk);
93
+ });
94
+
95
+ response.on("end", function () {
96
+ if (response.statusCode === 204) {
97
+ //204 is no content, and most JSON parses blow up on an empty string
98
+ resolve(null);
99
+ } else {
100
+ try {
101
+ let body: Buffer = Buffer.concat(chunks);
102
+ let parsedBody: any = body.toString();
103
+
104
+ //Get the response content-type header value so we can apply different parsing methods
105
+ const responseContentType: string = response.headers["content-type"]?.toLowerCase() ?? '';
106
+ if (responseContentType === '' || responseContentType.includes('application/json')) {
107
+ parsedBody = JSON.parse(body.toString());
108
+ } else if (responseContentType.includes('application/xml') || responseContentType.includes('text/xml')) {
109
+ const parser = new XMLParser({
110
+ ignoreDeclaration: true,
111
+ ignorePiTags: true
112
+ });
113
+ parsedBody = parser.parse(body.toString());
114
+ } else if (responseContentType.includes('image/')) {
115
+ parsedBody = body.toString('base64');
116
+ }
117
+
118
+ if (response.statusCode !== undefined && response.statusCode >= 200 && response.statusCode < 300) {
119
+ resolve(parsedBody);
210
120
  } else {
211
- body = body.toString();
121
+ reject(parsedBody);
212
122
  }
213
- resolve(body);
123
+ } catch (e: any) {
124
+ reject(e);
214
125
  }
215
- });
216
-
217
- response.on("error", function (e) {
218
- reject(e);
219
- })
126
+ }
220
127
  });
221
128
 
222
- req.end();
129
+ response.on("error", function (e) {
130
+ reject(e);
131
+ })
223
132
  });
224
133
  }
225
134
 
226
- async function doDeleteRequestExternal(hostname: string, path: string, headers: any, data: any, port: number | string = 443) {
227
- return getTracer().startActiveSpan(hostname+path, async (span) => {
228
- const result = await doDeleteRequest(hostname, path, headers, port);
229
- span.end();
230
- return result;
231
- });
135
+ function setRequestBody(request: ClientRequest, data: any) {
136
+ if (data) {
137
+ const requestContentType: string = request.getHeader('content-type')?.toString() ?? '';
138
+ if (requestContentType === '' || requestContentType.includes('application/json')) {
139
+ //We serialize using JSON.stringify as a default, or if JSON is specified
140
+ request.write(JSON.stringify(data));
141
+ } else {
142
+ // If another content-type is specified however, we respect the serialization provided
143
+ request.write(data);
144
+ }
145
+ }
232
146
  }
233
147
 
234
148
  module.exports = {
@@ -236,10 +150,6 @@ module.exports = {
236
150
  doGetRequest,
237
151
  doPostRequest,
238
152
  doPutRequest,
239
- doDeleteRequest,
240
- doGetRequestExternal,
241
- doPostRequestExternal,
242
- doPutRequestExternal,
243
- doDeleteRequestExternal
153
+ doDeleteRequest
244
154
  }
245
155
 
@@ -1,4 +0,0 @@
1
- /**
2
- * Copied from https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-exporter-zipkin/src/platform/index.ts
3
- */
4
- export * from './node';
@@ -1,35 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright The OpenTelemetry Authors
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * https://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
- if (k2 === undefined) k2 = k;
19
- var desc = Object.getOwnPropertyDescriptor(m, k);
20
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
- desc = { enumerable: true, get: function() { return m[k]; } };
22
- }
23
- Object.defineProperty(o, k2, desc);
24
- }) : (function(o, m, k, k2) {
25
- if (k2 === undefined) k2 = k;
26
- o[k2] = m[k];
27
- }));
28
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
29
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
30
- };
31
- Object.defineProperty(exports, "__esModule", { value: true });
32
- /**
33
- * Copied from https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-exporter-zipkin/src/platform/index.ts
34
- */
35
- __exportStar(require("./node"), exports);
@@ -1,4 +0,0 @@
1
- /**
2
- * Copied from https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-exporter-zipkin/src/platform/node/index.ts
3
- */
4
- export * from './util';
@@ -1,35 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright The OpenTelemetry Authors
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * https://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
- if (k2 === undefined) k2 = k;
19
- var desc = Object.getOwnPropertyDescriptor(m, k);
20
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
- desc = { enumerable: true, get: function() { return m[k]; } };
22
- }
23
- Object.defineProperty(o, k2, desc);
24
- }) : (function(o, m, k, k2) {
25
- if (k2 === undefined) k2 = k;
26
- o[k2] = m[k];
27
- }));
28
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
29
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
30
- };
31
- Object.defineProperty(exports, "__esModule", { value: true });
32
- /**
33
- * Copied from https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-exporter-zipkin/src/platform/node/index.ts
34
- */
35
- __exportStar(require("./util"), exports);
@@ -1,8 +0,0 @@
1
- import * as zipkinTypes from '../../types';
2
- /**
3
- * Prepares send function that will send spans to the remote Zipkin service.
4
- * @param urlStr - url to send spans
5
- * @param headers - headers
6
- * send
7
- */
8
- export declare function prepareSend(urlStr: string, headers?: Record<string, string>): zipkinTypes.SendFn;
@@ -1,105 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright The OpenTelemetry Authors
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * https://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
- if (k2 === undefined) k2 = k;
19
- var desc = Object.getOwnPropertyDescriptor(m, k);
20
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
- desc = { enumerable: true, get: function() { return m[k]; } };
22
- }
23
- Object.defineProperty(o, k2, desc);
24
- }) : (function(o, m, k, k2) {
25
- if (k2 === undefined) k2 = k;
26
- o[k2] = m[k];
27
- }));
28
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
29
- Object.defineProperty(o, "default", { enumerable: true, value: v });
30
- }) : function(o, v) {
31
- o["default"] = v;
32
- });
33
- var __importStar = (this && this.__importStar) || function (mod) {
34
- if (mod && mod.__esModule) return mod;
35
- var result = {};
36
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
37
- __setModuleDefault(result, mod);
38
- return result;
39
- };
40
- Object.defineProperty(exports, "__esModule", { value: true });
41
- exports.prepareSend = void 0;
42
- /**
43
- * Copied from https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-exporter-zipkin/src/platform/node/util.ts
44
- */
45
- const api_1 = require("@opentelemetry/api");
46
- const core_1 = require("@opentelemetry/core");
47
- const http = __importStar(require("http"));
48
- const https = __importStar(require("https"));
49
- const url = __importStar(require("url"));
50
- /**
51
- * Prepares send function that will send spans to the remote Zipkin service.
52
- * @param urlStr - url to send spans
53
- * @param headers - headers
54
- * send
55
- */
56
- function prepareSend(urlStr, headers) {
57
- const urlOpts = url.parse(urlStr);
58
- const reqOpts = Object.assign({
59
- method: 'POST',
60
- headers: Object.assign({ 'Content-Type': 'application/json' }, headers),
61
- }, urlOpts);
62
- /**
63
- * Send spans to the remote Zipkin service.
64
- */
65
- return function send(zipkinSpans, done) {
66
- if (zipkinSpans.length === 0) {
67
- api_1.diag.debug('Zipkin send with empty spans');
68
- return done({ code: core_1.ExportResultCode.SUCCESS });
69
- }
70
- const { request } = reqOpts.protocol === 'http:' ? http : https;
71
- const req = request(reqOpts, (res) => {
72
- let rawData = '';
73
- res.on('data', chunk => {
74
- rawData += chunk;
75
- });
76
- res.on('end', () => {
77
- const statusCode = res.statusCode || 0;
78
- api_1.diag.debug(`Zipkin response status code: ${statusCode}, body: ${rawData}`);
79
- // Consider 2xx and 3xx as success.
80
- if (statusCode < 400) {
81
- return done({ code: core_1.ExportResultCode.SUCCESS });
82
- // Consider 4xx as failed non-retriable.
83
- }
84
- else {
85
- return done({
86
- code: core_1.ExportResultCode.FAILED,
87
- error: new Error(`Got unexpected status code from zipkin: ${statusCode}`),
88
- });
89
- }
90
- });
91
- });
92
- req.on('error', error => {
93
- return done({
94
- code: core_1.ExportResultCode.FAILED,
95
- error,
96
- });
97
- });
98
- // Issue request to remote service
99
- const payload = JSON.stringify(zipkinSpans);
100
- api_1.diag.debug(`Zipkin request payload: ${payload}`);
101
- req.write(payload, 'utf8');
102
- req.end();
103
- };
104
- }
105
- exports.prepareSend = prepareSend;
@@ -1,22 +0,0 @@
1
- /**
2
- * Copied from https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-exporter-zipkin/src/transform.ts
3
- *
4
- * Modified to handle our traceId length being either 16 or 32 characters, and to send the correct Parent Span ID
5
- */
6
- import * as api from '@opentelemetry/api';
7
- import { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base';
8
- import * as zipkinTypes from './types';
9
- import { Resource } from '@opentelemetry/resources';
10
- export declare const defaultStatusCodeTagName = "otel.status_code";
11
- export declare const defaultStatusErrorTagName = "error";
12
- /**
13
- * Translate OpenTelemetry ReadableSpan to ZipkinSpan format
14
- * @param span Span to be translated
15
- */
16
- export declare function toZipkinSpan(span: ReadableSpan, serviceName: string, statusCodeTagName: string, statusErrorTagName: string): zipkinTypes.Span;
17
- /** Converts OpenTelemetry SpanAttributes and SpanStatus to Zipkin Tags format. */
18
- export declare function _toZipkinTags(attributes: api.SpanAttributes, status: api.SpanStatus, statusCodeTagName: string, statusErrorTagName: string, resource: Resource): zipkinTypes.Tags;
19
- /**
20
- * Converts OpenTelemetry Events to Zipkin Annotations format.
21
- */
22
- export declare function _toZipkinAnnotations(events: TimedEvent[]): zipkinTypes.Annotation[];
@@ -1,113 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright The OpenTelemetry Authors
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * https://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
- if (k2 === undefined) k2 = k;
19
- var desc = Object.getOwnPropertyDescriptor(m, k);
20
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
- desc = { enumerable: true, get: function() { return m[k]; } };
22
- }
23
- Object.defineProperty(o, k2, desc);
24
- }) : (function(o, m, k, k2) {
25
- if (k2 === undefined) k2 = k;
26
- o[k2] = m[k];
27
- }));
28
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
29
- Object.defineProperty(o, "default", { enumerable: true, value: v });
30
- }) : function(o, v) {
31
- o["default"] = v;
32
- });
33
- var __importStar = (this && this.__importStar) || function (mod) {
34
- if (mod && mod.__esModule) return mod;
35
- var result = {};
36
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
37
- __setModuleDefault(result, mod);
38
- return result;
39
- };
40
- Object.defineProperty(exports, "__esModule", { value: true });
41
- exports._toZipkinAnnotations = exports._toZipkinTags = exports.toZipkinSpan = exports.defaultStatusErrorTagName = exports.defaultStatusCodeTagName = void 0;
42
- /**
43
- * Copied from https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-exporter-zipkin/src/transform.ts
44
- *
45
- * Modified to handle our traceId length being either 16 or 32 characters, and to send the correct Parent Span ID
46
- */
47
- const api = __importStar(require("@opentelemetry/api"));
48
- const core_1 = require("@opentelemetry/core");
49
- const zipkinTypes = __importStar(require("./types"));
50
- const api_1 = require("@opentelemetry/api");
51
- const UoaB3Propagator_1 = require("../UoaB3Propagator");
52
- const ZIPKIN_SPAN_KIND_MAPPING = {
53
- [api.SpanKind.CLIENT]: zipkinTypes.SpanKind.CLIENT,
54
- [api.SpanKind.SERVER]: zipkinTypes.SpanKind.SERVER,
55
- [api.SpanKind.CONSUMER]: zipkinTypes.SpanKind.CONSUMER,
56
- [api.SpanKind.PRODUCER]: zipkinTypes.SpanKind.PRODUCER,
57
- // When absent, the span is local.
58
- //@ts-ignore
59
- [api.SpanKind.INTERNAL]: undefined,
60
- };
61
- exports.defaultStatusCodeTagName = 'otel.status_code';
62
- exports.defaultStatusErrorTagName = 'error';
63
- /**
64
- * Translate OpenTelemetry ReadableSpan to ZipkinSpan format
65
- * @param span Span to be translated
66
- */
67
- function toZipkinSpan(span, serviceName, statusCodeTagName, statusErrorTagName) {
68
- const traceIdLength = api_1.context.active().getValue(UoaB3Propagator_1.B3_TRACE_ID_LENGTH_KEY);
69
- let traceId = span.spanContext().traceId.slice(span.spanContext().traceId.length - traceIdLength);
70
- const parentSpanId = api_1.context.active().getValue(UoaB3Propagator_1.B3_PARENT_SPAN_ID_KEY);
71
- const zipkinSpan = {
72
- traceId: traceId,
73
- parentId: parentSpanId || span.parentSpanId,
74
- name: span.name,
75
- id: span.spanContext().spanId,
76
- kind: ZIPKIN_SPAN_KIND_MAPPING[span.kind],
77
- timestamp: (0, core_1.hrTimeToMicroseconds)(span.startTime),
78
- duration: (0, core_1.hrTimeToMicroseconds)(span.duration),
79
- localEndpoint: { serviceName },
80
- tags: _toZipkinTags(span.attributes, span.status, statusCodeTagName, statusErrorTagName, span.resource),
81
- annotations: span.events.length
82
- ? _toZipkinAnnotations(span.events)
83
- : undefined,
84
- };
85
- return zipkinSpan;
86
- }
87
- exports.toZipkinSpan = toZipkinSpan;
88
- /** Converts OpenTelemetry SpanAttributes and SpanStatus to Zipkin Tags format. */
89
- function _toZipkinTags(attributes, status, statusCodeTagName, statusErrorTagName, resource) {
90
- const tags = {};
91
- for (const key of Object.keys(attributes)) {
92
- tags[key] = String(attributes[key]);
93
- }
94
- if (status.code !== api.SpanStatusCode.UNSET) {
95
- tags[statusCodeTagName] = String(api.SpanStatusCode[status.code]);
96
- }
97
- if (status.code === api.SpanStatusCode.ERROR && status.message) {
98
- tags[statusErrorTagName] = status.message;
99
- }
100
- Object.keys(resource.attributes).forEach(name => (tags[name] = String(resource.attributes[name])));
101
- return tags;
102
- }
103
- exports._toZipkinTags = _toZipkinTags;
104
- /**
105
- * Converts OpenTelemetry Events to Zipkin Annotations format.
106
- */
107
- function _toZipkinAnnotations(events) {
108
- return events.map(event => ({
109
- timestamp: (0, core_1.hrTimeToMicroseconds)(event.time),
110
- value: event.name,
111
- }));
112
- }
113
- exports._toZipkinAnnotations = _toZipkinAnnotations;