-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathMockServerE2E.ts
More file actions
871 lines (788 loc) · 29.2 KB
/
MockServerE2E.ts
File metadata and controls
871 lines (788 loc) · 29.2 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
// eslint-disable-next-line @typescript-eslint/no-shadow
import { getLocal, Headers, Mockttp } from 'mockttp';
import { ALLOWLISTED_HOSTS, ALLOWLISTED_URLS } from './mock-e2e-allowlist.ts';
import { SUPPRESSED_LOGS_URLS } from './mock-config/suppressed-logs.ts';
import { createLogger, LogLevel } from '../framework/logger.ts';
import {
MockApiEndpoint,
MockEventsObject,
Resource,
ServerStatus,
TestSpecificMock,
} from '../framework';
import {
findMatchingPostEvent,
processPostRequestBody,
setupAccountsV2SupportedNetworksMock,
} from './helpers/mockHelpers.ts';
import { getLocalHost } from '../framework/fixtures/FixtureUtils.ts';
import PortManager, { ResourceType } from '../framework/PortManager.ts';
import {
FALLBACK_GANACHE_PORT,
FALLBACK_DAPP_SERVER_PORT,
} from '../framework/Constants.ts';
import { DEFAULT_ANVIL_PORT } from '../seeder/anvil-manager.ts';
import { logLiveMetaMetricsPostIfDebug } from '../helpers/analytics/analyticsDebug.ts';
const logger = createLogger({
name: 'MockServer',
level: LogLevel.INFO,
});
// ---------------------------------------------------------------------------
// Patch mockttp's matchesAll so aborted requests don't become unhandled
// rejections.
//
// findMatchingRule() starts ALL rules matching concurrently (.map) but awaits
// them one-by-one. When the first match succeeds it returns, abandoning the
// rest. If any of those reject (streamToBuffer → Error('Aborted') from a
// client disconnect), they become unhandled rejections that Jest turns into
// test failures.
//
// This patch catches only Error('Aborted') and returns false ("no match").
// All other errors propagate normally.
// ---------------------------------------------------------------------------
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const mockttpMatchers = require('mockttp/dist/rules/matchers');
const originalMatchesAll = mockttpMatchers.matchesAll;
mockttpMatchers.matchesAll = async function (
...args: Parameters<typeof originalMatchesAll>
) {
try {
return await originalMatchesAll.apply(this, args);
} catch (e) {
if (e instanceof Error && e.message === 'Aborted') {
return false;
}
throw e;
}
};
} catch (e) {
logger.warn('Failed to patch mockttp matchesAll:', e);
}
/**
* Safely reads request body text, catching abort errors.
* When a client drops a connection mid-request (e.g., app navigation, AbortController),
* mockttp's streamToBuffer rejects with Error('Aborted'). This wrapper catches those
* errors and returns undefined instead of letting them bubble up as unhandled rejections.
*
* @param request - The mockttp request object
* @returns The body text or undefined if reading failed or was aborted
*/
export const safeGetBodyText = async (request: {
body: { getText: () => Promise<string | undefined> };
}): Promise<string | undefined> => {
try {
return await request.body.getText();
} catch (error) {
if (error instanceof Error && error.message === 'Aborted') {
logger.debug('Request body read aborted (client disconnected)');
return undefined;
}
logger.warn('Failed to read request body:', error);
return undefined;
}
};
interface LiveRequest {
url: string;
method: string;
timestamp: string;
}
export interface InternalMockServer extends Mockttp {
_liveRequests?: LiveRequest[];
}
/**
* Translates fallback ports to actual allocated ports in URLs.
* This allows the MockServer (running on host) to forward requests to dynamically allocated local resources.
*
* @param url - The URL that may contain a fallback port
* @returns The URL with fallback port replaced by actual allocated port, or original URL
*/
const translateFallbackPortToActual = (url: string): string => {
try {
const parsedUrl = new URL(url);
const port = parsedUrl.port;
if (!port) {
return url;
}
const portNum = parseInt(port, 10);
const portManager = PortManager.getInstance();
let actualPort: number | undefined;
// Map fallback ports to actual allocated ports
// Try Ganache first, fallback to Anvil if Ganache not running
if (portNum === FALLBACK_GANACHE_PORT) {
actualPort = portManager.getPort(ResourceType.GANACHE);
if (actualPort === undefined) {
actualPort = portManager.getPort(ResourceType.ANVIL);
}
} else if (portNum === DEFAULT_ANVIL_PORT) {
actualPort = portManager.getPort(ResourceType.ANVIL);
} else if (
portNum >= FALLBACK_DAPP_SERVER_PORT &&
portNum < FALLBACK_DAPP_SERVER_PORT + 100
) {
// Dapp server ports start at FALLBACK_DAPP_SERVER_PORT (8085, 8086, etc.)
const dappIndex = portNum - FALLBACK_DAPP_SERVER_PORT;
actualPort = portManager.getMultiInstancePort(
ResourceType.DAPP_SERVER,
`dapp-server-${dappIndex}`,
);
}
if (actualPort !== undefined) {
parsedUrl.port = actualPort.toString();
const translatedUrl = parsedUrl.toString();
logger.info(`Port translation: ${url} → ${translatedUrl}`);
return translatedUrl;
}
return url;
} catch (error) {
logger.warn('Failed to parse URL for port translation:', url, error);
return url;
}
};
const isUrlAllowed = (url: string): boolean => {
try {
if (ALLOWLISTED_URLS.includes(url)) {
return true;
}
const parsedUrl = new URL(url);
const hostname = parsedUrl.hostname;
if (parsedUrl.protocol === 'data:') {
return true;
}
return ALLOWLISTED_HOSTS.some((allowedHost) => {
if (allowedHost.startsWith('*.')) {
const domain = allowedHost.slice(2);
return hostname === domain || hostname.endsWith(`.${domain}`);
}
return hostname === allowedHost;
});
} catch (error) {
logger.warn('Invalid URL:', url);
return false;
}
};
const isUrlSuppressedFromLogs = (url: string): boolean =>
SUPPRESSED_LOGS_URLS.some((pattern: RegExp) => pattern.test(url));
const handleDirectFetch = async (
url: string,
method: string,
headers: Headers,
requestBody?: string,
): Promise<{ statusCode: number; body: string }> => {
try {
const fetchHeaders: HeadersInit = {};
for (const [key, value] of Object.entries(headers)) {
if (value) {
fetchHeaders[key] = Array.isArray(value) ? value[0] : value;
}
}
const response = await global.fetch(url, {
method,
headers: fetchHeaders,
body: ['POST', 'PUT', 'PATCH'].includes(method) ? requestBody : undefined,
});
const responseBody = await response.text();
return { statusCode: response.status, body: responseBody };
} catch (error) {
if (!isUrlSuppressedFromLogs(url)) {
logger.error('Error forwarding request:', url, error);
}
return {
statusCode: 500,
body: JSON.stringify({ error: 'Failed to forward request' }),
};
}
};
export default class MockServerE2E implements Resource {
_serverPort: number;
_serverStatus: ServerStatus = ServerStatus.STOPPED;
private _server: InternalMockServer | null = null;
private _events: MockEventsObject;
private _testSpecificMock?: TestSpecificMock;
private _activeRequests = 0;
private _shuttingDown = false;
private _abortFilterHandler: ((...args: unknown[]) => void) | null = null;
private _abortExceptionHandler: ((...args: unknown[]) => void) | null = null;
private _abortSuppressCount = 0;
private _originalRejectionHandlers: ((...args: unknown[]) => void)[] = [];
private _originalExceptionHandlers: ((...args: unknown[]) => void)[] = [];
constructor(params: {
events: MockEventsObject;
testSpecificMock?: TestSpecificMock;
}) {
this._events = params.events;
this._serverPort = 0; // Will be set when starting the server
this._testSpecificMock = params.testSpecificMock;
}
isStarted(): boolean {
return this._serverStatus === ServerStatus.STARTED;
}
getServerPort(): number {
return this._serverPort;
}
getServerStatus(): ServerStatus {
return this._serverStatus;
}
get getServerUrl(): string {
return `http://${getLocalHost()}:${this._serverPort}`;
}
get server(): InternalMockServer {
if (!this._server) {
throw new Error('Mock server not started');
}
return this._server;
}
setServerPort(port: number): void {
this._serverPort = port;
}
async start(): Promise<void> {
if (this._serverStatus === ServerStatus.STARTED) {
logger.debug('Mock server already started');
return;
}
this._server = getLocal() as InternalMockServer;
this._server._liveRequests = [];
await this._server.start(this._serverPort);
logger.info(
`Mockttp server running at http://${getLocalHost()}:${this._serverPort}`,
);
await this._server
.forGet('/health-check')
.thenReply(200, 'Mock server is running');
await this._server
.forGet(
/^http:\/\/(localhost|127\.0\.0\.1|10\.0\.2\.2)(:\\d+)?\/favicon\.ico$/,
)
.thenReply(200, 'favicon.ico');
if (this._testSpecificMock) {
logger.info('Applying testSpecificMock function (takes precedence)');
await this._testSpecificMock(this._server);
}
await setupAccountsV2SupportedNetworksMock(this._server);
await this._server
.forAnyRequest()
.matching((request) => request.path.startsWith('/proxy'))
.thenCallback(async (request) => {
// During shutdown, consume the body (to prevent mockttp's streamToBuffer
// from producing an unhandled rejection) and return 503 immediately.
if (this._shuttingDown) {
try {
await request.body.getText();
} catch {
/* swallow abort errors */
}
return { statusCode: 503, body: 'Server shutting down' };
}
this._activeRequests++;
try {
const urlEndpoint = new URL(request.url).searchParams.get('url');
if (!urlEndpoint) {
return {
statusCode: 400,
body: JSON.stringify({ error: 'Missing url parameter' }),
};
}
const method = request.method;
let requestBodyText: string | undefined;
let requestBodyJson: unknown;
if (method === 'POST') {
try {
requestBodyText = await request.body.getText();
if (requestBodyText) {
try {
requestBodyJson = JSON.parse(requestBodyText);
} catch (e) {
requestBodyJson = undefined;
}
}
} catch (e) {
requestBodyText = undefined;
}
}
if (method === 'POST') {
logLiveMetaMetricsPostIfDebug(urlEndpoint, requestBodyJson);
}
const methodEvents = this._events[method] || [];
const candidateEvents = methodEvents.filter(
(event: MockApiEndpoint) => {
const eventUrl = event.urlEndpoint;
if (!eventUrl) return false;
if (event.urlEndpoint instanceof RegExp) {
return event.urlEndpoint.test(urlEndpoint);
}
const eventUrlStr = String(eventUrl);
return (
urlEndpoint === eventUrlStr ||
urlEndpoint.startsWith(eventUrlStr)
);
},
);
let matchingEvent: MockApiEndpoint | undefined;
if (candidateEvents.length > 0) {
if (method === 'POST') {
matchingEvent = findMatchingPostEvent(
candidateEvents,
requestBodyJson,
);
} else {
matchingEvent = candidateEvents[0];
}
}
if (matchingEvent) {
logger.debug(`Mocking ${method} request to: ${urlEndpoint}`);
logger.debug(`Response status: ${matchingEvent.responseCode}`);
logger.debug('Response:', matchingEvent.response);
if (method === 'POST' && matchingEvent.requestBody) {
const result = processPostRequestBody(
requestBodyText,
matchingEvent.requestBody,
{ ignoreFields: matchingEvent.ignoreFields || [] },
);
if (!result.matches) {
return {
statusCode:
result.error === 'Missing request body' ? 400 : 404,
body: JSON.stringify({
error: result.error,
expected: matchingEvent.requestBody,
received: result.requestBodyJson,
}),
};
}
}
return {
statusCode: matchingEvent.responseCode,
body:
typeof matchingEvent.response === 'string'
? matchingEvent.response
: JSON.stringify(matchingEvent.response),
};
}
let updatedUrl =
device.getPlatform() === 'android'
? urlEndpoint.replace('localhost', '127.0.0.1')
: urlEndpoint;
// Translate fallback ports to actual allocated ports (host-side forwarding)
updatedUrl = translateFallbackPortToActual(updatedUrl);
if (!isUrlAllowed(updatedUrl)) {
const errorMessage = `Request going to live server: ${updatedUrl}`;
logger.warn(errorMessage);
if (method === 'POST') {
logger.warn(`Request Body: ${requestBodyText}`);
}
this._server?._liveRequests?.push({
url: updatedUrl,
method,
timestamp: new Date().toISOString(),
});
} else if (ALLOWLISTED_URLS.includes(updatedUrl)) {
logger.warn(`Allowed URL: ${updatedUrl}`);
if (method === 'POST') {
logger.warn(`Request Body: ${requestBodyText}`);
}
}
try {
return await handleDirectFetch(
updatedUrl,
method,
request.headers,
method === 'POST' ? requestBodyText : undefined,
);
} catch (error) {
// Client dropped the connection before we could respond (e.g. bridge
// controller AbortController fired mid-request). Return a benign
// response so mockttp doesn't surface an unhandled rejection.
if (error instanceof Error && error.message === 'Aborted') {
return { statusCode: 499, body: '' };
}
throw error;
}
} finally {
this._activeRequests--;
}
});
await this._server.forUnmatchedRequest().thenCallback(async (request) => {
// During shutdown, consume the body and return 503 immediately.
if (this._shuttingDown) {
try {
await request.body.getText();
} catch {
/* swallow abort errors */
}
return { statusCode: 503, body: 'Server shutting down' };
}
this._activeRequests++;
try {
// Check for MockServer self-reference to prevent ECONNREFUSED
try {
const url = new URL(request.url);
const isLocalhost =
url.hostname === 'localhost' ||
url.hostname === '127.0.0.1' ||
url.hostname === '10.0.2.2';
const isMockServerPort =
url.port === '8000' || url.port === this._serverPort.toString();
if (isLocalhost && isMockServerPort) {
logger.debug(`Ignoring MockServer self-reference: ${request.url}`);
return { statusCode: 204, body: '' };
}
} catch (e) {
// Ignore URL parsing errors
}
// Translate fallback ports to actual allocated ports (host-side forwarding)
const translatedUrl = translateFallbackPortToActual(request.url);
if (!isUrlAllowed(translatedUrl)) {
const errorMessage = `Request going to live server: ${translatedUrl}`;
logger.warn(errorMessage);
if (request.method === 'POST') {
try {
logger.warn(`Request Body: ${await request.body.getText()}`);
} catch (bodyError) {
if (
bodyError instanceof Error &&
bodyError.message === 'Aborted'
) {
return { statusCode: 499, body: '' };
}
logger.warn('Failed to read request body for logging');
}
}
this._server?._liveRequests?.push({
url: translatedUrl,
method: request.method,
timestamp: new Date().toISOString(),
});
} else if (ALLOWLISTED_URLS.includes(translatedUrl)) {
logger.warn(`Allowed URL: ${translatedUrl}`);
if (request.method === 'POST') {
try {
logger.warn(`Request Body: ${await request.body.getText()}`);
} catch (bodyError) {
if (
bodyError instanceof Error &&
bodyError.message === 'Aborted'
) {
return { statusCode: 499, body: '' };
}
logger.warn('Failed to read request body for logging');
}
}
}
try {
// Read body safely before passing to handleDirectFetch to catch abort errors
const bodyText = await safeGetBodyText(request);
// If body read was aborted, return 499 (client closed request)
if (request.method === 'POST' && bodyText === undefined) {
return { statusCode: 499, body: '' };
}
return await handleDirectFetch(
translatedUrl,
request.method,
request.headers,
bodyText,
);
} catch (error) {
// Client dropped the connection before we could respond (e.g. bridge
// controller AbortController fired mid-request). Return a benign
// response so mockttp doesn't surface an unhandled rejection.
if (error instanceof Error && error.message === 'Aborted') {
return { statusCode: 499, body: '' };
}
throw error;
}
} finally {
this._activeRequests--;
}
});
this._serverStatus = ServerStatus.STARTED;
this._installAbortFilter();
}
/**
* Puts the server into draining mode — handlers return 503 immediately
* without forwarding. Call this before stopping backend services (Anvil/Ganache)
* to prevent forwarding requests to dead backends during cleanup.
*/
startDraining(): void {
logger.info(
'MockServer entering drain mode — new requests will receive 503',
);
this._shuttingDown = true;
}
/**
* Removes the lifecycle-wide abort filter. Call this AFTER all cleanup is
* complete to ensure late async "Aborted" rejections are caught.
*
* This method is intentionally async: CI logs show abort events firing up to
* ~200ms AFTER all cleanup has completed and this method is called. We hold
* the filter active for an extra 500ms before restoring Jest's handlers so
* those stragglers are still suppressed rather than recorded as test failures.
*/
async removeAbortFilter(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 500));
this._removeAbortFilter();
}
async stop(): Promise<void> {
logger.info('Mock server shutting down');
if (!this._server) {
this._serverStatus = ServerStatus.STOPPED;
return;
}
// Signal handlers to stop processing new requests. Any request arriving
// after this flag is set will have its body consumed (preventing mockttp's
// streamToBuffer from producing an unhandled rejection) and receive 503.
this._shuttingDown = true;
// Wait for in-flight request handlers to complete. This is the key to
// avoiding the "Aborted" unhandled rejections: mockttp's stop() calls
// destroy() which immediately kills all TCP connections. If a handler is
// still running (e.g. awaiting handleDirectFetch to a real backend), the
// IncomingMessage is aborted and streamToBuffer rejects its promise.
// By waiting for handlers to finish, destroy() only kills idle connections.
await this._waitForActiveRequests();
try {
if (this._server) {
await this._server.stop();
}
// Brief drain period: 'aborted' events from destroyed sockets may fire
// asynchronously on the next event-loop tick after `stop()` resolves.
// 500ms is generous for CI environments where event-loop ticks may be delayed.
await new Promise((resolve) => setTimeout(resolve, 500));
} catch (error) {
logger.error('Error stopping mock server:', error);
} finally {
this._shuttingDown = false;
this._server = null;
this._serverStatus = ServerStatus.STOPPED;
// Release the port after server is stopped
if (this._serverPort > 0) {
PortManager.getInstance().releasePort(ResourceType.MOCK_SERVER);
}
}
}
/**
* Checks whether an error is a mockttp "Aborted" error from streamToBuffer.
*/
private static _isMockttpAbortError(error: unknown): boolean {
return (
error instanceof Error &&
error.message === 'Aborted' &&
(error.stack?.includes('mockttp') ?? false)
);
}
/**
* Installs lifecycle-wide filters for mockttp "Aborted" errors on BOTH
* `unhandledRejection` AND `uncaughtException`.
*
* When the app unexpectedly drops connections during a test (e.g., UI transitions,
* RN bridge interruptions), mockttp's internal `streamToBuffer` rejects with
* `Error('Aborted')` from `buffer-utils.ts`. Depending on the Node.js runtime
* behaviour and how the error surfaces through mockttp's internals, this can appear
* as either an unhandled promise rejection OR an uncaught exception (e.g. from a
* stream 'error' event with no listener, or a throw inside a setImmediate callback).
*
* jest-circus installs the same `uncaught` handler on both event types, so we must
* intercept both to prevent the error from being recorded as a test failure.
*
* The filters are active for the entire server lifecycle (start → stop).
*/
private _installAbortFilter(): void {
if (this._abortFilterHandler) {
return; // Already installed
}
this._abortSuppressCount = 0;
// --- unhandledRejection filter ---
this._originalRejectionHandlers = process
.rawListeners('unhandledRejection')
.slice() as ((...args: unknown[]) => void)[];
process.removeAllListeners('unhandledRejection');
this._abortFilterHandler = (reason: unknown, promise: unknown) => {
const rejectedPromise = promise as Promise<unknown>;
if (MockServerE2E._isMockttpAbortError(reason)) {
// Mark the promise as handled so Node.js does not consider it unhandled.
// eslint-disable-next-line no-empty-function
rejectedPromise.catch(() => {});
this._abortSuppressCount++;
logger.debug(
`Suppressed mockttp Aborted rejection (#${this._abortSuppressCount})`,
);
return;
}
// Forward any other unhandled rejection to the original handlers (e.g. Jest).
if (this._originalRejectionHandlers.length === 0) {
throw reason;
}
let firstError: unknown;
for (const handler of this._originalRejectionHandlers) {
try {
handler(reason, rejectedPromise);
} catch (err) {
if (firstError === undefined) {
firstError = err;
}
}
}
if (firstError !== undefined) {
throw firstError;
}
};
process.on('unhandledRejection', this._abortFilterHandler);
// --- uncaughtException filter ---
this._originalExceptionHandlers = process
.rawListeners('uncaughtException')
.slice() as ((...args: unknown[]) => void)[];
process.removeAllListeners('uncaughtException');
this._abortExceptionHandler = (error: unknown, origin: unknown) => {
if (MockServerE2E._isMockttpAbortError(error)) {
this._abortSuppressCount++;
logger.debug(
`Suppressed mockttp Aborted exception (#${this._abortSuppressCount})`,
);
return;
}
// Forward any other exception to the original handlers (e.g. Jest).
if (this._originalExceptionHandlers.length === 0) {
throw error;
}
let firstError: unknown;
for (const handler of this._originalExceptionHandlers) {
try {
handler(error, origin);
} catch (err) {
if (firstError === undefined) {
firstError = err;
}
}
}
if (firstError !== undefined) {
throw firstError;
}
};
process.on('uncaughtException', this._abortExceptionHandler);
logger.info(
`Abort filter installed — listeners: unhandledRejection=${process.listenerCount('unhandledRejection')}, uncaughtException=${process.listenerCount('uncaughtException')}`,
);
}
/**
* Removes the lifecycle-wide Aborted error filters and restores original handlers.
* Any handlers added by other code during the filter's lifetime are preserved.
*/
private _removeAbortFilter(): void {
if (!this._abortFilterHandler) {
return;
}
// --- Restore unhandledRejection handlers ---
const currentRejectionHandlers = process
.rawListeners('unhandledRejection')
.slice();
const addedRejectionDuringLifecycle = currentRejectionHandlers.filter(
(h) =>
h !== this._abortFilterHandler &&
!this._originalRejectionHandlers.includes(
h as (...args: unknown[]) => void,
),
);
process.removeAllListeners('unhandledRejection');
for (const handler of [
...this._originalRejectionHandlers,
...(addedRejectionDuringLifecycle as ((...args: unknown[]) => void)[]),
]) {
process.on('unhandledRejection', handler);
}
// --- Restore uncaughtException handlers ---
if (this._abortExceptionHandler) {
const currentExceptionHandlers = process
.rawListeners('uncaughtException')
.slice();
const addedExceptionDuringLifecycle = currentExceptionHandlers.filter(
(h) =>
h !== this._abortExceptionHandler &&
!this._originalExceptionHandlers.includes(
h as (...args: unknown[]) => void,
),
);
process.removeAllListeners('uncaughtException');
for (const handler of [
...this._originalExceptionHandlers,
...(addedExceptionDuringLifecycle as ((...args: unknown[]) => void)[]),
]) {
process.on('uncaughtException', handler);
}
}
this._abortFilterHandler = null;
this._abortExceptionHandler = null;
this._originalRejectionHandlers = [];
this._originalExceptionHandlers = [];
logger.info(
`Abort filter removed — suppressed ${this._abortSuppressCount} mockttp "Aborted" error(s) during server lifecycle`,
);
this._abortSuppressCount = 0;
}
/**
* Waits for all active request handler callbacks to complete.
* Polls every 50ms until _activeRequests reaches 0 or the timeout expires.
*
* @param timeoutMs - Maximum time to wait (default 5s, generous for slow CI)
*/
private async _waitForActiveRequests(timeoutMs = 5000): Promise<void> {
if (this._activeRequests === 0) {
return;
}
logger.info(
`Waiting for ${this._activeRequests} active request(s) to complete before shutdown...`,
);
const start = Date.now();
while (this._activeRequests > 0 && Date.now() - start < timeoutMs) {
await new Promise((resolve) => setTimeout(resolve, 50));
}
if (this._activeRequests > 0) {
logger.warn(
`${this._activeRequests} request(s) still active after ${timeoutMs}ms timeout, proceeding with shutdown`,
);
} else {
logger.info(
`All requests drained in ${Date.now() - start}ms, proceeding with shutdown`,
);
}
}
validateLiveRequests(): void {
const mockServer = this._server;
if (!mockServer?._liveRequests || mockServer._liveRequests.length === 0) {
return;
}
const uniqueRequests = Array.from(
new Map(
mockServer._liveRequests.map((req) => [
`${req.method} ${req.url}`,
req,
]),
).values(),
);
const requestsSummary = uniqueRequests
.map(
(req, index) =>
`${index + 1}. [${req.method}] ${req.url} (${req.timestamp})`,
)
.join('\n');
const totalCount = mockServer._liveRequests.length;
const uniqueCount = uniqueRequests.length;
const message =
`Test made ${totalCount} unmocked request(s) (${uniqueCount} unique):\n${requestsSummary}\n\n` +
"Check your test-specific mocks or add them to the default mocks.\n You can also add the URL to the allowlist if it's a known live request.";
logger.error(message);
throw new Error(message);
}
private _sanitizeJson(value: unknown, ignoreFields: string[]): unknown {
if (Array.isArray(value)) {
return value.map((item) => this._sanitizeJson(item, ignoreFields));
}
if (value && typeof value === 'object') {
const obj = value as Record<string, unknown>;
const result: Record<string, unknown> = {};
for (const [key, val] of Object.entries(obj)) {
if (ignoreFields.includes(key)) continue;
result[key] = this._sanitizeJson(val, ignoreFields);
}
return result;
}
return value;
}
}