@uoa/lambda-tracing 2.0.1 → 2.1.0-beta.2

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
@@ -3,6 +3,8 @@ import * as http from "http";
3
3
  import { URL } from "url";
4
4
  import {context, propagation} from "@opentelemetry/api";
5
5
  import {RequestOptions} from "https";
6
+ import {ClientRequest} from "http";
7
+ import {XMLParser} from "fast-xml-parser";
6
8
 
7
9
  function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
8
10
  function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
@@ -27,24 +29,7 @@ async function doGetRequest(hostname: string, path: string, headers: any, port:
27
29
  }
28
30
  propagation.inject(context.active(), options.headers);
29
31
 
30
- const req = https.request(options, function (response) {
31
- const chunks: any[] = [];
32
-
33
- response.on("data", function (chunk) {
34
- chunks.push(chunk);
35
- });
36
-
37
- response.on("end", function () {
38
- let body = Buffer.concat(chunks);
39
- body = JSON.parse(body.toString());
40
- resolve(body);
41
- });
42
-
43
- response.on("error", function (e) {
44
- reject(e);
45
- })
46
- });
47
-
32
+ const req = doHttpsRequest(options, resolve, reject);
48
33
  req.end();
49
34
  });
50
35
  }
@@ -60,42 +45,8 @@ async function doPostRequest(hostname: string, path: string, headers: any, data:
60
45
  }
61
46
  propagation.inject(context.active(), options.headers);
62
47
 
63
- const req = https.request(options, function (response) {
64
- const chunks: any[] = [];
65
-
66
- response.on("data", function (chunk) {
67
- chunks.push(chunk);
68
- });
69
-
70
- response.on("end", function () {
71
- if (response.statusCode == 204) {
72
- //204 is no content, and most JSON parses blow up on an empty string
73
- resolve(null);
74
- } else {
75
- let body: any = Buffer.concat(chunks);
76
- if (!('Content-Type' in options.headers) || options.headers['Content-Type'] === 'application/json') {
77
- body = JSON.parse(body.toString());
78
- } else {
79
- body = body.toString();
80
- }
81
- resolve(body);
82
- }
83
- });
84
-
85
- response.on("error", function (e) {
86
- reject(e);
87
- })
88
- });
89
-
90
- if (data) {
91
- if (!('Content-Type' in options.headers) || options.headers['Content-Type'] === 'application/json') {
92
- //We serialize using JSON.stringify as a default, or if a JSON is specified
93
- req.write(JSON.stringify(data));
94
- } else {
95
- // If another content-type is specified however, we respect the serialization provided
96
- req.write(data);
97
- }
98
- }
48
+ const req = doHttpsRequest(options, resolve, reject);
49
+ setRequestBody(req, data);
99
50
  req.end();
100
51
  });
101
52
  }
@@ -111,42 +62,8 @@ async function doPutRequest(hostname: string, path: string, headers: any, data:
111
62
  }
112
63
  propagation.inject(context.active(), options.headers);
113
64
 
114
- const req = https.request(options, function (response) {
115
- const chunks: any[] = [];
116
-
117
- response.on("data", function (chunk) {
118
- chunks.push(chunk);
119
- });
120
-
121
- response.on("end", function () {
122
- if (response.statusCode == 204) {
123
- //204 is no content, and most JSON parses blow up on an empty string
124
- resolve(null);
125
- } else {
126
- let body: any = Buffer.concat(chunks);
127
- if (!('Content-Type' in options.headers) || options.headers['Content-Type'] === 'application/json') {
128
- body = JSON.parse(body.toString());
129
- } else {
130
- body = body.toString();
131
- }
132
- resolve(body);
133
- }
134
- });
135
-
136
- response.on("error", function (e) {
137
- reject(e);
138
- })
139
- });
140
-
141
- if (data) {
142
- if (!('Content-Type' in options.headers) || options.headers['Content-Type'] === 'application/json') {
143
- //We serialize using JSON.stringify as a default, or if a JSON is specified
144
- req.write(JSON.stringify(data));
145
- } else {
146
- // If another content-type is specified however, we respect the serialization provided
147
- req.write(data);
148
- }
149
- }
65
+ const req = doHttpsRequest(options, resolve, reject);
66
+ setRequestBody(req, data);
150
67
  req.end();
151
68
  });
152
69
  }
@@ -162,37 +79,72 @@ async function doDeleteRequest(hostname: string, path: string, headers: any, por
162
79
  }
163
80
  propagation.inject(context.active(), options.headers);
164
81
 
165
- const req = https.request(options, function (response) {
166
- const chunks: any[] = [];
167
-
168
- response.on("data", function (chunk) {
169
- chunks.push(chunk);
170
- });
171
-
172
- response.on("end", function () {
173
- if (response.statusCode == 204) {
174
- //204 is no content, and most JSON parses blow up on an empty string
175
- resolve(null);
176
- } else {
177
- let body: any = Buffer.concat(chunks);
178
- if (!('Content-Type' in options.headers) || options.headers['Content-Type'] === 'application/json') {
179
- 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);
180
120
  } else {
181
- body = body.toString();
121
+ reject(parsedBody);
182
122
  }
183
- resolve(body);
123
+ } catch (e: any) {
124
+ reject(e);
184
125
  }
185
- });
186
-
187
- response.on("error", function (e) {
188
- reject(e);
189
- })
126
+ }
190
127
  });
191
128
 
192
- req.end();
129
+ response.on("error", function (e) {
130
+ reject(e);
131
+ })
193
132
  });
194
133
  }
195
134
 
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
+ }
146
+ }
147
+
196
148
  module.exports = {
197
149
  request,
198
150
  doGetRequest,
@@ -200,3 +152,4 @@ module.exports = {
200
152
  doPutRequest,
201
153
  doDeleteRequest
202
154
  }
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;