forked from Lilly-Protocol/lily-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch-http-client.ts
More file actions
458 lines (409 loc) · 13.5 KB
/
Copy pathfetch-http-client.ts
File metadata and controls
458 lines (409 loc) · 13.5 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
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import { DEFAULT_RETRYABLE_STATUS_CODES } from '../config/defaults';
import type { ResolvedLilySdkConfig } from '../config/types';
import { resolveAuthHeaders } from './resolve-auth-headers';
import {
LILY_ERROR_CODES,
LilyApiError,
LilyAuthenticationError,
LilyConfigError,
LilySdkError,
LilyTransportError,
LilyValidationError,
LilyConfigError,
} from '../errors/sdk-error';
import type {
HttpClient,
HttpHeaders,
HttpRequest,
HttpResponse,
} from './types';
import { DEFAULT_RETRY_POLICY } from '../config/defaults';
const DEFAULT_RETRYABLE_STATUS_CODES =
DEFAULT_RETRY_POLICY.retryableStatusCodes;
/**
* Resolves and validates the per-request timeout override.
*
* - `undefined` → use the config default (caller must not pass an invalid value)
* - `0` → explicit opt-out of timeout (documented behavior)
* - Any other value that is not a finite non-negative number → throw
* `LilyValidationError` so the caller gets immediate feedback without
* dispatching a request or consuming a retry.
*/
export function resolveRequestTimeout(
requestTimeoutMs: number | undefined,
configTimeoutMs: number,
): number | 0 {
if (requestTimeoutMs === undefined) {
return configTimeoutMs;
}
// `0` is the documented per-request opt-out — allow it explicitly.
if (requestTimeoutMs === 0) {
return 0;
}
if (
typeof requestTimeoutMs !== 'number' ||
!Number.isFinite(requestTimeoutMs) ||
requestTimeoutMs < 0
) {
throw new LilyValidationError(
`Per-request \`timeoutMs\` must be a non-negative finite number (got ${JSON.stringify(requestTimeoutMs)}).`,
{
code: LILY_ERROR_CODES.VALIDATION_ERROR,
details: { timeoutMs: requestTimeoutMs },
},
);
}
return requestTimeoutMs;
}
/**
* Resolves and validates the per-request timeout override.
*
* - `undefined` → use the config default (caller must not pass an invalid value)
* - `0` → explicit opt-out of timeout (documented behavior)
* - Any other value that is not a finite non-negative number → throw
* `LilyValidationError` so the caller gets immediate feedback without
* dispatching a request or consuming a retry.
*/
export function resolveRequestTimeout(
requestTimeoutMs: number | undefined,
configTimeoutMs: number,
): number | 0 {
if (requestTimeoutMs === undefined) {
return configTimeoutMs;
}
// `0` is the documented per-request opt-out — allow it explicitly.
if (requestTimeoutMs === 0) {
return 0;
}
if (
typeof requestTimeoutMs !== 'number' ||
!Number.isFinite(requestTimeoutMs) ||
requestTimeoutMs < 0
) {
throw new LilyValidationError(
`Per-request \`timeoutMs\` must be a non-negative finite number (got ${JSON.stringify(requestTimeoutMs)}).`,
{
code: LILY_ERROR_CODES.VALIDATION_ERROR,
details: { timeoutMs: requestTimeoutMs },
},
);
}
return requestTimeoutMs;
}
export function createFetchHttpClient(
config: ResolvedLilySdkConfig,
hooks?: RequestLifecycleHooks,
): HttpClient {
// composeHooks swallows hook errors so observability can never break the
// request flow; composing a single set reuses those semantics verbatim.
const lifecycle = hooks ? composeHooks(hooks) : undefined;
return {
async request<TResponse, TRequest = unknown>(
request: HttpRequest<TRequest>,
): Promise<HttpResponse<TResponse>> {
if (request.timeoutMs !== undefined) {
if (
typeof request.timeoutMs !== 'number' ||
!Number.isFinite(request.timeoutMs) ||
request.timeoutMs < 0
) {
throw new LilyConfigError(
'`timeoutMs` must be a non-negative number.',
);
}
}
const url = buildUrl(config.baseUrl, request.path, request.query);
const body = serializeBody(request.body);
const headers = buildHeaders(config, request.headers);
// Validate per-request timeoutMs
if (request.timeoutMs !== undefined) {
if (
typeof request.timeoutMs !== 'number' ||
!Number.isFinite(request.timeoutMs) ||
request.timeoutMs < 0
) {
throw new LilyConfigError(
'`timeoutMs` must be a non-negative number.',
);
}
}
const timeoutMs = request.timeoutMs ?? config.timeoutMs;
if (request.timeoutMs !== undefined && (request.timeoutMs < 0 || !Number.isFinite(request.timeoutMs))) {
throw new LilyConfigError('timeoutMs must be a non-negative finite number.');
}
let attempt = 0;
for (;;) {
const controller = new AbortController();
let externallyAborted = false;
let onExternalAbort: (() => void) | undefined;
if (request.signal) {
if (request.signal.aborted) {
throw new LilyTransportError('Request cancelled by caller.', {
code: LILY_ERROR_CODES.CANCELLED,
cause: request.signal.reason ?? new Error('Aborted'),
request: requestMetadata(request, url),
});
}
onExternalAbort = () => {
externallyAborted = true;
controller.abort(request.signal?.reason);
};
request.signal.addEventListener('abort', onExternalAbort, {
once: true,
});
}
let timeout: ReturnType<typeof setTimeout> | undefined;
if (timeoutMs > 0) {
timeout = setTimeout(() => controller.abort(), timeoutMs);
}
const cleanup = (): void => {
if (timeout !== undefined) {
clearTimeout(timeout);
}
if (request.signal && onExternalAbort) {
request.signal.removeEventListener('abort', onExternalAbort);
}
};
const requestInit: RequestInit = {
method: request.method,
headers,
signal: controller.signal,
};
if (body !== undefined) {
requestInit.body = body;
}
try {
await lifecycle?.beforeRequest?.(request);
const response = await config.fetch(url, requestInit);
const data = (await parseResponse(response)) as TResponse;
if (response.ok) {
cleanup();
const result: HttpResponse<TResponse> = {
status: response.status,
headers: response.headers,
data,
attempts: attempt + 1,
retried: attempt > 0,
};
await lifecycle?.afterResponse?.(request, result);
return result;
}
// Auth failures are terminal: retrying with the same credential just
// burns the budget. Checked before shouldRetry for that reason.
if (response.status === 401 || response.status === 403) {
cleanup();
throw new LilyAuthenticationError(
'Authentication failed for Lily Protocol API.',
{
code: LILY_ERROR_CODES.AUTHENTICATION_ERROR,
statusCode: response.status,
details: data,
request: requestMetadata(request, url),
},
);
}
if (
shouldRetry(
response.status,
attempt,
config.retry.retries,
config.retry.retryableStatusCodes,
request.method,
)
) {
cleanup();
attempt += 1;
const delayMs = config.retry.retryDelayMs * attempt;
await lifecycle?.onRetry?.(request, attempt, delayMs);
await sleep(delayMs);
continue;
}
cleanup();
throw new LilyApiError('Lily Protocol API request failed.', {
code: LILY_ERROR_CODES.API_ERROR,
statusCode: response.status,
details: data,
request: requestMetadata(request, url),
});
} catch (error) {
cleanup();
// LilySdkError instances (validation, auth, API) are definitive:
// they must never be retried or re-wrapped.
if (error instanceof LilySdkError) {
await lifecycle?.onError?.(
request,
error instanceof Error ? error : new Error(String(error)),
);
throw error;
}
if (error instanceof Error && error.name === 'AbortError') {
// External cancellation is never retried: the caller asked us to stop.
if (
!externallyAborted &&
attempt < config.retry.retries &&
isRetryableMethod(request.method)
) {
attempt += 1;
const delayMs = config.retry.retryDelayMs * attempt;
await lifecycle?.onRetry?.(request, attempt, delayMs);
await sleep(delayMs);
continue;
}
const transportError = new LilyTransportError(
externallyAborted
? 'Request cancelled by caller while calling Lily Protocol API.'
: 'Request timed out while calling Lily Protocol API.',
{
code: externallyAborted
? LILY_ERROR_CODES.CANCELLED
: LILY_ERROR_CODES.TIMEOUT,
cause: error,
request: requestMetadata(request, url),
},
);
await lifecycle?.onError?.(request, transportError);
throw transportError;
}
if (
attempt < config.retry.retries &&
isRetryableTransportError(error, request.method)
) {
attempt += 1;
const delayMs = config.retry.retryDelayMs * attempt;
await lifecycle?.onRetry?.(request, attempt, delayMs);
await sleep(delayMs);
continue;
}
const transportError = new LilyTransportError(
'Network error while calling Lily Protocol API.',
{
code: LILY_ERROR_CODES.TRANSPORT_ERROR,
cause: error,
request: requestMetadata(request, url),
},
);
await lifecycle?.onError?.(
request,
transportError,
);
throw transportError;
}
}
},
};
}
function requestMetadata(
request: HttpRequest,
url: URL,
): { method: string; path: string; url: string } {
return {
method: request.method,
path: request.path,
url: url.toString(),
};
}
export function buildUrl(
baseUrl: URL,
path: string,
query?: Record<
string,
string | number | boolean | (string | number)[] | undefined
>,
): URL {
const cleanPath = path.startsWith('/') ? path.slice(1) : path;
const url = new URL(cleanPath, baseUrl);
for (const [key, value] of Object.entries(query ?? {})) {
if (value === undefined) {
continue;
}
if (Array.isArray(value)) {
for (const item of value) {
url.searchParams.append(key, String(item));
}
} else {
url.searchParams.set(key, String(value));
}
}
return url;
}
function buildHeaders(
config: ResolvedLilySdkConfig,
requestHeaders?: HttpHeaders,
): HttpHeaders {
const headers: Record<string, string> = {
accept: 'application/json',
'content-type': 'application/json',
'user-agent': config.userAgent,
...config.defaultHeaders,
...requestHeaders,
...resolveAuthHeaders(config),
};
return headers;
}
function serializeBody(body: unknown): BodyInit | undefined {
if (body === undefined || body === null) {
return undefined;
}
return JSON.stringify(body);
}
async function parseResponse(response: Response): Promise<unknown> {
if (response.status === 204) {
return null;
}
const contentType = response.headers.get('content-type') ?? '';
if (contentType.includes('application/json')) {
// Read body once as text to avoid double-consumption, then parse.
const text = await response.text();
try {
return JSON.parse(text) as unknown;
} catch (error) {
// For non-ok responses, surface the real HTTP error instead of a
// validation error ¡ª callers lose the actual status otherwise.
if (!response.ok) {
throw new LilyApiError(
`Failed to parse response body as JSON (status ${response.status}, content-type: ${contentType}).`,
{
code: LILY_ERROR_CODES.API_ERROR,
statusCode: response.status,
details: text,
cause: error,
},
);
}
throw new LilyValidationError(
`Failed to parse response body as JSON (status ${response.status}, content-type: ${contentType}).`,
{
code: LILY_ERROR_CODES.RESPONSE_VALIDATION_ERROR,
statusCode: response.status,
cause: error,
},
);
}
}
return await response.text();
}
function shouldRetry(
statusCode: number,
attempt: number,
maxRetries: number,
retryableStatusCodes: readonly number[] | undefined,
method: string,
): boolean {
const codes = retryableStatusCodes ?? DEFAULT_RETRYABLE_STATUS_CODES;
return (
isRetryableMethod(method) &&
attempt < maxRetries &&
codes.includes(statusCode)
);
}
function isRetryableTransportError(error: unknown, method: string): boolean {
return isRetryableMethod(method) && error instanceof Error;
}
function isRetryableMethod(method: string): boolean {
return method === 'GET' || method === 'PUT' || method === 'DELETE';
}
async function sleep(ms: number): Promise<void> {
await new Promise((resolve) => {
setTimeout(resolve, ms);
});
}