-
Notifications
You must be signed in to change notification settings - Fork 196
/
Copy pathnodeTransport.ts
352 lines (326 loc) · 9.83 KB
/
nodeTransport.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
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/*
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import nodeCrypto from 'crypto';
import type * as fs from 'fs';
import { Buffer } from 'buffer';
import * as process from 'process';
import type {
Authenticator,
HttpMethod,
ICryptoHash,
IRawRequest,
IRawResponse,
IRequestHeaders,
ISDKError,
ITransportSettings,
SDKResponse,
Values,
} from '@looker/sdk-rtl';
import {
BaseTransport,
BrowserTransport,
ResponseMode,
canRetry,
initResponse,
pauseForRetry,
responseMode,
retryError,
retryWait,
safeBase64,
mergeOptions,
verifySsl,
} from '@looker/sdk-rtl';
import { WritableStream } from 'node:stream/web';
const utf8 = 'utf8';
const asString = (value: any): string => {
if (value instanceof Buffer) {
return Buffer.from(value).toString(utf8);
}
if (value instanceof Object) {
return JSON.stringify(value);
}
return value.toString();
};
export class NodeCryptoHash implements ICryptoHash {
secureRandom(byteCount: number): string {
return nodeCrypto.randomBytes(byteCount).toString('hex');
}
async sha256Hash(message: string): Promise<string> {
const hash = nodeCrypto.createHash('sha256');
hash.update(message);
return safeBase64(new Uint8Array(hash.digest()));
}
}
export class NodeTransport extends BaseTransport {
constructor(protected readonly options: ITransportSettings) {
super(options);
}
/**
* Standard retry where requests will be retried based on configured
* transport settings. If retry is not enabled, no requests will be retried
*
* This default retry pattern implements the "full" jitter algorithm
* documented in https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
*
* @param request options for HTTP request
*/
async retry(request: IRawRequest): Promise<IRawResponse> {
const { method, path, queryParams, body, authenticator } = request;
const newOpts = mergeOptions(this.options, request.options ?? {});
const requestPath = this.makeUrl(path, newOpts, queryParams);
const waiter = newOpts.waitHandler || retryWait;
const props = await this.initRequest(
method,
requestPath,
body,
authenticator,
newOpts
);
let response = initResponse(method, requestPath);
// TODO assign to MaxTries constant when retry is opt-out instead of opt-in
const maxTries = newOpts.maxTries ?? 1; // MaxTries
let attempt = 1;
while (attempt <= maxTries) {
const req = fetch(
props.url,
props as RequestInit // Weird package issues with unresolved imports for RequestInit for node-fetch :(
);
const requestStarted = Date.now();
try {
const res = await req;
const responseCompleted = Date.now();
// Start tracking the time it takes to convert the response
const started = BrowserTransport.markStart(
BrowserTransport.markName(requestPath)
);
const contentType = String(res.headers.get('content-type'));
const mode = responseMode(contentType);
const responseBody =
mode === ResponseMode.binary ? res.blob() : res.text();
if (!('fromRequest' in newOpts)) {
// Request will markEnd, so don't mark the end here
BrowserTransport.markEnd(requestPath, started);
}
const headers: IRequestHeaders = {};
res.headers.forEach((value, key) => (headers[key] = value));
response = {
method,
url: requestPath,
body: responseBody,
contentType,
statusCode: res.status,
statusMessage: res.statusText,
startMark: started,
headers,
requestStarted,
responseCompleted,
ok: true,
};
response.ok = this.ok(response);
if (canRetry(response.statusCode) && attempt < maxTries) {
const result = await pauseForRetry(
request,
response,
attempt,
waiter
);
if (result.response === 'cancel') {
if (result.reason) {
response.statusMessage = result.reason;
}
break;
} else if (result.response === 'error') {
if (result.reason) {
response.statusMessage = result.reason;
}
return retryError(response);
}
} else {
break;
}
attempt++;
} catch (e: any) {
response.ok = false;
response.body = e;
response.statusCode = e.statusCode;
response.statusMessage = e.message;
return response;
}
}
return response;
}
async rawRequest(
method: HttpMethod,
path: string,
queryParams?: Values,
body?: any,
authenticator?: Authenticator,
options?: Partial<ITransportSettings>
): Promise<IRawResponse> {
const response = await this.retry({
method,
path,
queryParams,
body,
authenticator,
options,
});
return this.observer ? this.observer(response) : response;
}
async parseResponse<TSuccess, TError>(res: IRawResponse) {
const mode = responseMode(res.contentType);
let response: SDKResponse<TSuccess, TError>;
let error;
if (!res.ok) {
// Raw request had an error. Make sure it's a string before parsing the result
error = await res.body;
if (typeof error === 'string') {
try {
error = JSON.parse(error);
} catch {
error = { message: `Request failed: ${error}` };
}
}
response = { ok: false, error };
return response;
}
let result = await res.body;
if (mode === ResponseMode.string) {
if (res.contentType.match(/^application\/.*\bjson\b/g)) {
try {
if (result instanceof Buffer) {
result = Buffer.from(result).toString(); // (utf8);
}
if (!(result instanceof Object)) {
result = JSON.parse(result.toString());
}
} catch (err: any) {
error = err;
}
} else if (!error) {
// Convert to string otherwise
result = asString(result);
}
} else {
try {
const body = await result;
if (typeof body === 'string') {
result = body;
} else {
// must be a blob?
const bytes = await body.arrayBuffer();
result = Buffer.from(bytes ?? '').toString('binary');
}
} catch (err: any) {
error = err;
}
}
if (!error) {
response = { ok: true, value: result };
} else {
response = { ok: false, error: error as TError };
}
return response;
}
async request<TSuccess, TError>(
method: HttpMethod,
path: string,
queryParams?: Values,
body?: any,
authenticator?: Authenticator,
options?: Partial<ITransportSettings>
): Promise<SDKResponse<TSuccess, TError>> {
try {
const res = await this.rawRequest(
method,
path,
queryParams,
body,
authenticator,
options
);
return await this.parseResponse<TSuccess, TError>(res);
} catch (e: any) {
const error: ISDKError = {
message:
typeof e.message === 'string'
? e.message
: `The SDK call was not successful. The error was '${e}'.`,
type: 'sdk_error',
};
return { error, ok: false };
}
}
async stream<TSuccess>(
callback: (response: Response) => Promise<TSuccess>,
method: HttpMethod,
path: string,
queryParams?: Values,
body?: any,
authenticator?: Authenticator,
options?: Partial<ITransportSettings>
): Promise<TSuccess> {
const newOpts = { ...this.options, options };
const requestPath = this.makeUrl(path, newOpts, queryParams);
const init = await this.initRequest(
method,
requestPath,
body,
authenticator,
newOpts
);
const response: Response = await fetch(requestPath, init as RequestInit);
return await callback(response);
}
protected override async initRequest(
method: HttpMethod,
path: string,
body?: any,
authenticator?: Authenticator,
options?: Partial<ITransportSettings>
) {
const props = await super.initRequest(
method,
path,
body,
authenticator,
options
);
// don't default to same-origin for NodeJS
props.credentials = undefined;
if (!verifySsl(options)) {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
}
return props;
}
}
/**
* Turn a NodeJS WriteStream into a WritableStream for compatibility with browser standards
* @param writer usually created by fs.createWriteStream()
*/
export const createWritableStream = (
writer: ReturnType<typeof fs.createWriteStream>
) => {
return new WritableStream({
write: (chunk: any) => {
writer.write(chunk);
},
});
};