@moinulmoin/eden-runtime-cloudflare 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  // @moinulmoin/eden-runtime-cloudflare Eve host worker runtime bundle.
2
2
  // Generated by scripts/bundle-eve-host.mjs; do not edit.
3
- // Bundles @cloudflare/containers (Apache-2.0) with cloudflare:workers external.
3
+ // Externalizes cloudflare:workers only.
4
4
 
5
5
  var __create = Object.create;
6
6
  var __defProp = Object.defineProperty;
@@ -152,1495 +152,8 @@ var require_ms = __commonJS({
152
152
  }
153
153
  });
154
154
 
155
- // ../../node_modules/.pnpm/@cloudflare+containers@0.3.7/node_modules/@cloudflare/containers/dist/lib/helpers.js
156
- function generateId(length = 9) {
157
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
158
- const bytes2 = new Uint8Array(length);
159
- crypto.getRandomValues(bytes2);
160
- let result = "";
161
- for (let i = 0; i < length; i++) {
162
- result += alphabet[bytes2[i] % alphabet.length];
163
- }
164
- return result;
165
- }
166
- function parseTimeExpression(timeExpression) {
167
- if (typeof timeExpression === "number") {
168
- return timeExpression;
169
- }
170
- if (typeof timeExpression === "string") {
171
- const match = timeExpression.match(/^(\d+)([smh])$/);
172
- if (!match) {
173
- throw new Error(`invalid time expression ${timeExpression}`);
174
- }
175
- const value = parseInt(match[1]);
176
- const unit = match[2];
177
- switch (unit) {
178
- case "s":
179
- return value;
180
- case "m":
181
- return value * 60;
182
- case "h":
183
- return value * 60 * 60;
184
- default:
185
- throw new Error(`unknown time unit ${unit}`);
186
- }
187
- }
188
- throw new Error(`invalid type for a time expression: ${typeof timeExpression}`);
189
- }
190
-
191
- // ../../node_modules/.pnpm/@cloudflare+containers@0.3.7/node_modules/@cloudflare/containers/dist/lib/container.js
155
+ // src/eve-host-runtime.ts
192
156
  import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";
