@lunora/container 1.0.0-alpha.1 → 1.0.0-alpha.10

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/dist/do/index.mjs CHANGED
@@ -1,5 +1,8 @@
1
- import { Container } from '@cloudflare/containers';
2
- import { resolveContainerEnvVars as resolveContainerEnvVariables } from '../packem_shared/containerBindingName-BGdSdFNA.mjs';
1
+ import { Container } from '../packem_shared/ContainerProxy-DWqUX_re.mjs';
2
+ export { ContainerProxy, outboundParams } from '../packem_shared/ContainerProxy-DWqUX_re.mjs';
3
+ import { LunoraError } from '@lunora/errors';
4
+ import { resolveContainerEnvVars as resolveContainerEnvVariables, parseDurationSeconds } from '../packem_shared/containerBindingName-BiTrAF1J.mjs';
5
+ import { a as applyJurisdiction } from '../packem_shared/jurisdiction-CuPNcLDt.mjs';
3
6
 
4
7
  const LUNORA_EVENT_SOURCE = "lunora";
5
8
  const buildContainerLifecycleEvent = (container, instance, event, message) => {
@@ -34,13 +37,14 @@ const isShardNamespace = (value) => {
34
37
  const candidate = value;
35
38
  return typeof candidate.get === "function" && typeof candidate.idFromName === "function";
36
39
  };
37
- const resolveRootShard = (namespace) => {
38
- if (typeof namespace.getByName === "function") {
39
- return namespace.getByName(ROOT_SHARD_NAME);
40
+ const resolveRootShard = (namespace, jurisdiction) => {
41
+ const pinned = applyJurisdiction(namespace, jurisdiction);
42
+ if (typeof pinned.getByName === "function") {
43
+ return pinned.getByName(ROOT_SHARD_NAME);
40
44
  }
41
- return namespace.get(namespace.idFromName(ROOT_SHARD_NAME));
45
+ return pinned.get(pinned.idFromName(ROOT_SHARD_NAME));
42
46
  };
43
- const reportContainerLifecycle = async (env, envelope) => {
47
+ const reportContainerLifecycle = async (env, envelope, jurisdiction) => {
44
48
  try {
45
49
  const envRecord = env ?? {};
46
50
  const namespace = envRecord["SHARD"];
@@ -56,24 +60,99 @@ const reportContainerLifecycle = async (env, envelope) => {
56
60
  headers: { authorization: `Bearer ${adminBearer}`, "content-type": "application/json" },
57
61
  method: "POST"
58
62
  });
59
- await resolveRootShard(namespace).fetch(request);
63
+ await resolveRootShard(namespace, jurisdiction).fetch(request);
60
64
  } catch {
61
65
  }
62
66
  };
63
67
 
68
+ const READINESS_POLL_INTERVAL_MS = 500;
69
+ const READINESS_TIMEOUT_MS = 3e4;
70
+ const HARD_TIMEOUT_GENERATION_KEY = "__lunoraHardTimeoutGeneration";
64
71
  class LunoraContainer extends Container {
72
+ /**
73
+ * Data-residency jurisdiction the app's DOs are pinned to (codegen passes the
74
+ * schema's `.jurisdiction("…")`). Used to pin the best-effort lifecycle report
75
+ * to the same region as the root shard. `undefined` ⇒ un-pinned.
76
+ */
77
+ lunoraJurisdiction;
65
78
  /** The `lunora/containers.ts` export name, for lifecycle log correlation. */
66
79
  lunoraName;
67
- constructor(context, env, definition, exportName) {
80
+ /** Default port the readiness probes target when a check omits its own `port`. */
81
+ lunoraDefaultPort;
82
+ /** Hard-cap lifetime in whole seconds (from the `hardTimeout` config), or `undefined`. */
83
+ lunoraHardTimeoutSeconds;
84
+ /** Declarative readiness probes that gate request proxying (from the `readyOn` config). */
85
+ lunoraReadyOn;
86
+ /** Map of container env-var name → Worker Secrets Store binding name (from the `secretsStore` config). */
87
+ lunoraSecretsStore;
88
+ /** Memoised Secrets Store resolution: run once, then merged into `envVars` before the first start. */
89
+ lunoraSecretsStoreResolved;
90
+ constructor(context, env, definition, exportName, jurisdiction) {
68
91
  super(context, env, {
69
92
  defaultPort: definition.defaultPort,
93
+ entrypoint: definition.entrypoint ? [...definition.entrypoint] : void 0,
70
94
  envVars: resolveContainerEnvVariables(definition, env, exportName),
71
95
  sleepAfter: definition.sleepAfter
72
96
  });
73
97
  if (definition.enableInternet !== void 0) {
74
98
  this.enableInternet = definition.enableInternet;
75
99
  }
100
+ if (definition.requiredPorts !== void 0) {
101
+ this.requiredPorts = [...definition.requiredPorts];
102
+ }
103
+ if (definition.interceptHttps !== void 0) {
104
+ this.interceptHttps = definition.interceptHttps;
105
+ }
106
+ if (definition.allowedHosts !== void 0) {
107
+ this.allowedHosts = [...definition.allowedHosts];
108
+ }
109
+ if (definition.deniedHosts !== void 0) {
110
+ this.deniedHosts = [...definition.deniedHosts];
111
+ }
112
+ if (definition.pingEndpoint !== void 0) {
113
+ this.pingEndpoint = definition.pingEndpoint;
114
+ }
115
+ if (definition.labels !== void 0) {
116
+ this.labels = { ...definition.labels };
117
+ }
76
118
  this.lunoraName = exportName ?? "container";
119
+ this.lunoraJurisdiction = jurisdiction;
120
+ this.lunoraDefaultPort = definition.defaultPort;
121
+ this.lunoraReadyOn = definition.readyOn ? [...definition.readyOn] : [];
122
+ this.lunoraHardTimeoutSeconds = definition.hardTimeout === void 0 ? void 0 : parseDurationSeconds(definition.hardTimeout);
123
+ this.lunoraSecretsStore = definition.secretsStore;
124
+ }
125
+ /**
126
+ * Proxy entry for every `ctx.containers.<name>` fetch. Resolves the
127
+ * `secretsStore` bindings into `envVars` before delegating, so the values
128
+ * are present when the base implicitly starts the container for this
129
+ * request — a no-op when `secretsStore` is unset.
130
+ */
131
+ async containerFetch(...args) {
132
+ await this.resolveSecretsStoreEnv();
133
+ return super.containerFetch(...args);
134
+ }
135
+ /**
136
+ * Explicit start (`ctx.containers.<name>.get(id).start()`). Resolves the
137
+ * `secretsStore` bindings into `envVars` first, mirroring
138
+ * {@link containerFetch}. A per-instance `start({ envVars })` replaces the
139
+ * env set wholesale (base behavior), so the injected values only apply to a
140
+ * bare `start()` — same as the static `env`/`secrets`. When the caller
141
+ * supplies its own `envVars` we skip resolution entirely: those values would
142
+ * be discarded anyway, so a missing/unreadable binding shouldn't fail a start
143
+ * that never uses them.
144
+ */
145
+ async start(...args) {
146
+ const [options] = args;
147
+ if (options?.envVars === void 0) {
148
+ await this.resolveSecretsStoreEnv();
149
+ }
150
+ return super.start(...args);
151
+ }
152
+ async onActivityExpired() {
153
+ const envelope = emitContainerLifecycle(this.lunoraName, this.instanceId(), "sleep");
154
+ this.surfaceInStudioLogs(envelope);
155
+ await super.onActivityExpired();
77
156
  }
78
157
  onError(error) {
79
158
  const envelope = emitContainerLifecycle(this.lunoraName, this.instanceId(), "error", error instanceof Error ? error.message : String(error));
@@ -84,12 +163,135 @@ class LunoraContainer extends Container {
84
163
  const envelope = emitContainerLifecycle(this.lunoraName, this.instanceId(), "start");
85
164
  this.surfaceInStudioLogs(envelope);
86
165
  await super.onStart();
166
+ await this.armHardTimeout();
167
+ await this.awaitContainerReadiness();
168
+ }
169
+ /**
170
+ * Hook run when the container's `hardTimeout` elapses (dispatched by the base
171
+ * scheduler via the run-generation-stamped schedule armed in
172
+ * {@link onStart}). Default: stop the instance. Override to drain/checkpoint
173
+ * first. A stale schedule from a previous run, or an already-stopped
174
+ * instance, is ignored (upstream cloudflare/containers#85).
175
+ */
176
+ async onHardTimeoutExpired(payload) {
177
+ const current = await this.ctx.storage.get(HARD_TIMEOUT_GENERATION_KEY);
178
+ if (payload?.generation !== void 0 && payload.generation !== current) {
179
+ return;
180
+ }
181
+ if (this.ctx.container?.running !== true) {
182
+ return;
183
+ }
184
+ const envelope = emitContainerLifecycle(this.lunoraName, this.instanceId(), "stop", "hard timeout reached");
185
+ this.surfaceInStudioLogs(envelope);
186
+ await this.stop();
87
187
  }
88
188
  async onStop(parameters) {
89
189
  const envelope = emitContainerLifecycle(this.lunoraName, this.instanceId(), "stop", `${parameters.reason} (exit ${String(parameters.exitCode)})`);
90
190
  this.surfaceInStudioLogs(envelope);
91
191
  await super.onStop(parameters);
92
192
  }
193
+ /**
194
+ * Arm the hard-timeout kill via the base scheduler (so it integrates with
195
+ * the container's own alarm machinery instead of fighting it). Bumps the run
196
+ * generation and stamps the schedule with it, so {@link onHardTimeoutExpired}
197
+ * can tell a fresh schedule from a stale one. No-op without a `hardTimeout`.
198
+ */
199
+ async armHardTimeout() {
200
+ if (this.lunoraHardTimeoutSeconds === void 0) {
201
+ return;
202
+ }
203
+ const generation = (await this.ctx.storage.get(HARD_TIMEOUT_GENERATION_KEY) ?? 0) + 1;
204
+ await this.ctx.storage.put(HARD_TIMEOUT_GENERATION_KEY, generation);
205
+ await this.schedule(this.lunoraHardTimeoutSeconds, "onHardTimeoutExpired", { generation });
206
+ }
207
+ /**
208
+ * Resolve the `secretsStore` bindings (async `.get()`) once and merge the
209
+ * values into `envVars`, so they're present when the base starts the
210
+ * container. Memoised on the first call — every later start reuses the
211
+ * resolved promise. A missing binding or a non-string value fails fast (the
212
+ * start surfaces the error), the same fail-closed stance the static
213
+ * `secrets` resolution takes for a missing Worker secret. No-op without
214
+ * `secretsStore`.
215
+ */
216
+ async resolveSecretsStoreEnv() {
217
+ const secretsStore = this.lunoraSecretsStore;
218
+ if (secretsStore === void 0) {
219
+ return;
220
+ }
221
+ this.lunoraSecretsStoreResolved ??= (async () => {
222
+ const workerEnv = this.env;
223
+ const resolved = {};
224
+ for (const [envName, binding] of Object.entries(secretsStore)) {
225
+ const store = workerEnv[binding];
226
+ if (store === void 0 || typeof store.get !== "function") {
227
+ throw new LunoraError(
228
+ "INTERNAL",
229
+ `container "${this.lunoraName}": secretsStore env "${envName}" points at binding "${binding}", which is not a Secrets Store binding on the Worker env. Add a \`secrets_store_secrets\` entry binding "${binding}".`
230
+ );
231
+ }
232
+ const value = await store.get();
233
+ if (typeof value !== "string") {
234
+ throw new TypeError(
235
+ `container "${this.lunoraName}": Secrets Store binding "${binding}" (env "${envName}") did not resolve to a string value.`
236
+ );
237
+ }
238
+ resolved[envName] = value;
239
+ }
240
+ this.envVars = { ...this.envVars, ...resolved };
241
+ })().catch((error) => {
242
+ this.lunoraSecretsStoreResolved = void 0;
243
+ throw error;
244
+ });
245
+ await this.lunoraSecretsStoreResolved;
246
+ }
247
+ /**
248
+ * Block until every `readyOn` probe responds with its expected status, or
249
+ * throw once the readiness budget is spent. Probes run in parallel and hit
250
+ * the container's TCP port directly (NOT `containerFetch`, which would
251
+ * recurse back into the start path). No-op without `readyOn`.
252
+ */
253
+ async awaitContainerReadiness() {
254
+ if (this.lunoraReadyOn.length === 0) {
255
+ return;
256
+ }
257
+ const { container } = this.ctx;
258
+ if (container === void 0) {
259
+ return;
260
+ }
261
+ const deadline = Date.now() + READINESS_TIMEOUT_MS;
262
+ await Promise.all(this.lunoraReadyOn.map(async (check) => this.awaitReadinessCheck(container, check, deadline)));
263
+ }
264
+ /** Poll one readiness probe until it returns its expected status or the shared deadline passes. */
265
+ async awaitReadinessCheck(container, check, deadline) {
266
+ const port = check.port ?? this.lunoraDefaultPort;
267
+ if (port === void 0) {
268
+ throw new LunoraError(
269
+ "INTERNAL",
270
+ `container "${this.lunoraName}": readyOn check "${check.path}" has no port — set the check's \`port\` or the container \`defaultPort\`.`
271
+ );
272
+ }
273
+ const expectedStatus = check.status ?? 200;
274
+ const path = check.path.startsWith("/") ? check.path : `/${check.path}`;
275
+ const tcpPort = container.getTcpPort(port);
276
+ for (; ; ) {
277
+ try {
278
+ const response = await tcpPort.fetch(`http://container${path}`);
279
+ if (response.status === expectedStatus) {
280
+ return;
281
+ }
282
+ } catch {
283
+ }
284
+ if (Date.now() >= deadline) {
285
+ throw new LunoraError(
286
+ "INTERNAL",
287
+ `container "${this.lunoraName}": readiness check "${check.path}" (port ${String(port)}) did not return ${String(expectedStatus)} within ${String(READINESS_TIMEOUT_MS)}ms`
288
+ );
289
+ }
290
+ await new Promise((resolve) => {
291
+ setTimeout(resolve, READINESS_POLL_INTERVAL_MS);
292
+ });
293
+ }
294
+ }
93
295
  /**
94
296
  * Best-effort push of `envelope` into the root ShardDO's log buffer so it
95
297
  * also appears in the Studio Logs panel (the terminal already has it via
@@ -98,7 +300,7 @@ class LunoraContainer extends Container {
98
300
  * out of a lifecycle hook — the `console` path stays the source of truth.
99
301
  */
100
302
  surfaceInStudioLogs(envelope) {
101
- reportContainerLifecycle(this.env, envelope).catch(() => {
303
+ reportContainerLifecycle(this.env, envelope, this.lunoraJurisdiction).catch(() => {
102
304
  });
103
305
  }
104
306
  /**
@@ -116,4 +318,4 @@ class LunoraContainer extends Container {
116
318
  }
117
319
  }
118
320
 
119
- export { LunoraContainer as default };
321
+ export { LunoraContainer };
package/dist/index.d.mts CHANGED
@@ -1,14 +1,5 @@
1
- import { a as ContainerConfig, C as ContainerDefinition, b as ContainerImageSource, N as NormalizedContainerImage } from "./packem_shared/types.d-D2l2SYol.mjs";
2
- export type { B as BuildImageSource, c as ContainerInstanceType, d as ContainerRollout, e as CustomContainerInstanceType, f as NamedContainerInstanceType, R as RegistryImageSource } from "./packem_shared/types.d-D2l2SYol.mjs";
3
- /**
4
- * The `ctx.containers` action surface: typed handles over the `CONTAINER_*`
5
- * Durable Object namespace bindings the config layer reconciles.
6
- *
7
- * Deliberately structural (no `@cloudflare/containers` import): a Durable
8
- * Object namespace stub is all that is needed to route a request to a
9
- * container-enabled DO, so this module stays Node-safe and the test double
10
- * below can satisfy the exact same shape without a workerd runtime.
11
- */
1
+ import { D as DurableObjectJurisdiction, C as ContainerConfig, a as ContainerDefinition, b as ContainerImageSource, N as NormalizedContainerImage } from "./packem_shared/jurisdiction.d-TwTGkgTg.mjs";
2
+ export type { B as BuildImageSource, c as ContainerInstanceType, d as ContainerReadinessCheck, e as ContainerRollout, f as CustomContainerInstanceType, g as NamedContainerInstanceType, R as RegistryImageSource } from "./packem_shared/jurisdiction.d-TwTGkgTg.mjs";
12
3
  /** Options for explicitly starting an instance (mirrors `@cloudflare/containers`). */
13
4
  interface ContainerStartOptions {
14
5
  /** Override outbound internet access for this start. */
@@ -23,13 +14,25 @@ interface ContainerStartOptions {
23
14
  /** A container instance's runtime state, as returned by `getState()`. Structural — the platform adds fields over time. */
24
15
  interface ContainerInstanceState {
25
16
  [key: string]: unknown;
17
+ /** Process exit code, present once the instance has `stopped_with_code`. */
18
+ exitCode?: number;
19
+ /** Epoch-ms of the last state transition. */
26
20
  lastChange?: number;
21
+ /** Lifecycle status. Widening union — Cloudflare adds values over time. */
22
+ status?: "healthy" | "running" | "stopped" | "stopped_with_code" | "stopping";
27
23
  }
28
- /** What a handle needs from a Durable Object stub — `fetch` plus the optional lifecycle RPCs the container DO exposes. */
24
+ /** What a handle needs from a Durable Object stub — `fetch` plus the optional lifecycle/egress RPCs the container DO exposes. */
29
25
  interface ContainerStubLike {
26
+ allowHost?: (hostname: string) => Promise<void>;
27
+ denyHost?: (hostname: string) => Promise<void>;
30
28
  destroy?: () => Promise<void>;
31
29
  fetch: (input: Request) => Promise<Response>;
32
30
  getState?: () => Promise<ContainerInstanceState>;
31
+ removeAllowedHost?: (hostname: string) => Promise<void>;
32
+ removeDeniedHost?: (hostname: string) => Promise<void>;
33
+ renewActivityTimeout?: () => Promise<void>;
34
+ setAllowedHosts?: (hosts: string[]) => Promise<void>;
35
+ setDeniedHosts?: (hosts: string[]) => Promise<void>;
33
36
  start?: (options?: ContainerStartOptions) => Promise<void>;
34
37
  stop?: (signal?: number | string) => Promise<void>;
35
38
  }
@@ -37,6 +40,11 @@ interface ContainerStubLike {
37
40
  interface ContainerNamespaceLike {
38
41
  get: (id: unknown) => ContainerStubLike;
39
42
  idFromName: (name: string) => unknown;
43
+ /**
44
+ * Derive a jurisdiction-restricted subnamespace. Optional because older
45
+ * workers-types releases (and test doubles) may not expose it.
46
+ */
47
+ jurisdiction?: (jurisdiction: DurableObjectJurisdiction) => ContainerNamespaceLike;
40
48
  }
41
49
  /** A handle on one container instance (one Durable Object). */
42
50
  interface ContainerHandle {
@@ -46,6 +54,15 @@ interface ContainerHandle {
46
54
  * `Request`/URL passes through unchanged.
47
55
  */
48
56
  fetch: (input: Request | string, init?: RequestInit) => Promise<Response>;
57
+ /**
58
+ * Return a handle that routes every request to `targetPort` on the
59
+ * container instead of the definition's `defaultPort` — for multi-port
60
+ * containers (declare the ports in `requiredPorts`). Sets the
61
+ * `cf-container-target-port` header the way `@cloudflare/containers`'
62
+ * `switchPort` does, so it composes with `.get()`, `.any()`, and `.pool()`:
63
+ * `ctx.containers.app.get("u1").port(9090).fetch("/admin")`.
64
+ */
65
+ port: (targetPort: number) => ContainerHandle;
49
66
  }
50
67
  /**
51
68
  * A handle on a *named* instance (from `.get(name)`) — `fetch` plus explicit
@@ -57,23 +74,76 @@ interface ContainerHandle {
57
74
  interface ContainerInstanceHandle extends ContainerHandle {
58
75
  /** Stop and discard the instance (its ephemeral disk is lost). */
59
76
  destroy: () => Promise<void>;
77
+ /**
78
+ * Adjust this instance's egress allow/deny lists at runtime — the dynamic
79
+ * counterpart to the static `allowedHosts`/`deniedHosts` config. Useful for
80
+ * per-tenant egress policy. Requires the worker to export `ContainerProxy`
81
+ * (codegen re-exports it from the generated container file whenever any
82
+ * container is defined, so the runtime controls always work).
83
+ */
84
+ egress: ContainerEgressControls;
60
85
  /** Read the instance's current runtime state. */
61
86
  getState: () => Promise<ContainerInstanceState>;
87
+ /**
88
+ * Reset the instance's `sleepAfter` idle timer. The platform renews it on
89
+ * each proxied request, and because `@lunora/container` proxies WebSocket
90
+ * frames through the Durable Object, message traffic on an open socket
91
+ * renews it too (the WebSocket-keepalive gap of cloudflare/containers#147 is
92
+ * closed in the bundled base). This manual control is the escape hatch for
93
+ * keeping a container awake during activity that is neither an HTTP request
94
+ * nor a WS message — e.g. a long out-of-band job running inside it.
95
+ */
96
+ renewActivityTimeout: () => Promise<void>;
62
97
  /** Explicitly start the instance, optionally with per-instance env/entrypoint. */
63
98
  start: (options?: ContainerStartOptions) => Promise<void>;
64
99
  /** Stop the instance (optionally with a signal); it can start again on the next request. */
65
100
  stop: (signal?: number | string) => Promise<void>;
66
101
  }
102
+ /**
103
+ * Runtime egress-firewall controls for a named instance (`handle.egress.*`).
104
+ * Each maps to the corresponding `@cloudflare/containers` `Container` RPC, so
105
+ * an app can tighten or relax a single instance's allowed/denied hosts after
106
+ * start without redeploying.
107
+ */
108
+ interface ContainerEgressControls {
109
+ /** Add one hostname (or glob) to the allow-list. */
110
+ allow: (hostname: string) => Promise<void>;
111
+ /** Add one hostname (or glob) to the deny-list. */
112
+ deny: (hostname: string) => Promise<void>;
113
+ /** Remove one hostname from the allow-list. */
114
+ removeAllowed: (hostname: string) => Promise<void>;
115
+ /** Remove one hostname from the deny-list. */
116
+ removeDenied: (hostname: string) => Promise<void>;
117
+ /** Replace the entire allow-list. */
118
+ setAllowed: (hosts: ReadonlyArray<string>) => Promise<void>;
119
+ /** Replace the entire deny-list. */
120
+ setDenied: (hosts: ReadonlyArray<string>) => Promise<void>;
121
+ }
67
122
  /** The per-definition accessor exposed as `ctx.containers.&lt;exportName>`. */
68
123
  interface ContainerAccessor {
69
124
  /**
70
125
  * A random instance from a fixed pool of `count` (defaults to the
71
126
  * definition's `maxInstances`, else 3 — mirroring `getRandom` from
72
127
  * `@cloudflare/containers`). For stateless, interchangeable workloads.
128
+ *
129
+ * Like `.get()`, a path/URL-string fetch transparently retries the
130
+ * cold-start "instance is provisioning" transients (cloudflare/containers#45,
131
+ * #139); pass {@link InstanceRetryOptions} to tune or disable it.
73
132
  */
74
- any: (count?: number) => ContainerHandle;
75
- /** The instance for `name` — one container per entity (user, room, job…), with lifecycle control. */
76
- get: (name: string) => ContainerInstanceHandle;
133
+ any: (count?: number, options?: InstanceRetryOptions) => ContainerHandle;
134
+ /**
135
+ * The instance for `name` one container per entity (user, room, job…),
136
+ * with lifecycle control.
137
+ *
138
+ * A path/URL-string fetch transparently retries the platform's cold-start
139
+ * transients — "there is no Container instance available" / "container is
140
+ * not listening" while an instance is still provisioning
141
+ * (cloudflare/containers#45, #139) — on the *same* instance with backoff,
142
+ * since the request never reached the app. Pass {@link InstanceRetryOptions}
143
+ * to tune attempts/backoff or disable it (`{ attempts: 1 }`). A pre-built
144
+ * `Request` (possibly a one-shot stream body) is sent once, never retried.
145
+ */
146
+ get: (name: string, options?: InstanceRetryOptions) => ContainerInstanceHandle;
77
147
  /**
78
148
  * A resilient handle over the pool: each `fetch` picks a random instance and,
79
149
  * on a thrown error or a retryable response (5xx by default), retries on a
@@ -110,6 +180,24 @@ interface PoolOptions {
110
180
  /** Pool size to spread picks across. Defaults to the definition's `maxInstances`, else 3. */
111
181
  size?: number;
112
182
  }
183
+ /**
184
+ * Tuning for the cold-start retry on a `.get()`/`.any()` handle. The retry fires
185
+ * only on the platform's provisioning transients (no-instance / not-listening /
186
+ * rate-limited — see {@link isColdStartTransient}), which is why it's safe by
187
+ * default: those responses mean the request never reached the container.
188
+ */
189
+ interface InstanceRetryOptions {
190
+ /**
191
+ * Total attempts on a cold-start transient before the last outcome is
192
+ * surfaced as-is. `1` disables the retry. Default
193
+ * {@link DEFAULT_COLD_START_ATTEMPTS}.
194
+ */
195
+ attempts?: number;
196
+ /** Base backoff in ms between attempts; doubles each retry (0 disables the wait). Default {@link DEFAULT_COLD_START_BACKOFF_MS}. */
197
+ backoffMs?: number;
198
+ /** Upper bound on a single backoff sleep, in ms. Default {@link DEFAULT_MAX_BACKOFF_MS} (30s). */
199
+ maxBackoffMs?: number;
200
+ }
113
201
  /** Wiring info for one definition, emitted by codegen into the generated DO. */
114
202
  interface ContainerBindingSpec {
115
203
  /** Durable Object binding name, e.g. `CONTAINER_TRANSCODER`. */
@@ -126,7 +214,7 @@ interface ContainerBindingSpec {
126
214
  * handle is actually used — so one unprovisioned container never breaks
127
215
  * unrelated functions.
128
216
  */
129
- declare const createContainerContext: (env: Record<string, unknown>, specs: ReadonlyArray<ContainerBindingSpec>) => Record<string, ContainerAccessor>;
217
+ declare const createContainerContext: (env: Record<string, unknown>, specs: ReadonlyArray<ContainerBindingSpec>, jurisdiction?: DurableObjectJurisdiction) => Record<string, ContainerAccessor>;
130
218
  /** A test handler: receives the request plus the targeted instance name. */
131
219
  type ContainerTestHandler = (request: Request, instance: {
132
220
  name: string;
@@ -186,4 +274,4 @@ declare const isContainerDefinition: (value: unknown) => value is ContainerDefin
186
274
  * credential it was promised yields far worse errors downstream.
187
275
  */
188
276
  declare const resolveContainerEnvVariables: (definition: ContainerDefinition, workerEnv: Record<string, unknown>, exportName?: string) => Record<string, string>;
189
- export { type ContainerAccessor, type ContainerBindingSpec, type ContainerConfig, type ContainerDefinition, type ContainerHandle, type ContainerImageSource, type ContainerInstanceHandle, type ContainerInstanceState, type ContainerNamespaceLike, type ContainerStartOptions, type ContainerTestHandler, type NormalizedContainerImage, type PoolOptions, containerBindingName, containerBuildTag, containerClassName, createContainerContext, createContainerTestContext, defineContainer, isContainerDefinition, normalizeContainerImage, resolveContainerEnvVariables as resolveContainerEnvVars };
277
+ export { type ContainerAccessor, type ContainerBindingSpec, type ContainerConfig, type ContainerDefinition, type ContainerEgressControls, type ContainerHandle, type ContainerImageSource, type ContainerInstanceHandle, type ContainerInstanceState, type ContainerNamespaceLike, type ContainerStartOptions, type ContainerTestHandler, type DurableObjectJurisdiction, type InstanceRetryOptions, type NormalizedContainerImage, type PoolOptions, containerBindingName, containerBuildTag, containerClassName, createContainerContext, createContainerTestContext, defineContainer, isContainerDefinition, normalizeContainerImage, resolveContainerEnvVariables as resolveContainerEnvVars };
package/dist/index.d.ts CHANGED
@@ -1,14 +1,5 @@
1
- import { a as ContainerConfig, C as ContainerDefinition, b as ContainerImageSource, N as NormalizedContainerImage } from "./packem_shared/types.d-D2l2SYol.js";
2
- export type { B as BuildImageSource, c as ContainerInstanceType, d as ContainerRollout, e as CustomContainerInstanceType, f as NamedContainerInstanceType, R as RegistryImageSource } from "./packem_shared/types.d-D2l2SYol.js";
3
- /**
4
- * The `ctx.containers` action surface: typed handles over the `CONTAINER_*`
5
- * Durable Object namespace bindings the config layer reconciles.
6
- *
7
- * Deliberately structural (no `@cloudflare/containers` import): a Durable
8
- * Object namespace stub is all that is needed to route a request to a
9
- * container-enabled DO, so this module stays Node-safe and the test double
10
- * below can satisfy the exact same shape without a workerd runtime.
11
- */
1
+ import { D as DurableObjectJurisdiction, C as ContainerConfig, a as ContainerDefinition, b as ContainerImageSource, N as NormalizedContainerImage } from "./packem_shared/jurisdiction.d-TwTGkgTg.js";
2
+ export type { B as BuildImageSource, c as ContainerInstanceType, d as ContainerReadinessCheck, e as ContainerRollout, f as CustomContainerInstanceType, g as NamedContainerInstanceType, R as RegistryImageSource } from "./packem_shared/jurisdiction.d-TwTGkgTg.js";
12
3
  /** Options for explicitly starting an instance (mirrors `@cloudflare/containers`). */
13
4
  interface ContainerStartOptions {
14
5
  /** Override outbound internet access for this start. */
@@ -23,13 +14,25 @@ interface ContainerStartOptions {
23
14
  /** A container instance's runtime state, as returned by `getState()`. Structural — the platform adds fields over time. */
24
15
  interface ContainerInstanceState {
25
16
  [key: string]: unknown;
17
+ /** Process exit code, present once the instance has `stopped_with_code`. */
18
+ exitCode?: number;
19
+ /** Epoch-ms of the last state transition. */
26
20
  lastChange?: number;
21
+ /** Lifecycle status. Widening union — Cloudflare adds values over time. */
22
+ status?: "healthy" | "running" | "stopped" | "stopped_with_code" | "stopping";
27
23
  }
28
- /** What a handle needs from a Durable Object stub — `fetch` plus the optional lifecycle RPCs the container DO exposes. */
24
+ /** What a handle needs from a Durable Object stub — `fetch` plus the optional lifecycle/egress RPCs the container DO exposes. */
29
25
  interface ContainerStubLike {
26
+ allowHost?: (hostname: string) => Promise<void>;
27
+ denyHost?: (hostname: string) => Promise<void>;
30
28
  destroy?: () => Promise<void>;
31
29
  fetch: (input: Request) => Promise<Response>;
32
30
  getState?: () => Promise<ContainerInstanceState>;
31
+ removeAllowedHost?: (hostname: string) => Promise<void>;
32
+ removeDeniedHost?: (hostname: string) => Promise<void>;
33
+ renewActivityTimeout?: () => Promise<void>;
34
+ setAllowedHosts?: (hosts: string[]) => Promise<void>;
35
+ setDeniedHosts?: (hosts: string[]) => Promise<void>;
33
36
  start?: (options?: ContainerStartOptions) => Promise<void>;
34
37
  stop?: (signal?: number | string) => Promise<void>;
35
38
  }
@@ -37,6 +40,11 @@ interface ContainerStubLike {
37
40
  interface ContainerNamespaceLike {
38
41
  get: (id: unknown) => ContainerStubLike;
39
42
  idFromName: (name: string) => unknown;
43
+ /**
44
+ * Derive a jurisdiction-restricted subnamespace. Optional because older
45
+ * workers-types releases (and test doubles) may not expose it.
46
+ */
47
+ jurisdiction?: (jurisdiction: DurableObjectJurisdiction) => ContainerNamespaceLike;
40
48
  }
41
49
  /** A handle on one container instance (one Durable Object). */
42
50
  interface ContainerHandle {
@@ -46,6 +54,15 @@ interface ContainerHandle {
46
54
  * `Request`/URL passes through unchanged.
47
55
  */
48
56
  fetch: (input: Request | string, init?: RequestInit) => Promise<Response>;
57
+ /**
58
+ * Return a handle that routes every request to `targetPort` on the
59
+ * container instead of the definition's `defaultPort` — for multi-port
60
+ * containers (declare the ports in `requiredPorts`). Sets the
61
+ * `cf-container-target-port` header the way `@cloudflare/containers`'
62
+ * `switchPort` does, so it composes with `.get()`, `.any()`, and `.pool()`:
63
+ * `ctx.containers.app.get("u1").port(9090).fetch("/admin")`.
64
+ */
65
+ port: (targetPort: number) => ContainerHandle;
49
66
  }
50
67
  /**
51
68
  * A handle on a *named* instance (from `.get(name)`) — `fetch` plus explicit
@@ -57,23 +74,76 @@ interface ContainerHandle {
57
74
  interface ContainerInstanceHandle extends ContainerHandle {
58
75
  /** Stop and discard the instance (its ephemeral disk is lost). */
59
76
  destroy: () => Promise<void>;
77
+ /**
78
+ * Adjust this instance's egress allow/deny lists at runtime — the dynamic
79
+ * counterpart to the static `allowedHosts`/`deniedHosts` config. Useful for
80
+ * per-tenant egress policy. Requires the worker to export `ContainerProxy`
81
+ * (codegen re-exports it from the generated container file whenever any
82
+ * container is defined, so the runtime controls always work).
83
+ */
84
+ egress: ContainerEgressControls;
60
85
  /** Read the instance's current runtime state. */
61
86
  getState: () => Promise<ContainerInstanceState>;
87
+ /**
88
+ * Reset the instance's `sleepAfter` idle timer. The platform renews it on
89
+ * each proxied request, and because `@lunora/container` proxies WebSocket
90
+ * frames through the Durable Object, message traffic on an open socket
91
+ * renews it too (the WebSocket-keepalive gap of cloudflare/containers#147 is
92
+ * closed in the bundled base). This manual control is the escape hatch for
93
+ * keeping a container awake during activity that is neither an HTTP request
94
+ * nor a WS message — e.g. a long out-of-band job running inside it.
95
+ */
96
+ renewActivityTimeout: () => Promise<void>;
62
97
  /** Explicitly start the instance, optionally with per-instance env/entrypoint. */
63
98
  start: (options?: ContainerStartOptions) => Promise<void>;
64
99
  /** Stop the instance (optionally with a signal); it can start again on the next request. */
65
100
  stop: (signal?: number | string) => Promise<void>;
66
101
  }
102
+ /**
103
+ * Runtime egress-firewall controls for a named instance (`handle.egress.*`).
104
+ * Each maps to the corresponding `@cloudflare/containers` `Container` RPC, so
105
+ * an app can tighten or relax a single instance's allowed/denied hosts after
106
+ * start without redeploying.
107
+ */
108
+ interface ContainerEgressControls {
109
+ /** Add one hostname (or glob) to the allow-list. */
110
+ allow: (hostname: string) => Promise<void>;
111
+ /** Add one hostname (or glob) to the deny-list. */
112
+ deny: (hostname: string) => Promise<void>;
113
+ /** Remove one hostname from the allow-list. */
114
+ removeAllowed: (hostname: string) => Promise<void>;
115
+ /** Remove one hostname from the deny-list. */
116
+ removeDenied: (hostname: string) => Promise<void>;
117
+ /** Replace the entire allow-list. */
118
+ setAllowed: (hosts: ReadonlyArray<string>) => Promise<void>;
119
+ /** Replace the entire deny-list. */
120
+ setDenied: (hosts: ReadonlyArray<string>) => Promise<void>;
121
+ }
67
122
  /** The per-definition accessor exposed as `ctx.containers.&lt;exportName>`. */
68
123
  interface ContainerAccessor {
69
124
  /**
70
125
  * A random instance from a fixed pool of `count` (defaults to the
71
126
  * definition's `maxInstances`, else 3 — mirroring `getRandom` from
72
127
  * `@cloudflare/containers`). For stateless, interchangeable workloads.
128
+ *
129
+ * Like `.get()`, a path/URL-string fetch transparently retries the
130
+ * cold-start "instance is provisioning" transients (cloudflare/containers#45,
131
+ * #139); pass {@link InstanceRetryOptions} to tune or disable it.
73
132
  */
74
- any: (count?: number) => ContainerHandle;
75
- /** The instance for `name` — one container per entity (user, room, job…), with lifecycle control. */
76
- get: (name: string) => ContainerInstanceHandle;
133
+ any: (count?: number, options?: InstanceRetryOptions) => ContainerHandle;
134
+ /**
135
+ * The instance for `name` one container per entity (user, room, job…),
136
+ * with lifecycle control.
137
+ *
138
+ * A path/URL-string fetch transparently retries the platform's cold-start
139
+ * transients — "there is no Container instance available" / "container is
140
+ * not listening" while an instance is still provisioning
141
+ * (cloudflare/containers#45, #139) — on the *same* instance with backoff,
142
+ * since the request never reached the app. Pass {@link InstanceRetryOptions}
143
+ * to tune attempts/backoff or disable it (`{ attempts: 1 }`). A pre-built
144
+ * `Request` (possibly a one-shot stream body) is sent once, never retried.
145
+ */
146
+ get: (name: string, options?: InstanceRetryOptions) => ContainerInstanceHandle;
77
147
  /**
78
148
  * A resilient handle over the pool: each `fetch` picks a random instance and,
79
149
  * on a thrown error or a retryable response (5xx by default), retries on a
@@ -110,6 +180,24 @@ interface PoolOptions {
110
180
  /** Pool size to spread picks across. Defaults to the definition's `maxInstances`, else 3. */
111
181
  size?: number;
112
182
  }
183
+ /**
184
+ * Tuning for the cold-start retry on a `.get()`/`.any()` handle. The retry fires
185
+ * only on the platform's provisioning transients (no-instance / not-listening /
186
+ * rate-limited — see {@link isColdStartTransient}), which is why it's safe by
187
+ * default: those responses mean the request never reached the container.
188
+ */
189
+ interface InstanceRetryOptions {
190
+ /**
191
+ * Total attempts on a cold-start transient before the last outcome is
192
+ * surfaced as-is. `1` disables the retry. Default
193
+ * {@link DEFAULT_COLD_START_ATTEMPTS}.
194
+ */
195
+ attempts?: number;
196
+ /** Base backoff in ms between attempts; doubles each retry (0 disables the wait). Default {@link DEFAULT_COLD_START_BACKOFF_MS}. */
197
+ backoffMs?: number;
198
+ /** Upper bound on a single backoff sleep, in ms. Default {@link DEFAULT_MAX_BACKOFF_MS} (30s). */
199
+ maxBackoffMs?: number;
200
+ }
113
201
  /** Wiring info for one definition, emitted by codegen into the generated DO. */
114
202
  interface ContainerBindingSpec {
115
203
  /** Durable Object binding name, e.g. `CONTAINER_TRANSCODER`. */
@@ -126,7 +214,7 @@ interface ContainerBindingSpec {
126
214
  * handle is actually used — so one unprovisioned container never breaks
127
215
  * unrelated functions.
128
216
  */
129
- declare const createContainerContext: (env: Record<string, unknown>, specs: ReadonlyArray<ContainerBindingSpec>) => Record<string, ContainerAccessor>;
217
+ declare const createContainerContext: (env: Record<string, unknown>, specs: ReadonlyArray<ContainerBindingSpec>, jurisdiction?: DurableObjectJurisdiction) => Record<string, ContainerAccessor>;
130
218
  /** A test handler: receives the request plus the targeted instance name. */
131
219
  type ContainerTestHandler = (request: Request, instance: {
132
220
  name: string;
@@ -186,4 +274,4 @@ declare const isContainerDefinition: (value: unknown) => value is ContainerDefin
186
274
  * credential it was promised yields far worse errors downstream.
187
275
  */
188
276
  declare const resolveContainerEnvVariables: (definition: ContainerDefinition, workerEnv: Record<string, unknown>, exportName?: string) => Record<string, string>;
189
- export { type ContainerAccessor, type ContainerBindingSpec, type ContainerConfig, type ContainerDefinition, type ContainerHandle, type ContainerImageSource, type ContainerInstanceHandle, type ContainerInstanceState, type ContainerNamespaceLike, type ContainerStartOptions, type ContainerTestHandler, type NormalizedContainerImage, type PoolOptions, containerBindingName, containerBuildTag, containerClassName, createContainerContext, createContainerTestContext, defineContainer, isContainerDefinition, normalizeContainerImage, resolveContainerEnvVariables as resolveContainerEnvVars };
277
+ export { type ContainerAccessor, type ContainerBindingSpec, type ContainerConfig, type ContainerDefinition, type ContainerEgressControls, type ContainerHandle, type ContainerImageSource, type ContainerInstanceHandle, type ContainerInstanceState, type ContainerNamespaceLike, type ContainerStartOptions, type ContainerTestHandler, type DurableObjectJurisdiction, type InstanceRetryOptions, type NormalizedContainerImage, type PoolOptions, containerBindingName, containerBuildTag, containerClassName, createContainerContext, createContainerTestContext, defineContainer, isContainerDefinition, normalizeContainerImage, resolveContainerEnvVariables as resolveContainerEnvVars };