@moinulmoin/eden-runtime-cloudflare 0.4.1 → 0.6.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.
- package/NOTICE +0 -9
- package/dist/eden-eve-host-worker.mjs +415 -1637
- package/dist/eve-host-runtime.d.ts +82 -24
- package/dist/eve-host-runtime.js +335 -49
- package/dist/eve-host.d.ts +46 -29
- package/dist/eve-host.js +162 -114
- package/dist/index.d.ts +1 -1
- package/package.json +3 -4
|
@@ -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
|
-
//
|
|
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
|
-
//
|
|
156
|
-
|
|
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
|
|
192
|
-
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
|
-
};
|
|
155
|
+
// src/eve-host-runtime.ts
|
|
156
|
+
import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";
|
|
1644
157
|
|
|
1645
158
|
// ../../node_modules/.pnpm/cbor-x@1.6.4/node_modules/cbor-x/decode.js
|
|
1646
159
|
var decoder;
|
|
@@ -25296,8 +23809,7 @@ var EVE_HOST_DEFAULTS = {
|
|
|
25296
23809
|
compatibilityDate: "2026-04-01",
|
|
25297
23810
|
healthPath: "/eve/v1/health",
|
|
25298
23811
|
internalPort: 8080,
|
|
25299
|
-
|
|
25300
|
-
instanceType: "basic",
|
|
23812
|
+
instance: "standard-1",
|
|
25301
23813
|
sleepAfter: "24h"
|
|
25302
23814
|
};
|
|
25303
23815
|
var EVE_SCHEDULE_WAKE_LEAD_MS = 24e4;
|
|
@@ -25453,13 +23965,12 @@ var EVE_HOST_OWNED_HEADERS = [
|
|
|
25453
23965
|
"x-eden-eve-callback-base",
|
|
25454
23966
|
"x-eden-eve-deployment-id",
|
|
25455
23967
|
"x-eden-eve-generation-id",
|
|
23968
|
+
"x-eden-eve-started-deployment",
|
|
25456
23969
|
"x-eden-eve-public-origin",
|
|
25457
23970
|
"x-eden-eve-correlation-id",
|
|
25458
23971
|
"x-eden-eve-container-name",
|
|
25459
23972
|
"x-eden-eve-container-id",
|
|
25460
23973
|
"x-eden-eve-runtime-revision",
|
|
25461
|
-
"x-eden-deployment-id",
|
|
25462
|
-
"x-eden-generation-id",
|
|
25463
23974
|
"x-eden-container-name",
|
|
25464
23975
|
"x-eden-container-id",
|
|
25465
23976
|
"cf-container-target-port"
|
|
@@ -25667,8 +24178,7 @@ function raceWithAbort(promise2, signal) {
|
|
|
25667
24178
|
function createEveReadinessGate(options) {
|
|
25668
24179
|
const port = options.port ?? EVE_HOST_DEFAULTS.internalPort;
|
|
25669
24180
|
const healthPath = options.healthPath ?? EVE_HOST_DEFAULTS.healthPath;
|
|
25670
|
-
const
|
|
25671
|
-
const portReadyTimeoutMs = options.portReadyTimeoutMs ?? 3e4;
|
|
24181
|
+
const readinessTimeoutMs = options.readinessTimeoutMs ?? 15e4;
|
|
25672
24182
|
const healthTimeoutMs = options.healthTimeoutMs ?? 1e4;
|
|
25673
24183
|
const waitIntervalMs = options.waitIntervalMs ?? 300;
|
|
25674
24184
|
let evidence;
|
|
@@ -25676,111 +24186,121 @@ function createEveReadinessGate(options) {
|
|
|
25676
24186
|
let inFlightController;
|
|
25677
24187
|
let generation = 0;
|
|
25678
24188
|
const run = async (signal) => {
|
|
25679
|
-
|
|
25680
|
-
|
|
25681
|
-
|
|
25682
|
-
|
|
25683
|
-
|
|
25684
|
-
|
|
25685
|
-
|
|
25686
|
-
|
|
25687
|
-
|
|
24189
|
+
const deadline = Date.now() + readinessTimeoutMs;
|
|
24190
|
+
let lastFailure;
|
|
24191
|
+
const sleep = () => new Promise((resolve, reject) => {
|
|
24192
|
+
const timer = setTimeout(resolve, waitIntervalMs);
|
|
24193
|
+
signal.addEventListener("abort", () => {
|
|
24194
|
+
clearTimeout(timer);
|
|
24195
|
+
reject(
|
|
24196
|
+
new EveHostError(
|
|
24197
|
+
"HOST_REQUEST_ABORTED",
|
|
24198
|
+
"The client request was cancelled before Eve became ready."
|
|
24199
|
+
)
|
|
24200
|
+
);
|
|
24201
|
+
}, { once: true });
|
|
24202
|
+
});
|
|
24203
|
+
const probe = async () => {
|
|
24204
|
+
const healthController = new AbortController();
|
|
24205
|
+
let rejectHealthTimeout;
|
|
24206
|
+
const abortHealth = () => {
|
|
24207
|
+
healthController.abort();
|
|
24208
|
+
rejectHealthTimeout?.(
|
|
24209
|
+
new EveHostError(
|
|
24210
|
+
"HOST_REQUEST_ABORTED",
|
|
24211
|
+
"The client request was cancelled before Eve became ready."
|
|
24212
|
+
)
|
|
24213
|
+
);
|
|
24214
|
+
};
|
|
24215
|
+
signal.addEventListener("abort", abortHealth, { once: true });
|
|
24216
|
+
const healthTimeoutResult = new Promise((_resolve, reject) => {
|
|
24217
|
+
rejectHealthTimeout = reject;
|
|
25688
24218
|
});
|
|
25689
|
-
|
|
25690
|
-
|
|
25691
|
-
|
|
25692
|
-
|
|
25693
|
-
|
|
24219
|
+
const healthTimeout = setTimeout(() => {
|
|
24220
|
+
healthController.abort();
|
|
24221
|
+
rejectHealthTimeout?.(
|
|
24222
|
+
new EveHostError(
|
|
24223
|
+
"HOST_READINESS_UNPROVEN",
|
|
24224
|
+
"The bounded Eve health probe timed out."
|
|
24225
|
+
)
|
|
25694
24226
|
);
|
|
24227
|
+
}, healthTimeoutMs);
|
|
24228
|
+
let response;
|
|
24229
|
+
try {
|
|
24230
|
+
const healthRequest = new Request(`http://localhost${healthPath}`, {
|
|
24231
|
+
method: "GET",
|
|
24232
|
+
signal: healthController.signal
|
|
24233
|
+
});
|
|
24234
|
+
const healthResult = options.healthFetch(healthRequest);
|
|
24235
|
+
response = await Promise.race([healthResult, healthTimeoutResult]);
|
|
24236
|
+
} catch {
|
|
24237
|
+
return void 0;
|
|
24238
|
+
} finally {
|
|
24239
|
+
clearTimeout(healthTimeout);
|
|
24240
|
+
signal.removeEventListener("abort", abortHealth);
|
|
25695
24241
|
}
|
|
25696
|
-
|
|
25697
|
-
|
|
25698
|
-
|
|
25699
|
-
|
|
25700
|
-
|
|
25701
|
-
|
|
25702
|
-
|
|
25703
|
-
|
|
25704
|
-
|
|
25705
|
-
|
|
25706
|
-
new EveHostError(
|
|
25707
|
-
"
|
|
25708
|
-
"The
|
|
25709
|
-
)
|
|
25710
|
-
|
|
24242
|
+
if (response.status !== 200) {
|
|
24243
|
+
await response.arrayBuffer().catch(() => void 0);
|
|
24244
|
+
lastFailure = new EveHostError(
|
|
24245
|
+
"HOST_READINESS_UNPROVEN",
|
|
24246
|
+
"The Eve health route did not return the expected successful status."
|
|
24247
|
+
);
|
|
24248
|
+
return void 0;
|
|
24249
|
+
}
|
|
24250
|
+
if (!(response.headers.get("content-type") ?? "").toLowerCase().startsWith("application/json")) {
|
|
24251
|
+
await response.arrayBuffer().catch(() => void 0);
|
|
24252
|
+
lastFailure = new EveHostError(
|
|
24253
|
+
"HOST_READINESS_UNPROVEN",
|
|
24254
|
+
"The Eve health route did not return the expected JSON contract."
|
|
24255
|
+
);
|
|
24256
|
+
return void 0;
|
|
24257
|
+
}
|
|
24258
|
+
let body;
|
|
24259
|
+
try {
|
|
24260
|
+
body = await response.json();
|
|
24261
|
+
} catch {
|
|
24262
|
+
lastFailure = new EveHostError(
|
|
24263
|
+
"HOST_READINESS_UNPROVEN",
|
|
24264
|
+
"The Eve health route did not return a valid ready response."
|
|
24265
|
+
);
|
|
24266
|
+
return void 0;
|
|
24267
|
+
}
|
|
24268
|
+
if (!responseBodyIsReady(body)) {
|
|
24269
|
+
lastFailure = new EveHostError(
|
|
24270
|
+
"HOST_READINESS_UNPROVEN",
|
|
24271
|
+
"The Eve health route is reachable but has not reported ready."
|
|
24272
|
+
);
|
|
24273
|
+
return void 0;
|
|
24274
|
+
}
|
|
24275
|
+
return {
|
|
24276
|
+
healthPath,
|
|
24277
|
+
healthStatus: "ready",
|
|
24278
|
+
healthVerified: true,
|
|
24279
|
+
port,
|
|
24280
|
+
checkedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
24281
|
+
};
|
|
25711
24282
|
};
|
|
25712
|
-
|
|
25713
|
-
|
|
25714
|
-
|
|
25715
|
-
|
|
25716
|
-
|
|
25717
|
-
|
|
25718
|
-
|
|
25719
|
-
new EveHostError(
|
|
24283
|
+
for (; ; ) {
|
|
24284
|
+
throwIfAborted(signal);
|
|
24285
|
+
try {
|
|
24286
|
+
await options.start(signal);
|
|
24287
|
+
} catch (error61) {
|
|
24288
|
+
throwIfAborted(signal);
|
|
24289
|
+
lastFailure = error61 instanceof EveHostError ? error61 : new EveHostError(
|
|
25720
24290
|
"HOST_READINESS_UNPROVEN",
|
|
25721
|
-
"The
|
|
25722
|
-
)
|
|
25723
|
-
);
|
|
25724
|
-
}, healthTimeoutMs);
|
|
25725
|
-
let response;
|
|
25726
|
-
try {
|
|
25727
|
-
const healthRequest = new Request(`http://localhost${healthPath}`, {
|
|
25728
|
-
method: "GET",
|
|
25729
|
-
signal: healthController.signal
|
|
25730
|
-
});
|
|
25731
|
-
const healthResult = options.healthFetch(healthRequest);
|
|
25732
|
-
response = await Promise.race([healthResult, healthTimeoutResult]);
|
|
25733
|
-
} catch {
|
|
25734
|
-
if (signal.aborted) {
|
|
25735
|
-
throw new EveHostError(
|
|
25736
|
-
"HOST_REQUEST_ABORTED",
|
|
25737
|
-
"The client request was cancelled before Eve became ready."
|
|
24291
|
+
"The Eve Container could not be scheduled for start."
|
|
25738
24292
|
);
|
|
25739
24293
|
}
|
|
25740
|
-
|
|
25741
|
-
|
|
25742
|
-
|
|
25743
|
-
|
|
25744
|
-
|
|
25745
|
-
|
|
25746
|
-
|
|
25747
|
-
|
|
25748
|
-
|
|
25749
|
-
await response.arrayBuffer().catch(() => void 0);
|
|
25750
|
-
throw new EveHostError(
|
|
25751
|
-
"HOST_READINESS_UNPROVEN",
|
|
25752
|
-
"The Eve health route did not return the expected successful status."
|
|
25753
|
-
);
|
|
25754
|
-
}
|
|
25755
|
-
if (!(response.headers.get("content-type") ?? "").toLowerCase().startsWith("application/json")) {
|
|
25756
|
-
await response.arrayBuffer().catch(() => void 0);
|
|
25757
|
-
throw new EveHostError(
|
|
25758
|
-
"HOST_READINESS_UNPROVEN",
|
|
25759
|
-
"The Eve health route did not return the expected JSON contract."
|
|
25760
|
-
);
|
|
25761
|
-
}
|
|
25762
|
-
let body;
|
|
25763
|
-
try {
|
|
25764
|
-
body = await response.json();
|
|
25765
|
-
} catch {
|
|
25766
|
-
throw new EveHostError(
|
|
25767
|
-
"HOST_READINESS_UNPROVEN",
|
|
25768
|
-
"The Eve health route did not return a valid ready response."
|
|
25769
|
-
);
|
|
25770
|
-
}
|
|
25771
|
-
if (!responseBodyIsReady(body)) {
|
|
25772
|
-
throw new EveHostError(
|
|
25773
|
-
"HOST_READINESS_UNPROVEN",
|
|
25774
|
-
"The Eve health route is reachable but has not reported ready."
|
|
25775
|
-
);
|
|
24294
|
+
const result = await probe();
|
|
24295
|
+
if (result !== void 0) return result;
|
|
24296
|
+
if (Date.now() >= deadline) {
|
|
24297
|
+
throw lastFailure ?? new EveHostError(
|
|
24298
|
+
"HOST_READINESS_UNPROVEN",
|
|
24299
|
+
"The Eve Container did not reach its readiness deadline."
|
|
24300
|
+
);
|
|
24301
|
+
}
|
|
24302
|
+
await sleep();
|
|
25776
24303
|
}
|
|
25777
|
-
return {
|
|
25778
|
-
healthPath,
|
|
25779
|
-
healthStatus: "ready",
|
|
25780
|
-
healthVerified: true,
|
|
25781
|
-
port,
|
|
25782
|
-
checkedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
25783
|
-
};
|
|
25784
24304
|
};
|
|
25785
24305
|
const gate = ((signal) => {
|
|
25786
24306
|
throwIfAborted(signal);
|
|
@@ -25816,6 +24336,18 @@ function createEveReadinessGate(options) {
|
|
|
25816
24336
|
|
|
25817
24337
|
// src/eve-host-runtime.ts
|
|
25818
24338
|
var EVE_CLOUDFLARE_CONTAINERS_CA_PATH = "/etc/cloudflare/certs/cloudflare-containers-ca.crt";
|
|
24339
|
+
var EVE_HOST_CONTAINER_ACTIVITY_KEY = "eden.eve.host.last-activity-at";
|
|
24340
|
+
var EVE_HOST_CONTAINER_SNAPSHOT_KEY = "eden.eve.host.workspace-snapshot";
|
|
24341
|
+
var EVE_HOST_CONTAINER_SNAPSHOT_ATTEMPTS_KEY = "eden.eve.host.snapshot-attempts";
|
|
24342
|
+
var EVE_HOST_SNAPSHOT_MAX_ATTEMPTS = 3;
|
|
24343
|
+
function sleepAfterDurationMs(value) {
|
|
24344
|
+
const match = /^([0-9]+)(ms|s|m|h|d)?$/u.exec(value.trim());
|
|
24345
|
+
if (match === null) return void 0;
|
|
24346
|
+
const amount = Number.parseInt(match[1] ?? "", 10);
|
|
24347
|
+
const unit = match[2] ?? "s";
|
|
24348
|
+
const factor = unit === "ms" ? 1 : unit === "s" ? 1e3 : unit === "m" ? 6e4 : unit === "h" ? 36e5 : 864e5;
|
|
24349
|
+
return amount * factor;
|
|
24350
|
+
}
|
|
25819
24351
|
var EdenWorldDurableObject = class {
|
|
25820
24352
|
core;
|
|
25821
24353
|
constructor(ctx, env) {
|
|
@@ -25837,7 +24369,7 @@ var EdenWorldDurableObject = class {
|
|
|
25837
24369
|
throw new Error("The World queue Container identity is unavailable.");
|
|
25838
24370
|
}
|
|
25839
24371
|
const namespace = env[binding];
|
|
25840
|
-
const response = await namespace.getByName(instance).
|
|
24372
|
+
const response = await namespace.getByName(instance).loopbackFetch(
|
|
25841
24373
|
new Request(new URL(`/.well-known/workflow/v1/${message.path}`, origin), {
|
|
25842
24374
|
method: "POST",
|
|
25843
24375
|
headers: {
|
|
@@ -25848,8 +24380,7 @@ var EdenWorldDurableObject = class {
|
|
|
25848
24380
|
"x-vqs-message-attempt": String(message.attempt)
|
|
25849
24381
|
},
|
|
25850
24382
|
body: message.body
|
|
25851
|
-
})
|
|
25852
|
-
EVE_HOST_DEFAULTS.internalPort
|
|
24383
|
+
})
|
|
25853
24384
|
);
|
|
25854
24385
|
const body = await response.text();
|
|
25855
24386
|
let result = null;
|
|
@@ -25907,18 +24438,29 @@ async function routeEveOutboundRequest(request, env) {
|
|
|
25907
24438
|
"The configured Container binding is unavailable to the outbound handler."
|
|
25908
24439
|
);
|
|
25909
24440
|
}
|
|
25910
|
-
return namespace.getByName(instanceName).
|
|
24441
|
+
return namespace.getByName(instanceName).loopbackFetch(request);
|
|
25911
24442
|
}
|
|
25912
|
-
var
|
|
25913
|
-
|
|
25914
|
-
|
|
25915
|
-
|
|
25916
|
-
|
|
25917
|
-
|
|
25918
|
-
pingEndpoint = "localhost/eve/v1/health";
|
|
24443
|
+
var EveHostLoopback = class extends WorkerEntrypoint {
|
|
24444
|
+
async fetch(request) {
|
|
24445
|
+
return routeEveOutboundRequest(request, this.env);
|
|
24446
|
+
}
|
|
24447
|
+
};
|
|
24448
|
+
var EveHostDurableContainer = class extends DurableObject {
|
|
25919
24449
|
lifecycle = createEveHostLifecycleObserver();
|
|
25920
24450
|
readinessStarted = false;
|
|
24451
|
+
/** Evidence is cached only while the container it was proven on keeps running. */
|
|
25921
24452
|
readinessEvidence;
|
|
24453
|
+
/** True once the running container's image was proven to equal `images.eve`. */
|
|
24454
|
+
imageVerified = false;
|
|
24455
|
+
/**
|
|
24456
|
+
* Bumped whenever the Container stops or is reset. Readiness work captures
|
|
24457
|
+
* the epoch it started under and may only cache evidence if no stop
|
|
24458
|
+
* happened in between.
|
|
24459
|
+
*/
|
|
24460
|
+
readinessEpoch = 0;
|
|
24461
|
+
monitorAttached = false;
|
|
24462
|
+
envVars;
|
|
24463
|
+
sleepAfterMs;
|
|
25922
24464
|
readiness;
|
|
25923
24465
|
constructor(ctx, env) {
|
|
25924
24466
|
super(ctx, env);
|
|
@@ -25933,7 +24475,6 @@ var EveHostContainer = class extends Container {
|
|
|
25933
24475
|
}
|
|
25934
24476
|
assertStableOrigin(publicOrigin);
|
|
25935
24477
|
assertNonEmpty(deploymentId, "deployment identity");
|
|
25936
|
-
assertNonEmpty(generationId, "generation identity");
|
|
25937
24478
|
const runtimeEnv = readProtectedRuntimeVariables(env);
|
|
25938
24479
|
this.envVars = {
|
|
25939
24480
|
...runtimeEnv,
|
|
@@ -25955,15 +24496,160 @@ var EveHostContainer = class extends Container {
|
|
|
25955
24496
|
...env.EDEN_EVE_RUNTIME_REVISION === void 0 ? {} : { EDEN_EVE_RUNTIME_REVISION: env.EDEN_EVE_RUNTIME_REVISION }
|
|
25956
24497
|
};
|
|
25957
24498
|
const sleepAfterOverride = env.EDEN_EVE_CONTAINER_SLEEP_AFTER;
|
|
25958
|
-
|
|
25959
|
-
|
|
25960
|
-
|
|
24499
|
+
this.sleepAfterMs = sleepAfterOverride === void 0 ? sleepAfterDurationMs(EVE_HOST_DEFAULTS.sleepAfter) ?? 864e5 : sleepAfterDurationMs(sleepAfterOverride) ?? (() => {
|
|
24500
|
+
throw new EveHostError(
|
|
24501
|
+
"HOST_READINESS_UNPROVEN",
|
|
24502
|
+
"The Container sleepAfter override is not a parseable duration."
|
|
24503
|
+
);
|
|
24504
|
+
})();
|
|
25961
24505
|
this.readiness = createEveReadinessGate({
|
|
25962
|
-
|
|
25963
|
-
|
|
24506
|
+
start: async () => {
|
|
24507
|
+
await this.ensureContainerStarted();
|
|
24508
|
+
},
|
|
24509
|
+
healthFetch: (request) => {
|
|
24510
|
+
const container = this.containerRuntime();
|
|
24511
|
+
if (container === void 0) {
|
|
24512
|
+
throw new EveHostError(
|
|
24513
|
+
"HOST_READINESS_UNPROVEN",
|
|
24514
|
+
"The Container runtime is unavailable."
|
|
24515
|
+
);
|
|
24516
|
+
}
|
|
24517
|
+
const url2 = new URL(request.url);
|
|
24518
|
+
return container.getTcpPort(EVE_HOST_DEFAULTS.internalPort).fetch(
|
|
24519
|
+
new Request(`http://container${url2.pathname}${url2.search}`, request)
|
|
24520
|
+
);
|
|
24521
|
+
}
|
|
24522
|
+
});
|
|
24523
|
+
const runtime = this.containerRuntime();
|
|
24524
|
+
if (runtime?.running === true) {
|
|
24525
|
+
this.ctx.blockConcurrencyWhile(async () => {
|
|
24526
|
+
await runtime.setInactivityTimeout(this.inactivityTimeoutMs);
|
|
24527
|
+
this.attachMonitor(runtime);
|
|
24528
|
+
});
|
|
24529
|
+
}
|
|
24530
|
+
}
|
|
24531
|
+
containerRuntime() {
|
|
24532
|
+
return this.ctx.container;
|
|
24533
|
+
}
|
|
24534
|
+
/** Container lifetime the platform keeps after the DO goes inactive. */
|
|
24535
|
+
get inactivityTimeoutMs() {
|
|
24536
|
+
return this.sleepAfterMs + 15 * 6e4;
|
|
24537
|
+
}
|
|
24538
|
+
attachMonitor(runtime) {
|
|
24539
|
+
if (this.monitorAttached) return;
|
|
24540
|
+
this.monitorAttached = true;
|
|
24541
|
+
runtime.monitor().then(
|
|
24542
|
+
() => {
|
|
24543
|
+
this.monitorAttached = false;
|
|
24544
|
+
this.recordContainerStopped("exit");
|
|
24545
|
+
},
|
|
24546
|
+
(error61) => {
|
|
24547
|
+
this.monitorAttached = false;
|
|
24548
|
+
this.recordContainerStopped(
|
|
24549
|
+
error61 instanceof Error ? error61.name : "runtime_signal"
|
|
24550
|
+
);
|
|
24551
|
+
}
|
|
24552
|
+
);
|
|
24553
|
+
}
|
|
24554
|
+
recordContainerStopped(reason) {
|
|
24555
|
+
this.readinessEpoch += 1;
|
|
24556
|
+
this.readinessStarted = false;
|
|
24557
|
+
this.readinessEvidence = void 0;
|
|
24558
|
+
this.imageVerified = false;
|
|
24559
|
+
this.readiness.reset();
|
|
24560
|
+
this.lifecycle.record("stopped", reason);
|
|
24561
|
+
}
|
|
24562
|
+
/** Routes the container's own requests to its public origin back inside. */
|
|
24563
|
+
async registerLoopbackIntercept(runtime) {
|
|
24564
|
+
const exportsMap = this.ctx.exports;
|
|
24565
|
+
const entryFactory = exportsMap?.["EveHostLoopback"];
|
|
24566
|
+
if (typeof entryFactory !== "function") return;
|
|
24567
|
+
const entrypoint = entryFactory({ props: {} });
|
|
24568
|
+
await runtime.interceptOutboundHttps(
|
|
24569
|
+
new URL(this.env.EVE_PUBLIC_ORIGIN ?? "").hostname,
|
|
24570
|
+
entrypoint
|
|
24571
|
+
);
|
|
24572
|
+
}
|
|
24573
|
+
/**
|
|
24574
|
+
* Records request activity and arms the sleep alarm at
|
|
24575
|
+
* `lastActivityAt + sleepAfter`. The alarm — not the inactivity timeout —
|
|
24576
|
+
* is what snapshots the writable filesystem before the container stops.
|
|
24577
|
+
*/
|
|
24578
|
+
async touchActivity() {
|
|
24579
|
+
const now = Date.now();
|
|
24580
|
+
await this.ctx.storage.put(EVE_HOST_CONTAINER_ACTIVITY_KEY, now);
|
|
24581
|
+
await this.ctx.storage.setAlarm(now + this.sleepAfterMs);
|
|
24582
|
+
}
|
|
24583
|
+
/**
|
|
24584
|
+
* Starts the container when it is not running. A stored workspace snapshot
|
|
24585
|
+
* is restored only when it was captured from the exact image this Worker
|
|
24586
|
+
* version configures — restoring an older snapshot silently runs the
|
|
24587
|
+
* previous image — so after an image update the container starts fresh and
|
|
24588
|
+
* workspace files intentionally do not carry across.
|
|
24589
|
+
*/
|
|
24590
|
+
async ensureContainerStarted() {
|
|
24591
|
+
const runtime = this.containerRuntime();
|
|
24592
|
+
if (runtime === void 0) {
|
|
24593
|
+
throw new EveHostError(
|
|
24594
|
+
"HOST_READINESS_UNPROVEN",
|
|
24595
|
+
"The Container runtime is unavailable on this Durable Object."
|
|
24596
|
+
);
|
|
24597
|
+
}
|
|
24598
|
+
if (runtime.running) return;
|
|
24599
|
+
const expectedImage = runtime.images["eve"];
|
|
24600
|
+
if (expectedImage === void 0) {
|
|
24601
|
+
throw new EveHostError(
|
|
24602
|
+
"HOST_READINESS_UNPROVEN",
|
|
24603
|
+
"The configured Container image is unavailable to this Worker version."
|
|
24604
|
+
);
|
|
24605
|
+
}
|
|
24606
|
+
const storedSnapshot = await this.ctx.storage.get(
|
|
24607
|
+
EVE_HOST_CONTAINER_SNAPSHOT_KEY
|
|
24608
|
+
);
|
|
24609
|
+
if (this.lifecycle.events.some((event) => event.type === "started")) {
|
|
24610
|
+
this.lifecycle.record("replaced");
|
|
24611
|
+
}
|
|
24612
|
+
runtime.start({
|
|
24613
|
+
...storedSnapshot !== void 0 && storedSnapshot.image === expectedImage ? { containerSnapshot: { id: storedSnapshot.id } } : { image: expectedImage },
|
|
24614
|
+
instance: EVE_HOST_DEFAULTS.instance,
|
|
24615
|
+
enableInternet: true,
|
|
24616
|
+
env: this.envVars
|
|
25964
24617
|
});
|
|
24618
|
+
await this.registerLoopbackIntercept(runtime);
|
|
24619
|
+
this.attachMonitor(runtime);
|
|
24620
|
+
await runtime.setInactivityTimeout(this.inactivityTimeoutMs);
|
|
24621
|
+
this.lifecycle.record("started");
|
|
24622
|
+
}
|
|
24623
|
+
/**
|
|
24624
|
+
* Replaces the running container when `inspect()` proves it still serves a
|
|
24625
|
+
* pre-update image: this Worker version's `images.eve` is selected at
|
|
24626
|
+
* `start()`, so an in-place update must stop the stale instance itself.
|
|
24627
|
+
*/
|
|
24628
|
+
async reconcileRunningImage() {
|
|
24629
|
+
if (this.imageVerified) return;
|
|
24630
|
+
const runtime = this.containerRuntime();
|
|
24631
|
+
if (runtime === void 0 || !runtime.running) return;
|
|
24632
|
+
const expectedImage = runtime.images["eve"];
|
|
24633
|
+
let info;
|
|
24634
|
+
try {
|
|
24635
|
+
info = await runtime.inspect();
|
|
24636
|
+
} catch {
|
|
24637
|
+
info = null;
|
|
24638
|
+
}
|
|
24639
|
+
if (info?.image === expectedImage) {
|
|
24640
|
+
this.imageVerified = true;
|
|
24641
|
+
return;
|
|
24642
|
+
}
|
|
24643
|
+
this.lifecycle.record("image_mismatch");
|
|
24644
|
+
this.recordContainerStopped("replaced");
|
|
24645
|
+
await runtime.destroy();
|
|
24646
|
+
const stoppedAt = Date.now();
|
|
24647
|
+
while (runtime.running && Date.now() - stoppedAt < 1e4) {
|
|
24648
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
24649
|
+
}
|
|
25965
24650
|
}
|
|
25966
24651
|
async ensureEveReady(signal = new AbortController().signal) {
|
|
24652
|
+
await this.reconcileRunningImage();
|
|
25967
24653
|
if (this.readinessEvidence !== void 0) {
|
|
25968
24654
|
return this.readinessEvidence;
|
|
25969
24655
|
}
|
|
@@ -25971,40 +24657,125 @@ var EveHostContainer = class extends Container {
|
|
|
25971
24657
|
this.readinessStarted = true;
|
|
25972
24658
|
this.lifecycle.record("start_requested");
|
|
25973
24659
|
}
|
|
24660
|
+
const epoch = this.readinessEpoch;
|
|
25974
24661
|
const evidence = await this.readiness(signal);
|
|
25975
|
-
this.
|
|
24662
|
+
if (epoch === this.readinessEpoch) {
|
|
24663
|
+
this.readinessEvidence = evidence;
|
|
24664
|
+
this.imageVerified = true;
|
|
24665
|
+
}
|
|
25976
24666
|
this.lifecycle.record("health_ready", evidence.healthStatus);
|
|
25977
24667
|
return evidence;
|
|
25978
24668
|
}
|
|
25979
24669
|
async fetch(request) {
|
|
24670
|
+
const requestDeploymentId = request.headers.get("x-eden-eve-deployment-id") ?? void 0;
|
|
25980
24671
|
await this.ensureEveReady(request.signal);
|
|
25981
|
-
|
|
25982
|
-
|
|
25983
|
-
|
|
25984
|
-
|
|
25985
|
-
|
|
24672
|
+
await this.touchActivity();
|
|
24673
|
+
const runtime = this.containerRuntime();
|
|
24674
|
+
if (runtime === void 0) {
|
|
24675
|
+
throw new EveHostError(
|
|
24676
|
+
"HOST_READINESS_UNPROVEN",
|
|
24677
|
+
"The Container runtime is unavailable on this Durable Object."
|
|
24678
|
+
);
|
|
25986
24679
|
}
|
|
25987
|
-
|
|
25988
|
-
|
|
25989
|
-
|
|
25990
|
-
this.readinessStarted = false;
|
|
25991
|
-
this.readinessEvidence = void 0;
|
|
25992
|
-
this.readiness.reset();
|
|
25993
|
-
this.lifecycle.record("stopped", `${params.reason}:${params.exitCode}`);
|
|
25994
|
-
}
|
|
25995
|
-
onError(error61) {
|
|
25996
|
-
this.readinessStarted = false;
|
|
25997
|
-
this.readinessEvidence = void 0;
|
|
25998
|
-
this.readiness.reset();
|
|
25999
|
-
this.lifecycle.record(
|
|
26000
|
-
"errored",
|
|
26001
|
-
error61 instanceof Error ? error61.name : "unknown"
|
|
24680
|
+
const url2 = new URL(request.url);
|
|
24681
|
+
const response = await runtime.getTcpPort(EVE_HOST_DEFAULTS.internalPort).fetch(
|
|
24682
|
+
new Request(`http://container${url2.pathname}${url2.search}`, request)
|
|
26002
24683
|
);
|
|
26003
|
-
|
|
26004
|
-
|
|
26005
|
-
"
|
|
24684
|
+
if (requestDeploymentId !== void 0 && requestDeploymentId === this.env.EDEN_EVE_DEPLOYMENT_ID && this.readinessEvidence !== void 0 && this.imageVerified) {
|
|
24685
|
+
const headers = new Headers(response.headers);
|
|
24686
|
+
headers.set("x-eden-eve-started-deployment", requestDeploymentId);
|
|
24687
|
+
return new Response(response.body, {
|
|
24688
|
+
status: response.status,
|
|
24689
|
+
statusText: response.statusText,
|
|
24690
|
+
headers
|
|
24691
|
+
});
|
|
24692
|
+
}
|
|
24693
|
+
return response;
|
|
24694
|
+
}
|
|
24695
|
+
/**
|
|
24696
|
+
* Queue deliveries and loopback traffic enter here: same readiness and
|
|
24697
|
+
* forwarding as `fetch` without the deployment-header echo rules (the
|
|
24698
|
+
* loopback path is not a deployment-health signal).
|
|
24699
|
+
*/
|
|
24700
|
+
async loopbackFetch(request) {
|
|
24701
|
+
await this.ensureEveReady(request.signal);
|
|
24702
|
+
await this.touchActivity();
|
|
24703
|
+
const runtime = this.containerRuntime();
|
|
24704
|
+
if (runtime === void 0) {
|
|
24705
|
+
throw new EveHostError(
|
|
24706
|
+
"HOST_READINESS_UNPROVEN",
|
|
24707
|
+
"The Container runtime is unavailable on this Durable Object."
|
|
24708
|
+
);
|
|
24709
|
+
}
|
|
24710
|
+
const url2 = new URL(request.url);
|
|
24711
|
+
return runtime.getTcpPort(EVE_HOST_DEFAULTS.internalPort).fetch(
|
|
24712
|
+
new Request(`http://container${url2.pathname}${url2.search}`, request)
|
|
26006
24713
|
);
|
|
26007
24714
|
}
|
|
24715
|
+
/**
|
|
24716
|
+
* The idle-sleep path: once the container has been quiet for `sleepAfter`,
|
|
24717
|
+
* snapshot the writable filesystem (so `/workspace` survives the sleep)
|
|
24718
|
+
* and destroy the instance. A snapshot failure retries up to
|
|
24719
|
+
* `EVE_HOST_SNAPSHOT_MAX_ATTEMPTS` times, then destroys anyway so billing
|
|
24720
|
+
* for the running container stops.
|
|
24721
|
+
*/
|
|
24722
|
+
async alarm() {
|
|
24723
|
+
const runtime = this.containerRuntime();
|
|
24724
|
+
const lastActivity = await this.ctx.storage.get(EVE_HOST_CONTAINER_ACTIVITY_KEY) ?? 0;
|
|
24725
|
+
const now = Date.now();
|
|
24726
|
+
if (now - lastActivity < this.sleepAfterMs) {
|
|
24727
|
+
await this.ctx.storage.setAlarm(lastActivity + this.sleepAfterMs);
|
|
24728
|
+
return;
|
|
24729
|
+
}
|
|
24730
|
+
if (runtime === void 0 || !runtime.running) return;
|
|
24731
|
+
const attempts = await this.ctx.storage.get(
|
|
24732
|
+
EVE_HOST_CONTAINER_SNAPSHOT_ATTEMPTS_KEY
|
|
24733
|
+
) ?? 0;
|
|
24734
|
+
try {
|
|
24735
|
+
const snapshot = await runtime.snapshotContainer({
|
|
24736
|
+
name: "eden-workspace"
|
|
24737
|
+
});
|
|
24738
|
+
const image = (await runtime.inspect().catch(() => null))?.image ?? runtime.images["eve"] ?? "";
|
|
24739
|
+
const record2 = {
|
|
24740
|
+
id: snapshot.id,
|
|
24741
|
+
image,
|
|
24742
|
+
at: now
|
|
24743
|
+
};
|
|
24744
|
+
await this.ctx.storage.put(EVE_HOST_CONTAINER_SNAPSHOT_KEY, record2);
|
|
24745
|
+
await this.ctx.storage.put(EVE_HOST_CONTAINER_SNAPSHOT_ATTEMPTS_KEY, 0);
|
|
24746
|
+
const activityAfterSnapshot = await this.ctx.storage.get(EVE_HOST_CONTAINER_ACTIVITY_KEY) ?? 0;
|
|
24747
|
+
if (activityAfterSnapshot !== lastActivity) {
|
|
24748
|
+
await this.ctx.storage.setAlarm(activityAfterSnapshot + this.sleepAfterMs);
|
|
24749
|
+
return;
|
|
24750
|
+
}
|
|
24751
|
+
await runtime.destroy(new Error("idle-snapshot-done"));
|
|
24752
|
+
this.recordContainerStopped("snapshot:idle");
|
|
24753
|
+
} catch (error61) {
|
|
24754
|
+
const message = error61 instanceof Error ? error61.message : "unknown";
|
|
24755
|
+
if (attempts + 1 >= EVE_HOST_SNAPSHOT_MAX_ATTEMPTS) {
|
|
24756
|
+
console.error(
|
|
24757
|
+
`The Eve workspace snapshot failed ${attempts + 1} times; destroying the container without it: ${message}`
|
|
24758
|
+
);
|
|
24759
|
+
await this.ctx.storage.put(
|
|
24760
|
+
EVE_HOST_CONTAINER_SNAPSHOT_ATTEMPTS_KEY,
|
|
24761
|
+
0
|
|
24762
|
+
);
|
|
24763
|
+
await runtime.destroy(
|
|
24764
|
+
new Error("idle-snapshot-abandoned")
|
|
24765
|
+
);
|
|
24766
|
+
this.recordContainerStopped("snapshot:abandoned");
|
|
24767
|
+
return;
|
|
24768
|
+
}
|
|
24769
|
+
console.error(
|
|
24770
|
+
`The Eve workspace snapshot failed (attempt ${attempts + 1}): ${message}`
|
|
24771
|
+
);
|
|
24772
|
+
await this.ctx.storage.put(
|
|
24773
|
+
EVE_HOST_CONTAINER_SNAPSHOT_ATTEMPTS_KEY,
|
|
24774
|
+
attempts + 1
|
|
24775
|
+
);
|
|
24776
|
+
await this.ctx.storage.setAlarm(now + 6e4);
|
|
24777
|
+
}
|
|
24778
|
+
}
|
|
26008
24779
|
};
|
|
26009
24780
|
function createEveHostWorker(options) {
|
|
26010
24781
|
if (!WORKER_NAME_PATTERN.test(options.workerName)) {
|
|
@@ -26077,7 +24848,14 @@ function createEveHostWorker(options) {
|
|
|
26077
24848
|
if (!due) return;
|
|
26078
24849
|
ctx.waitUntil(
|
|
26079
24850
|
resolveContainer(env).fetch(new Request(
|
|
26080
|
-
new URL(EVE_HOST_DEFAULTS.healthPath, options.publicOrigin)
|
|
24851
|
+
new URL(EVE_HOST_DEFAULTS.healthPath, options.publicOrigin),
|
|
24852
|
+
{
|
|
24853
|
+
headers: {
|
|
24854
|
+
// Stamp the Worker's own deployment so a stale Durable
|
|
24855
|
+
// Object never falls back to its own environment.
|
|
24856
|
+
"x-eden-eve-deployment-id": options.deploymentId
|
|
24857
|
+
}
|
|
24858
|
+
}
|
|
26081
24859
|
)).catch((error61) => {
|
|
26082
24860
|
console.error(
|
|
26083
24861
|
"The scheduled wake request failed:",
|
|
@@ -26090,9 +24868,9 @@ function createEveHostWorker(options) {
|
|
|
26090
24868
|
};
|
|
26091
24869
|
}
|
|
26092
24870
|
export {
|
|
26093
|
-
ContainerProxy,
|
|
26094
24871
|
EdenWorldDurableObject,
|
|
26095
|
-
|
|
24872
|
+
EveHostDurableContainer,
|
|
24873
|
+
EveHostLoopback,
|
|
26096
24874
|
createEveHostWorker,
|
|
26097
24875
|
routeEveOutboundRequest
|
|
26098
24876
|
};
|