193
- var NO_CONTAINER_INSTANCE_ERROR = "there is no container instance that can be provided to this durable object";
194
- var RATE_LIMITED_ERROR = "you are requesting too many containers per second";
195
- var RUNTIME_SIGNALLED_ERROR = "runtime signalled the container to exit:";
196
- var UNEXPECTED_EXIT_ERROR = "container exited with unexpected exit code:";
197
- var NOT_LISTENING_ERROR = "the container is not listening";
198
- var CONTAINER_STATE_KEY = "__CF_CONTAINER_STATE";
199
- var OUTBOUND_CONFIGURATION_KEY = "OUTBOUND_CONFIGURATION";
200
- var MAX_ALARM_RETRIES = 3;
201
- var PING_TIMEOUT_MS = 5e3;
202
- var DEFAULT_SLEEP_AFTER = "10m";
203
- var INSTANCE_POLL_INTERVAL_MS = 300;
204
- var TIMEOUT_TO_GET_CONTAINER_MS = 8e3;
205
- var TIMEOUT_TO_GET_PORTS_MS = 2e4;
206
- var FALLBACK_PORT_TO_CHECK = 33;
207
- var outboundHandlersRegistry = /* @__PURE__ */ new Map();
208
- var defaultOutboundHandlerNameRegistry = /* @__PURE__ */ new Map();
209
- var outboundByHostRegistry = /* @__PURE__ */ new Map();
210
- var signalToNumbers = {
211
- SIGINT: 2,
212
- SIGTERM: 15,
213
- SIGKILL: 9
214
- };
215
- function isErrorOfType(e, matchingString) {
216
- const errorString = e instanceof Error ? e.message : String(e);
217
- return errorString.toLowerCase().includes(matchingString);
218
- }
219
- var isNoInstanceError = (error61) => isErrorOfType(error61, NO_CONTAINER_INSTANCE_ERROR);
220
- var isRateLimitedError = (error61) => isErrorOfType(error61, RATE_LIMITED_ERROR);
221
- var isRuntimeSignalledError = (error61) => isErrorOfType(error61, RUNTIME_SIGNALLED_ERROR);
222
- var isNotListeningError = (error61) => isErrorOfType(error61, NOT_LISTENING_ERROR);
223
- var isContainerExitNonZeroError = (error61) => isErrorOfType(error61, UNEXPECTED_EXIT_ERROR);
224
- function getExitCodeFromError(error61) {
225
- if (!(error61 instanceof Error)) {
226
- return null;
227
- }
228
- if (isRuntimeSignalledError(error61)) {
229
- return +error61.message.toLowerCase().slice(error61.message.toLowerCase().indexOf(RUNTIME_SIGNALLED_ERROR) + RUNTIME_SIGNALLED_ERROR.length + 1);
230
- }
231
- if (isContainerExitNonZeroError(error61)) {
232
- return +error61.message.toLowerCase().slice(error61.message.toLowerCase().indexOf(UNEXPECTED_EXIT_ERROR) + UNEXPECTED_EXIT_ERROR.length + 1);
233
- }
234
- return null;
235
- }
236
- function addTimeoutSignal(existingSignal, timeoutMs) {
237
- const controller = new AbortController();
238
- if (existingSignal?.aborted) {
239
- controller.abort();
240
- return controller.signal;
241
- }
242
- existingSignal?.addEventListener("abort", () => controller.abort());
243
- const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
244
- controller.signal.addEventListener("abort", () => clearTimeout(timeoutId));
245
- return controller.signal;
246
- }
247
- function simpleGlobMatch(pattern, value) {
248
- const parts = pattern.split("*");
249
- if (parts.length === 1)
250
- return pattern === value;
251
- if (!value.startsWith(parts[0]))
252
- return false;
253
- if (!value.endsWith(parts[parts.length - 1]))
254
- return false;
255
- let pos = parts[0].length;
256
- for (let i = 1; i < parts.length - 1; i++) {
257
- const idx = value.indexOf(parts[i], pos);
258
- if (idx === -1)
259
- return false;
260
- pos = idx + parts[i].length;
261
- }
262
- return pos <= value.length - parts[parts.length - 1].length;
263
- }
264
- function matchesHostList(hostname3, patterns) {
265
- return patterns.some((pattern) => simpleGlobMatch(pattern, hostname3));
266
- }
267
- function normalizeHostname(hostname3) {
268
- let end = hostname3.length;
269
- while (end > 0 && hostname3[end - 1] === ".") {
270
- end--;
271
- }
272
- return hostname3.slice(0, end);
273
- }
274
- var ContainerState = class {
275
- storage;
276
- status;
277
- constructor(storage) {
278
- this.storage = storage;
279
- }
280
- async setRunning() {
281
- await this.setStatusAndupdate("running");
282
- }
283
- async setHealthy() {
284
- await this.setStatusAndupdate("healthy");
285
- }
286
- async setStopping() {
287
- await this.setStatusAndupdate("stopping");
288
- }
289
- async setStopped() {
290
- await this.setStatusAndupdate("stopped");
291
- }
292
- async setStoppedIfUnchanged(previousState) {
293
- if (this.status !== previousState) {
294
- return;
295
- }
296
- await this.setStopped();
297
- }
298
- async setStoppedWithCode(exitCode) {
299
- this.status = { status: "stopped_with_code", lastChange: Date.now(), exitCode };
300
- await this.update();
301
- }
302
- async getState() {
303
- if (!this.status) {
304
- const state = await this.storage.get(CONTAINER_STATE_KEY);
305
- if (!state) {
306
- this.status = {
307
- status: "stopped",
308
- lastChange: Date.now()
309
- };
310
- await this.update();
311
- } else {
312
- this.status = state;
313
- }
314
- }
315
- return this.status;
316
- }
317
- async setStatusAndupdate(status) {
318
- this.status = { status, lastChange: Date.now() };
319
- await this.update();
320
- }
321
- async update() {
322
- if (!this.status)
323
- throw new Error("status should be init");
324
- await this.storage.put(CONTAINER_STATE_KEY, this.status);
325
- }
326
- };
327
- var ContainerProxy = class extends WorkerEntrypoint {
328
- async fetch(request) {
329
- const url2 = new URL(request.url);
330
- const hostname3 = normalizeHostname(url2.hostname);
331
- const { className, containerId, outboundByHostOverrides, outboundHandlerOverride, enableInternet, allowedHosts, deniedHosts, interceptAll } = this.ctx.props;
332
- const baseCtx = { containerId, className };
333
- if (deniedHosts && matchesHostList(hostname3, deniedHosts)) {
334
- return new Response("Origin is disallowed", { status: 520 });
335
- }
336
- if (allowedHosts && !matchesHostList(hostname3, allowedHosts)) {
337
- return new Response("Origin is disallowed", { status: 520 });
338
- }
339
- const handlers = outboundHandlersRegistry.get(className);
340
- if (outboundByHostOverrides && handlers) {
341
- const override = outboundByHostOverrides[hostname3] ?? Object.entries(outboundByHostOverrides).find(([pattern]) => pattern !== hostname3 && simpleGlobMatch(pattern, hostname3))?.[1];
342
- if (override && handlers[override.method]) {
343
- return handlers[override.method](request, this.env, {
344
- ...baseCtx,
345
- params: override.params
346
- });
347
- }
348
- }
349
- const handlersByHost = outboundByHostRegistry.get(className);
350
- if (handlersByHost) {
351
- const handler = handlersByHost[hostname3] ?? Object.entries(handlersByHost).find(([pattern]) => pattern !== hostname3 && simpleGlobMatch(pattern, hostname3))?.[1];
352
- if (handler) {
353
- return handler(request, this.env, baseCtx);
354
- }
355
- }
356
- if (!interceptAll) {
357
- if (allowedHosts || enableInternet) {
358
- return fetch(request);
359
- }
360
- return new Response("Origin is disallowed", { status: 520 });
361
- }
362
- if (outboundHandlerOverride && handlers?.[outboundHandlerOverride.method]) {
363
- return handlers[outboundHandlerOverride.method](request, this.env, {
364
- ...baseCtx,
365
- params: outboundHandlerOverride.params
366
- });
367
- }
368
- const defaultOutboundHandlerName = defaultOutboundHandlerNameRegistry.get(className);
369
- if (defaultOutboundHandlerName && handlers?.[defaultOutboundHandlerName]) {
370
- return handlers[defaultOutboundHandlerName](request, this.env, baseCtx);
371
- }
372
- if (allowedHosts) {
373
- return fetch(request);
374
- }
375
- if (enableInternet) {
376
- return fetch(request);
377
- }
378
- return new Response("Origin is disallowed", { status: 520 });
379
- }
380
- };
381
- var Container = class extends DurableObject {
382
- static get outboundByHost() {
383
- return outboundByHostRegistry.get(this.name);
384
- }
385
- static set outboundByHost(handlers) {
386
- outboundByHostRegistry.set(this.name, handlers);
387
- }
388
- static get outboundHandlers() {
389
- return outboundHandlersRegistry.get(this.name);
390
- }
391
- static set outboundHandlers(handlers) {
392
- const existing = outboundHandlersRegistry.get(this.name) ?? {};
393
- outboundHandlersRegistry.set(this.name, { ...existing, ...handlers });
394
- }
395
- static get outbound() {
396
- const handlerName = defaultOutboundHandlerNameRegistry.get(this.name);
397
- if (!handlerName)
398
- return void 0;
399
- return outboundHandlersRegistry.get(this.name)?.[handlerName];
400
- }
401
- static set outbound(handler) {
402
- const key = "__outbound__";
403
- const existing = outboundHandlersRegistry.get(this.name) ?? {};
404
- outboundHandlersRegistry.set(this.name, { ...existing, [key]: handler });
405
- defaultOutboundHandlerNameRegistry.set(this.name, key);
406
- }
407
- static get outboundProxies() {
408
- return this.outboundHandlers;
409
- }
410
- static set outboundProxies(handlers) {
411
- this.outboundHandlers = handlers;
412
- }
413
- static get outboundProxy() {
414
- return this.outbound;
415
- }
416
- static set outboundProxy(handler) {
417
- this.outbound = handler;
418
- }
419
- // =========================
420
- // Public Attributes
421
- // =========================
422
- // Default port for the container (undefined means no default port)
423
- defaultPort;
424
- // Required ports that should be checked for availability during container startup
425
- // Override this in your subclass to specify ports that must be ready
426
- requiredPorts;
427
- // Timeout after which the container will sleep if no activity
428
- // The signal sent to the container by default is a SIGTERM.
429
- // The container won't get a SIGKILL if this threshold is triggered.
430
- sleepAfter = DEFAULT_SLEEP_AFTER;
431
- // Container configuration properties
432
- // Set these properties directly in your container instance
433
- envVars = {};
434
- entrypoint;
435
- enableInternet = true;
436
- labels = {};
437
- // When true, outbound HTTPS traffic from the container will be intercepted.
438
- // The container must trust /etc/cloudflare/certs/cloudflare-containers-ca.crt
439
- interceptHttps = false;
440
- // Hosts that are allowed to access the internet, even when enableInternet is false.
441
- // Useful for allowing specific domains on a per-host basis.
442
- allowedHosts;
443
- // Hosts that are denied internet access, even when enableInternet is true.
444
- // Also blocks hosts from being handled by the catch-all outbound handler.
445
- deniedHosts;
446
- // pingEndpoint is the host and path value that the class will use to send a request to the container and check if the
447
- // instance is ready.
448
- //
449
- // The user does not have to implement this route by any means,
450
- // but it's still useful if you want to control the path that
451
- // the Container class uses to send HTTP requests to.
452
- pingEndpoint = "ping";
453
- applyOutboundInterceptionPromise = Promise.resolve();
454
- usingInterception = false;
455
- // =========================
456
- // PUBLIC INTERFACE
457
- // =========================
458
- constructor(ctx, env, options) {
459
- super(ctx, env);
460
- if (ctx.container === void 0) {
461
- 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");
462
- }
463
- this.state = new ContainerState(this.ctx.storage);
464
- const persistedOutboundConfiguration = this.restoreOutboundConfiguration();
465
- this.ctx.blockConcurrencyWhile(async () => {
466
- await this.scheduleNextAlarm();
467
- this.renewActivityTimeout();
468
- const ctor = this.constructor;
469
- if (persistedOutboundConfiguration !== void 0 || ctor.outboundByHost !== void 0 || ctor.outbound !== void 0 || ctor.outboundHandlers !== void 0 || this.effectiveAllowedHosts !== void 0 || this.effectiveDeniedHosts !== void 0) {
470
- this.usingInterception = true;
471
- }
472
- if (this.container.running) {
473
- this.applyOutboundInterceptionPromise = this.applyOutboundInterception();
474
- }
475
- });
476
- this.container = ctx.container;
477
- if (options) {
478
- if (options.defaultPort !== void 0)
479
- this.defaultPort = options.defaultPort;
480
- if (options.sleepAfter !== void 0)
481
- this.sleepAfter = options.sleepAfter;
482
- if (options.envVars !== void 0)
483
- this.envVars = options.envVars;
484
- if (options.entrypoint !== void 0)
485
- this.entrypoint = options.entrypoint;
486
- if (options.enableInternet !== void 0)
487
- this.enableInternet = options.enableInternet;
488
- }
489
- this.sql`
490
- CREATE TABLE IF NOT EXISTS container_schedules (
491
- id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
492
- callback TEXT NOT NULL,
493
- payload TEXT,
494
- type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed')),
495
- time INTEGER NOT NULL,
496
- delayInSeconds INTEGER,
497
- created_at INTEGER DEFAULT (unixepoch())
498
- )
499
- `;
500
- if (this.container.running) {
501
- this.monitor = this.container.monitor();
502
- this.setupMonitorCallbacks();
503
- }
504
- }
505
- /**
506
- * Gets the current state of the container
507
- * @returns Promise<State>
508
- */
509
- async getState() {
510
- return { ...await this.state.getState() };
511
- }
512
- // ====================================
513
- // OUTBOUND INTERCEPTION CONFIG
514
- // ====================================
515
- /**
516
- * Set the catch-all outbound handler to a named method from `outboundHandlers`.
517
- * Overrides the default `outbound` at runtime via ContainerProxy props.
518
- *
519
- * @param methodName - Name of a method defined in `static outboundHandlers`
520
- * @param params - Optional params passed to the handler as `ctx.params`
521
- * @throws Error if the method name is not found in `outboundHandlers`
522
- */
523
- async setOutboundHandler(methodName, ...paramsArg) {
524
- this.validateOutboundHandlerMethodName(methodName);
525
- this.outboundHandlerOverride = paramsArg.length === 0 ? { method: methodName } : { method: methodName, params: paramsArg[0] };
526
- await this.refreshOutboundInterception();
527
- }
528
- /**
529
- * Add or override a hostname-specific outbound handler at runtime,
530
- * referencing a named method from `outboundHandlers`.
531
- * Overrides any matching entry in `static outboundByHost` for this hostname.
532
- *
533
- * @param hostname - The hostname or ip:port to intercept (e.g. `'google.com'`)
534
- * @param methodName - Name of a method defined in `static outboundHandlers`
535
- * @param params - Optional params passed to the handler as `ctx.params`
536
- * @throws Error if the method name is not found in `outboundHandlers`
537
- */
538
- async setOutboundByHost(hostname3, methodName, ...paramsArg) {
539
- this.validateOutboundHandlerMethodName(methodName);
540
- this.outboundByHostOverrides[hostname3] = paramsArg.length === 0 ? { method: methodName } : { method: methodName, params: paramsArg[0] };
541
- await this.refreshOutboundInterception();
542
- }
543
- /**
544
- * Remove a runtime hostname override added via `setOutboundByHost`.
545
- * The default handler from `static outboundByHost` (if any) will be used again.
546
- *
547
- * @param hostname - The hostname or ip:port to stop overriding
548
- */
549
- async removeOutboundByHost(hostname3) {
550
- delete this.outboundByHostOverrides[hostname3];
551
- await this.refreshOutboundInterception();
552
- }
553
- /**
554
- * Replace all runtime hostname overrides at once.
555
- * Each value may be either a method name or an object with `method` and `params`.
556
- *
557
- * @param handlers - Record mapping hostnames to handler configs in `outboundHandlers`
558
- * @throws Error if any method name is not found in `outboundHandlers`
559
- */
560
- async setOutboundByHosts(handlers) {
561
- for (const handler of Object.values(handlers)) {
562
- const methodName = typeof handler === "string" ? handler : handler.method;
563
- this.validateOutboundHandlerMethodName(methodName);
564
- }
565
- this.outboundByHostOverrides = Object.fromEntries(Object.entries(handlers).map(([hostname3, handler]) => [
566
- hostname3,
567
- typeof handler === "string" ? { method: handler } : handler
568
- ]));
569
- await this.refreshOutboundInterception();
570
- }
571
- // ====================================
572
- // ALLOWED / DENIED HOSTS CONFIG
573
- // ====================================
574
- /**
575
- * Replace all allowed hosts at runtime.
576
- * Allowed hosts get internet access even when `enableInternet` is false.
577
- *
578
- * @param hosts - Array of hostnames to allow (e.g. `['api.stripe.com', 'example.com']`)
579
- */
580
- async setAllowedHosts(hosts) {
581
- this.allowedHostsOverride = [...hosts];
582
- this.usingInterception = true;
583
- await this.refreshOutboundInterception();
584
- }
585
- /**
586
- * Replace all denied hosts at runtime.
587
- * Denied hosts are blocked unconditionally, even when `enableInternet` is true
588
- * or a catch-all outbound handler is set.
589
- *
590
- * @param hosts - Array of hostnames to deny (e.g. `['evil.com', 'blocked.org']`)
591
- */
592
- async setDeniedHosts(hosts) {
593
- this.deniedHostsOverride = [...hosts];
594
- this.usingInterception = true;
595
- await this.refreshOutboundInterception();
596
- }
597
- /**
598
- * Add a single hostname to the allowed hosts list at runtime.
599
- *
600
- * @param hostname - The hostname to allow (e.g. `'api.stripe.com'`)
601
- */
602
- async allowHost(hostname3) {
603
- const effective = this.effectiveAllowedHosts ?? [];
604
- if (!effective.includes(hostname3)) {
605
- this.allowedHostsOverride = [...effective, hostname3];
606
- }
607
- this.usingInterception = true;
608
- await this.refreshOutboundInterception();
609
- }
610
- /**
611
- * Add a single hostname to the denied hosts list at runtime.
612
- *
613
- * @param hostname - The hostname to deny (e.g. `'evil.com'`)
614
- */
615
- async denyHost(hostname3) {
616
- const effective = this.effectiveDeniedHosts ?? [];
617
- if (!effective.includes(hostname3)) {
618
- this.deniedHostsOverride = [...effective, hostname3];
619
- }
620
- this.usingInterception = true;
621
- await this.refreshOutboundInterception();
622
- }
623
- /**
624
- * Remove a hostname from the allowed hosts list.
625
- *
626
- * @param hostname - The hostname to remove from the allow list
627
- */
628
- async removeAllowedHost(hostname3) {
629
- this.allowedHostsOverride = (this.effectiveAllowedHosts ?? []).filter((h) => h !== hostname3);
630
- await this.refreshOutboundInterception();
631
- }
632
- /**
633
- * Remove a hostname from the denied hosts list.
634
- *
635
- * @param hostname - The hostname to remove from the deny list
636
- */
637
- async removeDeniedHost(hostname3) {
638
- this.deniedHostsOverride = (this.effectiveDeniedHosts ?? []).filter((h) => h !== hostname3);
639
- await this.refreshOutboundInterception();
640
- }
641
- // ==========================
642
- // CONTAINER STARTING
643
- // ==========================
644
- /**
645
- * Start the container if it's not running and set up monitoring and lifecycle hooks,
646
- * without waiting for ports to be ready.
647
- *
648
- * It will automatically retry if the container fails to start, using the specified waitOptions
649
- *
650
- *
651
- * @example
652
- * await this.start({
653
- * envVars: { DEBUG: 'true', NODE_ENV: 'development' },
654
- * entrypoint: ['npm', 'run', 'dev'],
655
- * enableInternet: false,
656
- * labels: { tenant: 'acme', env: 'prod' },
657
- * });
658
- *
659
- * @param startOptions - Override `envVars`, `entrypoint`, `enableInternet` and `labels` on a per-instance basis
660
- * @param waitOptions - Optional wait configuration with abort signal for cancellation. Default ~8s timeout.
661
- * @returns A promise that resolves when the container start command has been issued
662
- * @throws Error if no container context is available or if all start attempts fail
663
- */
664
- async start(startOptions, waitOptions) {
665
- const portToCheck = waitOptions?.portToCheck ?? this.defaultPort ?? (this.requiredPorts ? this.requiredPorts[0] : FALLBACK_PORT_TO_CHECK);
666
- const pollInterval = waitOptions?.waitInterval ?? INSTANCE_POLL_INTERVAL_MS;
667
- await this.startContainerIfNotRunning({
668
- signal: waitOptions?.signal,
669
- waitInterval: pollInterval,
670
- retries: waitOptions?.retries ?? Math.ceil(TIMEOUT_TO_GET_CONTAINER_MS / pollInterval),
671
- portToCheck
672
- }, startOptions);
673
- this.setupMonitorCallbacks();
674
- await this.ctx.blockConcurrencyWhile(async () => {
675
- await this.onStart();
676
- });
677
- }
678
- async startAndWaitForPorts(portsOrArgs, cancellationOptions, startOptions) {
679
- let ports;
680
- let resolvedCancellationOptions;
681
- let resolvedStartOptions;
682
- if (typeof portsOrArgs === "object" && portsOrArgs !== null && !Array.isArray(portsOrArgs)) {
683
- ports = portsOrArgs.ports;
684
- resolvedCancellationOptions = portsOrArgs.cancellationOptions;
685
- resolvedStartOptions = portsOrArgs.startOptions;
686
- } else {
687
- ports = portsOrArgs;
688
- resolvedCancellationOptions = cancellationOptions;
689
- resolvedStartOptions = startOptions;
690
- }
691
- const portsToCheck = await this.getPortsToCheck(ports);
692
- await this.syncPendingStoppedEvents();
693
- resolvedCancellationOptions ??= {};
694
- const containerGetTimeout = resolvedCancellationOptions.instanceGetTimeoutMS ?? TIMEOUT_TO_GET_CONTAINER_MS;
695
- const pollInterval = resolvedCancellationOptions.waitInterval ?? INSTANCE_POLL_INTERVAL_MS;
696
- const containerGetRetries = Math.ceil(containerGetTimeout / pollInterval);
697
- const waitOptions = {
698
- signal: resolvedCancellationOptions.abort,
699
- retries: containerGetRetries,
700
- waitInterval: pollInterval,
701
- portToCheck: portsToCheck[0]
702
- };
703
- const triesUsed = await this.startContainerIfNotRunning(waitOptions, resolvedStartOptions);
704
- const totalPortReadyTries = Math.ceil((resolvedCancellationOptions.portReadyTimeoutMS ?? TIMEOUT_TO_GET_PORTS_MS) / pollInterval);
705
- let triesLeft = totalPortReadyTries - triesUsed;
706
- for (const port of portsToCheck) {
707
- triesLeft = await this.waitForPort({
708
- signal: resolvedCancellationOptions.abort,
709
- waitInterval: pollInterval,
710
- retries: triesLeft,
711
- portToCheck: port
712
- });
713
- }
714
- this.setupMonitorCallbacks();
715
- await this.ctx.blockConcurrencyWhile(async () => {
716
- await this.state.setHealthy();
717
- await this.onStart();
718
- });
719
- }
720
- /**
721
- *
722
- * Waits for a specified port to be ready
723
- *
724
- * Returns the number of tries used to get the port, or throws if it couldn't get the port within the specified retry limits.
725
- *
726
- * @param waitOptions -
727
- * - `portToCheck`: The port number to check
728
- * - `abort`: Optional AbortSignal to cancel waiting
729
- * - `retries`: Number of retries before giving up (default: TRIES_TO_GET_PORTS)
730
- * - `waitInterval`: Interval between retries in milliseconds (default: INSTANCE_POLL_INTERVAL_MS)
731
- */
732
- async waitForPort(waitOptions) {
733
- const port = waitOptions.portToCheck;
734
- const tcpPort = this.container.getTcpPort(port);
735
- const abortedSignal = new Promise((res) => {
736
- waitOptions.signal?.addEventListener("abort", () => {
737
- res(true);
738
- });
739
- });
740
- const pollInterval = waitOptions.waitInterval ?? INSTANCE_POLL_INTERVAL_MS;
741
- const tries = waitOptions.retries ?? Math.ceil(TIMEOUT_TO_GET_PORTS_MS / pollInterval);
742
- for (let i = 0; i < tries; i++) {
743
- try {
744
- const combinedSignal = addTimeoutSignal(waitOptions.signal, PING_TIMEOUT_MS);
745
- await tcpPort.fetch(`http://${this.pingEndpoint}`, { signal: combinedSignal });
746
- break;
747
- } catch (e) {
748
- const errorMessage = e instanceof Error ? e.message : String(e);
749
- if (!this.container.running) {
750
- try {
751
- await this.onError(new Error(`Container crashed while checking for ports, did you start the container and setup the entrypoint correctly?`));
752
- } catch {
753
- }
754
- throw e;
755
- }
756
- if (i === tries - 1) {
757
- try {
758
- await this.onError(`Failed to verify port ${port} is available after ${(i + 1) * pollInterval}ms, last error: ${errorMessage}`);
759
- } catch {
760
- }
761
- throw e;
762
- }
763
- await Promise.any([
764
- new Promise((resolve) => setTimeout(resolve, pollInterval)),
765
- abortedSignal
766
- ]);
767
- if (waitOptions.signal?.aborted) {
768
- throw new Error("Container request aborted.", { cause: e });
769
- }
770
- }
771
- }
772
- return tries;
773
- }
774
- // =======================
775
- // LIFECYCLE HOOKS
776
- // =======================
777
- /**
778
- * Send a signal to the container.
779
- * @param signal - The signal to send to the container (default: 15 for SIGTERM)
780
- */
781
- async stop(signal = "SIGTERM") {
782
- if (this.container.running) {
783
- this.container.signal(typeof signal === "string" ? signalToNumbers[signal] : signal);
784
- }
785
- await this.syncPendingStoppedEvents();
786
- }
787
- /**
788
- * Destroys the container with a SIGKILL. Triggers onStop.
789
- */
790
- async destroy() {
791
- await this.container.destroy();
792
- }
793
- /**
794
- * Lifecycle method called when container starts successfully
795
- * Override this method in subclasses to handle container start events
796
- */
797
- onStart() {
798
- }
799
- /**
800
- * Lifecycle method called when container shuts down
801
- * Override this method in subclasses to handle Container stopped events
802
- * @param params - Object containing exitCode and reason for the stop
803
- */
804
- onStop(params) {
805
- void params;
806
- }
807
- /**
808
- * Lifecycle method called when the container is running, and the activity timeout
809
- * expiration (set by `sleepAfter`) has been reached.
810
- *
811
- * If you want to shutdown the container, you should call this.stop() here
812
- *
813
- * By default, this method calls `this.stop()`
814
- */
815
- async onActivityExpired() {
816
- console.log("Activity expired, signalling container to stop");
817
- if (!this.container.running) {
818
- return;
819
- }
820
- await this.stop();
821
- }
822
- /**
823
- * Error handler for container errors
824
- * Override this method in subclasses to handle container errors
825
- * @param error - The error that occurred
826
- * @returns Can return any value or throw the error
827
- */
828
- onError(error61) {
829
- console.error("Container error:", error61);
830
- throw error61;
831
- }
832
- /**
833
- * Renew the container's activity timeout
834
- *
835
- * Call this method whenever there is activity on the container
836
- */
837
- renewActivityTimeout() {
838
- const timeoutInMs = parseTimeExpression(this.sleepAfter) * 1e3;
839
- this.sleepAfterMs = Date.now() + timeoutInMs;
840
- }
841
- /**
842
- * Decrement the inflight request counter.
843
- * When the counter transitions to 0, renew the activity timeout so the
844
- * inactivity window starts fresh from the moment the last request completes.
845
- */
846
- decrementInflight() {
847
- this.inflightRequests = Math.max(0, this.inflightRequests - 1);
848
- if (this.inflightRequests === 0) {
849
- this.renewActivityTimeout();
850
- }
851
- }
852
- // ==================
853
- // SCHEDULING
854
- // ==================
855
- /**
856
- * Schedule a task to be executed in the future.
857
- *
858
- * We strongly recommend using this instead of the `alarm` handler.
859
- *
860
- * @template T Type of the payload data
861
- * @param when When to execute the task (Date object or number of seconds delay)
862
- * @param callback Name of the method to call
863
- * @param payload Data to pass to the callback
864
- * @returns Schedule object representing the scheduled task
865
- */
866
- async schedule(when, callback, payload) {
867
- const id = generateId(9);
868
- if (typeof callback !== "string") {
869
- throw new Error("Callback must be a string (method name)");
870
- }
871
- if (typeof this[callback] !== "function") {
872
- throw new Error(`this.${callback} is not a function`);
873
- }
874
- if (when instanceof Date) {
875
- const timestamp = Math.floor(when.getTime() / 1e3);
876
- this.sql`
877
- INSERT OR REPLACE INTO container_schedules (id, callback, payload, type, time)
878
- VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'scheduled', ${timestamp})
879
- `;
880
- await this.scheduleNextAlarm();
881
- return {
882
- taskId: id,
883
- callback,
884
- payload,
885
- time: timestamp,
886
- type: "scheduled"
887
- };
888
- }
889
- if (typeof when === "number") {
890
- const time3 = Math.floor(Date.now() / 1e3 + when);
891
- this.sql`
892
- INSERT OR REPLACE INTO container_schedules (id, callback, payload, type, delayInSeconds, time)
893
- VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'delayed', ${when}, ${time3})
894
- `;
895
- await this.scheduleNextAlarm();
896
- return {
897
- taskId: id,
898
- callback,
899
- payload,
900
- delayInSeconds: when,
901
- time: time3,
902
- type: "delayed"
903
- };
904
- }
905
- throw new Error("Invalid schedule type. 'when' must be a Date or number of seconds");
906
- }
907
- // ============
908
- // HTTP
909
- // ============
910
- /**
911
- * Send a request to the container (HTTP or WebSocket) using standard fetch API signature
912
- *
913
- * This method handles HTTP requests to the container.
914
- *
915
- * WebSocket requests done outside the DO won't work until https://github.com/cloudflare/workerd/issues/2319 is addressed.
916
- * Until then, please use `switchPort` + `fetch()`.
917
- *
918
- * Method supports multiple signatures to match standard fetch API:
919
- * - containerFetch(request: Request, port?: number)
920
- * - containerFetch(url: string | URL, init?: RequestInit, port?: number)
921
- *
922
- * Starts the container if not already running, and waits for the target port to be ready.
923
- *
924
- * @returns A Response from the container
925
- */
926
- async containerFetch(requestOrUrl, portOrInit, portParam) {
927
- const { request, port } = this.requestAndPortFromContainerFetchArgs(requestOrUrl, portOrInit, portParam);
928
- const state = await this.state.getState();
929
- if (!this.container.running || state.status !== "healthy") {
930
- try {
931
- await this.startAndWaitForPorts(port, { abort: request.signal });
932
- } catch (e) {
933
- if (isNoInstanceError(e)) {
934
- return new Response("There is no Container instance available at this time.\nThis is likely because you have reached your max concurrent instance count (set in wrangler config) or are you currently provisioning the Container.\nIf you are deploying your Container for the first time, check your dashboard to see provisioning status, this may take a few minutes.", { status: 503 });
935
- }
936
- if (isRateLimitedError(e)) {
937
- return new Response(e instanceof Error ? e.message : String(e), { status: 429 });
938
- }
939
- return new Response(`Failed to start container: ${e instanceof Error ? e.message : String(e)}`, {
940
- status: 500
941
- });
942
- }
943
- }
944
- const tcpPort = this.container.getTcpPort(port);
945
- const containerUrl = request.url.replace("https:", "http:");
946
- this.inflightRequests++;
947
- try {
948
- this.renewActivityTimeout();
949
- const res = await tcpPort.fetch(containerUrl, request);
950
- if (res.webSocket !== null) {
951
- const containerWs = res.webSocket;
952
- const [client, server] = Object.values(new WebSocketPair());
953
- let settled = false;
954
- const settleInflight = () => {
955
- if (!settled) {
956
- settled = true;
957
- this.decrementInflight();
958
- }
959
- };
960
- containerWs.accept();
961
- server.accept();
962
- server.addEventListener("message", async (event) => {
963
- this.renewActivityTimeout();
964
- try {
965
- const data = event.data instanceof Blob ? await event.data.arrayBuffer() : event.data;
966
- containerWs.send(data);
967
- } catch {
968
- server.close(1011, "Failed to forward message to container");
969
- }
970
- });
971
- containerWs.addEventListener("message", async (event) => {
972
- this.renewActivityTimeout();
973
- try {
974
- const data = event.data instanceof Blob ? await event.data.arrayBuffer() : event.data;
975
- server.send(data);
976
- } catch {
977
- containerWs.close(1011, "Failed to forward message to client");
978
- }
979
- });
980
- server.addEventListener("close", (event) => {
981
- settleInflight();
982
- const code = event.code === 1005 || event.code === 1006 ? 1e3 : event.code;
983
- containerWs.close(code, event.reason);
984
- });
985
- containerWs.addEventListener("close", (event) => {
986
- settleInflight();
987
- const code = event.code === 1005 || event.code === 1006 ? 1e3 : event.code;
988
- server.close(code, event.reason);
989
- });
990
- server.addEventListener("error", () => {
991
- settleInflight();
992
- containerWs.close(1011, "Client WebSocket error");
993
- });
994
- containerWs.addEventListener("error", () => {
995
- settleInflight();
996
- server.close(1011, "Container WebSocket error");
997
- });
998
- return new Response(null, { status: res.status, webSocket: client, headers: res.headers });
999
- }
1000
- if (res.body !== null) {
1001
- const { readable, writable } = new IdentityTransformStream();
1002
- res.body?.pipeTo(writable).finally(() => {
1003
- this.decrementInflight();
1004
- });
1005
- return new Response(readable, res);
1006
- }
1007
- this.decrementInflight();
1008
- return res;
1009
- } catch (e) {
1010
- this.decrementInflight();
1011
- if (!(e instanceof Error)) {
1012
- throw e;
1013
- }
1014
- if (e.message.includes("Network connection lost.")) {
1015
- return new Response("Container suddenly disconnected, try again", { status: 500 });
1016
- }
1017
- console.error(`Error proxying request to container ${this.ctx.id}:`, e);
1018
- return new Response(`Error proxying request to container: ${e instanceof Error ? e.message : String(e)}`, { status: 500 });
1019
- }
1020
- }
1021
- /**
1022
- *
1023
- * Fetch handler on the Container class.
1024
- * By default this forwards all requests to the container by calling `containerFetch`.
1025
- * Use `switchPort` to specify which port on the container to target, or this will use `defaultPort`.
1026
- * @param request The request to handle
1027
- */
1028
- async fetch(request) {
1029
- if (this.defaultPort === void 0 && !request.headers.has("cf-container-target-port")) {
1030
- throw new Error("No port configured for this container. Set the `defaultPort` in your Container subclass, or specify a port with `container.fetch(switchPort(request, port))`.");
1031
- }
1032
- let portValue = this.defaultPort;
1033
- if (request.headers.has("cf-container-target-port")) {
1034
- const portFromHeaders = parseInt(request.headers.get("cf-container-target-port") ?? "");
1035
- if (isNaN(portFromHeaders)) {
1036
- throw new Error("port value from switchPort is not a number");
1037
- } else {
1038
- portValue = portFromHeaders;
1039
- }
1040
- }
1041
- return await this.containerFetch(request, portValue);
1042
- }
1043
- // ===============================
1044
- // ===============================
1045
- // PRIVATE METHODS & ATTRS
1046
- // ===============================
1047
- // ===============================
1048
- // ==========================
1049
- // PRIVATE ATTRIBUTES
1050
- // ==========================
1051
- container;
1052
- // onStopCalled will be true when we are in the middle of an onStop call
1053
- onStopCalled = false;
1054
- state;
1055
- monitor;
1056
- // Coalesces concurrent calls to startContainerIfNotRunning so we never
1057
- // call `this.container.start()` twice. Without this guard, two requests
1058
- // racing the readiness path can both pass the `if (this.container.running)`
1059
- // early-return (each yielding the DO input gate at storage awaits) and
1060
- // both reach the synchronous workerd `start()`, causing the second to
1061
- // throw "start() cannot be called on a container that is already running."
1062
- // See https://github.com/cloudflare/containers/issues/173.
1063
- startInFlight;
1064
- monitoredPromise;
1065
- sleepAfterMs = 0;
1066
- inflightRequests = 0;
1067
- // Outbound interception runtime overrides (passed through ContainerProxy props)
1068
- outboundByHostOverrides = {};
1069
- outboundHandlerOverride;
1070
- // Only set when the user calls setAllowedHosts/setDeniedHosts at runtime
1071
- allowedHostsOverride;
1072
- deniedHostsOverride;
1073
- // The runtime does not expose a way to remove outbound interceptions yet, so
1074
- // once we promote an instance to intercept-all we must keep using it.
1075
- hasInterceptAllRegistration = false;
1076
- // ==========================
1077
- // GENERAL HELPERS
1078
- // ==========================
1079
- /**
1080
- * Validates that a method name exists in the outboundHandlers registry for this class.
1081
- * @throws Error if the method name is not found
1082
- */
1083
- validateOutboundHandlerMethodName(methodName) {
1084
- const handlers = outboundHandlersRegistry.get(this.constructor.name);
1085
- if (!handlers || !(methodName in handlers)) {
1086
- throw new Error(`Outbound handler method '${methodName}' not found in outboundHandlers for ${this.constructor.name}`);
1087
- }
1088
- }
1089
- get effectiveAllowedHosts() {
1090
- return this.allowedHostsOverride ?? this.allowedHosts;
1091
- }
1092
- get effectiveDeniedHosts() {
1093
- return this.deniedHostsOverride ?? this.deniedHosts;
1094
- }
1095
- getOutboundConfiguration() {
1096
- return {
1097
- outboundByHostOverrides: Object.keys(this.outboundByHostOverrides).length > 0 ? this.outboundByHostOverrides : void 0,
1098
- outboundHandlerOverride: this.outboundHandlerOverride,
1099
- allowedHosts: this.effectiveAllowedHosts,
1100
- deniedHosts: this.effectiveDeniedHosts,
1101
- hasInterceptAllRegistration: this.hasInterceptAllRegistration || void 0
1102
- };
1103
- }
1104
- persistOutboundConfiguration(configuration) {
1105
- this.ctx.storage.kv.put(OUTBOUND_CONFIGURATION_KEY, {
1106
- ...configuration,
1107
- allowedHosts: this.allowedHostsOverride,
1108
- deniedHosts: this.deniedHostsOverride
1109
- });
1110
- }
1111
- restoreOutboundConfiguration() {
1112
- const configuration = this.ctx.storage.kv.get(OUTBOUND_CONFIGURATION_KEY);
1113
- if (!configuration) {
1114
- return void 0;
1115
- }
1116
- this.outboundHandlerOverride = void 0;
1117
- if (configuration.outboundHandlerOverride !== void 0) {
1118
- try {
1119
- this.validateOutboundHandlerMethodName(configuration.outboundHandlerOverride.method);
1120
- this.outboundHandlerOverride = configuration.outboundHandlerOverride;
1121
- } catch (error61) {
1122
- console.warn("Ignoring invalid persisted outbound handler override:", error61);
1123
- }
1124
- }
1125
- this.outboundByHostOverrides = {};
1126
- for (const [hostname3, override] of Object.entries(configuration.outboundByHostOverrides ?? {})) {
1127
- try {
1128
- this.validateOutboundHandlerMethodName(override.method);
1129
- this.outboundByHostOverrides[hostname3] = override;
1130
- } catch (error61) {
1131
- console.warn(`Ignoring invalid persisted outbound override for ${hostname3}:`, error61);
1132
- }
1133
- }
1134
- this.hasInterceptAllRegistration = configuration.hasInterceptAllRegistration === true;
1135
- if (configuration.allowedHosts) {
1136
- this.allowedHostsOverride = configuration.allowedHosts;
1137
- }
1138
- if (configuration.deniedHosts) {
1139
- this.deniedHostsOverride = configuration.deniedHosts;
1140
- }
1141
- return this.getOutboundConfiguration();
1142
- }
1143
- /**
1144
- * Returns true if a catch-all outbound HTTP interception is needed.
1145
- * This is the case when a static `outbound` handler or a runtime
1146
- * `outboundHandlerOverride` (catch-all) is configured.
1147
- * When false, we only intercept specific hosts to avoid overhead.
1148
- */
1149
- needsCatchAllInterception() {
1150
- const ctor = this.constructor;
1151
- return ctor.outbound !== void 0 || this.outboundHandlerOverride !== void 0;
1152
- }
1153
- hasMutableOutboundConfiguration() {
1154
- return Object.keys(this.outboundByHostOverrides).length > 0 || this.allowedHostsOverride !== void 0 || this.deniedHostsOverride !== void 0;
1155
- }
1156
- shouldInterceptAllOutbound() {
1157
- return this.hasInterceptAllRegistration || this.needsCatchAllInterception() || this.effectiveAllowedHosts !== void 0 || this.effectiveDeniedHosts !== void 0 || this.hasMutableOutboundConfiguration();
1158
- }
1159
- getStaticOutboundByHostKeys() {
1160
- const ctor = this.constructor;
1161
- return ctor.outboundByHost ? Object.keys(ctor.outboundByHost) : [];
1162
- }
1163
- /**
1164
- * Collects all hostnames that need per-host outbound interception.
1165
- * This path is only used for the narrow optimized case where outbound
1166
- * handling is static and host-specific.
1167
- */
1168
- getHostsToIntercept() {
1169
- const hosts = /* @__PURE__ */ new Set();
1170
- const ctor = this.constructor;
1171
- if (ctor.outboundByHost) {
1172
- for (const hostname3 of Object.keys(ctor.outboundByHost)) {
1173
- hosts.add(hostname3);
1174
- }
1175
- }
1176
- for (const hostname3 of Object.keys(this.outboundByHostOverrides)) {
1177
- hosts.add(hostname3);
1178
- }
1179
- return [...hosts];
1180
- }
1181
- async refreshOutboundInterception() {
1182
- if (!this.usingInterception) {
1183
- return;
1184
- }
1185
- this.applyOutboundInterceptionPromise = this.applyOutboundInterception();
1186
- await this.applyOutboundInterceptionPromise;
1187
- }
1188
- /**
1189
- * Applies (or re-applies) outbound HTTP interception with the current
1190
- * default registries + runtime overrides passed through ContainerProxy props.
1191
- *
1192
- * Uses per-host interception only for static host-specific outbound handlers.
1193
- * As soon as the config needs to evaluate all hosts (catch-all outbound,
1194
- * allow/deny lists, or runtime-mutated outbound config), we promote the
1195
- * container to intercept-all and keep it there until the instance restarts.
1196
- *
1197
- * When `interceptHttps` is enabled, also applies HTTPS interception:
1198
- * - Intercept-all mode: `interceptOutboundHttps('*', ...)` for all HTTPS traffic
1199
- * - Per-host mode: `interceptOutboundHttps(host, ...)` for each known host
1200
- */
1201
- async applyOutboundInterception() {
1202
- const ctx = this.ctx;
1203
- if (ctx.exports === void 0) {
1204
- throw new Error("ctx.exports is undefined, please try to update your compatibility date or export ContainerProxy from the containers package in your worker entrypoint");
1205
- }
1206
- if (ctx.exports.ContainerProxy === void 0) {
1207
- throw new Error("ctx.exports.ContainerProxy is undefined, export ContainerProxy from the containers package in your worker entrypoint");
1208
- }
1209
- const interceptAll = this.shouldInterceptAllOutbound();
1210
- if (interceptAll) {
1211
- this.hasInterceptAllRegistration = interceptAll;
1212
- }
1213
- const outboundConfiguration = this.getOutboundConfiguration();
1214
- this.persistOutboundConfiguration(outboundConfiguration);
1215
- const hosts = this.getHostsToIntercept();
1216
- const props = {
1217
- enableInternet: this.enableInternet,
1218
- containerId: this.ctx.id.toString(),
1219
- className: this.constructor.name,
1220
- outboundByHostOverrides: outboundConfiguration.outboundByHostOverrides,
1221
- outboundHandlerOverride: outboundConfiguration.outboundHandlerOverride,
1222
- allowedHosts: outboundConfiguration.allowedHosts,
1223
- deniedHosts: outboundConfiguration.deniedHosts,
1224
- interceptAll
1225
- };
1226
- const fetcher = ctx.exports.ContainerProxy({
1227
- props
1228
- });
1229
- if (interceptAll) {
1230
- for (const host of this.getStaticOutboundByHostKeys()) {
1231
- await this.container.interceptOutboundHttp(host, fetcher);
1232
- if (this.interceptHttps) {
1233
- await this.container.interceptOutboundHttps(host, fetcher);
1234
- }
1235
- }
1236
- if (this.interceptHttps) {
1237
- await this.container.interceptOutboundHttps("*", fetcher);
1238
- }
1239
- await this.container.interceptAllOutboundHttp(fetcher);
1240
- } else {
1241
- for (const host of hosts) {
1242
- await this.container.interceptOutboundHttp(host, fetcher);
1243
- if (this.interceptHttps) {
1244
- await this.container.interceptOutboundHttps(host, fetcher);
1245
- }
1246
- }
1247
- }
1248
- }
1249
- /**
1250
- * Execute SQL queries against the Container's database
1251
- */
1252
- sql(strings2, ...values) {
1253
- const query = strings2.reduce((acc, str, i) => acc + str + (i < values.length ? "?" : ""), "");
1254
- return [...this.ctx.storage.sql.exec(query, ...values)];
1255
- }
1256
- requestAndPortFromContainerFetchArgs(requestOrUrl, portOrInit, portParam) {
1257
- let request;
1258
- let port;
1259
- if (requestOrUrl instanceof Request) {
1260
- request = requestOrUrl;
1261
- port = typeof portOrInit === "number" ? portOrInit : void 0;
1262
- } else {
1263
- const url2 = typeof requestOrUrl === "string" ? requestOrUrl : requestOrUrl.toString();
1264
- const init = typeof portOrInit === "number" ? {} : portOrInit || {};
1265
- port = typeof portOrInit === "number" ? portOrInit : typeof portParam === "number" ? portParam : void 0;
1266
- request = new Request(url2, init);
1267
- }
1268
- port ??= this.defaultPort;
1269
- if (port === void 0) {
1270
- throw new Error("No port specified for container fetch. Set defaultPort or specify a port parameter.");
1271
- }
1272
- return { request, port };
1273
- }
1274
- /**
1275
- *
1276
- * The method prioritizes port sources in this order:
1277
- * 1. Ports specified directly in the method call
1278
- * 2. `requiredPorts` class property (if set)
1279
- * 3. `defaultPort` (if neither of the above is specified)
1280
- * 4. Falls back to port 33 if none of the above are set
1281
- */
1282
- async getPortsToCheck(overridePorts) {
1283
- if (overridePorts !== void 0) {
1284
- return Array.isArray(overridePorts) ? overridePorts : [overridePorts];
1285
- }
1286
- if (this.requiredPorts && this.requiredPorts.length > 0) {
1287
- return [...this.requiredPorts];
1288
- }
1289
- return [this.defaultPort ?? FALLBACK_PORT_TO_CHECK];
1290
- }
1291
- // ===========================================
1292
- // CONTAINER INTERACTION & MONITORING
1293
- // ===========================================
1294
- /**
1295
- * Tries to start a container if it's not already running
1296
- * Returns the number of tries used
1297
- */
1298
- async startContainerIfNotRunning(waitOptions, options) {
1299
- if (this.startInFlight) {
1300
- return this.startInFlight;
1301
- }
1302
- if (this.container.running) {
1303
- if (!this.monitor) {
1304
- this.monitor = this.container.monitor();
1305
- }
1306
- return 0;
1307
- }
1308
- const startPromise = this.doStartContainer(waitOptions, options);
1309
- this.startInFlight = startPromise;
1310
- try {
1311
- return await startPromise;
1312
- } finally {
1313
- if (this.startInFlight === startPromise) {
1314
- this.startInFlight = void 0;
1315
- }
1316
- }
1317
- }
1318
- async doStartContainer(waitOptions, options) {
1319
- const abortedSignal = new Promise((res) => {
1320
- waitOptions.signal?.addEventListener("abort", () => {
1321
- res(true);
1322
- });
1323
- });
1324
- const pollInterval = waitOptions.waitInterval ?? INSTANCE_POLL_INTERVAL_MS;
1325
- const totalTries = waitOptions.retries ?? Math.ceil(TIMEOUT_TO_GET_CONTAINER_MS / pollInterval);
1326
- for (let tries = 0; tries < totalTries; tries++) {
1327
- const envVars = options?.envVars ?? this.envVars;
1328
- const entrypoint = options?.entrypoint ?? this.entrypoint;
1329
- const enableInternet = options?.enableInternet ?? this.enableInternet;
1330
- const labels = options?.labels ?? this.labels;
1331
- const startConfig = {
1332
- enableInternet
1333
- };
1334
- if (envVars && Object.keys(envVars).length > 0)
1335
- startConfig.env = envVars;
1336
- if (entrypoint)
1337
- startConfig.entrypoint = entrypoint;
1338
- if (labels && Object.keys(labels).length > 0)
1339
- startConfig.labels = labels;
1340
- this.renewActivityTimeout();
1341
- const handleError = async () => {
1342
- const err = await this.monitor?.catch((err2) => err2);
1343
- if (typeof err === "number") {
1344
- const toThrow = new Error(`Container exited before we could determine the container health, exit code: ${err}`);
1345
- await this.state.setStoppedWithCode(err);
1346
- this.monitor = void 0;
1347
- try {
1348
- await this.onError(toThrow);
1349
- } catch {
1350
- }
1351
- throw toThrow;
1352
- } else if (!isNoInstanceError(err)) {
1353
- await this.state.setStopped();
1354
- this.monitor = void 0;
1355
- try {
1356
- await this.onError(err);
1357
- } catch {
1358
- }
1359
- throw err;
1360
- }
1361
- };
1362
- if (tries > 0 && !this.container.running) {
1363
- await handleError();
1364
- }
1365
- await this.scheduleNextAlarm();
1366
- if (!this.container.running) {
1367
- await this.refreshOutboundInterception();
1368
- this.container.start(startConfig);
1369
- this.monitor = this.container.monitor();
1370
- await this.state.setRunning();
1371
- } else {
1372
- await this.scheduleNextAlarm();
1373
- }
1374
- this.renewActivityTimeout();
1375
- const port = this.container.getTcpPort(waitOptions.portToCheck);
1376
- try {
1377
- const combinedSignal = addTimeoutSignal(waitOptions.signal, PING_TIMEOUT_MS);
1378
- await port.fetch("http://containerstarthealthcheck", { signal: combinedSignal });
1379
- return tries;
1380
- } catch (error61) {
1381
- if (isNotListeningError(error61) && this.container.running) {
1382
- return tries;
1383
- }
1384
- if (!this.container.running && isNotListeningError(error61)) {
1385
- await handleError();
1386
- }
1387
- await Promise.any([
1388
- new Promise((res) => setTimeout(res, waitOptions.waitInterval)),
1389
- abortedSignal
1390
- ]);
1391
- if (waitOptions.signal?.aborted) {
1392
- throw new Error("Aborted waiting for container to start as we received a cancellation signal", { cause: error61 });
1393
- }
1394
- if (totalTries === tries + 1) {
1395
- if (error61 instanceof Error && error61.message.includes("Network connection lost")) {
1396
- this.ctx.abort();
1397
- }
1398
- await handleError();
1399
- await this.state.setStopped();
1400
- this.monitor = void 0;
1401
- throw new Error(NO_CONTAINER_INSTANCE_ERROR, { cause: error61 });
1402
- }
1403
- continue;
1404
- }
1405
- }
1406
- throw new Error(`Container did not start after ${totalTries * pollInterval}ms`);
1407
- }
1408
- setupMonitorCallbacks() {
1409
- const monitor = this.monitor;
1410
- if (!monitor || this.monitoredPromise === monitor) {
1411
- return;
1412
- }
1413
- this.monitoredPromise = monitor;
1414
- monitor.then(async () => {
1415
- await this.ctx.blockConcurrencyWhile(async () => {
1416
- if (this.monitor === monitor) {
1417
- await this.state.setStoppedWithCode(0);
1418
- }
1419
- });
1420
- }).catch(async (error61) => {
1421
- if (this.monitor !== monitor) {
1422
- return;
1423
- }
1424
- if (isNoInstanceError(error61)) {
1425
- await this.ctx.blockConcurrencyWhile(async () => {
1426
- if (this.monitor === monitor) {
1427
- await this.state.setStopped();
1428
- }
1429
- });
1430
- return;
1431
- }
1432
- const exitCode = getExitCodeFromError(error61);
1433
- if (exitCode !== null) {
1434
- await this.ctx.blockConcurrencyWhile(async () => {
1435
- if (this.monitor === monitor) {
1436
- await this.state.setStoppedWithCode(exitCode);
1437
- }
1438
- });
1439
- return;
1440
- }
1441
- await this.ctx.blockConcurrencyWhile(async () => {
1442
- if (this.monitor === monitor) {
1443
- await this.state.setStopped();
1444
- }
1445
- });
1446
- if (this.monitor !== monitor) {
1447
- return;
1448
- }
1449
- try {
1450
- await this.onError(error61);
1451
- } catch {
1452
- }
1453
- }).finally(() => {
1454
- if (this.monitor !== monitor) {
1455
- return;
1456
- }
1457
- this.monitoredPromise = void 0;
1458
- this.monitor = void 0;
1459
- if (this.timeout) {
1460
- if (this.resolve)
1461
- this.resolve();
1462
- clearTimeout(this.timeout);
1463
- }
1464
- });
1465
- }
1466
- deleteSchedules(name) {
1467
- this.sql`DELETE FROM container_schedules WHERE callback = ${name}`;
1468
- }
1469
- // ============================
1470
- // ALARMS AND SCHEDULES
1471
- // ============================
1472
- /**
1473
- * Method called when an alarm fires
1474
- * Executes any scheduled tasks that are due
1475
- */
1476
- async alarm(alarmProps) {
1477
- if (alarmProps !== void 0 && alarmProps.isRetry && alarmProps.retryCount > MAX_ALARM_RETRIES) {
1478
- const scheduleCount = Number(this.sql`SELECT COUNT(*) as count FROM container_schedules`[0]?.count) || 0;
1479
- const hasScheduledTasks = scheduleCount > 0;
1480
- if (hasScheduledTasks || this.container.running) {
1481
- await this.scheduleNextAlarm();
1482
- }
1483
- return;
1484
- }
1485
- const prevAlarm = Date.now();
1486
- await this.ctx.storage.setAlarm(prevAlarm);
1487
- await this.ctx.storage.sync();
1488
- const result = this.sql`
1489
- SELECT * FROM container_schedules;
1490
- `;
1491
- let minTime = Date.now() + 3 * 60 * 1e3;
1492
- const now = Date.now() / 1e3;
1493
- for (const row of result) {
1494
- if (row.time > now) {
1495
- continue;
1496
- }
1497
- const callback = this[row.callback];
1498
- if (!callback || typeof callback !== "function") {
1499
- console.error(`Callback ${row.callback} not found or is not a function`);
1500
- continue;
1501
- }
1502
- const schedule = this.getSchedule(row.id);
1503
- try {
1504
- const payload = row.payload ? JSON.parse(row.payload) : void 0;
1505
- await callback.call(this, payload, await schedule);
1506
- } catch (e) {
1507
- console.error(`Error executing scheduled callback "${row.callback}":`, e);
1508
- }
1509
- this.sql`DELETE FROM container_schedules WHERE id = ${row.id}`;
1510
- }
1511
- const resultForMinTime = this.sql`
1512
- SELECT * FROM container_schedules;
1513
- `;
1514
- const minTimeFromSchedules = Math.min(...resultForMinTime.map((r) => r.time * 1e3));
1515
- if (!this.container.running) {
1516
- await this.syncPendingStoppedEvents();
1517
- if (resultForMinTime.length == 0) {
1518
- await this.ctx.storage.deleteAlarm();
1519
- } else {
1520
- await this.ctx.storage.setAlarm(minTimeFromSchedules);
1521
- }
1522
- return;
1523
- }
1524
- if (this.isActivityExpired()) {
1525
- await this.onActivityExpired();
1526
- this.renewActivityTimeout();
1527
- return;
1528
- }
1529
- minTime = Math.min(minTimeFromSchedules, minTime, this.sleepAfterMs);
1530
- const timeout = Math.max(0, minTime - Date.now());
1531
- await new Promise((resolve) => {
1532
- this.resolve = resolve;
1533
- if (!this.container.running) {
1534
- resolve();
1535
- return;
1536
- }
1537
- this.timeout = setTimeout(() => {
1538
- resolve();
1539
- }, timeout);
1540
- });
1541
- await this.ctx.storage.setAlarm(Date.now());
1542
- }
1543
- timeout;
1544
- resolve;
1545
- // synchronises container state with the container source of truth to process events
1546
- async syncPendingStoppedEvents() {
1547
- const state = await this.state.getState();
1548
- if (!this.container.running && (state.status === "healthy" || state.status === "running")) {
1549
- await this.callOnStop({ exitCode: 0, reason: "exit" }, state);
1550
- return;
1551
- }
1552
- if (!this.container.running && state.status === "stopped_with_code") {
1553
- await this.callOnStop({ exitCode: state.exitCode ?? 0, reason: "exit" }, state);
1554
- return;
1555
- }
1556
- }
1557
- async callOnStop(onStopParams, stateBeforeOnStop) {
1558
- if (this.onStopCalled) {
1559
- return;
1560
- }
1561
- this.onStopCalled = true;
1562
- const promise2 = this.onStop(onStopParams);
1563
- if (promise2 instanceof Promise) {
1564
- await promise2.finally(() => {
1565
- this.onStopCalled = false;
1566
- });
1567
- } else {
1568
- this.onStopCalled = false;
1569
- }
1570
- await this.state.setStoppedIfUnchanged(stateBeforeOnStop);
1571
- }
1572
- /**
1573
- * Schedule the next alarm based on upcoming tasks
1574
- */
1575
- async scheduleNextAlarm(ms2 = 1e3) {
1576
- const nextTime = ms2 + Date.now();
1577
- if (this.timeout) {
1578
- if (this.resolve)
1579
- this.resolve();
1580
- clearTimeout(this.timeout);
1581
- }
1582
- await this.ctx.storage.setAlarm(nextTime);
1583
- await this.ctx.storage.sync();
1584
- }
1585
- async listSchedules(name) {
1586
- const result = this.sql`
1587
- SELECT * FROM container_schedules WHERE callback = ${name} LIMIT 1
1588
- `;
1589
- if (!result || result.length === 0) {
1590
- return [];
1591
- }
1592
- return result.map(this.toSchedule);
1593
- }
1594
- toSchedule(schedule) {
1595
- let payload;
1596
- try {
1597
- payload = JSON.parse(schedule.payload);
1598
- } catch (e) {
1599
- console.error(`Error parsing payload for schedule ${schedule.id}:`, e);
1600
- payload = void 0;
1601
- }
1602
- if (schedule.type === "delayed") {
1603
- return {
1604
- taskId: schedule.id,
1605
- callback: schedule.callback,
1606
- payload,
1607
- type: "delayed",
1608
- time: schedule.time,
1609
- delayInSeconds: schedule.delayInSeconds
1610
- };
1611
- }
1612
- return {
1613
- taskId: schedule.id,
1614
- callback: schedule.callback,
1615
- payload,
1616
- type: "scheduled",
1617
- time: schedule.time
1618
- };
1619
- }
1620
- /**
1621
- * Get a scheduled task by ID
1622
- * @template T Type of the payload data
1623
- * @param id ID of the scheduled task
1624
- * @returns The Schedule object or undefined if not found
1625
- */
1626
- async getSchedule(id) {
1627
- const result = this.sql`
1628
- SELECT * FROM container_schedules WHERE id = ${id} LIMIT 1
1629
- `;
1630
- if (!result || result.length === 0) {
1631
- return void 0;
1632
- }
1633
- const schedule = result[0];
1634
- return this.toSchedule(schedule);
1635
- }
1636
- isActivityExpired() {
1637
- if (this.inflightRequests > 0) {
1638
- this.renewActivityTimeout();
1639
- return false;
1640
- }
1641
- return this.sleepAfterMs <= Date.now();
1642
- }
1643
- };
1644
157
 
