-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathcontainer.ts
More file actions
2136 lines (1825 loc) · 70.2 KB
/
Copy pathcontainer.ts
File metadata and controls
2136 lines (1825 loc) · 70.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
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
import type {
ContainerOptions,
ContainerStartOptions,
ContainerStartConfigOptions,
Schedule,
StopParams,
ScheduleSQL,
State,
WaitOptions,
CancellationOptions,
StartAndWaitForPortsOptions,
} from '../types';
import { generateId, parseTimeExpression } from './helpers';
import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
// ====================
// ====================
// CONSTANTS
// ====================
// ====================
const NO_CONTAINER_INSTANCE_ERROR =
'there is no container instance that can be provided to this durable object';
const RUNTIME_SIGNALLED_ERROR = 'runtime signalled the container to exit:';
const UNEXPECTED_EXIT_ERROR = 'container exited with unexpected exit code:';
const NOT_LISTENING_ERROR = 'the container is not listening';
const CONTAINER_STATE_KEY = '__CF_CONTAINER_STATE';
const OUTBOUND_CONFIGURATION_KEY = 'OUTBOUND_CONFIGURATION';
// maxRetries before scheduling next alarm is purposely set to 3,
// as according to DO docs at https://developers.cloudflare.com/durable-objects/api/alarms/
// the maximum amount for alarm retries is 6.
const MAX_ALARM_RETRIES = 3;
const PING_TIMEOUT_MS = 5000;
const DEFAULT_SLEEP_AFTER = '10m'; // Default sleep after inactivity time
const INSTANCE_POLL_INTERVAL_MS = 300; // Default interval for polling container state
// Timeout for getting container instance and launching a VM
// Time to find an instance, attach a DO, call start, but NOT
// the time for the app the actually start
const TIMEOUT_TO_GET_CONTAINER_MS = 8_000;
// Timeout for getting a container instance and launching
// the actual application and have it listen for specific ports
// One day might be configurable by the end user in Container class attribute
const TIMEOUT_TO_GET_PORTS_MS = 20_000;
// If user has specified no ports and we need to check one
// to see if the container is up at all.
const FALLBACK_PORT_TO_CHECK = 33;
export type OutboundHandlerContext<Params = unknown> = {
containerId: string;
className: string;
} & ([Params] extends [undefined]
? { params?: undefined }
: undefined extends Params
? { params?: Params }
: { params: Params });
type OutboundParamsArg<Params> = [Params] extends [undefined]
? []
: undefined extends Params
? [params?: Params]
: [params: Params];
export type OutboundHandler<E = Cloudflare.Env, P = unknown> = {
bivarianceHack(
req: Request,
env: E,
ctx: OutboundHandlerContext<P>
): Promise<Response> | Response;
}['bivarianceHack'];
export type OutboundHandlerParams = Record<string, unknown>;
export type OutboundHandlerParamsOf<THandler> = THandler extends (
req: Request,
env: unknown,
ctx: OutboundHandlerContext<infer Params>
) => Promise<Response> | Response
? Params
: never;
export function outboundParams<THandler extends OutboundHandler<unknown, unknown>>(
_handler: THandler,
params: OutboundHandlerParamsOf<THandler>
): OutboundHandlerParamsOf<THandler> {
return params;
}
export type OutboundHandlers<ParamsByMethod extends OutboundHandlerParams, E = Cloudflare.Env> = {
[Method in keyof ParamsByMethod]?: OutboundHandler<E, ParamsByMethod[Method]>;
};
type OutboundHandlerOverride<Params = unknown> = {
method: string;
} & ([Params] extends [undefined]
? { params?: undefined }
: undefined extends Params
? { params?: Params }
: { params: Params });
type OutboundByHostOverrides = Record<string, OutboundHandlerOverride>;
type OutboundByHostOverrideInput<Params = unknown> = Record<
string,
string | OutboundHandlerOverride<Params>
>;
// class name to named outbound handlers (includes the default outbound handler)
const outboundHandlersRegistry = new Map<string, Record<string, OutboundHandler>>();
// class name to default catch-all outbound handler method name in outboundHandlersRegistry
const defaultOutboundHandlerNameRegistry = new Map<string, string>();
// class name to hostname to default outbound handler function
const outboundByHostRegistry = new Map<string, Record<string, OutboundHandler>>();
export type Signal = 'SIGKILL' | 'SIGINT' | 'SIGTERM';
export type SignalInteger = number;
const signalToNumbers: Record<Signal, SignalInteger> = {
SIGINT: 2,
SIGTERM: 15,
SIGKILL: 9,
};
// =====================
// =====================
// HELPER FUNCTIONS
// =====================
// =====================
// ==== Error helpers ====
function isErrorOfType(e: unknown, matchingString: string): boolean {
const errorString = e instanceof Error ? e.message : String(e);
return errorString.toLowerCase().includes(matchingString);
}
const isNoInstanceError = (error: unknown): boolean =>
isErrorOfType(error, NO_CONTAINER_INSTANCE_ERROR);
const isRuntimeSignalledError = (error: unknown): boolean =>
isErrorOfType(error, RUNTIME_SIGNALLED_ERROR);
const isNotListeningError = (error: unknown): boolean => isErrorOfType(error, NOT_LISTENING_ERROR);
const isContainerExitNonZeroError = (error: unknown): boolean =>
isErrorOfType(error, UNEXPECTED_EXIT_ERROR);
function getExitCodeFromError(error: unknown): number | null {
if (!(error instanceof Error)) {
return null;
}
if (isRuntimeSignalledError(error)) {
return +error.message
.toLowerCase()
.slice(
error.message.toLowerCase().indexOf(RUNTIME_SIGNALLED_ERROR) +
RUNTIME_SIGNALLED_ERROR.length +
1
);
}
if (isContainerExitNonZeroError(error)) {
return +error.message
.toLowerCase()
.slice(
error.message.toLowerCase().indexOf(UNEXPECTED_EXIT_ERROR) +
UNEXPECTED_EXIT_ERROR.length +
1
);
}
return null;
}
/**
* Combines the existing user-defined signal with a signal that aborts after the timeout specified by waitInterval
*/
function addTimeoutSignal(existingSignal: AbortSignal | undefined, timeoutMs: number): AbortSignal {
const controller = new AbortController();
// Forward existing signal abort
if (existingSignal?.aborted) {
controller.abort();
return controller.signal;
}
existingSignal?.addEventListener('abort', () => controller.abort());
// Add timeout
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
// Clean up timeout if signal is aborted early
controller.signal.addEventListener('abort', () => clearTimeout(timeoutId));
return controller.signal;
}
// ==== Glob helpers ====
/**
* Matches a value against a simple glob pattern where `*` matches
* any sequence of characters. e.g. `google.*.com`, `*.example.com`, `goo*gle`
*/
function simpleGlobMatch(pattern: string, value: string): boolean {
const parts = pattern.split('*');
if (parts.length === 1) return pattern === value;
if (!value.startsWith(parts[0])) return false;
if (!value.endsWith(parts[parts.length - 1])) return false;
let pos = parts[0].length;
for (let i = 1; i < parts.length - 1; i++) {
const idx = value.indexOf(parts[i], pos);
if (idx === -1) return false;
pos = idx + parts[i].length;
}
return pos <= value.length - parts[parts.length - 1].length;
}
function matchesHostList(hostname: string, patterns: string[]): boolean {
return patterns.some(pattern => simpleGlobMatch(pattern, hostname));
}
function normalizeHostname(hostname: string): string {
let end = hostname.length;
while (end > 0 && hostname[end - 1] === '.') {
end--;
}
return hostname.slice(0, end);
}
// ===============================
// CONTAINER STATE WRAPPER
// ===============================
/**
* ContainerState is a wrapper around a DO storage to store and get
* the container state.
* It's useful to track which kind of events have been handled by the user,
* a transition to a new state won't be successful unless the user's hook has been
* triggered and waited for.
* A user hook might be repeated multiple times if they throw errors.
*/
class ContainerState {
status?: State;
constructor(private storage: DurableObject['ctx']['storage']) {}
async setRunning() {
await this.setStatusAndupdate('running');
}
async setHealthy() {
await this.setStatusAndupdate('healthy');
}
async setStopping() {
await this.setStatusAndupdate('stopping');
}
async setStopped() {
await this.setStatusAndupdate('stopped');
}
async setStoppedWithCode(exitCode: number) {
this.status = { status: 'stopped_with_code', lastChange: Date.now(), exitCode };
await this.update();
}
async getState(): Promise<State> {
if (!this.status) {
const state = await this.storage.get<State>(CONTAINER_STATE_KEY);
if (!state) {
this.status = {
status: 'stopped',
lastChange: Date.now(),
};
await this.update();
} else {
this.status = state;
}
}
return this.status!;
}
private async setStatusAndupdate(status: State['status']) {
this.status = { status: status, lastChange: Date.now() };
await this.update();
}
private async update() {
if (!this.status) throw new Error('status should be init');
await this.storage.put<State>(CONTAINER_STATE_KEY, this.status);
}
}
type ContainerProxyOptions = {
enableInternet?: boolean;
containerId: string;
className: string;
outboundByHostOverrides?: OutboundByHostOverrides;
outboundHandlerOverride?: OutboundHandlerOverride;
allowedHosts?: string[];
deniedHosts?: string[];
// When false, this proxy only handles explicitly intercepted hosts.
// When true, it also applies the normal internet fallback chain.
interceptAll?: boolean;
};
type PersistedOutboundConfiguration = Pick<
ContainerProxyOptions,
'outboundByHostOverrides' | 'outboundHandlerOverride' | 'allowedHosts' | 'deniedHosts'
> & {
hasInterceptAllRegistration?: boolean;
};
export class ContainerProxy extends WorkerEntrypoint<Cloudflare.Env, ContainerProxyOptions> {
override async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
const hostname = normalizeHostname(url.hostname);
const {
className,
containerId,
outboundByHostOverrides,
outboundHandlerOverride,
enableInternet,
allowedHosts,
deniedHosts,
interceptAll,
} = this.ctx.props;
const baseCtx = { containerId, className };
// 1. deniedHosts: overrides everything, blocks unconditionally
if (deniedHosts && matchesHostList(hostname, deniedHosts)) {
return new Response('Origin is disallowed', { status: 520 });
}
// 2. allowedHosts: when set, acts as a whitelist gate — only matching
// hosts can proceed. This gates everything below, including outboundByHost.
// outboundByHost only maps a handler for a hostname, it does not allow it.
if (allowedHosts && !matchesHostList(hostname, allowedHosts)) {
return new Response('Origin is disallowed', { status: 520 });
}
// 3. outboundByHost (runtime override) — exact match then glob
const handlers = outboundHandlersRegistry.get(className);
if (outboundByHostOverrides && handlers) {
const override =
outboundByHostOverrides[hostname] ??
Object.entries(outboundByHostOverrides).find(
([pattern]) => pattern !== hostname && simpleGlobMatch(pattern, hostname)
)?.[1];
if (override && handlers[override.method]) {
return handlers[override.method](request, this.env, {
...baseCtx,
params: override.params,
});
}
}
// 4. outboundByHost (static) — exact match then glob
const handlersByHost = outboundByHostRegistry.get(className);
if (handlersByHost) {
const handler =
handlersByHost[hostname] ??
Object.entries(handlersByHost).find(
([pattern]) => pattern !== hostname && simpleGlobMatch(pattern, hostname)
)?.[1];
if (handler) {
return handler(request, this.env, baseCtx);
}
}
// In per-host mode, only specific hosts were intercepted.
// If no handler matched above, fall back to direct internet access only
// when the container already allows it.
if (!interceptAll) {
if (allowedHosts || enableInternet) {
return fetch(request);
}
return new Response('Origin is disallowed', { status: 520 });
}
// 5. Runtime catch-all handler override
if (outboundHandlerOverride && handlers?.[outboundHandlerOverride.method]) {
return handlers[outboundHandlerOverride.method](request, this.env, {
...baseCtx,
params: outboundHandlerOverride.params,
});
}
// 6. Default catch-all handler (static outbound)
const defaultOutboundHandlerName = defaultOutboundHandlerNameRegistry.get(className);
if (defaultOutboundHandlerName && handlers?.[defaultOutboundHandlerName]) {
return handlers[defaultOutboundHandlerName](request, this.env, baseCtx);
}
// 7. If the host was explicitly allowed and no outbound handled it, grant internet
if (allowedHosts) {
return fetch(request);
}
// 8. enableInternet fallback
if (enableInternet) {
return fetch(request);
}
return new Response('Origin is disallowed', { status: 520 });
}
}
// ===============================
// ===============================
// MAIN CONTAINER CLASS
// ===============================
// ===============================
//
export class Container<Env = Cloudflare.Env> extends DurableObject<Env> {
static get outboundByHost(): Record<string, OutboundHandler> | undefined {
return outboundByHostRegistry.get(this.name);
}
static set outboundByHost(handlers: Record<string, OutboundHandler>) {
outboundByHostRegistry.set(this.name, handlers);
}
static get outboundHandlers(): Record<string, OutboundHandler> | undefined {
return outboundHandlersRegistry.get(this.name);
}
static set outboundHandlers(handlers: Record<string, OutboundHandler>) {
const existing = outboundHandlersRegistry.get(this.name) ?? {};
outboundHandlersRegistry.set(this.name, { ...existing, ...handlers });
}
static get outbound(): OutboundHandler | undefined {
const handlerName = defaultOutboundHandlerNameRegistry.get(this.name);
if (!handlerName) return undefined;
return outboundHandlersRegistry.get(this.name)?.[handlerName];
}
static set outbound(handler: OutboundHandler) {
const key = '__outbound__';
const existing = outboundHandlersRegistry.get(this.name) ?? {};
outboundHandlersRegistry.set(this.name, { ...existing, [key]: handler });
defaultOutboundHandlerNameRegistry.set(this.name, key);
}
static get outboundProxies(): Record<string, OutboundHandler> | undefined {
return this.outboundHandlers;
}
static set outboundProxies(handlers: Record<string, OutboundHandler>) {
this.outboundHandlers = handlers;
}
static get outboundProxy(): OutboundHandler | undefined {
return this.outbound;
}
static set outboundProxy(handler: OutboundHandler) {
this.outbound = handler;
}
// =========================
// Public Attributes
// =========================
// Default port for the container (undefined means no default port)
defaultPort?: number;
// Required ports that should be checked for availability during container startup
// Override this in your subclass to specify ports that must be ready
requiredPorts?: number[];
// Timeout after which the container will sleep if no activity
// The signal sent to the container by default is a SIGTERM.
// The container won't get a SIGKILL if this threshold is triggered.
sleepAfter: string | number = DEFAULT_SLEEP_AFTER;
// Timeout after which the container will be forcefully killed
// This timeout is absolute from container start time, regardless of activity
// When this timeout expires, the container is sent a SIGKILL signal
timeout?: string | number;
// Container configuration properties
// Set these properties directly in your container instance
envVars: ContainerStartOptions['env'] = {};
entrypoint: ContainerStartOptions['entrypoint'];
enableInternet: ContainerStartOptions['enableInternet'] = true;
labels: ContainerStartOptions['labels'] = {};
// When true, outbound HTTPS traffic from the container will be intercepted.
// The container must trust /etc/cloudflare/certs/cloudflare-containers-ca.crt
interceptHttps: boolean = false;
// Hosts that are allowed to access the internet, even when enableInternet is false.
// Useful for allowing specific domains on a per-host basis.
allowedHosts?: string[];
// Hosts that are denied internet access, even when enableInternet is true.
// Also blocks hosts from being handled by the catch-all outbound handler.
deniedHosts?: string[];
// pingEndpoint is the host and path value that the class will use to send a request to the container and check if the
// instance is ready.
//
// The user does not have to implement this route by any means,
// but it's still useful if you want to control the path that
// the Container class uses to send HTTP requests to.
pingEndpoint: string = 'ping';
applyOutboundInterceptionPromise: Promise<void> = Promise.resolve();
usingInterception = false;
// =========================
// PUBLIC INTERFACE
// =========================
constructor(ctx: DurableObject['ctx'], env: Env, options?: ContainerOptions) {
super(ctx, env);
if (ctx.container === undefined) {
throw new Error(
'Containers have not been enabled for this Durable Object class. Have you correctly setup your Wrangler config? More info: https://developers.cloudflare.com/containers/get-started/#configuration'
);
}
this.state = new ContainerState(this.ctx.storage);
const persistedOutboundConfiguration = this.restoreOutboundConfiguration();
this.ctx.blockConcurrencyWhile(async () => {
// First thing, schedule the next alarms. Also yields a microtask
// so subclass class-field initializers (e.g. `sleepAfter = "2h"`)
// run before renewActivityTimeout reads `this.sleepAfter`.
await this.scheduleNextAlarm();
this.renewActivityTimeout();
const ctor = this.constructor as typeof Container;
if (
persistedOutboundConfiguration !== undefined ||
ctor.outboundByHost !== undefined ||
ctor.outbound !== undefined ||
ctor.outboundHandlers !== undefined ||
this.effectiveAllowedHosts !== undefined ||
this.effectiveDeniedHosts !== undefined
) {
this.usingInterception = true;
}
if (this.container.running) {
this.applyOutboundInterceptionPromise = this.applyOutboundInterception();
}
});
this.container = ctx.container;
// Apply options if provided
if (options) {
if (options.defaultPort !== undefined) this.defaultPort = options.defaultPort;
if (options.sleepAfter !== undefined) this.sleepAfter = options.sleepAfter;
if (options.timeout !== undefined) this.timeout = options.timeout;
}
// Create schedules table if it doesn't exist
this.sql`
CREATE TABLE IF NOT EXISTS container_schedules (
id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
callback TEXT NOT NULL,
payload TEXT,
type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed')),
time INTEGER NOT NULL,
delayInSeconds INTEGER,
created_at INTEGER DEFAULT (unixepoch())
)
`;
if (this.container.running) {
this.monitor = this.container.monitor();
this.setupMonitorCallbacks();
}
}
/**
* Gets the current state of the container
* @returns Promise<State>
*/
async getState(): Promise<State> {
return { ...(await this.state.getState()) };
}
// ====================================
// OUTBOUND INTERCEPTION CONFIG
// ====================================
/**
* Set the catch-all outbound handler to a named method from `outboundHandlers`.
* Overrides the default `outbound` at runtime via ContainerProxy props.
*
* @param methodName - Name of a method defined in `static outboundHandlers`
* @param params - Optional params passed to the handler as `ctx.params`
* @throws Error if the method name is not found in `outboundHandlers`
*/
async setOutboundHandler<Params = unknown>(
methodName: string,
...paramsArg: OutboundParamsArg<Params>
): Promise<void> {
this.validateOutboundHandlerMethodName(methodName);
this.outboundHandlerOverride =
paramsArg.length === 0
? { method: methodName }
: { method: methodName, params: paramsArg[0] };
await this.refreshOutboundInterception();
}
/**
* Add or override a hostname-specific outbound handler at runtime,
* referencing a named method from `outboundHandlers`.
* Overrides any matching entry in `static outboundByHost` for this hostname.
*
* @param hostname - The hostname or ip:port to intercept (e.g. `'google.com'`)
* @param methodName - Name of a method defined in `static outboundHandlers`
* @param params - Optional params passed to the handler as `ctx.params`
* @throws Error if the method name is not found in `outboundHandlers`
*/
async setOutboundByHost<Params = unknown>(
hostname: string,
methodName: string,
...paramsArg: OutboundParamsArg<Params>
): Promise<void> {
this.validateOutboundHandlerMethodName(methodName);
this.outboundByHostOverrides[hostname] =
paramsArg.length === 0
? { method: methodName }
: { method: methodName, params: paramsArg[0] };
await this.refreshOutboundInterception();
}
/**
* Remove a runtime hostname override added via `setOutboundByHost`.
* The default handler from `static outboundByHost` (if any) will be used again.
*
* @param hostname - The hostname or ip:port to stop overriding
*/
async removeOutboundByHost(hostname: string): Promise<void> {
delete this.outboundByHostOverrides[hostname];
await this.refreshOutboundInterception();
}
/**
* Replace all runtime hostname overrides at once.
* Each value may be either a method name or an object with `method` and `params`.
*
* @param handlers - Record mapping hostnames to handler configs in `outboundHandlers`
* @throws Error if any method name is not found in `outboundHandlers`
*/
async setOutboundByHosts<Params = unknown>(
handlers: OutboundByHostOverrideInput<Params>
): Promise<void> {
for (const handler of Object.values(handlers)) {
const methodName = typeof handler === 'string' ? handler : handler.method;
this.validateOutboundHandlerMethodName(methodName);
}
this.outboundByHostOverrides = Object.fromEntries(
Object.entries(handlers).map(([hostname, handler]) => [
hostname,
typeof handler === 'string' ? { method: handler } : handler,
])
);
await this.refreshOutboundInterception();
}
// ====================================
// ALLOWED / DENIED HOSTS CONFIG
// ====================================
/**
* Replace all allowed hosts at runtime.
* Allowed hosts get internet access even when `enableInternet` is false.
*
* @param hosts - Array of hostnames to allow (e.g. `['api.stripe.com', 'example.com']`)
*/
async setAllowedHosts(hosts: string[]): Promise<void> {
this.allowedHostsOverride = [...hosts];
this.usingInterception = true;
await this.refreshOutboundInterception();
}
/**
* Replace all denied hosts at runtime.
* Denied hosts are blocked unconditionally, even when `enableInternet` is true
* or a catch-all outbound handler is set.
*
* @param hosts - Array of hostnames to deny (e.g. `['evil.com', 'blocked.org']`)
*/
async setDeniedHosts(hosts: string[]): Promise<void> {
this.deniedHostsOverride = [...hosts];
this.usingInterception = true;
await this.refreshOutboundInterception();
}
/**
* Add a single hostname to the allowed hosts list at runtime.
*
* @param hostname - The hostname to allow (e.g. `'api.stripe.com'`)
*/
async allowHost(hostname: string): Promise<void> {
const effective = this.effectiveAllowedHosts ?? [];
if (!effective.includes(hostname)) {
this.allowedHostsOverride = [...effective, hostname];
}
this.usingInterception = true;
await this.refreshOutboundInterception();
}
/**
* Add a single hostname to the denied hosts list at runtime.
*
* @param hostname - The hostname to deny (e.g. `'evil.com'`)
*/
async denyHost(hostname: string): Promise<void> {
const effective = this.effectiveDeniedHosts ?? [];
if (!effective.includes(hostname)) {
this.deniedHostsOverride = [...effective, hostname];
}
this.usingInterception = true;
await this.refreshOutboundInterception();
}
/**
* Remove a hostname from the allowed hosts list.
*
* @param hostname - The hostname to remove from the allow list
*/
async removeAllowedHost(hostname: string): Promise<void> {
this.allowedHostsOverride = (this.effectiveAllowedHosts ?? []).filter(h => h !== hostname);
await this.refreshOutboundInterception();
}
/**
* Remove a hostname from the denied hosts list.
*
* @param hostname - The hostname to remove from the deny list
*/
async removeDeniedHost(hostname: string): Promise<void> {
this.deniedHostsOverride = (this.effectiveDeniedHosts ?? []).filter(h => h !== hostname);
await this.refreshOutboundInterception();
}
// ==========================
// CONTAINER STARTING
// ==========================
/**
* Start the container if it's not running and set up monitoring and lifecycle hooks,
* without waiting for ports to be ready.
*
* It will automatically retry if the container fails to start, using the specified waitOptions
*
*
* @example
* await this.start({
* envVars: { DEBUG: 'true', NODE_ENV: 'development' },
* entrypoint: ['npm', 'run', 'dev'],
* enableInternet: false,
* labels: { tenant: 'acme', env: 'prod' },
* });
*
* @param startOptions - Override `envVars`, `entrypoint`, `enableInternet` and `labels` on a per-instance basis
* @param waitOptions - Optional wait configuration with abort signal for cancellation. Default ~8s timeout.
* @returns A promise that resolves when the container start command has been issued
* @throws Error if no container context is available or if all start attempts fail
*/
public async start(
startOptions?: ContainerStartConfigOptions,
waitOptions?: WaitOptions
): Promise<void> {
const portToCheck =
waitOptions?.portToCheck ??
this.defaultPort ??
(this.requiredPorts ? this.requiredPorts[0] : FALLBACK_PORT_TO_CHECK);
const pollInterval = waitOptions?.waitInterval ?? INSTANCE_POLL_INTERVAL_MS;
await this.startContainerIfNotRunning(
{
signal: waitOptions?.signal,
waitInterval: pollInterval,
retries: waitOptions?.retries ?? Math.ceil(TIMEOUT_TO_GET_CONTAINER_MS / pollInterval),
portToCheck,
},
startOptions
);
this.setupMonitorCallbacks();
// TODO: We should consider an onHealthy callback
await this.ctx.blockConcurrencyWhile(async () => {
await this.onStart();
});
}
/**
* Start the container and wait for ports to be available.
*
* For each specified port, it polls until the port is available or `cancellationOptions.portReadyTimeoutMS` is reached.
*
* @param ports - The ports to wait for (if undefined, uses requiredPorts or defaultPort)
* @param cancellationOptions - Options to configure timeouts, polling intereva, and abort signal
* @param startOptions Override configuration on a per-instance basis for env vars, entrypoint command, internet access, and labels
* @returns A promise that resolves when the container has been started and the ports are listening
* @throws Error if port checks fail after the specified timeout or if the container fails to start.
*/
public async startAndWaitForPorts(args: StartAndWaitForPortsOptions): Promise<void>;
public async startAndWaitForPorts(
ports?: number | number[],
cancellationOptions?: CancellationOptions,
startOptions?: ContainerStartConfigOptions
): Promise<void>;
public async startAndWaitForPorts(
portsOrArgs?: number | number[] | StartAndWaitForPortsOptions,
cancellationOptions?: CancellationOptions,
startOptions?: ContainerStartConfigOptions
): Promise<void>;
public async startAndWaitForPorts(
portsOrArgs?: number | number[] | StartAndWaitForPortsOptions,
cancellationOptions?: CancellationOptions,
startOptions?: ContainerStartConfigOptions
): Promise<void> {
// Parse arguments to handle different overload signatures
let ports: number | number[] | undefined;
let resolvedCancellationOptions: CancellationOptions | undefined = {};
let resolvedStartOptions: ContainerStartConfigOptions | undefined = {};
if (typeof portsOrArgs === 'object' && portsOrArgs !== null && !Array.isArray(portsOrArgs)) {
// Object-based overload: { startOptions?, ports?, cancellationOptions? }
ports = portsOrArgs.ports;
resolvedCancellationOptions = portsOrArgs.cancellationOptions;
resolvedStartOptions = portsOrArgs.startOptions;
} else {
ports = portsOrArgs;
resolvedCancellationOptions = cancellationOptions;
resolvedStartOptions = startOptions;
}
// Determine which ports to check
const portsToCheck = await this.getPortsToCheck(ports);
// trigger all onStop that we didn't do yet
await this.syncPendingStoppedEvents();
// Prepare to start the container
resolvedCancellationOptions ??= {};
const containerGetTimeout =
resolvedCancellationOptions.instanceGetTimeoutMS ?? TIMEOUT_TO_GET_CONTAINER_MS;
const pollInterval = resolvedCancellationOptions.waitInterval ?? INSTANCE_POLL_INTERVAL_MS;
let containerGetRetries = Math.ceil(containerGetTimeout / pollInterval);
const waitOptions: WaitOptions = {
signal: resolvedCancellationOptions.abort,
retries: containerGetRetries,
waitInterval: pollInterval,
portToCheck: portsToCheck[0],
};
// Start the container if it's not running
const triesUsed = await this.startContainerIfNotRunning(waitOptions, resolvedStartOptions);
// Check each port
const totalPortReadyTries = Math.ceil(
(resolvedCancellationOptions.portReadyTimeoutMS ?? TIMEOUT_TO_GET_PORTS_MS) / pollInterval
);
let triesLeft = totalPortReadyTries - triesUsed;
for (const port of portsToCheck) {
triesLeft = await this.waitForPort({
signal: resolvedCancellationOptions.abort,
waitInterval: pollInterval,
retries: triesLeft,
portToCheck: port,
});
}
this.setupMonitorCallbacks();
await this.ctx.blockConcurrencyWhile(async () => {
// All ports are ready
await this.state.setHealthy();
await this.onStart();
});
}
/**
*
* Waits for a specified port to be ready
*
* Returns the number of tries used to get the port, or throws if it couldn't get the port within the specified retry limits.
*
* @param waitOptions -
* - `portToCheck`: The port number to check
* - `abort`: Optional AbortSignal to cancel waiting
* - `retries`: Number of retries before giving up (default: TRIES_TO_GET_PORTS)
* - `waitInterval`: Interval between retries in milliseconds (default: INSTANCE_POLL_INTERVAL_MS)
*/
public async waitForPort(waitOptions: WaitOptions): Promise<number> {
const port = waitOptions.portToCheck;
const tcpPort = this.container.getTcpPort(port);
const abortedSignal = new Promise(res => {
waitOptions.signal?.addEventListener('abort', () => {
res(true);
});
});
const pollInterval = waitOptions.waitInterval ?? INSTANCE_POLL_INTERVAL_MS;
let tries = waitOptions.retries ?? Math.ceil(TIMEOUT_TO_GET_PORTS_MS / pollInterval);
// Try to connect to the port multiple times
for (let i = 0; i < tries; i++) {
try {
const combinedSignal = addTimeoutSignal(waitOptions.signal, PING_TIMEOUT_MS);
await tcpPort.fetch(`http://${this.pingEndpoint}`, { signal: combinedSignal });
// Successfully connected to this port
console.log(`Port ${port} is ready`);
break;
} catch (e) {
// Check for specific error messages that indicate we should keep retrying
const errorMessage = e instanceof Error ? e.message : String(e);
console.debug(`Error checking ${port}: ${errorMessage}`);
// If not running, it means the container crashed
if (!this.container.running) {
try {
await this.onError(
new Error(
`Container crashed while checking for ports, did you start the container and setup the entrypoint correctly?`
)
);
} catch {}
throw e;
}
// If we're on the last attempt and the port is still not ready, fail
if (i === tries - 1) {
try {
await this.onError(
`Failed to verify port ${port} is available after ${(i + 1) * pollInterval}ms, last error: ${errorMessage}`
);
} catch {}
throw e;
}
// Wait a bit before trying again
await Promise.any([
new Promise(resolve => setTimeout(resolve, pollInterval)),
abortedSignal,
]);
if (waitOptions.signal?.aborted) {
throw new Error('Container request aborted.');
}
}
}
return tries;
}
// =======================
// LIFECYCLE HOOKS
// =======================
/**
* Send a signal to the container.
* @param signal - The signal to send to the container (default: 15 for SIGTERM)
*/
public async stop(signal: Signal | SignalInteger = 'SIGTERM'): Promise<void> {
if (this.container.running) {
this.container.signal(typeof signal === 'string' ? signalToNumbers[signal] : signal);
}
await this.syncPendingStoppedEvents();
}
/**
* Destroys the container with a SIGKILL. Triggers onStop.
*/
public async destroy(): Promise<void> {
await this.container.destroy();
}
/**
* Lifecycle method called when container starts successfully
* Override this method in subclasses to handle container start events
*/
public onStart(): void | Promise<void> {
// Default implementation does nothing
}
/**