Repository navigation
Expand file tree
/
Copy pathorb-container.ts
More file actions
1237 lines (1178 loc) · 40 KB
/
Copy pathorb-container.ts
File metadata and controls
1237 lines (1178 loc) · 40 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 { CloudflareContainerInstance } from "@dx/domain";
import { orbContainerLogger } from "../../logging.js";
/**
* One Thread's Cloudflare Containers workspace, owned by one Durable Object
* instance (the Orb container object) in the deployer's account.
*
* Containers' disk is ephemeral, so this object makes the filesystem
* durable with snapshots (`durable_object` scheduling policy):
*
* - **Open** starts the container from the Thread's latest snapshot, or from
* the standard Orb image the first time. The image's entrypoint
* (`dx-orb-init`) starts dxd again, so dxd reconnects to Core on its own.
* - **Pause** (the idle deadline, or archive) snapshots the filesystem and
* stops the container. Processes and memory do not survive
* (`execution.pause-resume` with `preserves: "filesystem"`).
* - **Destroy** stops the container and forgets its snapshot; Cloudflare
* expires it. The Worker API cannot delete or list snapshots.
* - **Refresh**: a snapshot expires 30 days after it was created or last
* restored. A paused workspace's alarm restores it (with a sleeping
* entrypoint, no Internet, no dxd) and re-snapshots it after 25 days, so
* archived and long-idle Threads stay resumable.
* - **Stop notice**: Cloudflare may stop a container at any time; before a
* planned stop it sends SIGTERM and waits up to 15 minutes. The entrypoint
* then posts to `ORB_STOP_NOTICE_ADDRESS`, which this object intercepts,
* and the object snapshots the filesystem while the container still runs,
* so the next use restores it.
* - **Reset**: a container that stopped before it ever had a snapshot lost
* its files. Commands never run on the empty container that would replace
* it: they fail (`stopped before its first pause`), and only Core's
* activation, which sets the workspace up again, may start it over from
* the image (`open` with `allowReset`).
*
* Commands and files go through `ctx.container.exec()`; nothing in the
* container serves them. While the container runs, a short heartbeat alarm
* keeps this object resident: a Durable Object that restarts (a deploy of
* the Orb Worker, a runtime restart) loses its container inactivity timeout,
* and Cloudflare stops an orphaned container shortly after, without the
* snapshot. The heartbeat re-arms the timeout within seconds.
*
* Core reaches this object only by RPC; every method here is that surface.
*/
/** The `ctx.container` surface this object uses. */
export interface OrbContainerRuntime {
readonly running: boolean;
start(options: OrbContainerStartOptions): void;
exec(
command: string[],
options?: {
readonly cwd?: string;
readonly env?: Record<string, string>;
readonly stdin?: ReadableStream;
readonly stdout?: "pipe";
readonly stderr?: "pipe";
},
): Promise<OrbContainerProcess>;
snapshotContainer(options: {
readonly name?: string;
}): Promise<OrbContainerSnapshot>;
destroy(reason?: unknown): Promise<void>;
setInactivityTimeout(durationMs: number): Promise<void>;
interceptOutboundHttp(address: string, binding: Fetcher): Promise<void>;
}
export interface OrbContainerProcess {
readonly stdout: ReadableStream<Uint8Array> | null;
readonly stderr: ReadableStream<Uint8Array> | null;
readonly exitCode: Promise<number>;
kill(signal?: number): void;
}
export interface OrbContainerSnapshot {
readonly id: string;
readonly size: number;
readonly name?: string;
}
export type OrbContainerStartOptions = {
readonly enableInternet: boolean;
readonly instance: CloudflareContainerInstance;
readonly entrypoint?: string[];
readonly env?: Readonly<Record<string, string>>;
} & (
| { readonly image: string; readonly containerSnapshot?: never }
| { readonly containerSnapshot: { readonly id: string } }
);
export interface OrbContainerStorage {
get<T>(key: string): Promise<T | undefined>;
put<T>(key: string, value: T): Promise<void>;
setAlarm(scheduledTime: number): Promise<void>;
getAlarm(): Promise<number | null>;
deleteAlarm(): Promise<void>;
}
/** What this object remembers about its Thread's workspace. */
export interface OrbWorkspaceState {
readonly version: 1;
/** Fixed when the workspace is created; a wake never resizes it. */
readonly instance: CloudflareContainerInstance;
readonly createdAt: number;
/**
* `active`: the container should be running. `paused`: stopped, restorable
* from `snapshot` (or, before the first pause, never snapshotted).
* `destroyed`: released for good.
*/
readonly status: "active" | "paused" | "destroyed";
readonly snapshot?: {
readonly id: string;
readonly size: number;
/** When it was taken or last restored: Cloudflare's 30-day TTL clock. */
readonly refreshedAt: number;
};
/** Pause after this time unless Core renews it. */
readonly idleDeadline: number;
/**
* When the running container last started (a create, a wake, or a
* restart); every process in it, Terminal shells included, is younger.
*/
readonly startedAt?: number;
}
export type OrbOpenResult =
| {
readonly kind: "ready";
readonly sandboxId: string;
/**
* `running`: the container was up. `paused`: restored from its
* snapshot (processes restarted). `created`: started from the image.
*/
readonly residency: "running" | "paused" | "created";
/** When the container's processes started; see `startedAt`. */
readonly processesStartedAt?: number;
}
| { readonly kind: "missing" }
| { readonly kind: "destroyed" };
export interface OrbExecOptions {
readonly cwd?: string;
readonly env?: Record<string, string>;
readonly timeoutMs?: number;
}
export interface OrbExecResult {
readonly stdout: string;
readonly stderr: string;
readonly exitCode: number;
readonly timedOut: boolean;
}
export interface OrbFileStat {
readonly isFile: boolean;
readonly isDirectory: boolean;
readonly isSymbolicLink: boolean;
}
const STATE_KEY = "workspace";
/**
* Where the entrypoint announces a stop (`DX_ORB_STOP_NOTICE`). A
* documentation address (TEST-NET-1) that nothing else uses; the object's
* intercept answers it, never the Internet.
*/
export const ORB_STOP_NOTICE_ADDRESS = "192.0.2.1:80";
/** While the container runs, the alarm fires this often. */
export const ORB_HEARTBEAT_MS = 10_000;
/** Restore and re-snapshot a paused workspace this long after its TTL clock. */
export const ORB_SNAPSHOT_REFRESH_MS = 25 * 24 * 60 * 60 * 1000;
/** Cloudflare stops a container this long after its object goes quiet. */
const MAX_CONTAINER_INACTIVITY_MS = 6 * 60 * 60 * 1000;
const CONTAINER_INACTIVITY_MARGIN_MS = 15 * 60 * 1000;
const READY_TIMEOUT_MS = 90_000;
const READY_RETRY_MS = 100;
/** While a start waits for readiness, log its progress this often. */
const READY_PROGRESS_LOG_MS = 30_000;
/**
* How long an operation that must follow the restart work waits for it.
* Storage can stall for minutes; past this the operation goes ahead.
*/
const RESTART_WAIT_MS = 10_000;
/** How long stopping a container that never became ready may take. */
const ABANDON_START_MS = 5_000;
/** A command's output kept in this object's memory, per stream. */
const MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
/** The largest file read in one call (one RPC result). */
const MAX_FILE_BYTES = 16 * 1024 * 1024;
/** After the command exits, how long its streams may keep draining. */
const OUTPUT_DRAIN_MS = 250;
/** Beyond `timeoutMs`, how long `timeout` gets before this object kills it. */
const TIMEOUT_BACKSTOP_MS = 15_000;
const SIGKILL = 9;
/** The image user (`user`, uid 1000) and the environment E2B gives commands. */
const BASE_ENVIRONMENT = {
HOME: "/home/user",
USER: "user",
LOGNAME: "user",
SHELL: "/bin/bash",
LANG: "C.UTF-8",
} as const;
/**
* The entrypoint's environment. Cloudflare names the host after the 64-hex
* object ID; `dx-orb-init` sets this short, stable name instead, so the
* Terminal prompt reads `user@cloudflare` (E2B's reads `user@e2b`).
*/
const ORB_START_ENVIRONMENT = {
DX_ORB_HOSTNAME: "cloudflare",
DX_ORB_STOP_NOTICE: `http://${ORB_STOP_NOTICE_ADDRESS}/stopping`,
} as const;
const textDecoder = () => new TextDecoder("utf-8", { fatal: false });
const sleep = (durationMs: number) =>
new Promise<void>((resolve) => setTimeout(resolve, durationMs));
const failure = (operation: string, detail: string) =>
new Error(`Orb container ${operation} failed: ${detail}`.trim());
/** Core's provider reads this text as `WORKSPACE_RESET`. */
export const ORB_WORKSPACE_RESET_DETAIL =
"the workspace stopped before its first pause, and its files are gone";
/** `promise`, or `undefined` once `durationMs` passes. */
const within = async <A>(
promise: Promise<A>,
durationMs: number,
): Promise<A | undefined> => {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
promise,
new Promise<undefined>((resolve) => {
timer = setTimeout(() => resolve(undefined), durationMs);
}),
]);
} finally {
clearTimeout(timer);
}
};
/** Reads a stream to the end, keeping at most `limit` bytes. */
const collect = (
stream: ReadableStream<Uint8Array> | null,
limit: number,
): {
readonly done: Promise<Uint8Array>;
readonly cancel: () => Promise<void>;
readonly truncated: () => boolean;
} => {
if (stream === null)
return {
done: Promise.resolve(new Uint8Array()),
cancel: async () => {},
truncated: () => false,
};
const reader = stream.getReader();
const chunks: Uint8Array[] = [];
let kept = 0;
let dropped = false;
let cancelled = false;
const done = (async () => {
try {
while (true) {
const { done: finished, value } = await reader.read();
if (finished) break;
if (kept + value.byteLength > limit) dropped = true;
if (kept >= limit) continue;
const slice = value.subarray(0, limit - kept);
chunks.push(slice);
kept += slice.byteLength;
}
} catch (cause) {
if (!cancelled) throw cause;
}
const bytes = new Uint8Array(kept);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return bytes;
})();
return {
done,
cancel: async () => {
cancelled = true;
await reader.cancel().catch(() => undefined);
},
truncated: () => dropped,
};
};
const streamOf = (bytes: Uint8Array) =>
new ReadableStream<Uint8Array>({
type: "bytes",
start(controller) {
if (bytes.byteLength > 0) controller.enqueue(new Uint8Array(bytes));
controller.close();
},
});
export interface OrbContainerControllerInput {
readonly container: OrbContainerRuntime;
readonly storage: OrbContainerStorage;
/** The standard Orb image (`ctx.container.images.orb`). */
readonly image: () => string | undefined;
readonly sandboxId: string;
/** Answers the entrypoint's stop notice by calling `stopping`. */
readonly stopNotice?: () => Fetcher;
readonly now?: () => number;
}
/**
* The Orb container object's behavior, independent of the Durable Object
* class so it can be tested with a fake container and storage.
*/
export class OrbContainerController {
readonly #container: OrbContainerRuntime;
readonly #storage: OrbContainerStorage;
readonly #image: () => string | undefined;
readonly #sandboxId: string;
readonly #stopNotice: (() => Fetcher) | undefined;
readonly #now: () => number;
/** This object is stopping the container itself; a stop notice is moot. */
#stoppingItself = false;
#state: OrbWorkspaceState | undefined | null = null;
/** Serializes start, pause, refresh, and destroy. */
#lifecycle: Promise<unknown> = Promise.resolve();
#busy = 0;
#inflight = 0;
/** The restart work (`resumeAfterRestart`) while it runs. */
#restart: Promise<void> | undefined;
constructor(input: OrbContainerControllerInput) {
this.#container = input.container;
this.#storage = input.storage;
this.#image = input.image;
this.#sandboxId = input.sandboxId;
this.#stopNotice = input.stopNotice;
this.#now = input.now ?? Date.now;
}
/** Stops the container on this object's own account (pause, destroy). */
async #destroyContainer() {
this.#stoppingItself = true;
try {
await this.#container.destroy();
} finally {
this.#stoppingItself = false;
}
}
/**
* Routes the entrypoint's stop notice to this object. An intercept lasts
* until the container stops, so every start registers it. Without it a
* planned stop loses what the last snapshot does not hold, so a failure
* is logged, never fatal.
*/
async #watchForStop() {
if (this.#stopNotice === undefined) return;
try {
await this.#container.interceptOutboundHttp(
ORB_STOP_NOTICE_ADDRESS,
this.#stopNotice(),
);
} catch (cause) {
orbContainerLogger.warn("Orb container stop notice is not routed.", {
event: "orb_container_stop_notice",
sandboxId: this.#sandboxId,
outcome: "unrouted",
error: cause instanceof Error ? cause.message : String(cause),
});
}
}
/**
* A container that is not running and has no snapshot lost its files: it
* stopped before its first pause. Starting it from the image would hand
* callers an empty workspace, so only a caller that sets it up again may.
*/
#refuseReset(state: OrbWorkspaceState, operation: string) {
if (state.snapshot !== undefined) return;
orbContainerLogger.warn("Orb container lost its files before a pause.", {
event: "orb_container_reset",
sandboxId: this.#sandboxId,
operation,
status: state.status,
...(state.startedAt === undefined
? {}
: { ranMs: this.#now() - state.startedAt }),
});
throw failure(operation, ORB_WORKSPACE_RESET_DETAIL);
}
async #load(): Promise<OrbWorkspaceState | undefined> {
if (this.#state === null) {
const loaded = await this.#storage.get<OrbWorkspaceState>(STATE_KEY);
// A read that stalled must not overwrite a save made meanwhile.
if (this.#state === null) this.#state = loaded;
}
return this.#state;
}
async #save(state: OrbWorkspaceState) {
this.#state = state;
await this.#storage.put(STATE_KEY, state);
}
#exclusive<A>(operation: () => Promise<A>): Promise<A> {
this.#busy += 1;
const after = () => this.#afterRestart().then(operation);
const run = this.#lifecycle.then(after, after);
this.#lifecycle = run.then(
() => undefined,
() => undefined,
);
return run.finally(() => {
this.#busy -= 1;
});
}
/**
* Waits for the restart work, at most `RESTART_WAIT_MS`: the object
* answers while storage stalls, and an operation that must follow the
* restart does not hang behind it.
*/
async #afterRestart() {
const restart = this.#restart;
if (restart === undefined) return;
const startedAt = this.#now();
const settled = await within(
restart.then(() => true),
RESTART_WAIT_MS,
);
if (settled === undefined)
orbContainerLogger.warn("Orb container restart work is still running.", {
event: "orb_container_restart_wait",
sandboxId: this.#sandboxId,
outcome: "timed_out",
waitedMs: this.#now() - startedAt,
});
}
async #idle() {
while (this.#busy > 0) await this.#lifecycle;
}
async #schedule(at: number) {
await this.#storage.setAlarm(at);
}
async #armInactivity(idleMs: number) {
await this.#container.setInactivityTimeout(
Math.min(
MAX_CONTAINER_INACTIVITY_MS,
idleMs + CONTAINER_INACTIVITY_MARGIN_MS,
),
);
}
/**
* The container accepts `exec` once it has started. Logs progress while it
* waits, so a stalled start shows whether one probe hung
* (`currentAttemptMs`) or probes kept failing (`attempts`, `lastFailure`).
*/
async #waitReady(operation: string) {
const startedAt = this.#now();
const deadline = startedAt + READY_TIMEOUT_MS;
let lastFailure: unknown;
let attempts = 0;
let attemptStartedAt = startedAt;
let slowestAttemptMs = 0;
const progress = (outcome: "waiting" | "ready" | "timed_out") => ({
event: "orb_container_ready_wait",
outcome,
sandboxId: this.#sandboxId,
operation,
elapsedMs: this.#now() - startedAt,
attempts,
slowestAttemptMs,
currentAttemptMs: this.#now() - attemptStartedAt,
running: this.#container.running,
...(lastFailure === undefined
? {}
: {
lastFailure:
lastFailure instanceof Error
? lastFailure.message
: String(lastFailure),
}),
});
const watchdog = setInterval(
() =>
orbContainerLogger.warn(
"Orb container is not ready yet.",
progress("waiting"),
),
READY_PROGRESS_LOG_MS,
);
try {
while (this.#now() < deadline) {
attempts += 1;
attemptStartedAt = this.#now();
try {
// A probe can hang without failing; the deadline bounds it.
const exitCode = await within(
this.#container.exec(["true"]).then((process) => process.exitCode),
Math.max(0, deadline - this.#now()),
);
if (exitCode === undefined) {
lastFailure = new Error("the readiness probe did not return");
break;
}
if (exitCode === 0) {
slowestAttemptMs = Math.max(
slowestAttemptMs,
this.#now() - attemptStartedAt,
);
orbContainerLogger.info(
"Orb container is ready.",
progress("ready"),
);
return;
}
} catch (cause) {
lastFailure = cause;
}
slowestAttemptMs = Math.max(
slowestAttemptMs,
this.#now() - attemptStartedAt,
);
await sleep(READY_RETRY_MS);
}
orbContainerLogger.error(
"Orb container did not become ready.",
progress("timed_out"),
);
} finally {
clearInterval(watchdog);
}
// Text the run-failure classifier reads as a platform failure.
throw new Error(
`Orb container ${operation} timed out after ${READY_TIMEOUT_MS / 1000} s: ${
lastFailure instanceof Error ? lastFailure.message : "not ready"
}`,
);
}
/**
* Starts the stopped container from its latest snapshot, or from the
* image when it never paused. Runs under the lifecycle lock.
*/
async #start(
state: OrbWorkspaceState,
idleMs: number,
fresh = false,
lockWaitMs = 0,
): Promise<"paused" | "created"> {
const now = this.#now();
const snapshot = state.snapshot;
const details = {
event: "orb_container_start",
sandboxId: this.#sandboxId,
source: snapshot === undefined ? "image" : "snapshot",
...(snapshot === undefined
? {}
: {
snapshotId: snapshot.id,
snapshotSize: snapshot.size,
snapshotAgeMs: now - snapshot.refreshedAt,
}),
instance: state.instance,
fresh,
lockWaitMs,
};
orbContainerLogger.info("Orb container start requested.", details);
try {
const residency = await this.#startContainer(state, idleMs, fresh, now);
orbContainerLogger.info("Orb container started.", {
...details,
outcome: "started",
durationMs: this.#now() - now,
});
return residency;
} catch (cause) {
orbContainerLogger.error("Orb container start failed.", {
...details,
outcome: "error",
durationMs: this.#now() - now,
error: cause instanceof Error ? cause.message : String(cause),
});
throw cause;
}
}
async #startContainer(
state: OrbWorkspaceState,
idleMs: number,
fresh: boolean,
now: number,
): Promise<"paused" | "created"> {
const snapshot = state.snapshot;
if (snapshot === undefined) {
const image = this.#image();
if (image === undefined)
throw failure("start", "the Orb image is not configured");
if (!fresh)
// Stopped before its first pause (a crash, or Cloudflare stopped
// it): the filesystem is gone, and the image starts it over.
orbContainerLogger.warn("Orb container restarted without a snapshot.", {
event: "orb_container_restart_without_snapshot",
sandboxId: this.#sandboxId,
});
this.#container.start({
image,
instance: state.instance,
enableInternet: true,
env: ORB_START_ENVIRONMENT,
});
} else
this.#container.start({
containerSnapshot: { id: snapshot.id },
instance: state.instance,
enableInternet: true,
env: ORB_START_ENVIRONMENT,
});
try {
await this.#waitReady("start");
} catch (cause) {
// A container that never became ready would pass for running on the
// next open; stop it so a retry starts it again.
await within(
this.#destroyContainer().catch(() => undefined),
ABANDON_START_MS,
);
throw cause;
}
await this.#armInactivity(idleMs);
await this.#watchForStop();
await this.#save({
...state,
status: "active",
idleDeadline: Math.max(state.idleDeadline, this.#now() + idleMs),
startedAt: now,
...(snapshot === undefined
? {}
: { snapshot: { ...snapshot, refreshedAt: now } }),
});
await this.#schedule(this.#now() + ORB_HEARTBEAT_MS);
return snapshot === undefined ? "created" : "paused";
}
/**
* Core's create (`create: true`) or connect. A paused workspace is
* restored; a new one starts from the image with `instance`, which stays
* fixed afterwards.
*/
async open(input: {
readonly create: boolean;
readonly instance: CloudflareContainerInstance;
readonly idleMs: number;
/**
* The caller sets the workspace up again (Core's activation), so one
* that lost its files may start over from the image. Unset means
* allowed, as for a Core from before this option.
*/
readonly allowReset?: boolean;
}): Promise<OrbOpenResult> {
const requestedAt = this.#now();
return this.#exclusive(async () => {
const lockWaitMs = this.#now() - requestedAt;
let state = await this.#load();
let fresh = false;
if (state === undefined) {
if (!input.create) return { kind: "missing" };
fresh = true;
const now = this.#now();
state = {
version: 1,
instance: input.instance,
createdAt: now,
status: "active",
idleDeadline: now + input.idleMs,
};
await this.#save(state);
}
if (state.status === "destroyed") return { kind: "destroyed" };
if (this.#container.running) {
const deadline = Math.max(
state.idleDeadline,
this.#now() + input.idleMs,
);
if (deadline !== state.idleDeadline || state.status !== "active")
await this.#save({
...state,
status: "active",
idleDeadline: deadline,
});
return {
kind: "ready",
sandboxId: this.#sandboxId,
residency: "running",
...(state.startedAt === undefined
? {}
: { processesStartedAt: state.startedAt }),
};
}
if (!fresh && input.allowReset === false)
this.#refuseReset(state, "open");
const residency = await this.#start(
state,
input.idleMs,
fresh,
lockWaitMs,
);
const started = await this.#load();
return {
kind: "ready",
sandboxId: this.#sandboxId,
residency,
...(started?.startedAt === undefined
? {}
: { processesStartedAt: started.startedAt }),
};
});
}
/** Whether the container runs now; lets Core report a wake before it. */
async status(): Promise<{
readonly running: boolean;
readonly status: OrbWorkspaceState["status"] | "missing";
}> {
const state = await this.#load();
return {
running: this.#container.running,
status: state?.status ?? "missing",
};
}
/** Core's idle deadline: pause `durationMs` from now unless renewed. */
async setIdleDeadline(durationMs: number): Promise<void> {
await this.#afterRestart();
const state = await this.#load();
if (state === undefined || state.status === "destroyed") return;
await this.#save({ ...state, idleDeadline: this.#now() + durationMs });
if (this.#container.running) await this.#armInactivity(durationMs);
}
/**
* Runs an operation in the running container. A container that paused
* meanwhile is restored first, as E2B resumes a paused sandbox on use; one
* that lost its files is not started (see `#refuseReset`).
*/
async #use<A>(operation: () => Promise<A>): Promise<A> {
await this.#afterRestart();
while (true) {
await this.#idle();
if (this.#container.running) break;
await this.#exclusive(async () => {
if (this.#container.running) return;
const state = await this.#load();
if (state === undefined) throw failure("use", "no workspace");
if (state.status === "destroyed")
throw failure("use", "the workspace was destroyed");
this.#refuseReset(state, "use");
await this.#start(
state,
Math.max(ORB_HEARTBEAT_MS, state.idleDeadline - this.#now()),
);
});
}
this.#inflight += 1;
try {
return await operation();
} finally {
this.#inflight -= 1;
}
}
async #run(
argv: string[],
options: {
readonly cwd?: string;
readonly env?: Record<string, string>;
readonly stdin?: Uint8Array;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
} = {},
) {
const timeoutSeconds =
options.timeoutMs === undefined
? undefined
: Math.max(1, Math.ceil(options.timeoutMs / 1000));
const command =
timeoutSeconds === undefined
? argv
: // `timeout` signals the command's whole process group.
["timeout", "--kill-after=5s", `${timeoutSeconds}s`, ...argv];
const startedAt = this.#now();
const process = await this.#container.exec(command, {
env: { ...BASE_ENVIRONMENT, ...options.env },
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
...(options.stdin === undefined
? {}
: { stdin: streamOf(options.stdin) }),
stdout: "pipe",
stderr: "pipe",
});
const stdout = collect(
process.stdout,
options.maxOutputBytes ?? MAX_OUTPUT_BYTES,
);
const stderr = collect(process.stderr, MAX_OUTPUT_BYTES);
let exited = false;
const backstop =
timeoutSeconds === undefined
? undefined
: setTimeout(
() => {
// Signalling a process that already exited raises an internal
// error in the Durable Object.
if (!exited) process.kill(SIGKILL);
},
timeoutSeconds * 1000 + TIMEOUT_BACKSTOP_MS,
);
let exitCode: number;
try {
exitCode = await process.exitCode;
} finally {
exited = true;
if (backstop !== undefined) clearTimeout(backstop);
}
// A background process that inherited the pipes keeps them open; its
// output after the command exits is not the command's.
const drained = await Promise.race([
Promise.all([stdout.done, stderr.done]),
sleep(OUTPUT_DRAIN_MS).then(() => undefined),
]);
if (drained === undefined)
await Promise.all([stdout.cancel(), stderr.cancel()]);
const [out, err] =
drained ?? (await Promise.all([stdout.done, stderr.done]));
const timedOut =
timeoutSeconds !== undefined &&
(exitCode === 124 || exitCode === 137) &&
this.#now() - startedAt >= timeoutSeconds * 1000;
return {
exitCode,
stdout: out,
stderr: err,
timedOut,
truncated: stdout.truncated(),
};
}
/** A shell command, as E2B runs it: `bash -l -c` as `user`. */
exec(command: string, options: OrbExecOptions = {}): Promise<OrbExecResult> {
return this.#use(async () => {
const result = await this.#run(["bash", "-l", "-c", command], options);
const decoder = textDecoder();
return {
stdout: decoder.decode(result.stdout),
stderr: textDecoder().decode(result.stderr),
exitCode: result.exitCode,
timedOut: result.timedOut,
};
});
}
async #file(
operation: string,
script: string,
args: string[],
stdin?: Uint8Array,
) {
const result = await this.#run(["sh", "-c", script, "sh", ...args], {
...(stdin === undefined ? {} : { stdin }),
});
if (result.exitCode !== 0)
throw failure(
operation,
textDecoder().decode(result.stderr).trim() || `exit ${result.exitCode}`,
);
return result.stdout;
}
readFile(path: string): Promise<Uint8Array> {
return this.#use(async () => {
const result = await this.#run(
["sh", "-c", 'exec cat -- "$1"', "sh", path],
{ maxOutputBytes: MAX_FILE_BYTES },
);
if (result.exitCode !== 0)
throw failure(
"readFile",
textDecoder().decode(result.stderr).trim() ||
`exit ${result.exitCode}`,
);
if (result.truncated)
throw failure(
"readFile",
`${path} is larger than ${MAX_FILE_BYTES} bytes`,
);
return result.stdout;
});
}
/** Creates missing parent directories, as E2B's file write does. */
writeFile(path: string, content: Uint8Array): Promise<void> {
return this.#use(async () => {
await this.#file(
"writeFile",
'mkdir -p -- "$(dirname -- "$1")" && exec cat > "$1"',
[path],
content,
);
});
}
stat(path: string): Promise<OrbFileStat> {
return this.#use(async () => {
const output = textDecoder().decode(
await this.#file(
"stat",
'if [ -L "$1" ]; then l=1; else l=0; fi; t=$(stat -L -c %F -- "$1") || exit 1; printf "%s\\n%s" "$l" "$t"',
[path],
),
);
const [link, type] = output.split("\n");
return {
isFile: type === "regular file" || type === "regular empty file",
isDirectory: type === "directory",
isSymbolicLink: link === "1",
};
});
}
readdir(path: string): Promise<string[]> {
return this.#use(async () => {
const output = textDecoder().decode(
await this.#file(
"readdir",
'test -d "$1" || { echo "not a directory: $1" >&2; exit 1; }; find "$1" -mindepth 1 -maxdepth 1 -printf "%f\\0"',
[path],
),
);
return output.split("\0").filter((name) => name.length > 0);
});
}
exists(path: string): Promise<boolean> {
return this.#use(async () => {
const result = await this.#run(
["sh", "-c", 'test -e "$1" || test -L "$1"', "sh", path],
{},
);
return result.exitCode === 0;
});
}
mkdir(path: string): Promise<void> {
return this.#use(async () => {
await this.#file("mkdir", 'exec mkdir -p -- "$1"', [path]);
});
}
rm(
path: string,
options: { readonly recursive?: boolean; readonly force?: boolean } = {},
): Promise<void> {
const flags = `${options.recursive ? "r" : ""}${options.force ? "f" : ""}`;
return this.#use(async () => {
await this.#file(
"rm",
flags === "" ? 'exec rm -- "$1"' : `exec rm -${flags} -- "$1"`,
[path],
);
});
}
/**
* Snapshot, then stop. With `keepIfActive`, a container that Core used
* while the snapshot ran keeps running (the snapshot still becomes the
* latest). Runs under the lifecycle lock.
*/
async #pause(state: OrbWorkspaceState, keepIfActive: boolean) {
const startedAt = this.#now();
const snapshot = await this.#container.snapshotContainer({
name: `dx-orb-${this.#sandboxId.slice(0, 16)}`,
});
const current = (await this.#load()) ?? state;
const next: OrbWorkspaceState = {
...current,
snapshot: {
id: snapshot.id,
size: snapshot.size,
refreshedAt: this.#now(),
},
};