-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBacktraceNodeRequestHandler.ts
More file actions
276 lines (238 loc) · 9.36 KB
/
BacktraceNodeRequestHandler.ts
File metadata and controls
276 lines (238 loc) · 9.36 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import {
BacktraceAttachment,
BacktraceAttachmentResponse,
BacktraceReportSubmissionResult,
BacktraceRequestHandler,
BacktraceSubmissionResponse,
ConnectionError,
DEFAULT_TIMEOUT,
} from '@backtrace/sdk-core';
import FormData from 'form-data';
import http, { ClientRequest, IncomingMessage } from 'http';
import https from 'https';
import { PassThrough, Readable } from 'stream';
export interface BacktraceNodeRequestHandlerOptions {
readonly timeout?: number;
readonly ignoreSslCertificate?: boolean;
}
export class BacktraceNodeRequestHandler implements BacktraceRequestHandler {
private readonly UPLOAD_FILE_NAME = 'upload_file';
private readonly _timeout: number;
private readonly _ignoreSslCertificate?: boolean;
private readonly JSON_HEADERS = {
'Content-type': 'application/json',
'Transfer-Encoding': 'chunked',
};
private readonly MULTIPART_HEADERS = {
'Transfer-Encoding': 'chunked',
};
constructor(options?: BacktraceNodeRequestHandlerOptions) {
this._timeout = options?.timeout ?? DEFAULT_TIMEOUT;
this._ignoreSslCertificate = options?.ignoreSslCertificate;
}
public async postError(
submissionUrl: string,
dataJson: string,
attachments: BacktraceAttachment<Buffer | Readable | string | Uint8Array>[],
abortSignal?: AbortSignal,
): Promise<BacktraceReportSubmissionResult<BacktraceSubmissionResponse>> {
const formData = attachments.length === 0 ? dataJson : this.createFormData(dataJson, attachments);
return this.send<BacktraceSubmissionResponse>(submissionUrl, formData, abortSignal);
}
public async post<T>(
submissionUrl: string,
payload: string,
abortSignal?: AbortSignal,
): Promise<BacktraceReportSubmissionResult<T>> {
return this.send<T>(submissionUrl, payload, abortSignal);
}
public async postAttachment(
submissionUrl: string,
attachment: BacktraceAttachment<Buffer | Readable | string | Uint8Array>,
abortSignal?: AbortSignal,
): Promise<BacktraceReportSubmissionResult<BacktraceAttachmentResponse>> {
try {
const attachmentData = attachment.get();
if (!attachmentData) {
return BacktraceReportSubmissionResult.ReportSkipped();
}
const url = new URL(submissionUrl);
const httpClient = this.getHttpClient(url);
return new Promise<BacktraceReportSubmissionResult<BacktraceAttachmentResponse>>((res) => {
const request = httpClient.request(
url,
{
rejectUnauthorized: this._ignoreSslCertificate === true,
timeout: this._timeout,
method: 'POST',
},
(response) => {
let result = '';
response.on('data', (d) => {
result += d.toString();
});
response.on('end', () => {
cleanup();
return res(this.handleResponse(response, result));
});
response.on('error', () => {
cleanup();
});
},
);
abortSignal?.addEventListener(
'abort',
() => BacktraceNodeRequestHandler.abortFn(abortSignal, request),
{ once: true },
);
function cleanup() {
abortSignal?.removeEventListener('abort', cleanup);
}
request.on('error', (err: Error) => {
cleanup();
return res(this.handleRequestError(err));
});
if (attachmentData instanceof Readable) {
attachmentData.pipe(request);
} else {
request.write(attachmentData);
}
});
} catch (err) {
return this.handleError(err);
}
}
private async send<T>(
submissionUrl: string,
payload: string | FormData,
abortSignal?: AbortSignal,
): Promise<BacktraceReportSubmissionResult<T>> {
try {
const url = new URL(submissionUrl);
const httpClient = this.getHttpClient(url);
return new Promise<BacktraceReportSubmissionResult<T>>((res) => {
const request = httpClient.request(
url,
{
rejectUnauthorized: this._ignoreSslCertificate === true,
timeout: this._timeout,
method: 'POST',
headers:
typeof payload === 'string'
? this.JSON_HEADERS
: { ...payload.getHeaders(), ...this.MULTIPART_HEADERS },
},
(response) => {
let result = '';
response.on('data', (d) => {
result += d.toString();
});
response.on('end', () => {
cleanup();
return res(this.handleResponse(response, result));
});
response.on('error', () => {
cleanup();
});
},
);
abortSignal?.addEventListener(
'abort',
() => BacktraceNodeRequestHandler.abortFn(abortSignal, request),
{ once: true },
);
function cleanup() {
abortSignal?.removeEventListener('abort', cleanup);
}
request.on('error', (err: Error) => {
cleanup();
return res(this.handleRequestError(err));
});
if (typeof payload === 'string') {
request.write(payload);
request.end();
} else {
payload.pipe(request);
}
});
} catch (err) {
return this.handleError(err);
}
}
private getHttpClient(submissionUrl: URL) {
return submissionUrl.protocol === 'https:' ? https : http;
}
private handleResponse<T>(response: IncomingMessage, result: string) {
switch (response.statusCode) {
case 200: {
return BacktraceReportSubmissionResult.Ok<T>(JSON.parse(result));
}
case 401:
case 403: {
return BacktraceReportSubmissionResult.OnInvalidToken<T>();
}
case 429: {
return BacktraceReportSubmissionResult.OnLimitReached<T>();
}
default: {
return BacktraceReportSubmissionResult.OnInternalServerError<T>(result);
}
}
}
private handleRequestError<T>(err: Error) {
if (ConnectionError.isConnectionError(err)) {
return BacktraceReportSubmissionResult.OnNetworkingError<T>(err.message);
}
return BacktraceReportSubmissionResult.OnInternalServerError<T>(err.message);
}
private handleError<T>(err: unknown) {
if (ConnectionError.isConnectionError(err)) {
return BacktraceReportSubmissionResult.OnNetworkingError<T>(err.message);
}
const errorMessage = err instanceof Error ? err.message : (err as string);
return BacktraceReportSubmissionResult.OnUnknownError<T>(errorMessage);
}
private static abortFn(signal: AbortSignal, request: ClientRequest) {
const reason =
signal.reason instanceof Error
? signal.reason
: typeof signal.reason === 'string'
? new Error(signal.reason)
: new Error('Operation cancelled.');
request.destroy(reason);
}
private createFormData(json: string, attachments?: BacktraceAttachment<Buffer | Readable | string | Uint8Array>[]) {
const formData = new FormData();
formData.append(this.UPLOAD_FILE_NAME, json, `${this.UPLOAD_FILE_NAME}.json`);
if (!attachments || attachments.length === 0) {
return formData;
}
for (const attachment of attachments) {
let data = attachment.get();
if (!data) {
continue;
}
if (data instanceof Readable) {
data = this.wrapReadableSuppressErrors(data);
}
formData.append(`attachment_${attachment.name}`, data, attachment.name);
}
return formData;
}
/**
* When inputStream emits an error, it will be suppressed, and the stream will be closed.
*/
private wrapReadableSuppressErrors(inputStream: Readable) {
const safeStream = new PassThrough();
inputStream.on('data', (chunk) => {
safeStream.write(chunk);
});
inputStream.on('end', () => {
safeStream.end();
});
inputStream.on('error', () => {
safeStream.end();
});
return safeStream;
}
}