Repository navigation
Expand file tree
/
Copy pathFetchService.ts
More file actions
1085 lines (972 loc) · 42 KB
/
Copy pathFetchService.ts
File metadata and controls
1085 lines (972 loc) · 42 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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file belongs to Hoist, an application development toolkit
* developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
*
* Copyright © 2026 Extremely Heavy Industries Inc.
*/
import type {
Awaitable,
CallContext,
CallContextLike,
PlainObject,
TrackOptions,
Span,
SpanConfig
} from '@xh/hoist/core';
import {HoistService, XH, formatTraceparent} from '@xh/hoist/core';
import type {HoistException, TimeoutException} from '@xh/hoist/exception';
import {Exception} from '@xh/hoist/exception';
import type {PromiseTimeoutSpec} from '@xh/hoist/promise';
import {isLocalDate, SECONDS} from '@xh/hoist/utils/datetime';
import {genRandomId, warnIf} from '@xh/hoist/utils/js';
import {isDate, isFunction, isNil, isObject, isString, noop, omit, omitBy, truncate} from 'lodash';
import type {IStringifyOptions} from 'qs';
import {stringify} from 'qs';
import {NdjsonResultImpl} from './impl/NdjsonResultImpl';
import {StringInterner} from './impl/StringInterner';
export interface FetchServiceDefaults {
autoGenCorrelationIds?: boolean | ((opts: FetchOptions) => boolean);
correlationIdHeaderKey?: string;
genCorrelationId?: () => string;
propagateTrace?: boolean | ((opts: FetchOptions) => boolean);
}
/**
* Service for making managed HTTP requests, both to the app's own Hoist server and to remote APIs.
*
* Typically accessed via `XH.fetchService` or the matching convenience aliases on `XH`
* (`XH.fetchJson()`, `XH.postJson()`, etc.), which delegate here.
*
* Wraps the standard Fetch API with CORS enabled, credentials included, and redirects followed.
* Provides JSON convenience methods (`fetchJson`, `postJson`, `putJson`, `patchJson`,
* `deleteJson`, `getJson`) that handle serialization and content-type headers automatically,
* plus `fetchNdjson` for consuming streamed NDJSON responses incrementally.
*
* Key features:
* - Configurable timeouts (default 30s) via {@link FetchOptions.timeout}
* - Auto-abort of duplicate in-flight requests via {@link FetchOptions.autoAbortKey}
* - Optional correlation IDs for request tracking (see `defaults.autoGenCorrelationIds`)
* - W3C `traceparent` headers when tracing is enabled, sent by default only to the app's own
* server (see `defaults.propagateTrace` and {@link FetchOptions.propagateTrace})
* - Request/response interceptors via {@link addInterceptor}
* - Default headers for all requests via {@link addDefaultHeaders}
* - Rich exception handling with HTTP status, server messages, and trace IDs
*
* All convenience methods accept the same {@link FetchOptions} as the main `fetch()` entry point.
*
* @see FetchOptions
*/
export class FetchService extends HoistService {
static instance: FetchService;
/** App-level defaults for FetchService. Instance options take precedence. */
static defaults: FetchServiceDefaults = {
autoGenCorrelationIds: false,
correlationIdHeaderKey: 'X-Correlation-ID',
genCorrelationId: () => genRandomId(16),
propagateTrace: opts => FetchService.isHoistServerUrl(opts.url)
};
/**
* Does a request url target the app's own server? True for relative and root-relative urls,
* and for absolute urls on the origin of the page or of {@link XH.baseUrl}.
*/
static isHoistServerUrl(url: string): boolean {
if (!url?.includes('//')) return true;
try {
const {origin} = window.location,
target = new URL(url, origin).origin;
return target === origin || target === new URL(XH.baseUrl, origin).origin;
} catch {
return false;
}
}
/** Response statuses carrying no body - No Content and Reset Content. */
NO_JSON_RESPONSES = [204, 205];
/**
* Regex applied during failed response handling to determine if contentType indicates JSON.
* Matches `application/json` as well as variants such as `application/problem+json`
*/
JSON_CONTENT_TYPE_RE = /application\/[^+]*[+]?(json);?.*/i;
private autoAborters = {};
private _defaultHeaders: DefaultHeaders[] = [];
private _interceptors: FetchInterceptor[] = [];
private interners: Map<string, StringInterner> = new Map();
/** Default timeout to be used for all requests made via this service */
defaultTimeout: PromiseTimeoutSpec = 30 * SECONDS;
/** Default headers to be sent with all subsequent requests. */
get defaultHeaders(): DefaultHeaders[] {
return this._defaultHeaders;
}
/**
* Promise handlers to be executed before fulfilling or rejecting returned Promise.
*
* Use the `onRejected` handler for apps requiring common handling for particular exceptions.
* Useful for recognizing 401s (i.e., session end), or wrapping, logging, or enhancing exceptions.
* The simplest onRejected handler will simply rethrow the passed exception, or a wrapped version of it.
* Such handlers may also return `never()` to prevent further processing of the request -- this
* is useful, i.e., if the handler is going to redirect the entire app, or otherwise end normal
* app processing. Rejected handlers may also be able to retry and return valid results via
* another call to fetch.
*
* Use the `onFulfilled` handler for enhancing, tracking, or even rejecting "successful" returns.
* For example, a handler of this form could be used to transform a 200 response returned by
* an API with an "error" flag into a proper client-side exception.
*/
addInterceptor(handler: FetchInterceptor) {
this._interceptors.push(handler);
}
/**
* Add default headers to be sent with all subsequent requests.
* @param headers - to be sent with all fetch requests, or a function to generate.
*/
addDefaultHeaders(headers: DefaultHeaders) {
this._defaultHeaders.push(headers);
}
//--------------------
// Main Entry Points
//--------------------
/**
* Send a request via the underlying fetch API.
*
* This is the main entry point for this API, and can be used to satisfy all
* requests. Other shortcut variants will delegate to this method, after setting
* default options and pre-processing content.
*
* Set `asJson` to true return a parsed JSON result, rather than the raw Response.
* Note that shortcut variant of this method (e.g. `fetchJson`, `postJson`) will set this
* flag for you.
*
* @param opts - request options.
* @param ctx - optional {@link CallContextLike} supplying parent span and load context.
* @returns Promise which resolves to a Response or JSON.
*/
async fetch(opts: FetchOptions, ctx?: CallContextLike): Promise<any> {
return this.fetchInternalAsync(opts, ctx);
}
/**
* Send an HTTP request and decode the response as JSON.
* @returns the decoded JSON object, or null if the response has status in {@link NO_JSON_RESPONSES}.
*/
async fetchJson(opts: FetchOptions, ctx?: CallContextLike): Promise<any> {
return this.fetchInternalAsync({asJson: true, ...opts}, ctx);
}
/**
* Send a GET request and decode the response as JSON.
* @returns the decoded JSON object, or null if the response status is in {@link NO_JSON_RESPONSES}.
*/
async getJson(opts: FetchOptions, ctx?: CallContextLike): Promise<any> {
return this.fetchInternalAsync({asJson: true, method: 'GET', ...opts}, ctx);
}
/**
* Send an HTTP request and decode the response body incrementally as NDJSON - newline
* delimited JSON, aka JSON Lines / JSONL. Returns an {@link NdjsonResult} whose `lines`
* generator yields parsed records one at a time as they arrive off the network. No more
* than one network chunk of raw text is buffered, making this suitable for consuming
* very large or long-running streamed responses.
*
* The natural source for {@link Store.loadDataAsync} - e.g.
* `store.loadDataAsync(XH.fetchNdjson({url}).lines)` - or iterate `lines` directly via
* `for await` for non-Store streaming.
*
* Set {@link NdjsonFetchOptions.firstLineIsMeta} to treat the first record in the stream as
* out-of-band metadata, delivered via the result's `meta` promise rather than `lines`. The
* promise resolves as soon as the record arrives - before `lines` is consumed - so callers
* can use it to decide how to process the balance of the stream.
*
* Tracing spans and `track` cover the full lifetime of the stream, through complete
* consumption. Note that `timeout` covers the request phase only - no timeout applies while
* the stream is being read.
*
* A stream truncated by a server-side failure surfaces as a 'Fetch Stream Failed' exception -
* hoist-core's `renderNdjson` guarantees such a stream ends with an unparseable line.
*/
fetchNdjson(opts: NdjsonFetchOptions, ctx?: CallContextLike): NdjsonResult {
opts = this.withCorrelationId(opts);
let runner = this.runner(ctx);
// Configure special track and spanning across the async consumption.
const spanConfig = this.createSpanConfig(opts),
{track} = opts;
if (spanConfig) {
runner = runner.span(spanConfig);
}
if (track) {
const trackOptions: TrackOptions = isString(track) ? {message: track} : track;
runner = runner.track({...trackOptions, correlationId: opts.correlationId as string});
}
// The runner will manage the lifecycle, but we won't await it here -- return
// the result straight away. Also stifle telemetry exception. Stream already produces them.
let ret: NdjsonResultImpl;
const aborter = new AbortController();
runner
.run(async innerCtx => {
ret = new NdjsonResultImpl(
this.fetchInternalAsync(opts, innerCtx, aborter),
opts,
this.getInterner(opts.internStrings),
(cause, response) =>
this.isAborted(opts, aborter)
? this.abortedException(opts, innerCtx, cause)
: this.streamFailedException(opts, innerCtx, response, cause)
);
try {
await ret.whenCompleteAsync();
} finally {
this.releaseAutoAbortKey(opts.autoAbortKey, aborter);
}
})
.catch(noop);
return ret;
}
/**
* Send a POST request with a JSON body and decode the response as JSON.
* @returns the decoded JSON object, or null if the response status is in {@link NO_JSON_RESPONSES}.
*/
async postJson(opts: FetchOptions, ctx?: CallContextLike): Promise<any> {
return this.sendJsonInternalAsync({method: 'POST', ...opts}, ctx);
}
/**
* Send a PUT request with a JSON body and decode the response as JSON.
* @returns the decoded JSON object, or null if the response status is in {@link NO_JSON_RESPONSES}.
*/
async putJson(opts: FetchOptions, ctx?: CallContextLike): Promise<any> {
return this.sendJsonInternalAsync({method: 'PUT', ...opts}, ctx);
}
/**
* Send a PATCH request with a JSON body and decode the response as JSON.
* @returns the decoded JSON object, or null if the response status is in {@link NO_JSON_RESPONSES}.
*/
async patchJson(opts: FetchOptions, ctx?: CallContextLike): Promise<any> {
return this.sendJsonInternalAsync({method: 'PATCH', ...opts}, ctx);
}
/**
* Send a DELETE request with optional JSON body and decode the optional response as JSON.
* @returns the decoded JSON object, or null if the response status is in {@link NO_JSON_RESPONSES}.
*/
async deleteJson(opts: FetchOptions, ctx?: CallContextLike): Promise<any> {
return this.sendJsonInternalAsync({method: 'DELETE', ...opts}, ctx);
}
/**
* Manually abort any pending request for a given autoAbortKey.
* @returns false if no request pending for the given key.
*/
abort(autoAbortKey: string): boolean {
const {autoAborters} = this,
aborter = autoAborters[autoAbortKey];
if (!aborter) return false;
aborter.abort();
delete autoAborters[autoAbortKey];
return true;
}
/**
* Clear string-interning caches maintained for {@link FetchOptions.internStrings} - all of
* them, or just the cache for a single key.
*
* Interned strings referenced by live records remain retained by those records - this
* releases only the cache's own references. Useful after tearing down large views whose
* datasets will not be refetched, where the cache would otherwise continue to retain the
* last response's distinct values.
*
* @param key - specific {@link StringInternSpec.key} to clear, or omit to clear all.
*/
clearInternCaches(key?: string) {
key ? this.interners.delete(key) : this.interners.clear();
}
/**
* Snapshot of string-interning stats for each active {@link FetchOptions.internStrings}
* key, covering the most recently completed response per key: total string values
* processed, distinct values retained (with % of processed - lower = more duplication
* removed), and values carried over from the prior generation (with % of retained -
* higher = more stability across refreshes).
*
* Convenient from the console via `console.table(XH.fetchService.getInternStats())`.
*/
getInternStats(): PlainObject[] {
return Array.from(this.interners.values()).map(it => it.stats);
}
//-----------------------
// Implementation
//-----------------------
/**
* @param streamAborter - aborter for a stream, set by fetchNdjson. It applies its own span and
* track across the full stream lifetime - suppresses both here - and releases any
* autoAbortKey once the stream completes.
*/
private async fetchInternalAsync(
opts: FetchOptions,
ctx?: CallContextLike,
streamAborter: AbortController = null
): Promise<any> {
ctx ??= {};
const forStreaming = !!streamAborter;
let spanConfig = forStreaming ? null : this.createSpanConfig(opts),
runner = spanConfig ? this.runner(ctx).span(spanConfig) : this.runner(ctx),
ret = runner.run(ctx => {
opts = this.withCorrelationId(opts);
opts = this.withTraceId(opts, ctx.span);
return this.withResolvedHeadersAsync(opts, ctx.span).then(opts =>
this.managedFetchAsync(opts, ctx, streamAborter)
);
});
// 2) Apply tracking
if (opts.track && !forStreaming) {
const {correlationId, track} = opts;
const trackOptions: TrackOptions = isString(track) ? {message: track} : track;
warnIf(
trackOptions.correlationId || trackOptions.loadSpec,
'Neither Correlation ID nor LoadSpec should be set in `FetchOptions.track`. Use `FetchOptions` top-level properties instead.'
);
ret = ret.track({
...trackOptions,
correlationId: correlationId as string,
loadSpec: ctx.loadSpec
});
}
// 3) Apply interceptors - run after span has ended and exported.
for (const interceptor of this._interceptors) {
ret = ret.then(
value => interceptor.onFulfilled(opts, value),
cause => interceptor.onRejected(opts, cause)
);
}
return ret;
}
private sendJsonInternalAsync(opts: FetchOptions, ctx?: CallContextLike) {
return this.fetchInternalAsync(
{
asJson: true,
...opts,
body: JSON.stringify(opts.body),
headers: {
'Content-Type': 'application/json',
...opts.headers
}
},
ctx
);
}
// Resolve convenience options for Correlation ID to server-ready string
private withCorrelationId(opts: FetchOptions): FetchOptions {
const cid = opts.correlationId,
autoCid = FetchService.defaults.autoGenCorrelationIds;
if (isString(cid)) return opts;
if (cid === false || cid === null) return omit(opts, 'correlationId');
if (cid === true || autoCid === true || (isFunction(autoCid) && autoCid(opts))) {
return {...opts, correlationId: FetchService.defaults.genCorrelationId()};
}
return opts;
}
private withTraceId(opts: FetchOptions, span: Span): FetchOptions {
return span ? {...opts, traceId: span.traceId} : opts;
}
private async withResolvedHeadersAsync(opts: FetchOptions, span: Span): Promise<FetchOptions> {
const method = opts.method ?? 'GET',
isForm = ['POST', 'PUT'].includes(method);
const defaultHeaders = {};
for (const h of this.defaultHeaders) {
Object.assign(defaultHeaders, isFunction(h) ? await h(opts) : h);
}
const headers = {
'Content-Type': isForm ? 'application/x-www-form-urlencoded' : 'text/plain',
...defaultHeaders,
...(opts.asJson ? {Accept: 'application/json'} : {}),
...(span && this.shouldPropagateTrace(opts)
? {traceparent: formatTraceparent(span.traceId, span.spanId, span.sampled)}
: {}),
...opts.headers
};
const {correlationIdHeaderKey} = FetchService.defaults;
if (opts.correlationId) {
if (headers[correlationIdHeaderKey]) {
this.logWarn(
`Header ${correlationIdHeaderKey} value already set within FetchOptions.`
);
} else {
headers[correlationIdHeaderKey] = opts.correlationId;
}
}
return {...opts, method, headers};
}
private shouldPropagateTrace(opts: FetchOptions): boolean {
if (!isNil(opts.propagateTrace)) return opts.propagateTrace;
const {propagateTrace} = FetchService.defaults;
return isFunction(propagateTrace) ? propagateTrace(opts) : propagateTrace;
}
private async managedFetchAsync(
opts: FetchOptions,
callCtx: CallContext,
streamAborter: AbortController
): Promise<any> {
// Prepare auto-aborter
const {autoAborters, defaultTimeout} = this,
{autoAbortKey, timeout = defaultTimeout} = opts,
aborter = streamAborter ?? new AbortController();
// autoAbortKey handling. Abort anything running under this key, and mark this run
if (autoAbortKey) {
this.abort(autoAbortKey);
autoAborters[autoAbortKey] = aborter;
}
try {
return await this.abortableFetchAsync(opts, aborter, callCtx)
.then(r => (opts.asJson ? this.parseJsonAsync(opts, r, callCtx) : r))
.timeout(timeout);
} catch (e) {
if (e.isTimeout) {
aborter.abort();
const msg =
isObject(timeout) && 'message' in timeout
? timeout.message
: // Exception.timeout() message already includes interval - add URL here.
e.message + ` loading '${opts.url}'`;
throw this.timeoutException(opts, callCtx, e, msg);
}
if (this.isAborted(opts, aborter)) throw this.abortedException(opts, callCtx, e);
if (e.isHoistException) throw e;
// Any other error means the server could not be reached.
throw this.serverUnavailableException(opts, callCtx, e);
} finally {
if (!streamAborter) this.releaseAutoAbortKey(autoAbortKey, aborter);
}
}
// Fetch listens to both signals, joined - check each, as a custom abort reason is no AbortError.
private isAborted(opts: FetchOptions, aborter: AbortController): boolean {
return aborter.signal.aborted || !!opts.fetchOpts?.signal?.aborted;
}
private releaseAutoAbortKey(autoAbortKey: string, aborter: AbortController) {
if (autoAbortKey && this.autoAborters[autoAbortKey] === aborter) {
delete this.autoAborters[autoAbortKey];
}
}
private async abortableFetchAsync(
opts: FetchOptions,
aborter: AbortController,
callCtx: CallContext
): Promise<Response> {
// 1) Prepare URL
let {url, method, headers, body, params} = opts;
url = this.resolveUrl(url);
// 2) Prepare options for fetch API. Join any caller signal with ours, so either aborts.
const {signal, ...callerFetchOpts} = opts.fetchOpts ?? {},
fetchOpts: RequestInit = {
credentials: 'include',
redirect: 'follow',
headers: new Headers(omitBy(headers, isNil)),
method,
body,
...callerFetchOpts,
signal: signal ? AbortSignal.any([aborter.signal, signal]) : aborter.signal
};
// 3) Preprocess and apply params
if (params) {
const qsOpts: IStringifyOptions<true> = {
arrayFormat: 'repeat',
allowDots: true,
filter: this.qsFilterFn,
...opts.qsOpts
};
const paramsString = stringify(params, qsOpts);
if (
['POST', 'PUT'].includes(method) &&
headers['Content-Type'] !== 'application/json'
) {
// Fall back to an 'application/x-www-form-urlencoded' POST/PUT body if not sending json.
fetchOpts.body = paramsString;
} else {
url += '?' + paramsString;
}
}
// 4) Await underlying fetch and post-process response.
const ret = await fetch(url, fetchOpts);
callCtx.span?.setHttpStatus(ret.status);
if (!ret.ok) {
throw this.exceptionFromResponse(
opts,
callCtx,
ret,
await this.safeResponseTextAsync(ret)
);
}
return ret;
}
private async parseJsonAsync(
opts: FetchOptions,
r: Response,
callCtx: CallContext
): Promise<any> {
if (this.NO_JSON_RESPONSES.includes(r.status)) return null;
const ret = await r.json().catchWhen('SyntaxError', e => {
throw this.jsonParseException(opts, callCtx, e);
});
const interner = this.getInterner(opts.internStrings);
interner?.intern(ret);
interner?.commit();
return ret;
}
private async safeResponseTextAsync(response: Response) {
try {
return await response.text();
} catch (ignore) {
return null;
}
}
private createSpanConfig(opts: FetchOptions): SpanConfig {
if (!XH.traceService.enabled) return null;
const method = opts.method ?? 'GET',
fullUrl = this.buildFullUrl(opts.url),
tags: PlainObject = {
'xh.source': 'hoist',
'http.request.method': method,
'url.full': fullUrl
};
// Per OTel HTTP semconv, populate server.address (and server.port if non-default).
try {
const {hostname, port, protocol} = new URL(fullUrl, window.location.origin);
if (hostname) tags['server.address'] = hostname;
if (port) {
tags['server.port'] = parseInt(port, 10);
} else if (protocol === 'http:') {
tags['server.port'] = 80;
} else if (protocol === 'https:') {
tags['server.port'] = 443;
}
} catch {}
return {
name: method,
kind: 'client',
tags
};
}
/** Prefix relative URLs with {@link XH.baseUrl}; leave absolute/root-relative URLs as-is. */
private resolveUrl(url: string): string {
if (!url) return '';
const isRelative = !url.startsWith('/') && !url.includes('//');
return isRelative ? XH.baseUrl + url : url;
}
private buildFullUrl(url: string): string {
const raw = this.resolveUrl(url);
if (!raw) return '';
try {
const parsed = new URL(raw, window.location.origin);
// Redact values of query params that commonly carry secrets. Collect keys via
// forEach (declared in base lib.dom, unlike the iterator methods) so this shipped
// source type-checks in apps without dom.iterable or @types/node in their program.
const sensitive =
/^(token|access_token|id_token|password|pwd|secret|api[_-]?key|auth|session|sig|signature)$/i;
const keys: string[] = [];
parsed.searchParams.forEach((_v, key) => keys.push(key));
keys.forEach(key => {
if (sensitive.test(key)) parsed.searchParams.set(key, 'REDACTED');
});
return parsed.toString();
} catch {
return raw;
}
}
private qsFilterFn = (_prefix: string, value: any) => {
if (isDate(value)) return value.getTime();
if (isLocalDate(value)) return value.isoString;
return value;
};
//---------------------
// Exception Handling
//--------------------
/**
* Create an Error to throw when a fetch call returns a !ok response.
* @param fetchOptions - original options passed to FetchService.
* @param response - return value of native fetch.
* @param responseText - optional additional details from the server.
*/
private exceptionFromResponse(
fetchOptions: FetchOptions,
callContext: CallContext,
response: Response,
responseText: string = null
): FetchException {
const {headers, status, statusText} = response,
defaults = {
name: 'HTTP Error ' + (status || ''),
message: statusText,
httpStatus: status,
serverDetails: responseText,
fetchOptions,
callContext
};
if (status === 401) {
return this.createException({
...defaults,
name: 'Unauthorized',
message: 'Your session may have timed out and you may need to log in again.'
});
}
// Attempt to decode server-provided exception if returned as JSON.
try {
if (headers.get('Content-Type')?.match(this.JSON_CONTENT_TYPE_RE)) {
const parsedResp = this.safeParseJson(responseText);
return this.createException({
...defaults,
name: parsedResp?.name ?? defaults.name,
message: this.extractMessage(parsedResp, responseText, statusText),
isRoutine: parsedResp?.isRoutine ?? false,
serverDetails: parsedResp ?? responseText
});
}
} catch (ignored) {}
// Fall back to raw defaults
return this.createException(defaults);
}
/**
* Get or create the {@link StringInterner} for the given spec's key, or null if interning
* was not requested. Interners are retained per key with the latest spec adopted on each
* call - see {@link clearInternCaches} to reset.
*/
private getInterner(spec: StringInternSpec): StringInterner {
if (!spec) return null;
const {interners} = this;
let ret = interners.get(spec.key);
if (!ret) {
ret = new StringInterner(spec);
interners.set(spec.key, ret);
} else {
ret.spec = spec;
}
return ret;
}
/**
* Create an Error to throw when a fetchJson call encounters a SyntaxError.
* @param fetchOptions - original options passed to FetchService.
* @param cause - object thrown by native {@link response.json}.
*/
private jsonParseException(
fetchOptions: FetchOptions,
callContext: CallContext,
cause: any
): FetchException {
return this.createException({
name: 'JSON Parsing Error',
message:
'Error parsing the response body as JSON. The server may have returned an invalid ' +
'or empty response. Use "XH.fetch()" to process the response manually.',
fetchOptions,
callContext,
cause
});
}
/**
* Create an Error to throw when a fetch call is aborted.
* @param fetchOptions - original options passed to FetchService.
* @param cause - object thrown by native fetch
*/
private abortedException(
fetchOptions: FetchOptions,
callContext: CallContextLike,
cause: any
): FetchException {
return this.createException({
name: 'Fetch Aborted',
message: `Fetch request aborted, url: "${fetchOptions.url}"`,
isRoutine: true,
isFetchAborted: true,
fetchOptions,
callContext,
cause
});
}
/**
* Create an Error to throw when a fetch call times out.
* @param fetchOptions - original options the app passed when calling FetchService.
* @param cause - underlying timeout exception
* @param message - optional custom message
*
* @returns an exception that is both a TimeoutException, and a FetchException, with the
* underlying TimeoutException as its cause.
*/
private timeoutException(
fetchOptions: FetchOptions,
callContext: CallContext,
cause: TimeoutException,
message: string
): FetchException & TimeoutException {
return this.createException({
name: 'Fetch Timeout',
message,
isFetchTimeout: true,
isTimeout: true,
interval: cause.interval,
fetchOptions,
callContext,
cause
}) as FetchException & TimeoutException;
}
/**
* Create an Error to throw when a fetch call fails while reading or parsing its streamed
* response body.
* @param fetchOptions - original options passed to FetchService.
* @param response - response whose body was being streamed.
* @param cause - underlying error raised while reading or parsing the stream.
*/
private streamFailedException(
fetchOptions: FetchOptions,
callContext: CallContextLike,
response: Response,
cause: any
): FetchException {
return this.createException({
name: 'Fetch Stream Failed',
message: `Failure while reading streamed response, url: "${fetchOptions.url}" - ${cause.message}`,
httpStatus: response.status,
fetchOptions,
callContext,
cause
});
}
/**
* Create an Error for when the server called by fetch does not respond
* @param fetchOptions - original options the app passed to FetchService.fetch
* @param cause - object thrown by native fetch
*/
private serverUnavailableException(
fetchOptions: FetchOptions,
callContext: CallContext,
cause: any
): FetchException {
const protocolPattern = /^[a-z]+:\/\//i,
originPattern = /^[a-z]+:\/\/[^/]+/i,
match = fetchOptions.url.match(originPattern),
origin = match
? match[0]
: protocolPattern.test(XH.baseUrl)
? XH.baseUrl
: window.location.origin;
return this.createException({
name: 'Server Unavailable',
message: `Unable to contact the server at ${origin}`,
isServerUnavailable: true,
fetchOptions,
callContext,
cause
});
}
private createException(attributes: PlainObject) {
const {fetchOptions} = attributes;
// Prefer the header actually sent, falling back to the option if pre-resolution.
const correlationId: string =
fetchOptions?.headers?.[FetchService.defaults.correlationIdHeaderKey] ??
(isString(fetchOptions?.correlationId) ? fetchOptions.correlationId : null);
const traceId: string = fetchOptions?.traceId ?? null;
return Exception.create({
isFetchAborted: false,
httpStatus: 0, // native fetch doesn't put status on its Error
serverDetails: null,
stack: null, // server-sourced exceptions do not include, neither should client, not relevant
correlationId,
traceId,
...attributes
}) as FetchException;
}
private safeParseJson(txt: string): PlainObject {
try {
return JSON.parse(txt);
} catch (ignored) {
return null;
}
}
private extractMessage(
parsedResp: PlainObject,
responseText: string,
statusText: string
): string {
let ret: string;
if (parsedResp) {
// Append cause (e.g. ExternalHttpException) - not for routine, whose message is complete.
ret = parsedResp.message;
if (isString(parsedResp.cause) && !parsedResp.isRoutine) {
const cause = truncate(parsedResp.cause, {length: 255});
ret = ret ? `${ret} (Caused by: ${cause})` : cause;
}
} else {
// Use raw text if not JSON parseable
ret = truncate(responseText?.trim(), {length: 255});
}
// Fallback to statusText if we have nothing else.
return ret || statusText;
}
}
/** Headers to be applied to all requests. Specified as object, or dynamic function to create. */
export type DefaultHeaders = PlainObject | ((opts: FetchOptions) => Awaitable<PlainObject>);
/** Handlers to be executed before fufilling or rejecting any exception to caller. */
export interface FetchInterceptor {
onFulfilled: (opts: FetchOptions, value: any) => Promise<any>;
onRejected: (opts: FetchOptions, cause: unknown) => Promise<any>;
}
/**
* Standard options to pass through to fetch, with some additions.
* See MDN for available options - {@link https://developer.mozilla.org/en-US/docs/Web/API/Request}.
*/
export interface FetchOptions {
/** URL for the request. Relative urls will be appended to XH.baseUrl. */
url: string;
/**
* Data to send in the request body (for POSTs/PUTs of JSON).
* When using `fetch`, provide a string. Otherwise, provide a JSON Serializable object
*/
body?: any;
/**
* Unique identifier for this request, used for tracking and logging. If `false`, no
* `correlationId` will be set. If `true`, one will be auto-generated.
*/
correlationId?: string | boolean;
/**
* True to send a W3C `traceparent` header with this request, false to omit it. Applies only
* when tracing is enabled. The request still records a client span either way, but only a
* server that receives the header can join the trace. Defaults to
* `FetchService.defaults.propagateTrace`, which sends the header only to the app's own server.
*
* Note `traceparent` is not a CORS-safelisted header. A cross-origin server must list it in
* `Access-Control-Allow-Headers`, or the browser blocks the request.
*/
propagateTrace?: boolean;
/**
* Parameters to encode as a query string, or as a form-url-encoded body for a POST or PUT
* whose `Content-Type` is not JSON. A request with no `method` is a GET, so its params go on
* the query string - set `method: 'POST'` to send them in the body instead.
*/
params?: PlainObject;
/**
* HTTP Request method to use for the request. Defaults to GET, whether or not `params` are set.
*/
method?: string;
/**
* Headers to send with this request. A Content-Type header will be set if not provided by
* the caller directly or via one of the xxxJson convenience methods.
*/
headers?: PlainObject;
/**
* MS to wait for response before rejecting with a timeout exception. Defaults to 30 seconds,
* but may be specified as null to specify no timeout.
*/
timeout?: PromiseTimeoutSpec;
/**
* Options to pass to the underlying fetch request.
* @see https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
*/
fetchOpts?: PlainObject;
/**
* Options for qs, the library used to encode query strings.
*/
qsOpts?: Partial<IStringifyOptions>;
/**
* If set, any pending requests made with the same autoAbortKey will be immediately
* aborted in favor of the new request.
*/
autoAbortKey?: string;
/**
* If set, intern string values in array-based JSON and NDJSON responses to reduce retained
* memory on large tabular datasets - each distinct string value is stored once and shared
* across all rows, rather than duplicated per row as produced by JSON parsing.
*
* Applies to string values at the root level of each object within an array response (or
* each NDJSON record). A single plain-object response is treated as a root record and
* processed likewise. Nested values are not processed, with the exception of recursion
* into child records via `childrenKey`. No-op for response payloads of any other shape.
*
* Interned values are also optionally shared across successive responses with the same `key` -
* e.g. a polling refresh of the same grid - with cache retention per each key's
* {@link StringInternSpec.retainMode}, by default bounded to the values present in the most
* recent complete response.
*/
internStrings?: StringInternSpec;
/**
* True to decode the HTTP response as JSON. Default false.
*/
asJson?: boolean;
/**
* If set, the request will be tracked via Hoist activity tracking. (Do not set `correlationId`
* here - use the top-level `correlationId` property instead.)
*/
track?: string | TrackOptions;
/**
* Distributed trace ID for this request. Set automatically by FetchService
* @internal
*/
traceId?: string;
}
/** Options for {@link FetchService.fetchNdjson}. */
export interface NdjsonFetchOptions extends FetchOptions {
/**
* True to treat the first record in the stream as metadata, delivered via
* {@link NdjsonResult.meta} rather than yielded with the data records. Default false.
*/
firstLineIsMeta?: boolean;
}
/** Streamed result returned by {@link FetchService.fetchNdjson}. */