1645
158
  // ../../node_modules/.pnpm/cbor-x@1.6.4/node_modules/cbor-x/decode.js
1646
159
  var decoder;
@@ -25296,10 +23809,31 @@ var EVE_HOST_DEFAULTS = {
25296
23809
  compatibilityDate: "2026-04-01",
25297
23810
  healthPath: "/eve/v1/health",
25298
23811
  internalPort: 8080,
25299
- maxInstances: 1,
25300
- instanceType: "basic",
25301
- sleepAfter: "24h"
23812
+ instance: "standard-1",
23813
+ sleepAfter: "1h"
25302
23814
  };
23815
+ var EVE_HOST_SLEEP_SNAPSHOT_MARGIN_MS = 15 * 6e4;
23816
+ var EVE_HOST_MAX_SLEEP_AFTER_MS = 6 * 36e5 - EVE_HOST_SLEEP_SNAPSHOT_MARGIN_MS;
23817
+ function parseEveSleepAfterMs(value) {
23818
+ const match = /^([0-9]+)(ms|s|m|h|d)?$/u.exec(value.trim());
23819
+ if (match === null) {
23820
+ throw new EveHostError(
23821
+ "HOST_READINESS_UNPROVEN",
23822
+ "The Container sleepAfter override is not a parseable duration."
23823
+ );
23824
+ }
23825
+ const amount = Number.parseInt(match[1] ?? "", 10);
23826
+ const unit = match[2] ?? "s";
23827
+ const factor = unit === "ms" ? 1 : unit === "s" ? 1e3 : unit === "m" ? 6e4 : unit === "h" ? 36e5 : 864e5;
23828
+ const ms2 = amount * factor;
23829
+ if (ms2 > EVE_HOST_MAX_SLEEP_AFTER_MS) {
23830
+ throw new EveHostError(
23831
+ "HOST_READINESS_UNPROVEN",
23832
+ "The Container sleepAfter override exceeds 345m (5 h 45 min); Cloudflare stops a container within 6 hours of its Durable Object going idle, so Eden must snapshot before then."
23833
+ );
23834
+ }
23835
+ return ms2;
23836
+ }
25303
23837
  var EVE_SCHEDULE_WAKE_LEAD_MS = 24e4;
