-
Notifications
You must be signed in to change notification settings - Fork 836
/
Copy pathutil.ts
99 lines (91 loc) · 2.76 KB
/
util.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { diag } from '@opentelemetry/api';
import { ExportResult, ExportResultCode } from '@opentelemetry/core';
import * as http from 'http';
import * as https from 'https';
import * as url from 'url';
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 function prepareSend(
urlStr: string,
headers?: Record<string, string>
): zipkinTypes.SendFn {
const urlOpts = url.parse(urlStr);
const reqOpts: http.RequestOptions = Object.assign(
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers,
},
},
urlOpts
);
/**
* Send spans to the remote Zipkin service.
*/
return function send(
zipkinSpans: zipkinTypes.Span[],
done: (result: ExportResult) => void
) {
if (zipkinSpans.length === 0) {
diag.debug('Zipkin send with empty spans');
return done({ code: ExportResultCode.SUCCESS });
}
const { request } = reqOpts.protocol === 'http:' ? http : https;
const req = request(reqOpts, (res: http.IncomingMessage) => {
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();
};
}