25304
23838
  var EVE_SCHEDULE_WAKE_GRACE_MS = 6e4;
25305
23839
  var MINUTE_MS = 6e4;
@@ -25432,15 +23966,7 @@ function isEveWorkflowInternalRoute(pathname) {
25432
23966
  }
25433
23967
  var EVE_HOST_OWNED_HEADERS = [
25434
23968
  "forwarded",
25435
- "x-forwarded-for",
25436
- "x-forwarded-host",
25437
- "x-forwarded-port",
25438
- "x-forwarded-proto",
25439
- "x-forwarded-server",
25440
- "x-forwarded-scheme",
25441
23969
  "x-real-ip",
25442
- "cf-connecting-ip",
25443
- "cf-visitor",
25444
23970
  "true-client-ip",
25445
23971
  "x-original-host",
25446
23972
  "x-original-proto",
@@ -25449,24 +23975,11 @@ var EVE_HOST_OWNED_HEADERS = [
25449
23975
  "x-proxy-host",
25450
23976
  "x-host",
25451
23977
  "x-eve-public-origin",
25452
- "x-workflow-local-base-url",
25453
- "x-eden-eve-callback-base",
25454
- "x-eden-eve-deployment-id",
25455
- "x-eden-eve-generation-id",
25456
- "x-eden-eve-image",
25457
- "x-eden-eve-started-deployment",
25458
- "x-eden-eve-public-origin",
25459
- "x-eden-eve-correlation-id",
25460
- "x-eden-eve-container-name",
25461
- "x-eden-eve-container-id",
25462
- "x-eden-eve-runtime-revision",
25463
- "x-eden-container-name",
25464
- "x-eden-container-id",
25465
- "cf-container-target-port"
23978
+ "x-workflow-local-base-url"
25466
23979
  ];
25467
23980
  var EVE_HOST_OWNED_HEADER_SET = new Set(EVE_HOST_OWNED_HEADERS);
25468
23981
  var WORKER_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
25469
- var SUBDOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
23982
+ var SUBDOMAIN_PATTERN = WORKER_NAME_PATTERN;
25470
23983
  var IDENTIFIER_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/u;
25471
23984
  var EveHostError = class extends Error {
25472
23985
  code;
@@ -25556,9 +24069,6 @@ function createTrustedEveRequest(request, metadata) {
25556
24069
  headers.set("x-eden-eve-deployment-id", metadata.deploymentId);
25557
24070
  headers.set("x-eden-eve-generation-id", metadata.generationId);
25558
24071
  headers.set("x-eden-eve-correlation-id", metadata.correlationId);
25559
- if (metadata.containerImage !== void 0) {
25560
- headers.set("x-eden-eve-image", metadata.containerImage);
25561
- }
25562
24072
  if (metadata.runtimeRevisionHandle !== void 0) {
25563
24073
  headers.set(
25564
24074
  "x-eden-eve-runtime-revision",
@@ -25582,21 +24092,6 @@ function throwIfAborted(signal) {
25582
24092
  );
25583
24093
  }
25584
24094
  }
25585
- function createEveHostLifecycleObserver(now = Date.now) {
25586
- const events = [];
25587
- return {
25588
- events,
25589
- record(type, safeStatus) {
25590
- const event = {
25591
- type,
25592
- at: now(),
25593
- ...safeStatus === void 0 ? {} : { safeStatus }
25594
- };
25595
- events.push(event);
25596
- return event;
25597
- }
25598
- };
25599
- }
25600
24095
  function responseBodyIsReady(value) {
25601
24096
  if (typeof value !== "object" || value === null) return false;
25602
24097
  const record2 = value;
@@ -25670,8 +24165,7 @@ function raceWithAbort(promise2, signal) {
25670
24165
  function createEveReadinessGate(options) {
25671
24166
  const port = options.port ?? EVE_HOST_DEFAULTS.internalPort;
25672
24167
  const healthPath = options.healthPath ?? EVE_HOST_DEFAULTS.healthPath;
25673
- const instanceGetTimeoutMs = options.instanceGetTimeoutMs ?? 12e4;
25674
- const portReadyTimeoutMs = options.portReadyTimeoutMs ?? 3e4;
24168
+ const readinessTimeoutMs = options.readinessTimeoutMs ?? 15e4;
25675
24169
  const healthTimeoutMs = options.healthTimeoutMs ?? 1e4;
25676
24170
  const waitIntervalMs = options.waitIntervalMs ?? 300;
25677
24171
  let evidence;
@@ -25679,111 +24173,121 @@ function createEveReadinessGate(options) {
25679
24173
  let inFlightController;
25680
24174
  let generation = 0;
25681
24175
  const run = async (signal) => {
25682
- try {
25683
- await options.startAndWaitForPorts({
25684
- ports: port,
25685
- cancellationOptions: {
25686
- abort: signal,
25687
- instanceGetTimeoutMS: instanceGetTimeoutMs,
25688
- portReadyTimeoutMS: portReadyTimeoutMs,
25689
- waitInterval: waitIntervalMs
25690
- }
24176
+ const deadline = Date.now() + readinessTimeoutMs;
24177
+ let lastFailure;
24178
+ const sleep = () => new Promise((resolve, reject) => {
24179
+ const timer = setTimeout(resolve, waitIntervalMs);
24180
+ signal.addEventListener("abort", () => {
24181
+ clearTimeout(timer);
24182
+ reject(
24183
+ new EveHostError(
24184
+ "HOST_REQUEST_ABORTED",
24185
+ "The client request was cancelled before Eve became ready."
24186
+ )
24187
+ );
24188
+ }, { once: true });
24189
+ });
24190
+ const probe = async () => {
24191
+ const healthController = new AbortController();
24192
+ let rejectHealthTimeout;
24193
+ const abortHealth = () => {
24194
+ healthController.abort();
24195
+ rejectHealthTimeout?.(
24196
+ new EveHostError(
24197
+ "HOST_REQUEST_ABORTED",
24198
+ "The client request was cancelled before Eve became ready."
24199
+ )
24200
+ );
24201
+ };
24202
+ signal.addEventListener("abort", abortHealth, { once: true });
24203
+ const healthTimeoutResult = new Promise((_resolve, reject) => {
24204
+ rejectHealthTimeout = reject;
25691
24205
  });
25692
- } catch {
25693
- if (signal.aborted) {
25694
- throw new EveHostError(
25695
- "HOST_REQUEST_ABORTED",
25696
- "The client request was cancelled before Eve became ready."
24206
+ const healthTimeout = setTimeout(() => {
24207
+ healthController.abort();
24208
+ rejectHealthTimeout?.(
24209
+ new EveHostError(
24210
+ "HOST_READINESS_UNPROVEN",
24211
+ "The bounded Eve health probe timed out."
24212
+ )
25697
24213
  );
24214
+ }, healthTimeoutMs);
24215
+ let response;
24216
+ try {
24217
+ const healthRequest = new Request(`http://localhost${healthPath}`, {
24218
+ method: "GET",
24219
+ signal: healthController.signal
24220
+ });
24221
+ const healthResult = options.healthFetch(healthRequest);
24222
+ response = await Promise.race([healthResult, healthTimeoutResult]);
24223
+ } catch {
24224
+ return void 0;
24225
+ } finally {
24226
+ clearTimeout(healthTimeout);
24227
+ signal.removeEventListener("abort", abortHealth);
25698
24228
  }
25699
- throw new EveHostError(
25700
- "HOST_READINESS_UNPROVEN",
25701
- "The Eve Container did not reach its internal port readiness deadline."
25702
- );
25703
- }
25704
- const healthController = new AbortController();
25705
- let rejectHealthTimeout;
25706
- const abortHealth = () => {
25707
- healthController.abort();
25708
- rejectHealthTimeout?.(
25709
- new EveHostError(
25710
- "HOST_REQUEST_ABORTED",
25711
- "The client request was cancelled before Eve became ready."
25712
- )
25713
- );
24229
+ if (response.status !== 200) {
24230
+ await response.arrayBuffer().catch(() => void 0);
24231
+ lastFailure = new EveHostError(
24232
+ "HOST_READINESS_UNPROVEN",
24233
+ "The Eve health route did not return the expected successful status."
24234
+ );
24235
+ return void 0;
24236
+ }
24237
+ if (!(response.headers.get("content-type") ?? "").toLowerCase().startsWith("application/json")) {
24238
+ await response.arrayBuffer().catch(() => void 0);
24239
+ lastFailure = new EveHostError(
24240
+ "HOST_READINESS_UNPROVEN",
24241
+ "The Eve health route did not return the expected JSON contract."
24242
+ );
24243
+ return void 0;
24244
+ }
24245
+ let body;
24246
+ try {
24247
+ body = await response.json();
24248
+ } catch {
24249
+ lastFailure = new EveHostError(
24250
+ "HOST_READINESS_UNPROVEN",
24251
+ "The Eve health route did not return a valid ready response."
24252
+ );
24253
+ return void 0;
24254
+ }
24255
+ if (!responseBodyIsReady(body)) {
24256
+ lastFailure = new EveHostError(
24257
+ "HOST_READINESS_UNPROVEN",
24258
+ "The Eve health route is reachable but has not reported ready."
24259
+ );
24260
+ return void 0;
24261
+ }
24262
+ return {
24263
+ healthPath,
24264
+ healthStatus: "ready",
24265
+ healthVerified: true,
24266
+ port,
24267
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString()
24268
+ };
25714
24269
  };
25715
- signal.addEventListener("abort", abortHealth, { once: true });
25716
- const healthTimeoutResult = new Promise((_resolve, reject) => {
25717
- rejectHealthTimeout = reject;
25718
- });
25719
- const healthTimeout = setTimeout(() => {
25720
- healthController.abort();
25721
- rejectHealthTimeout?.(
25722
- new EveHostError(
24270
+ for (; ; ) {
24271
+ throwIfAborted(signal);
24272
+ try {
24273
+ await options.start(signal);
24274
+ } catch (error61) {
24275
+ throwIfAborted(signal);
24276
+ lastFailure = error61 instanceof EveHostError ? error61 : new EveHostError(
25723
24277
  "HOST_READINESS_UNPROVEN",
25724
- "The bounded Eve health probe timed out."
25725
- )
25726
- );
25727
- }, healthTimeoutMs);
25728
- let response;
25729
- try {
25730
- const healthRequest = new Request(`http://localhost${healthPath}`, {
25731
- method: "GET",
25732
- signal: healthController.signal
25733
- });
25734
- const healthResult = options.healthFetch(healthRequest);
25735
- response = await Promise.race([healthResult, healthTimeoutResult]);
25736
- } catch {
25737
- if (signal.aborted) {
25738
- throw new EveHostError(
25739
- "HOST_REQUEST_ABORTED",
25740
- "The client request was cancelled before Eve became ready."
24278
+ "The Eve Container could not be scheduled for start."
25741
24279
  );
25742
24280
  }
25743
- throw new EveHostError(
25744
- "HOST_READINESS_UNPROVEN",
25745
- "The bounded Eve health probe did not complete."
25746
- );
25747
- } finally {
25748
- clearTimeout(healthTimeout);
25749
- signal.removeEventListener("abort", abortHealth);
25750
- }
25751
- if (response.status !== 200) {
25752
- await response.arrayBuffer().catch(() => void 0);
25753
- throw new EveHostError(
25754
- "HOST_READINESS_UNPROVEN",
25755
- "The Eve health route did not return the expected successful status."
25756
- );
25757
- }
25758
- if (!(response.headers.get("content-type") ?? "").toLowerCase().startsWith("application/json")) {
25759
- await response.arrayBuffer().catch(() => void 0);
25760
- throw new EveHostError(
25761
- "HOST_READINESS_UNPROVEN",
25762
- "The Eve health route did not return the expected JSON contract."
25763
- );
25764
- }
25765
- let body;
25766
- try {
25767
- body = await response.json();
25768
- } catch {
25769
- throw new EveHostError(
25770
- "HOST_READINESS_UNPROVEN",
25771
- "The Eve health route did not return a valid ready response."
25772
- );
25773
- }
25774
- if (!responseBodyIsReady(body)) {
25775
- throw new EveHostError(
25776
- "HOST_READINESS_UNPROVEN",
25777
- "The Eve health route is reachable but has not reported ready."
25778
- );
24281
+ const result = await probe();
24282
+ if (result !== void 0) return result;
24283
+ if (Date.now() >= deadline) {
24284
+ throw lastFailure ?? new EveHostError(
24285
+ "HOST_READINESS_UNPROVEN",
24286
+ "The Eve Container did not reach its readiness deadline."
24287
+ );
24288
+ }
24289
+ await sleep();
25779
24290
  }
25780
- return {
25781
- healthPath,
25782
- healthStatus: "ready",
25783
- healthVerified: true,
25784
- port,
25785
- checkedAt: (/* @__PURE__ */ new Date()).toISOString()
25786
- };
25787
24291
  };
25788
24292
  const gate = ((signal) => {
25789
24293
  throwIfAborted(signal);
@@ -25819,6 +24323,23 @@ function createEveReadinessGate(options) {
25819
24323
 
25820
24324
  // src/eve-host-runtime.ts
25821
24325
  var EVE_CLOUDFLARE_CONTAINERS_CA_PATH = "/etc/cloudflare/certs/cloudflare-containers-ca.crt";
24326
+ var EVE_HOST_ENTRYPOINT = Object.freeze([
24327
+ "/bin/sh",
24328
+ "-c",
24329
+ "rm -f /dev/kvm; cd /workspace && exec ./node_modules/.bin/eve start --host 0.0.0.0 --port 8080"
24330
+ ]);
24331
+ var EVE_HOST_CONTAINER_ACTIVITY_KEY = "eden.eve.host.last-activity-at";
24332
+ var EVE_HOST_CONTAINER_SNAPSHOT_KEY = "eden.eve.host.workspace-snapshot";
24333
+ var EVE_HOST_CONTAINER_SNAPSHOT_ATTEMPTS_KEY = "eden.eve.host.snapshot-attempts";
24334
+ var EVE_HOST_CONTAINER_STARTED_IMAGE_KEY = "eden.eve.host.started-image";
24335
+ var EVE_HOST_SANDBOX_CARRY_KEY = "eden.eve.host.sandbox-carry";
24336
+ var EVE_HOST_SANDBOX_CARRY_CHUNK_PREFIX = "eden.eve.host.sandbox-carry";
24337
+ var EVE_HOST_SANDBOX_CARRY_SOURCE = "/workspace/.eve/sandbox-cache/just-bash";
24338
+ var EVE_HOST_CARRY_LIMITS = {
24339
+ chunkBytes: 1024 * 1024,
24340
+ maxBytes: 1024 * 1024 * 1024
24341
+ };
24342
+ var EVE_HOST_SNAPSHOT_MAX_ATTEMPTS = 3;
25822
24343
  var EdenWorldDurableObject = class {
25823
24344
  core;
25824
24345
  constructor(ctx, env) {
@@ -25834,13 +24355,12 @@ var EdenWorldDurableObject = class {
25834
24355
  delivery: {
25835
24356
  deliver: async (message) => {
25836
24357
  const origin = env.EVE_PUBLIC_ORIGIN;
25837
- const binding = env.EVE_CONTAINER_BINDING_NAME;
25838
24358
  const instance = env.EVE_CONTAINER_INSTANCE_NAME;
25839
- if (typeof origin !== "string" || typeof binding !== "string" || typeof instance !== "string") {
24359
+ if (typeof origin !== "string" || typeof instance !== "string") {
25840
24360
  throw new Error("The World queue Container identity is unavailable.");
25841
24361
  }
25842
- const namespace = env[binding];
25843
- const response = await namespace.getByName(instance).containerFetch(
24362
+ const namespace = env.EVE_CONTAINER;
24363
+ const response = await namespace.getByName(instance).loopbackFetch(
25844
24364
  new Request(new URL(`/.well-known/workflow/v1/${message.path}`, origin), {
25845
24365
  method: "POST",
25846
24366
  headers: {
@@ -25851,8 +24371,7 @@ var EdenWorldDurableObject = class {
25851
24371
  "x-vqs-message-attempt": String(message.attempt)
25852
24372
  },
25853
24373
  body: message.body
25854
- }),
25855
- EVE_HOST_DEFAULTS.internalPort
24374
+ })
25856
24375
  );
25857
24376
  const body = await response.text();
25858
24377
  let result = null;
@@ -25883,16 +24402,14 @@ var EdenWorldDurableObject = class {
25883
24402
  };
25884
24403
  async function routeEveOutboundRequest(request, env) {
25885
24404
  const publicOrigin = env.EVE_PUBLIC_ORIGIN;
25886
- const bindingName = env.EVE_CONTAINER_BINDING_NAME;
25887
24405
  const instanceName = env.EVE_CONTAINER_INSTANCE_NAME;
25888
- if (typeof publicOrigin !== "string" || typeof bindingName !== "string" || typeof instanceName !== "string") {
24406
+ if (typeof publicOrigin !== "string" || typeof instanceName !== "string") {
25889
24407
  throw new EveHostError(
25890
24408
  "HOST_ORIGIN_UNAVAILABLE",
25891
24409
  "The container loopback identity is unavailable to the outbound handler."
25892
24410
  );
25893
24411
  }
25894
24412
  assertStableOrigin(publicOrigin);
25895
- assertNonEmpty(bindingName, "Container binding name");
25896
24413
  assertNonEmpty(instanceName, "Container instance name");
25897
24414
  const hostname3 = new URL(request.url).hostname;
25898
24415
  if (hostname3 !== new URL(publicOrigin).hostname) {
@@ -25903,37 +24420,40 @@ async function routeEveOutboundRequest(request, env) {
25903
24420
  if (world === void 0) return new Response(null, { status: 404 });
25904
24421
  return world.get(world.idFromName("world")).fetch(request);
25905
24422
  }
25906
- const namespace = env[bindingName];
24423
+ const namespace = env.EVE_CONTAINER;
25907
24424
  if (namespace === void 0) {
25908
24425
  throw new EveHostError(
25909
24426
  "HOST_READINESS_UNPROVEN",
25910
24427
  "The configured Container binding is unavailable to the outbound handler."
25911
24428
  );
25912
24429
  }
25913
- return namespace.getByName(instanceName).containerFetch(request, EVE_HOST_DEFAULTS.internalPort);
25914
- }
25915
- var EVE_HOST_CONTAINER_DEPLOYMENT_KEY = "eden.eve.host.started-deployment";
25916
- var EVE_HOST_CONTAINER_RESTART_ATTEMPT_KEY = "eden.eve.host.restart-attempted-at";
25917
- function containerRepositoryName(image) {
25918
- return (image.split("@")[0] ?? "").split(":")[0] ?? "";
25919
- }
25920
- var EveHostContainer = class extends Container {
25921
- defaultPort = EVE_HOST_DEFAULTS.internalPort;
25922
- sleepAfter = EVE_HOST_DEFAULTS.sleepAfter;
25923
- requiredPorts = [EVE_HOST_DEFAULTS.internalPort];
25924
- interceptHttps = true;
25925
- enableInternet = true;
25926
- pingEndpoint = "localhost/eve/v1/health";
25927
- lifecycle = createEveHostLifecycleObserver();
25928
- readinessStarted = false;
25929
- /** Evidence is cached only under the deployment whose image was verified. */
24430
+ return namespace.getByName(instanceName).loopbackFetch(request);
24431
+ }
24432
+ var EveHostLoopback = class extends WorkerEntrypoint {
24433
+ async fetch(request) {
24434
+ return routeEveOutboundRequest(request, this.env);
24435
+ }
24436
+ };
24437
+ var EveHostDurableContainer = class extends DurableObject {
24438
+ /** Evidence is cached only while the container it was proven on keeps running. */
25930
24439
  readinessEvidence;
24440
+ /** True once the running container's image was proven to equal `images.eve`. */
24441
+ imageVerified = false;
25931
24442
  /**
25932
24443
  * Bumped whenever the Container stops or is reset. Readiness work captures
25933
- * the epoch it started under and may only record a marker or cache
25934
- * evidence if no stop happened in between.
24444
+ * the epoch it started under and may only cache evidence if no stop
24445
+ * happened in between.
25935
24446
  */
25936
24447
  readinessEpoch = 0;
24448
+ monitorAttached = false;
24449
+ /** Serializes sandbox-session carry-outs on this Durable Object instance. */
24450
+ carryOutQueue = Promise.resolve();
24451
+ /** True only while the last start was fresh from `images.eve`, not a snapshot. */
24452
+ pendingCarryRestore = false;
24453
+ /** Shared single-flight carry restore for the current container generation. */
24454
+ carryRestorePromise;
24455
+ envVars;
24456
+ sleepAfterMs;
25937
24457
  readiness;
25938
24458
  constructor(ctx, env) {
25939
24459
  super(ctx, env);
@@ -25968,136 +24488,386 @@ var EveHostContainer = class extends Container {
25968
24488
  NODE_EXTRA_CA_CERTS: EVE_CLOUDFLARE_CONTAINERS_CA_PATH,
25969
24489
  ...env.EDEN_EVE_RUNTIME_REVISION === void 0 ? {} : { EDEN_EVE_RUNTIME_REVISION: env.EDEN_EVE_RUNTIME_REVISION }
25970
24490
  };
25971
- const sleepAfterOverride = env.EDEN_EVE_CONTAINER_SLEEP_AFTER;
25972
- if (sleepAfterOverride !== void 0) {
25973
- this.sleepAfter = sleepAfterOverride;
25974
- }
24491
+ this.sleepAfterMs = parseEveSleepAfterMs(
24492
+ env.EDEN_EVE_CONTAINER_SLEEP_AFTER ?? EVE_HOST_DEFAULTS.sleepAfter
24493
+ );
25975
24494
  this.readiness = createEveReadinessGate({
25976
- startAndWaitForPorts: (options) => this.startAndWaitForPorts(options),
25977
- healthFetch: (request) => this.containerFetch(request, EVE_HOST_DEFAULTS.internalPort)
24495
+ start: async () => {
24496
+ await this.ensureContainerStarted();
24497
+ },
24498
+ healthFetch: (request) => {
24499
+ const container = this.containerRuntime();
24500
+ if (container === void 0) {
24501
+ throw new EveHostError(
24502
+ "HOST_READINESS_UNPROVEN",
24503
+ "The Container runtime is unavailable."
24504
+ );
24505
+ }
24506
+ const url2 = new URL(request.url);
24507
+ return container.getTcpPort(EVE_HOST_DEFAULTS.internalPort).fetch(
24508
+ new Request(`http://container${url2.pathname}${url2.search}`, request)
24509
+ );
24510
+ }
25978
24511
  });
24512
+ const runtime = this.containerRuntime();
24513
+ if (runtime?.running === true) {
24514
+ this.ctx.blockConcurrencyWhile(async () => {
24515
+ await runtime.setInactivityTimeout(this.inactivityTimeoutMs);
24516
+ this.attachMonitor(runtime);
24517
+ });
24518
+ }
24519
+ }
24520
+ containerRuntime() {
24521
+ return this.ctx.container;
24522
+ }
24523
+ /** Container lifetime the platform keeps after the DO goes inactive: long
24524
+ * enough for the idle alarm to snapshot first, within Cloudflare's 6 h cap. */
24525
+ get inactivityTimeoutMs() {
24526
+ return this.sleepAfterMs + EVE_HOST_SLEEP_SNAPSHOT_MARGIN_MS;
24527
+ }
24528
+ attachMonitor(runtime) {
24529
+ if (this.monitorAttached) return;
24530
+ this.monitorAttached = true;
24531
+ runtime.monitor().then(
24532
+ () => {
24533
+ this.monitorAttached = false;
24534
+ this.recordContainerStopped();
24535
+ },
24536
+ () => {
24537
+ this.monitorAttached = false;
24538
+ this.recordContainerStopped();
24539
+ }
24540
+ );
24541
+ }
24542
+ recordContainerStopped() {
24543
+ this.readinessEpoch += 1;
24544
+ this.readinessEvidence = void 0;
24545
+ this.imageVerified = false;
24546
+ this.pendingCarryRestore = false;
24547
+ this.carryRestorePromise = void 0;
24548
+ this.readiness.reset();
24549
+ }
24550
+ /** Routes the container's own requests to its public origin back inside. */
24551
+ async registerLoopbackIntercept(runtime) {
24552
+ const exportsMap = this.ctx.exports;
24553
+ const entryFactory = exportsMap?.["EveHostLoopback"];
24554
+ if (typeof entryFactory !== "function") return;
24555
+ const entrypoint = entryFactory({ props: {} });
24556
+ await runtime.interceptOutboundHttps(
24557
+ new URL(this.env.EVE_PUBLIC_ORIGIN ?? "").hostname,
24558
+ entrypoint
24559
+ );
25979
24560
  }
25980
24561
  /**
25981
- * Compares the deployment the running Container was started under (stored
25982
- * in Durable Object storage, which survives Worker redeploys) against the
25983
- * deployment the *current* Worker stamps on the forwarded request. A
25984
- * stale Durable Object still detects the update because the header is
25985
- * stamped by new Worker code, not this code's environment.
25986
- *
25987
- * DO-managed Container instances are excluded from the application's fleet
25988
- * rollout — the image is only re-selected on the next
25989
- * `ctx.container.start()` — so an update must stop the instance itself.
25990
- * A missing marker means the running image cannot be trusted, so the
25991
- * container is restarted too (first update from runtimes that predate the
25992
- * marker). Restarts are rate-limited because Cloudflare activates a new
25993
- * Worker before the image rollout lands; starting in that window would
25994
- * re-launch the *old* image, so the deployment marker is only recorded
25995
- * after `inspect()` proves the running image is the expected one.
24562
+ * Records request activity and arms the sleep alarm at
24563
+ * `lastActivityAt + sleepAfter`. The alarm — not the inactivity timeout —
24564
+ * is what snapshots the writable filesystem before the container stops.
25996
24565
  */
25997
- async reconcileStartedDeployment(requestDeploymentId, requestImage) {
25998
- if (requestDeploymentId === void 0) return;
25999
- const storage = this.ctx?.storage;
26000
- if (storage === void 0 || typeof storage.get !== "function" || typeof storage.put !== "function") {
26001
- return;
24566
+ async touchActivity() {
24567
+ const now = Date.now();
24568
+ await this.ctx.storage.put(EVE_HOST_CONTAINER_ACTIVITY_KEY, now);
24569
+ await this.ctx.storage.setAlarm(now + this.sleepAfterMs);
24570
+ }
24571
+ /**
24572
+ * Starts the container when it is not running. A stored workspace snapshot
24573
+ * is restored only when it was captured from the exact image this Worker
24574
+ * version configures — restoring an older snapshot silently runs the
24575
+ * previous image — so after an image update the container starts fresh and
24576
+ * the readiness path restores the carried sandbox sessions instead.
24577
+ */
24578
+ async ensureContainerStarted() {
24579
+ const runtime = this.containerRuntime();
24580
+ if (runtime === void 0) {
24581
+ throw new EveHostError(
24582
+ "HOST_READINESS_UNPROVEN",
24583
+ "The Container runtime is unavailable on this Durable Object."
24584
+ );
24585
+ }
24586
+ if (runtime.running) return;
24587
+ const expectedImage = runtime.images["eve"];
24588
+ if (expectedImage === void 0) {
24589
+ throw new EveHostError(
24590
+ "HOST_READINESS_UNPROVEN",
24591
+ "The configured Container image is unavailable to this Worker version."
24592
+ );
26002
24593
  }
26003
- const lastStarted = await storage.get(
26004
- EVE_HOST_CONTAINER_DEPLOYMENT_KEY
24594
+ const storedSnapshot = await this.ctx.storage.get(
24595
+ EVE_HOST_CONTAINER_SNAPSHOT_KEY
26005
24596
  );
26006
- if (lastStarted === requestDeploymentId) return;
26007
- const runtime = this.ctx?.container;
26008
- if (runtime?.running !== true) return;
26009
- if (requestImage !== void 0 && await this.containerServesImage(runtime, requestImage) === true) {
26010
- await storage.put(EVE_HOST_CONTAINER_DEPLOYMENT_KEY, requestDeploymentId);
24597
+ const snapshotId = storedSnapshot !== void 0 && storedSnapshot.image === expectedImage ? storedSnapshot.id : void 0;
24598
+ runtime.start({
24599
+ ...snapshotId === void 0 ? { image: expectedImage } : { containerSnapshot: { id: snapshotId } },
24600
+ instance: EVE_HOST_DEFAULTS.instance,
24601
+ enableInternet: true,
24602
+ env: this.envVars,
24603
+ entrypoint: EVE_HOST_ENTRYPOINT
24604
+ });
24605
+ this.pendingCarryRestore = snapshotId === void 0;
24606
+ await this.ctx.storage.put(EVE_HOST_CONTAINER_STARTED_IMAGE_KEY, expectedImage);
24607
+ await this.registerLoopbackIntercept(runtime);
24608
+ this.attachMonitor(runtime);
24609
+ await runtime.setInactivityTimeout(this.inactivityTimeoutMs);
24610
+ }
24611
+ /**
24612
+ * Replaces the running container when it still serves a pre-update image:
24613
+ * this Worker version's `images.eve` is selected at `start()`, so an
24614
+ * in-place update must stop the stale instance itself. `inspect()` reports
24615
+ * an empty image for a snapshot-restored container, so the image recorded
24616
+ * at start stands in for it.
24617
+ */
24618
+ async reconcileRunningImage() {
24619
+ if (this.imageVerified) return;
24620
+ const runtime = this.containerRuntime();
24621
+ if (runtime === void 0 || !runtime.running) return;
24622
+ const expectedImage = runtime.images["eve"];
24623
+ let info;
24624
+ try {
24625
+ info = await runtime.inspect();
24626
+ } catch {
24627
+ info = null;
24628
+ }
24629
+ const runningImage = info?.image !== void 0 && info.image !== "" ? info.image : await this.ctx.storage.get(EVE_HOST_CONTAINER_STARTED_IMAGE_KEY);
24630
+ if (runningImage === expectedImage) {
24631
+ this.imageVerified = true;
26011
24632
  return;
26012
24633
  }
26013
- const attemptedAt = await storage.get(
26014
- EVE_HOST_CONTAINER_RESTART_ATTEMPT_KEY
26015
- );
26016
- const now = Date.now();
26017
- if (attemptedAt !== void 0 && now - attemptedAt < 3e4) return;
26018
- await storage.put(EVE_HOST_CONTAINER_RESTART_ATTEMPT_KEY, now);
26019
- this.lifecycle.record("replaced");
26020
- this.readinessEpoch += 1;
26021
- this.readinessStarted = false;
26022
- this.readinessEvidence = void 0;
26023
- this.readiness.reset();
26024
- await this.stop();
24634
+ this.recordContainerStopped();
24635
+ try {
24636
+ await this.carrySandboxSessionsOut(runtime);
24637
+ } catch (error61) {
24638
+ console.error(
24639
+ "The Eve sandbox session carry failed before the image update:",
24640
+ error61 instanceof Error ? error61.message : "unknown"
24641
+ );
24642
+ }
24643
+ await runtime.destroy();
26025
24644
  const stoppedAt = Date.now();
26026
24645
  while (runtime.running && Date.now() - stoppedAt < 1e4) {
26027
24646
  await new Promise((resolve) => setTimeout(resolve, 25));
26028
24647
  }
26029
24648
  }
26030
- async containerServesImage(runtime, expectedImage) {
26031
- const inspect = runtime.inspect;
26032
- if (typeof inspect !== "function") return void 0;
26033
- let info;
24649
+ /**
24650
+ * Streams `/workspace/.eve/sandbox-cache/just-bash/sessions` — every
24651
+ * conversation's sandbox files and metadata — into Durable Object storage,
24652
+ * so a fresh container started by an image update can restore them. Not
24653
+ * carried: templates and the rest of `/workspace`, which come from the new
24654
+ * image. One carry runs at a time on this Durable Object; a failure never
24655
+ * blocks the destroy that follows and leaves the previous carry intact.
24656
+ */
24657
+ carrySandboxSessionsOut(runtime) {
24658
+ const run = this.carryOutQueue.then(
24659
+ () => this.carrySandboxSessionsOutNow(runtime)
24660
+ );
24661
+ this.carryOutQueue = run.then(
24662
+ () => void 0,
24663
+ () => void 0
24664
+ );
24665
+ return run;
24666
+ }
24667
+ async carrySandboxSessionsOutNow(runtime) {
24668
+ const previous = await this.ctx.storage.get(
24669
+ EVE_HOST_SANDBOX_CARRY_KEY
24670
+ );
24671
+ const carryId = globalThis.crypto.randomUUID();
24672
+ const chunkPrefix = `${EVE_HOST_SANDBOX_CARRY_CHUNK_PREFIX}.${carryId}.`;
24673
+ const writtenChunkKeys = [];
24674
+ const discardWrittenChunks = async () => {
24675
+ for (const key of writtenChunkKeys) await this.ctx.storage.delete(key);
24676
+ };
24677
+ const exec = await runtime.exec(
24678
+ [
24679
+ "sh",
24680
+ "-c",
24681
+ `cd ${EVE_HOST_SANDBOX_CARRY_SOURCE} && [ -d sessions ] && tar -czf - sessions || true`
24682
+ ],
24683
+ { stdout: "pipe", stderr: "pipe" }
24684
+ );
24685
+ const buffered = [];
24686
+ let bufferedBytes = 0;
24687
+ let chunks = 0;
24688
+ let bytes2 = 0;
24689
+ const flushOnce = async () => {
24690
+ if (bufferedBytes === 0) return;
24691
+ const size = Math.min(bufferedBytes, EVE_HOST_CARRY_LIMITS.chunkBytes);
24692
+ const value = new Uint8Array(size);
24693
+ let offset = 0;
24694
+ while (offset < size) {
24695
+ const part = buffered[0];
24696
+ if (part === void 0) break;
24697
+ const take = Math.min(part.byteLength, size - offset);
24698
+ value.set(
24699
+ take === part.byteLength ? part : part.subarray(0, take),
24700
+ offset
24701
+ );
24702
+ offset += take;
24703
+ if (take === part.byteLength) buffered.shift();
24704
+ else buffered[0] = part.subarray(take);
24705
+ }
24706
+ bufferedBytes -= size;
24707
+ const key = `${chunkPrefix}${chunks}`;
24708
+ writtenChunkKeys.push(key);
24709
+ await this.ctx.storage.put(key, value);
24710
+ chunks += 1;
24711
+ bytes2 += value.byteLength;
24712
+ };
24713
+ const flushBufferedChunks = async () => {
24714
+ while (bufferedBytes >= EVE_HOST_CARRY_LIMITS.chunkBytes) {
24715
+ await flushOnce();
24716
+ }
24717
+ };
24718
+ try {
24719
+ const stdout = exec.stdout;
24720
+ if (stdout === null) throw new Error("the exec stdout was not piped");
24721
+ const reader = stdout.getReader();
24722
+ let overflowed = false;
24723
+ for (; ; ) {
24724
+ const { done, value } = await reader.read();
24725
+ if (done) break;
24726
+ if (value === void 0) continue;
24727
+ buffered.push(value);
24728
+ bufferedBytes += value.byteLength;
24729
+ if (bytes2 + bufferedBytes > EVE_HOST_CARRY_LIMITS.maxBytes) {
24730
+ overflowed = true;
24731
+ break;
24732
+ }
24733
+ await flushBufferedChunks();
24734
+ }
24735
+ await reader.cancel().catch(() => void 0);
24736
+ if (overflowed) {
24737
+ await discardWrittenChunks();
24738
+ console.error(
24739
+ `The Eve sandbox session carry exceeded ${EVE_HOST_CARRY_LIMITS.maxBytes} compressed bytes; keeping the previous carry.`
24740
+ );
24741
+ return;
24742
+ }
24743
+ await flushOnce();
24744
+ } catch (error61) {
24745
+ await discardWrittenChunks();
24746
+ throw error61;
24747
+ }
24748
+ let exitCode = -1;
26034
24749
  try {
26035
- info = await inspect.call(runtime);
24750
+ exitCode = await exec.exitCode;
26036
24751
  } catch {
26037
- return void 0;
24752
+ exitCode = -1;
24753
+ }
24754
+ if (exitCode !== 0) {
24755
+ await discardWrittenChunks();
24756
+ console.error(
24757
+ `The Eve sandbox session carry failed with exit code ${exitCode}; keeping the previous carry.`
24758
+ );
24759
+ return;
24760
+ }
24761
+ if (bytes2 === 0) {
24762
+ return;
24763
+ }
24764
+ await this.ctx.storage.put(EVE_HOST_SANDBOX_CARRY_KEY, {
24765
+ id: carryId,
24766
+ chunks,
24767
+ bytes: bytes2,
24768
+ at: Date.now()
24769
+ });
24770
+ if (previous !== void 0) {
24771
+ for (let index = 0; index < previous.chunks; index += 1) {
24772
+ await this.ctx.storage.delete(
24773
+ `${EVE_HOST_SANDBOX_CARRY_CHUNK_PREFIX}.${previous.id}.${index}`
24774
+ );
24775
+ }
26038
24776
  }
26039
- if (info?.image === void 0) return void 0;
26040
- return containerRepositoryName(info.image) === containerRepositoryName(expectedImage);
26041
24777
  }
26042
24778
  /**
26043
- * Records the started deployment only when the running Container provably
26044
- * serves this deployment's image (`inspect()` matches the forwarded
26045
- * `x-eden-eve-image`). `false` or unknown (no `inspect`, a throwing call,
26046
- * or no image field) never records — a start inside the
26047
- * Worker-active-before-image-rollout window must not pin the old image.
26048
- * When the Worker stamps no image, the marker is recorded unverified,
26049
- * matching pre-drift behavior.
24779
+ * Single restore per fresh container generation, shared by every
24780
+ * concurrent readiness caller: the first caller starts it, everyone awaits
24781
+ * the same promise, and no request is forwarded before it settles.
26050
24782
  */
26051
- async recordStartedDeployment(requestDeploymentId, requestImage) {
26052
- if (requestDeploymentId === void 0) return true;
26053
- const storage = this.ctx?.storage;
26054
- if (storage === void 0 || typeof storage.get !== "function" || typeof storage.put !== "function") {
26055
- return true;
26056
- }
26057
- const runtime = this.ctx?.container;
26058
- if (requestImage !== void 0) {
26059
- if (runtime?.running !== true) {
26060
- this.lifecycle.record("image_mismatch");
26061
- return false;
24783
+ async restoreCarriedSandboxSessions() {
24784
+ if (!this.pendingCarryRestore) return;
24785
+ this.carryRestorePromise ??= this.carrySandboxSessionsIn();
24786
+ await this.carryRestorePromise;
24787
+ this.pendingCarryRestore = false;
24788
+ }
24789
+ /**
24790
+ * Extracts the carried sandbox sessions into a container that started
24791
+ * fresh from `images.eve`. The archive streams chunk by chunk from Durable
24792
+ * Object storage through exec stdin, so it never sits in isolate memory. A
24793
+ * failure is logged and swallowed: the agent still serves, only the
24794
+ * carried files are missing.
24795
+ */
24796
+ async carrySandboxSessionsIn() {
24797
+ try {
24798
+ const carry = await this.ctx.storage.get(
24799
+ EVE_HOST_SANDBOX_CARRY_KEY
24800
+ );
24801
+ if (carry === void 0) return;
24802
+ let nextChunk = 0;
24803
+ const archive = new ReadableStream({
24804
+ pull: async (controller) => {
24805
+ if (nextChunk >= carry.chunks) {
24806
+ controller.close();
24807
+ return;
24808
+ }
24809
+ const chunk = await this.ctx.storage.get(
24810
+ `${EVE_HOST_SANDBOX_CARRY_CHUNK_PREFIX}.${carry.id}.${nextChunk}`
24811
+ );
24812
+ const index = nextChunk;
24813
+ nextChunk += 1;
24814
+ if (chunk === void 0) {
24815
+ controller.error(
24816
+ new Error(`The sandbox carry chunk ${index} is missing.`)
24817
+ );
24818
+ return;
24819
+ }
24820
+ controller.enqueue(chunk);
24821
+ }
24822
+ });
24823
+ const runtime = this.containerRuntime();
24824
+ if (runtime === void 0) {
24825
+ throw new Error("the Container runtime is unavailable");
24826
+ }
24827
+ const exec = await runtime.exec(
24828
+ [
24829
+ "sh",
24830
+ "-c",
24831
+ `mkdir -p ${EVE_HOST_SANDBOX_CARRY_SOURCE} && tar -xzf - -C ${EVE_HOST_SANDBOX_CARRY_SOURCE}`
24832
+ ],
24833
+ { stdin: archive, stderr: "pipe" }
24834
+ );
24835
+ let exitCode = -1;
24836
+ try {
24837
+ exitCode = await exec.exitCode;
24838
+ } catch {
24839
+ exitCode = -1;
26062
24840
  }
26063
- const verified = await this.containerServesImage(runtime, requestImage);
26064
- if (verified !== true) {
26065
- this.lifecycle.record("image_mismatch");
26066
- return false;
24841
+ if (exitCode !== 0) {
24842
+ console.error(
24843
+ `The Eve sandbox session restore failed with exit code ${exitCode}; the agent serves without the carried files.`
24844
+ );
26067
24845
  }
24846
+ } catch (error61) {
24847
+ console.error(
24848
+ "The Eve sandbox session restore failed; the agent serves without the carried files:",
24849
+ error61 instanceof Error ? error61.message : "unknown"
24850
+ );
26068
24851
  }
26069
- await storage.put(EVE_HOST_CONTAINER_DEPLOYMENT_KEY, requestDeploymentId);
26070
- return true;
26071
24852
  }
26072
- async ensureEveReady(signal = new AbortController().signal, requestDeploymentId, requestImage) {
26073
- await this.reconcileStartedDeployment(requestDeploymentId, requestImage);
26074
- if (this.readinessEvidence !== void 0 && this.readinessEvidence.deploymentId === requestDeploymentId) {
26075
- return this.readinessEvidence.evidence;
26076
- }
26077
- if (!this.readinessStarted) {
26078
- this.readinessStarted = true;
26079
- this.lifecycle.record("start_requested");
24853
+ async ensureEveReady(signal = new AbortController().signal) {
24854
+ await this.reconcileRunningImage();
24855
+ if (this.readinessEvidence !== void 0) {
24856
+ return this.readinessEvidence;
26080
24857
  }
26081
24858
  const epoch = this.readinessEpoch;
26082
24859
  const evidence = await this.readiness(signal);
26083
- if (epoch === this.readinessEpoch && await this.recordStartedDeployment(requestDeploymentId, requestImage) && epoch === this.readinessEpoch) {
26084
- this.readinessEvidence = {
26085
- deploymentId: requestDeploymentId,
26086
- evidence
26087
- };
24860
+ if (epoch === this.readinessEpoch) {
24861
+ await this.restoreCarriedSandboxSessions();
24862
+ this.readinessEvidence = evidence;
24863
+ this.imageVerified = true;
26088
24864
  }
26089
- this.lifecycle.record("health_ready", evidence.healthStatus);
26090
24865
  return evidence;
26091
24866
  }
26092
24867
  async fetch(request) {
26093
24868
  const requestDeploymentId = request.headers.get("x-eden-eve-deployment-id") ?? void 0;
26094
- await this.ensureEveReady(
26095
- request.signal,
26096
- requestDeploymentId,
26097
- request.headers.get("x-eden-eve-image") ?? void 0
26098
- );
26099
- const response = await super.fetch(request);
26100
- if (this.readinessEvidence !== void 0 && this.readinessEvidence.deploymentId === requestDeploymentId && requestDeploymentId !== void 0) {
24869
+ const response = await this.forwardToEve(request);
24870
+ if (requestDeploymentId !== void 0 && requestDeploymentId === this.env.EDEN_EVE_DEPLOYMENT_ID && this.readinessEvidence !== void 0 && this.imageVerified) {
26101
24871
  const headers = new Headers(response.headers);
26102
24872
  headers.set("x-eden-eve-started-deployment", requestDeploymentId);
26103
24873
  return new Response(response.body, {
@@ -26108,33 +24878,101 @@ var EveHostContainer = class extends Container {
26108
24878
  }
26109
24879
  return response;
26110
24880
  }
26111
- onStart() {
26112
- if (this.lifecycle.events.some((event) => event.type === "started")) {
26113
- this.lifecycle.record("replaced");
24881
+ /**
24882
+ * Queue deliveries and loopback traffic enter here: same readiness and
24883
+ * forwarding as `fetch` without the deployment-header echo rules (the
24884
+ * loopback path is not a deployment-health signal).
24885
+ */
24886
+ async loopbackFetch(request) {
24887
+ return this.forwardToEve(request);
24888
+ }
24889
+ async forwardToEve(request) {
24890
+ await this.ensureEveReady(request.signal);
24891
+ await this.touchActivity();
24892
+ const runtime = this.containerRuntime();
24893
+ if (runtime === void 0) {
24894
+ throw new EveHostError(
24895
+ "HOST_READINESS_UNPROVEN",
24896
+ "The Container runtime is unavailable on this Durable Object."
24897
+ );
26114
24898
  }
26115
- this.lifecycle.record("started");
26116
- }
26117
- onStop(params) {
26118
- this.readinessEpoch += 1;
26119
- this.readinessStarted = false;
26120
- this.readinessEvidence = void 0;
26121
- this.readiness.reset();
26122
- this.lifecycle.record("stopped", `${params.reason}:${params.exitCode}`);
26123
- }
26124
- onError(error61) {
26125
- this.readinessEpoch += 1;
26126
- this.readinessStarted = false;
26127
- this.readinessEvidence = void 0;
26128
- this.readiness.reset();
26129
- this.lifecycle.record(
26130
- "errored",
26131
- error61 instanceof Error ? error61.name : "unknown"
26132
- );
26133
- throw new EveHostError(
26134
- "HOST_READINESS_UNPROVEN",
26135
- "The Eve Container supervisor reported an error."
24899
+ const url2 = new URL(request.url);
24900
+ return runtime.getTcpPort(EVE_HOST_DEFAULTS.internalPort).fetch(
24901
+ new Request(`http://container${url2.pathname}${url2.search}`, request)
26136
24902
  );
26137
24903
  }
24904
+ /**
24905
+ * The idle-sleep path: once the container has been quiet for `sleepAfter`,
24906
+ * snapshot the writable filesystem (so `/workspace` survives the sleep)
24907
+ * and destroy the instance. A snapshot failure retries up to
24908
+ * `EVE_HOST_SNAPSHOT_MAX_ATTEMPTS` times, then destroys anyway so billing
24909
+ * for the running container stops.
24910
+ */
24911
+ async alarm() {
24912
+ const runtime = this.containerRuntime();
24913
+ const lastActivity = await this.ctx.storage.get(EVE_HOST_CONTAINER_ACTIVITY_KEY) ?? 0;
24914
+ const now = Date.now();
24915
+ if (now - lastActivity < this.sleepAfterMs) {
24916
+ await this.ctx.storage.setAlarm(lastActivity + this.sleepAfterMs);
24917
+ return;
24918
+ }
24919
+ if (runtime === void 0 || !runtime.running) return;
24920
+ try {
24921
+ await this.carrySandboxSessionsOut(runtime);
24922
+ } catch (error61) {
24923
+ console.error(
24924
+ "The Eve sandbox session carry failed during idle sleep:",
24925
+ error61 instanceof Error ? error61.message : "unknown"
24926
+ );
24927
+ }
24928
+ const attempts = await this.ctx.storage.get(
24929
+ EVE_HOST_CONTAINER_SNAPSHOT_ATTEMPTS_KEY
24930
+ ) ?? 0;
24931
+ try {
24932
+ const snapshot = await runtime.snapshotContainer({
24933
+ name: "eden-workspace"
24934
+ });
24935
+ const image = (await runtime.inspect().catch(() => null))?.image ?? runtime.images["eve"] ?? "";
24936
+ const record2 = {
24937
+ id: snapshot.id,
24938
+ image,
24939
+ at: now
24940
+ };
24941
+ await this.ctx.storage.put(EVE_HOST_CONTAINER_SNAPSHOT_KEY, record2);
24942
+ await this.ctx.storage.put(EVE_HOST_CONTAINER_SNAPSHOT_ATTEMPTS_KEY, 0);
24943
+ const activityAfterSnapshot = await this.ctx.storage.get(EVE_HOST_CONTAINER_ACTIVITY_KEY) ?? 0;
24944
+ if (activityAfterSnapshot !== lastActivity) {
24945
+ await this.ctx.storage.setAlarm(activityAfterSnapshot + this.sleepAfterMs);
24946
+ return;
24947
+ }
24948
+ await runtime.destroy(new Error("idle-snapshot-done"));
24949
+ this.recordContainerStopped();
24950
+ } catch (error61) {
24951
+ const message = error61 instanceof Error ? error61.message : "unknown";
24952
+ if (attempts + 1 >= EVE_HOST_SNAPSHOT_MAX_ATTEMPTS) {
24953
+ console.error(
24954
+ `The Eve workspace snapshot failed ${attempts + 1} times; destroying the container without it: ${message}`
24955
+ );
24956
+ await this.ctx.storage.put(
24957
+ EVE_HOST_CONTAINER_SNAPSHOT_ATTEMPTS_KEY,
24958
+ 0
24959
+ );
24960
+ await runtime.destroy(
24961
+ new Error("idle-snapshot-abandoned")
24962
+ );
24963
+ this.recordContainerStopped();
24964
+ return;
24965
+ }
24966
+ console.error(
24967
+ `The Eve workspace snapshot failed (attempt ${attempts + 1}): ${message}`
24968
+ );
24969
+ await this.ctx.storage.put(
24970
+ EVE_HOST_CONTAINER_SNAPSHOT_ATTEMPTS_KEY,
24971
+ attempts + 1
24972
+ );
24973
+ await this.ctx.storage.setAlarm(now + 6e4);
24974
+ }
24975
+ }
26138
24976
  };
26139
24977
  function createEveHostWorker(options) {
26140
24978
  if (!WORKER_NAME_PATTERN.test(options.workerName)) {
@@ -26145,15 +24983,9 @@ function createEveHostWorker(options) {
26145
24983
  }
26146
24984
  assertStableOrigin(options.publicOrigin, options.workerName);
26147
24985
  assertNonEmpty(options.stableContainerInstanceName, "Container instance name");
26148
- if (!IDENTIFIER_PATTERN.test(options.containerBindingName)) {
26149
- throw new EveHostError(
26150
- "HOST_READINESS_UNPROVEN",
26151
- "The Container binding name is not valid."
26152
- );
26153
- }
26154
24986
  const schedules = options.schedules ?? [];
26155
24987
  const resolveContainer = (env) => {
26156
- const namespace = env[options.containerBindingName];
24988
+ const namespace = env.EVE_CONTAINER;
26157
24989
  if (namespace === void 0) {
26158
24990
  throw new EveHostError(
26159
24991
  "HOST_READINESS_UNPROVEN",
@@ -26173,7 +25005,6 @@ function createEveHostWorker(options) {
26173
25005
  deploymentId: options.deploymentId,
26174
25006
  generationId: options.generationId,
26175
25007
  correlationId: globalThis.crypto.randomUUID(),
26176
- ...options.containerImage === void 0 ? {} : { containerImage: options.containerImage },
26177
25008
  ...options.runtimeRevisionHandle === void 0 ? {} : { runtimeRevisionHandle: options.runtimeRevisionHandle }
26178
25009
  });
26179
25010
  const response = await container.fetch(forwarded);
@@ -26208,16 +25039,7 @@ function createEveHostWorker(options) {
26208
25039
  if (!due) return;
26209
25040
  ctx.waitUntil(
26210
25041
  resolveContainer(env).fetch(new Request(
26211
- new URL(EVE_HOST_DEFAULTS.healthPath, options.publicOrigin),
26212
- {
26213
- headers: {
26214
- // Stamp the Worker's own deployment so a stale Durable
26215
- // Object never falls back to its own environment when
26216
- // deciding whether to restart the running Container.
26217
- "x-eden-eve-deployment-id": options.deploymentId,
26218
- ...options.containerImage === void 0 ? {} : { "x-eden-eve-image": options.containerImage }
26219
- }
26220
- }
25042
+ new URL(EVE_HOST_DEFAULTS.healthPath, options.publicOrigin)
26221
25043
  )).catch((error61) => {
26222
25044
  console.error(
26223
25045
  "The scheduled wake request failed:",
@@ -26230,9 +25052,10 @@ function createEveHostWorker(options) {
26230
25052
  };
26231
25053
  }
26232
25054
  export {
26233
- ContainerProxy,
25055
+ EVE_HOST_CARRY_LIMITS,
26234
25056
  EdenWorldDurableObject,
26235
- EveHostContainer,
25057
+ EveHostDurableContainer,
25058
+ EveHostLoopback,
26236
25059
  createEveHostWorker,
26237
25060
  routeEveOutboundRequest
26238
25061
  };