@lunora/container 1.0.0-alpha.1 → 1.0.0-alpha.100
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/LICENSE.md +26 -0
- package/README.md +118 -3
- package/__assets__/package-og.svg +1 -1
- package/dist/bridge.d.mts +60 -35
- package/dist/bridge.d.ts +60 -35
- package/dist/bridge.mjs +1 -76
- package/dist/do/index.d.mts +870 -32
- package/dist/do/index.d.ts +870 -32
- package/dist/do/index.mjs +1 -119
- package/dist/index.d.mts +634 -109
- package/dist/index.d.ts +634 -109
- package/dist/index.mjs +1 -2
- package/dist/otel.d.mts +217 -0
- package/dist/otel.d.ts +217 -0
- package/dist/otel.mjs +1 -0
- package/dist/packem_shared/CONTAINER_EXEC_PATH-7Hcd6-zs.mjs +1 -0
- package/dist/packem_shared/CUSTOM_INSTANCE_MIN_MEMORY_MIB_PER_VCPU-D8Hy9Rxv.mjs +1 -0
- package/dist/packem_shared/ContainerProxy-CfXjS6ZI.mjs +27 -0
- package/dist/packem_shared/DURABLE_OBJECT_POLICY_FORBIDDEN_KEYS-gYi8RBUO.mjs +1 -0
- package/dist/packem_shared/LunoraSandboxContainer-DPnhJUu1.mjs +1 -0
- package/dist/packem_shared/abort-deadline-jwbW9Ala.mjs +1 -0
- package/dist/packem_shared/createContainerContext-p6QxWjsm.mjs +1 -0
- package/dist/packem_shared/exec-BYLW70sR.mjs +1 -0
- package/dist/packem_shared/jurisdiction-DtE9s70w.mjs +1 -0
- package/dist/packem_shared/jurisdiction.d-BwpauCoI.d.mts +471 -0
- package/dist/packem_shared/jurisdiction.d-BwpauCoI.d.ts +471 -0
- package/dist/packem_shared/sampling-D21rpu_s.mjs +1 -0
- package/dist/packem_shared/sandbox-types.d-DXlHnsEg.d.mts +110 -0
- package/dist/packem_shared/sandbox-types.d-DXlHnsEg.d.ts +110 -0
- package/dist/sandbox/index.d.mts +66 -0
- package/dist/sandbox/index.d.ts +66 -0
- package/dist/sandbox/index.mjs +1 -0
- package/package.json +13 -3
- package/dist/packem_shared/containerBindingName-BGdSdFNA.mjs +0 -116
- package/dist/packem_shared/createContainerContext-ChDD53ys.mjs +0 -122
- package/dist/packem_shared/types.d-D2l2SYol.d.mts +0 -140
- package/dist/packem_shared/types.d-D2l2SYol.d.ts +0 -140
package/dist/do/index.d.mts
CHANGED
|
@@ -1,43 +1,881 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* `@lunora/container/do` — the workerd-only half of the package.
|
|
3
|
+
*
|
|
4
|
+
* `@cloudflare/containers` imports `cloudflare:workers` at module scope, so
|
|
5
|
+
* anything touching it lives behind this subpath: the package root stays
|
|
6
|
+
* importable from Node tooling (codegen, config, app unit tests) while the
|
|
7
|
+
* generated `_generated/containers.ts` imports the base class from here.
|
|
8
|
+
*/
|
|
9
|
+
import { d as ContainerRuntimeInstanceType, C as ContainerDefinition, D as DurableObjectJurisdiction, b as ContainerSnapshot, e as ContainerSpawnRequest } from "../packem_shared/jurisdiction.d-BwpauCoI.mjs";
|
|
10
|
+
import { DurableObject, WorkerEntrypoint, RpcTarget } from 'cloudflare:workers';
|
|
11
|
+
/**
|
|
12
|
+
* ContainerStartOptions as they come from worker types
|
|
13
|
+
*/
|
|
14
|
+
type ContainerStartOptions = NonNullable<Parameters<NonNullable<DurableObject['ctx']['container']>['start']>[0]>;
|
|
15
|
+
/**
|
|
16
|
+
* Options for container configuration
|
|
17
|
+
*/
|
|
18
|
+
interface ContainerOptions {
|
|
19
|
+
/** Optional ID for the container */
|
|
20
|
+
id?: string;
|
|
21
|
+
/** Default port number to connect to (defaults to container.defaultPort) */
|
|
22
|
+
defaultPort?: number;
|
|
23
|
+
/** How long to keep the container alive without activity */
|
|
24
|
+
sleepAfter?: string | number;
|
|
25
|
+
/** Environment variables to pass to the container */
|
|
26
|
+
envVars?: Record<string, string>;
|
|
27
|
+
/** Custom entrypoint to override container default */
|
|
28
|
+
entrypoint?: string[];
|
|
29
|
+
/** Whether to enable internet access for the container */
|
|
30
|
+
enableInternet?: boolean;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Options for starting a container with specific configuration
|
|
34
|
+
*/
|
|
35
|
+
interface ContainerStartConfigOptions {
|
|
36
|
+
/** Environment variables to pass to the container */
|
|
37
|
+
envVars?: Record<string, string>;
|
|
38
|
+
/** Custom entrypoint to override container default */
|
|
39
|
+
entrypoint?: string[];
|
|
40
|
+
/** Whether to enable internet access for the container */
|
|
41
|
+
enableInternet?: boolean;
|
|
42
|
+
/** Key-value metadata labels attached to the container for metrics/observability */
|
|
43
|
+
labels?: Record<string, string>;
|
|
44
|
+
}
|
|
45
|
+
interface StartAndWaitForPortsOptions {
|
|
46
|
+
startOptions?: ContainerStartConfigOptions;
|
|
47
|
+
ports?: number | number[];
|
|
48
|
+
cancellationOptions?: CancellationOptions;
|
|
49
|
+
}
|
|
50
|
+
/** cancellationOptions for startAndWaitForPorts() */
|
|
51
|
+
interface CancellationOptions {
|
|
52
|
+
/** abort signal, use to abort startAndWaitForPorts manually. */
|
|
53
|
+
abort?: AbortSignal;
|
|
54
|
+
/** max time to get container instance and start it (application inside may not be ready), in milliseconds */
|
|
55
|
+
instanceGetTimeoutMS?: number;
|
|
56
|
+
/** max time to wait for application to be listening at all specified ports, in milliseconds. */
|
|
57
|
+
portReadyTimeoutMS?: number;
|
|
58
|
+
/** time to wait between polling, in milliseconds */
|
|
59
|
+
waitInterval?: number;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Options for waitForPort()
|
|
63
|
+
*/
|
|
64
|
+
interface WaitOptions {
|
|
65
|
+
/** The port number to check for readiness */
|
|
66
|
+
portToCheck: number;
|
|
67
|
+
/** Optional AbortSignal, use this to abort waiting for ports */
|
|
68
|
+
signal?: AbortSignal;
|
|
69
|
+
/** Number of attempts to wait for port to be ready */
|
|
70
|
+
retries?: number;
|
|
71
|
+
/** Time to wait in between polling port for readiness, in milliseconds */
|
|
72
|
+
waitInterval?: number;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Represents a scheduled task within a Container
|
|
76
|
+
* @template T Type of the payload data
|
|
77
|
+
*/
|
|
78
|
+
type Schedule<T = string> = {
|
|
79
|
+
/** Unique identifier for the schedule */
|
|
80
|
+
taskId: string;
|
|
81
|
+
/** Name of the method to be called */
|
|
82
|
+
callback: string;
|
|
83
|
+
/** Data to be passed to the callback */
|
|
84
|
+
payload: T;
|
|
85
|
+
} & ({
|
|
86
|
+
/** Type of schedule for one-time execution at a specific time */
|
|
87
|
+
type: 'scheduled';
|
|
88
|
+
/** Timestamp when the task should execute */
|
|
89
|
+
time: number;
|
|
90
|
+
} | {
|
|
91
|
+
/** Type of schedule for delayed execution */
|
|
92
|
+
type: 'delayed';
|
|
93
|
+
/** Timestamp when the task should execute */
|
|
94
|
+
time: number;
|
|
95
|
+
/** Number of seconds to delay execution */
|
|
96
|
+
delayInSeconds: number;
|
|
97
|
+
});
|
|
98
|
+
/**
|
|
99
|
+
* Params sent to `onStop` method when the container stops
|
|
100
|
+
*/
|
|
101
|
+
type StopParams = {
|
|
102
|
+
exitCode: number;
|
|
103
|
+
reason: 'exit' | 'runtime_signal';
|
|
104
|
+
};
|
|
105
|
+
type State = {
|
|
106
|
+
lastChange: number;
|
|
107
|
+
} & ({
|
|
108
|
+
status: 'running' | 'stopping' | 'stopped' | 'healthy';
|
|
109
|
+
} | {
|
|
110
|
+
status: 'stopped_with_code';
|
|
111
|
+
exitCode?: number;
|
|
112
|
+
});
|
|
113
|
+
type OutboundHandlerContext<Params = unknown> = {
|
|
114
|
+
containerId: string;
|
|
115
|
+
className: string;
|
|
116
|
+
} & ([Params] extends [undefined] ? {
|
|
117
|
+
params?: undefined;
|
|
118
|
+
} : undefined extends Params ? {
|
|
119
|
+
params?: Params;
|
|
120
|
+
} : {
|
|
121
|
+
params: Params;
|
|
122
|
+
});
|
|
123
|
+
type OutboundParamsArg<Params> = [Params] extends [undefined] ? [] : undefined extends Params ? [params?: Params] : [params: Params];
|
|
124
|
+
type OutboundHandler<E = Cloudflare.Env, P = unknown> = {
|
|
125
|
+
bivarianceHack(req: Request, env: E, ctx: OutboundHandlerContext<P>): Promise<Response> | Response;
|
|
126
|
+
}['bivarianceHack'];
|
|
127
|
+
type OutboundHandlerParams = Record<string, unknown>;
|
|
128
|
+
type OutboundHandlerParamsOf<THandler> = THandler extends ((req: Request, env: unknown, ctx: OutboundHandlerContext<infer Params>) => Promise<Response> | Response) ? Params : never;
|
|
129
|
+
declare function outboundParams<THandler extends OutboundHandler<unknown, unknown>>(_handler: THandler, params: OutboundHandlerParamsOf<THandler>): OutboundHandlerParamsOf<THandler>;
|
|
130
|
+
type OutboundHandlers<ParamsByMethod extends OutboundHandlerParams, E = Cloudflare.Env> = { [Method in keyof ParamsByMethod]?: OutboundHandler<E, ParamsByMethod[Method]>; };
|
|
131
|
+
type OutboundHandlerOverride<Params = unknown> = {
|
|
132
|
+
method: string;
|
|
133
|
+
} & ([Params] extends [undefined] ? {
|
|
134
|
+
params?: undefined;
|
|
135
|
+
} : undefined extends Params ? {
|
|
136
|
+
params?: Params;
|
|
137
|
+
} : {
|
|
138
|
+
params: Params;
|
|
139
|
+
});
|
|
140
|
+
type OutboundByHostOverrides = Record<string, OutboundHandlerOverride>;
|
|
141
|
+
type OutboundByHostOverrideInput<Params = unknown> = Record<string, string | OutboundHandlerOverride<Params>>;
|
|
142
|
+
type Signal = 'SIGKILL' | 'SIGINT' | 'SIGTERM';
|
|
143
|
+
type SignalInteger = number;
|
|
144
|
+
type ContainerProxyOptions = {
|
|
145
|
+
enableInternet?: boolean;
|
|
146
|
+
containerId: string;
|
|
147
|
+
className: string;
|
|
148
|
+
outboundByHostOverrides?: OutboundByHostOverrides;
|
|
149
|
+
outboundHandlerOverride?: OutboundHandlerOverride;
|
|
150
|
+
allowedHosts?: string[];
|
|
151
|
+
deniedHosts?: string[];
|
|
152
|
+
interceptAll?: boolean;
|
|
153
|
+
};
|
|
154
|
+
declare class ContainerProxy extends WorkerEntrypoint<Cloudflare.Env, ContainerProxyOptions> {
|
|
155
|
+
fetch(request: Request): Promise<Response>;
|
|
156
|
+
}
|
|
157
|
+
declare class Container<Env = Cloudflare.Env> extends DurableObject<Env> {
|
|
158
|
+
static get outboundByHost(): Record<string, OutboundHandler> | undefined;
|
|
159
|
+
static set outboundByHost(handlers: Record<string, OutboundHandler>);
|
|
160
|
+
static get outboundHandlers(): Record<string, OutboundHandler> | undefined;
|
|
161
|
+
static set outboundHandlers(handlers: Record<string, OutboundHandler>);
|
|
162
|
+
static get outbound(): OutboundHandler | undefined;
|
|
163
|
+
static set outbound(handler: OutboundHandler);
|
|
164
|
+
static get outboundProxies(): Record<string, OutboundHandler> | undefined;
|
|
165
|
+
static set outboundProxies(handlers: Record<string, OutboundHandler>);
|
|
166
|
+
static get outboundProxy(): OutboundHandler | undefined;
|
|
167
|
+
static set outboundProxy(handler: OutboundHandler);
|
|
168
|
+
defaultPort?: number;
|
|
169
|
+
requiredPorts?: number[];
|
|
170
|
+
sleepAfter: string | number;
|
|
171
|
+
envVars: ContainerStartOptions['env'];
|
|
172
|
+
entrypoint: ContainerStartOptions['entrypoint'];
|
|
173
|
+
enableInternet: ContainerStartOptions['enableInternet'];
|
|
174
|
+
labels: ContainerStartOptions['labels'];
|
|
175
|
+
interceptHttps: boolean;
|
|
176
|
+
allowedHosts?: string[];
|
|
177
|
+
deniedHosts?: string[];
|
|
178
|
+
pingEndpoint: string;
|
|
179
|
+
applyOutboundInterceptionPromise: Promise<void>;
|
|
180
|
+
usingInterception: boolean;
|
|
181
|
+
constructor(ctx: DurableObject['ctx'], env: Env, options?: ContainerOptions);
|
|
182
|
+
/**
|
|
183
|
+
* Gets the current state of the container
|
|
184
|
+
* @returns Promise<State>
|
|
185
|
+
*/
|
|
186
|
+
getState(): Promise<State>;
|
|
187
|
+
/**
|
|
188
|
+
* Set the catch-all outbound handler to a named method from `outboundHandlers`.
|
|
189
|
+
* Overrides the default `outbound` at runtime via ContainerProxy props.
|
|
190
|
+
*
|
|
191
|
+
* @param methodName - Name of a method defined in `static outboundHandlers`
|
|
192
|
+
* @param params - Optional params passed to the handler as `ctx.params`
|
|
193
|
+
* @throws Error if the method name is not found in `outboundHandlers`
|
|
194
|
+
*/
|
|
195
|
+
setOutboundHandler<Params = unknown>(methodName: string, ...paramsArg: OutboundParamsArg<Params>): Promise<void>;
|
|
196
|
+
/**
|
|
197
|
+
* Add or override a hostname-specific outbound handler at runtime,
|
|
198
|
+
* referencing a named method from `outboundHandlers`.
|
|
199
|
+
* Overrides any matching entry in `static outboundByHost` for this hostname.
|
|
200
|
+
*
|
|
201
|
+
* @param hostname - The hostname or ip:port to intercept (e.g. `'google.com'`)
|
|
202
|
+
* @param methodName - Name of a method defined in `static outboundHandlers`
|
|
203
|
+
* @param params - Optional params passed to the handler as `ctx.params`
|
|
204
|
+
* @throws Error if the method name is not found in `outboundHandlers`
|
|
205
|
+
*/
|
|
206
|
+
setOutboundByHost<Params = unknown>(hostname: string, methodName: string, ...paramsArg: OutboundParamsArg<Params>): Promise<void>;
|
|
207
|
+
/**
|
|
208
|
+
* Remove a runtime hostname override added via `setOutboundByHost`.
|
|
209
|
+
* The default handler from `static outboundByHost` (if any) will be used again.
|
|
210
|
+
*
|
|
211
|
+
* @param hostname - The hostname or ip:port to stop overriding
|
|
212
|
+
*/
|
|
213
|
+
removeOutboundByHost(hostname: string): Promise<void>;
|
|
214
|
+
/**
|
|
215
|
+
* Replace all runtime hostname overrides at once.
|
|
216
|
+
* Each value may be either a method name or an object with `method` and `params`.
|
|
217
|
+
*
|
|
218
|
+
* @param handlers - Record mapping hostnames to handler configs in `outboundHandlers`
|
|
219
|
+
* @throws Error if any method name is not found in `outboundHandlers`
|
|
220
|
+
*/
|
|
221
|
+
setOutboundByHosts<Params = unknown>(handlers: OutboundByHostOverrideInput<Params>): Promise<void>;
|
|
222
|
+
/**
|
|
223
|
+
* Replace all allowed hosts at runtime.
|
|
224
|
+
* Allowed hosts get internet access even when `enableInternet` is false.
|
|
225
|
+
*
|
|
226
|
+
* @param hosts - Array of hostnames to allow (e.g. `['api.stripe.com', 'example.com']`)
|
|
227
|
+
*/
|
|
228
|
+
setAllowedHosts(hosts: string[]): Promise<void>;
|
|
229
|
+
/**
|
|
230
|
+
* Replace all denied hosts at runtime.
|
|
231
|
+
* Denied hosts are blocked unconditionally, even when `enableInternet` is true
|
|
232
|
+
* or a catch-all outbound handler is set.
|
|
233
|
+
*
|
|
234
|
+
* @param hosts - Array of hostnames to deny (e.g. `['evil.com', 'blocked.org']`)
|
|
235
|
+
*/
|
|
236
|
+
setDeniedHosts(hosts: string[]): Promise<void>;
|
|
237
|
+
/**
|
|
238
|
+
* Add a single hostname to the allowed hosts list at runtime.
|
|
239
|
+
*
|
|
240
|
+
* @param hostname - The hostname to allow (e.g. `'api.stripe.com'`)
|
|
241
|
+
*/
|
|
242
|
+
allowHost(hostname: string): Promise<void>;
|
|
243
|
+
/**
|
|
244
|
+
* Add a single hostname to the denied hosts list at runtime.
|
|
245
|
+
*
|
|
246
|
+
* @param hostname - The hostname to deny (e.g. `'evil.com'`)
|
|
247
|
+
*/
|
|
248
|
+
denyHost(hostname: string): Promise<void>;
|
|
249
|
+
/**
|
|
250
|
+
* Remove a hostname from the allowed hosts list.
|
|
251
|
+
*
|
|
252
|
+
* @param hostname - The hostname to remove from the allow list
|
|
253
|
+
*/
|
|
254
|
+
removeAllowedHost(hostname: string): Promise<void>;
|
|
255
|
+
/**
|
|
256
|
+
* Remove a hostname from the denied hosts list.
|
|
257
|
+
*
|
|
258
|
+
* @param hostname - The hostname to remove from the deny list
|
|
259
|
+
*/
|
|
260
|
+
removeDeniedHost(hostname: string): Promise<void>;
|
|
261
|
+
/**
|
|
262
|
+
* Start the container if it's not running and set up monitoring and lifecycle hooks,
|
|
263
|
+
* without waiting for ports to be ready.
|
|
264
|
+
*
|
|
265
|
+
* It will automatically retry if the container fails to start, using the specified waitOptions
|
|
266
|
+
*
|
|
267
|
+
*
|
|
268
|
+
* @example
|
|
269
|
+
* await this.start({
|
|
270
|
+
* envVars: { DEBUG: 'true', NODE_ENV: 'development' },
|
|
271
|
+
* entrypoint: ['npm', 'run', 'dev'],
|
|
272
|
+
* enableInternet: false,
|
|
273
|
+
* labels: { tenant: 'acme', env: 'prod' },
|
|
274
|
+
* });
|
|
275
|
+
*
|
|
276
|
+
* @param startOptions - Override `envVars`, `entrypoint`, `enableInternet` and `labels` on a per-instance basis
|
|
277
|
+
* @param waitOptions - Optional wait configuration with abort signal for cancellation. Default ~8s timeout.
|
|
278
|
+
* @returns A promise that resolves when the container start command has been issued
|
|
279
|
+
* @throws Error if no container context is available or if all start attempts fail
|
|
280
|
+
*/
|
|
281
|
+
start(startOptions?: ContainerStartConfigOptions, waitOptions?: WaitOptions): Promise<void>;
|
|
282
|
+
/**
|
|
283
|
+
* Start the container and wait for ports to be available.
|
|
284
|
+
*
|
|
285
|
+
* For each specified port, it polls until the port is available or `cancellationOptions.portReadyTimeoutMS` is reached.
|
|
286
|
+
*
|
|
287
|
+
* @param ports - The ports to wait for (if undefined, uses requiredPorts or defaultPort)
|
|
288
|
+
* @param cancellationOptions - Options to configure timeouts, polling intereva, and abort signal
|
|
289
|
+
* @param startOptions Override configuration on a per-instance basis for env vars, entrypoint command, internet access, and labels
|
|
290
|
+
* @returns A promise that resolves when the container has been started and the ports are listening
|
|
291
|
+
* @throws Error if port checks fail after the specified timeout or if the container fails to start.
|
|
292
|
+
*/
|
|
293
|
+
startAndWaitForPorts(args: StartAndWaitForPortsOptions): Promise<void>;
|
|
294
|
+
startAndWaitForPorts(ports?: number | number[], cancellationOptions?: CancellationOptions, startOptions?: ContainerStartConfigOptions): Promise<void>;
|
|
295
|
+
startAndWaitForPorts(portsOrArgs?: number | number[] | StartAndWaitForPortsOptions, cancellationOptions?: CancellationOptions, startOptions?: ContainerStartConfigOptions): Promise<void>;
|
|
296
|
+
/**
|
|
297
|
+
*
|
|
298
|
+
* Waits for a specified port to be ready
|
|
299
|
+
*
|
|
300
|
+
* Returns the number of tries used to get the port, or throws if it couldn't get the port within the specified retry limits.
|
|
301
|
+
*
|
|
302
|
+
* @param waitOptions -
|
|
303
|
+
* - `portToCheck`: The port number to check
|
|
304
|
+
* - `abort`: Optional AbortSignal to cancel waiting
|
|
305
|
+
* - `retries`: Number of retries before giving up (default: TRIES_TO_GET_PORTS)
|
|
306
|
+
* - `waitInterval`: Interval between retries in milliseconds (default: INSTANCE_POLL_INTERVAL_MS)
|
|
307
|
+
*/
|
|
308
|
+
waitForPort(waitOptions: WaitOptions): Promise<number>;
|
|
309
|
+
/**
|
|
310
|
+
* Send a signal to the container.
|
|
311
|
+
* @param signal - The signal to send to the container (default: 15 for SIGTERM)
|
|
312
|
+
*/
|
|
313
|
+
stop(signal?: Signal | SignalInteger): Promise<void>;
|
|
314
|
+
/**
|
|
315
|
+
* Destroys the container with a SIGKILL. Triggers onStop.
|
|
316
|
+
*/
|
|
317
|
+
destroy(): Promise<void>;
|
|
318
|
+
/**
|
|
319
|
+
* Lifecycle method called when container starts successfully
|
|
320
|
+
* Override this method in subclasses to handle container start events
|
|
321
|
+
*/
|
|
322
|
+
onStart(): void | Promise<void>;
|
|
323
|
+
/**
|
|
324
|
+
* Lifecycle method called when container shuts down
|
|
325
|
+
* Override this method in subclasses to handle Container stopped events
|
|
326
|
+
* @param params - Object containing exitCode and reason for the stop
|
|
327
|
+
*/
|
|
328
|
+
onStop(params: StopParams): void | Promise<void>;
|
|
329
|
+
/**
|
|
330
|
+
* Lifecycle method called when the container is running, and the activity timeout
|
|
331
|
+
* expiration (set by `sleepAfter`) has been reached.
|
|
332
|
+
*
|
|
333
|
+
* If you want to shutdown the container, you should call this.stop() here
|
|
334
|
+
*
|
|
335
|
+
* By default, this method calls `this.stop()`
|
|
336
|
+
*/
|
|
337
|
+
onActivityExpired(): Promise<void>;
|
|
338
|
+
/**
|
|
339
|
+
* Error handler for container errors
|
|
340
|
+
* Override this method in subclasses to handle container errors
|
|
341
|
+
* @param error - The error that occurred
|
|
342
|
+
* @returns Can return any value or throw the error
|
|
343
|
+
*/
|
|
344
|
+
onError(error: unknown): unknown;
|
|
345
|
+
/**
|
|
346
|
+
* Renew the container's activity timeout
|
|
347
|
+
*
|
|
348
|
+
* Call this method whenever there is activity on the container
|
|
349
|
+
*/
|
|
350
|
+
renewActivityTimeout(): void;
|
|
351
|
+
/**
|
|
352
|
+
* Decrement the inflight request counter.
|
|
353
|
+
* When the counter transitions to 0, renew the activity timeout so the
|
|
354
|
+
* inactivity window starts fresh from the moment the last request completes.
|
|
355
|
+
*/
|
|
356
|
+
protected decrementInflight(): void;
|
|
357
|
+
/**
|
|
358
|
+
* Schedule a task to be executed in the future.
|
|
359
|
+
*
|
|
360
|
+
* We strongly recommend using this instead of the `alarm` handler.
|
|
361
|
+
*
|
|
362
|
+
* @template T Type of the payload data
|
|
363
|
+
* @param when When to execute the task (Date object or number of seconds delay)
|
|
364
|
+
* @param callback Name of the method to call
|
|
365
|
+
* @param payload Data to pass to the callback
|
|
366
|
+
* @returns Schedule object representing the scheduled task
|
|
367
|
+
*/
|
|
368
|
+
schedule<T = string>(when: Date | number, callback: string, payload?: T): Promise<Schedule<T>>;
|
|
369
|
+
/**
|
|
370
|
+
* Send a request to the container (HTTP or WebSocket) using standard fetch API signature
|
|
371
|
+
*
|
|
372
|
+
* This method handles HTTP requests to the container.
|
|
373
|
+
*
|
|
374
|
+
* WebSocket requests done outside the DO won't work until https://github.com/cloudflare/workerd/issues/2319 is addressed.
|
|
375
|
+
* Until then, please use `switchPort` + `fetch()`.
|
|
376
|
+
*
|
|
377
|
+
* Method supports multiple signatures to match standard fetch API:
|
|
378
|
+
* - containerFetch(request: Request, port?: number)
|
|
379
|
+
* - containerFetch(url: string | URL, init?: RequestInit, port?: number)
|
|
380
|
+
*
|
|
381
|
+
* Starts the container if not already running, and waits for the target port to be ready.
|
|
382
|
+
*
|
|
383
|
+
* @returns A Response from the container
|
|
384
|
+
*/
|
|
385
|
+
containerFetch(requestOrUrl: Request | string | URL, portOrInit?: number | RequestInit, portParam?: number): Promise<Response>;
|
|
386
|
+
/**
|
|
387
|
+
*
|
|
388
|
+
* Fetch handler on the Container class.
|
|
389
|
+
* By default this forwards all requests to the container by calling `containerFetch`.
|
|
390
|
+
* Use `switchPort` to specify which port on the container to target, or this will use `defaultPort`.
|
|
391
|
+
* @param request The request to handle
|
|
392
|
+
*/
|
|
393
|
+
fetch(request: Request): Promise<Response>;
|
|
394
|
+
private container;
|
|
395
|
+
private onStopCalled;
|
|
396
|
+
private state;
|
|
397
|
+
private monitor;
|
|
398
|
+
protected startInFlight?: Promise<unknown>;
|
|
399
|
+
private monitoredPromise;
|
|
400
|
+
private sleepAfterMs;
|
|
401
|
+
protected inflightRequests: number;
|
|
402
|
+
/** Patched (Lunora): the `durable_object`-policy image reference and size `start()` forwards. */
|
|
403
|
+
protected image?: string;
|
|
404
|
+
protected instance?: string | {
|
|
405
|
+
vcpu: number;
|
|
406
|
+
memoryMib: number;
|
|
407
|
+
diskMb: number;
|
|
408
|
+
};
|
|
409
|
+
private outboundByHostOverrides;
|
|
410
|
+
private outboundHandlerOverride?;
|
|
411
|
+
private allowedHostsOverride?;
|
|
412
|
+
private deniedHostsOverride?;
|
|
413
|
+
private hasInterceptAllRegistration;
|
|
414
|
+
/**
|
|
415
|
+
* Validates that a method name exists in the outboundHandlers registry for this class.
|
|
416
|
+
* @throws Error if the method name is not found
|
|
417
|
+
*/
|
|
418
|
+
private validateOutboundHandlerMethodName;
|
|
419
|
+
private get effectiveAllowedHosts();
|
|
420
|
+
private get effectiveDeniedHosts();
|
|
421
|
+
private getOutboundConfiguration;
|
|
422
|
+
private persistOutboundConfiguration;
|
|
423
|
+
private restoreOutboundConfiguration;
|
|
424
|
+
/**
|
|
425
|
+
* Returns true if a catch-all outbound HTTP interception is needed.
|
|
426
|
+
* This is the case when a static `outbound` handler or a runtime
|
|
427
|
+
* `outboundHandlerOverride` (catch-all) is configured.
|
|
428
|
+
* When false, we only intercept specific hosts to avoid overhead.
|
|
429
|
+
*/
|
|
430
|
+
private needsCatchAllInterception;
|
|
431
|
+
private hasMutableOutboundConfiguration;
|
|
432
|
+
private shouldInterceptAllOutbound;
|
|
433
|
+
private getStaticOutboundByHostKeys;
|
|
434
|
+
/**
|
|
435
|
+
* Collects all hostnames that need per-host outbound interception.
|
|
436
|
+
* This path is only used for the narrow optimized case where outbound
|
|
437
|
+
* handling is static and host-specific.
|
|
438
|
+
*/
|
|
439
|
+
private getHostsToIntercept;
|
|
440
|
+
private refreshOutboundInterception;
|
|
441
|
+
/**
|
|
442
|
+
* Applies (or re-applies) outbound HTTP interception with the current
|
|
443
|
+
* default registries + runtime overrides passed through ContainerProxy props.
|
|
444
|
+
*
|
|
445
|
+
* Uses per-host interception only for static host-specific outbound handlers.
|
|
446
|
+
* As soon as the config needs to evaluate all hosts (catch-all outbound,
|
|
447
|
+
* allow/deny lists, or runtime-mutated outbound config), we promote the
|
|
448
|
+
* container to intercept-all and keep it there until the instance restarts.
|
|
449
|
+
*
|
|
450
|
+
* When `interceptHttps` is enabled, also applies HTTPS interception:
|
|
451
|
+
* - Intercept-all mode: `interceptOutboundHttps('*', ...)` for all HTTPS traffic
|
|
452
|
+
* - Per-host mode: `interceptOutboundHttps(host, ...)` for each known host
|
|
453
|
+
*/
|
|
454
|
+
private applyOutboundInterception;
|
|
455
|
+
/**
|
|
456
|
+
* Execute SQL queries against the Container's database
|
|
457
|
+
*/
|
|
458
|
+
private sql;
|
|
459
|
+
private requestAndPortFromContainerFetchArgs;
|
|
460
|
+
/**
|
|
461
|
+
*
|
|
462
|
+
* The method prioritizes port sources in this order:
|
|
463
|
+
* 1. Ports specified directly in the method call
|
|
464
|
+
* 2. `requiredPorts` class property (if set)
|
|
465
|
+
* 3. `defaultPort` (if neither of the above is specified)
|
|
466
|
+
* 4. Falls back to port 33 if none of the above are set
|
|
467
|
+
*/
|
|
468
|
+
private getPortsToCheck;
|
|
469
|
+
/**
|
|
470
|
+
* Tries to start a container if it's not already running
|
|
471
|
+
* Returns the number of tries used
|
|
472
|
+
*/
|
|
473
|
+
private startContainerIfNotRunning;
|
|
474
|
+
private doStartContainer;
|
|
475
|
+
private setupMonitorCallbacks;
|
|
476
|
+
deleteSchedules(name: string): void;
|
|
477
|
+
/**
|
|
478
|
+
* Method called when an alarm fires
|
|
479
|
+
* Executes any scheduled tasks that are due
|
|
480
|
+
*/
|
|
481
|
+
alarm(alarmProps?: AlarmInvocationInfo): Promise<void>;
|
|
482
|
+
timeout?: ReturnType<typeof setTimeout>;
|
|
483
|
+
resolve?: () => void;
|
|
484
|
+
private syncPendingStoppedEvents;
|
|
485
|
+
private callOnStop;
|
|
486
|
+
/**
|
|
487
|
+
* Schedule the next alarm based on upcoming tasks
|
|
488
|
+
*/
|
|
489
|
+
scheduleNextAlarm(ms?: number): Promise<void>;
|
|
490
|
+
listSchedules<T = string>(name: string): Promise<Schedule<T>[]>;
|
|
491
|
+
private toSchedule;
|
|
492
|
+
/**
|
|
493
|
+
* Get a scheduled task by ID
|
|
494
|
+
* @template T Type of the payload data
|
|
495
|
+
* @param id ID of the scheduled task
|
|
496
|
+
* @returns The Schedule object or undefined if not found
|
|
497
|
+
*/
|
|
498
|
+
getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined>;
|
|
499
|
+
private isActivityExpired;
|
|
500
|
+
}
|
|
501
|
+
/** The runtime's `ExecProcess`, structurally — only what a spawned process uses. */
|
|
502
|
+
interface NativeProcess {
|
|
503
|
+
exitCode: Promise<number>;
|
|
504
|
+
isPty?: boolean;
|
|
505
|
+
kill: (signal?: number) => void;
|
|
506
|
+
pid?: number;
|
|
507
|
+
resize?: (cols: number, rows: number) => void;
|
|
508
|
+
stderr?: ReadableStream | null;
|
|
509
|
+
stdin?: WritableStream | null;
|
|
510
|
+
stdout?: ReadableStream | null;
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Control half of a spawned process, returned to the caller as an RPC stub.
|
|
514
|
+
* The streams travel next to it in {@link SpawnedProcess}: a stream can cross
|
|
515
|
+
* RPC only once, so it is handed over directly rather than exposed through a
|
|
516
|
+
* property that could be read twice.
|
|
517
|
+
*/
|
|
518
|
+
declare class ContainerProcessControl extends RpcTarget {
|
|
519
|
+
#private;
|
|
520
|
+
constructor(process: NativeProcess, exit: Promise<number>);
|
|
521
|
+
/** Resolves with the exit code once the process ends. */
|
|
522
|
+
exitCode(): Promise<number>;
|
|
523
|
+
/** Send `signal` (default `SIGTERM`) to the process. A no-op once it has exited. */
|
|
524
|
+
kill(signal?: number): void;
|
|
525
|
+
/** Resize a PTY process's terminal. Throws for a process spawned without `pty`. */
|
|
526
|
+
resize(cols: number, rows: number): void;
|
|
527
|
+
}
|
|
528
|
+
/** What `lunoraSpawn` returns over RPC. */
|
|
529
|
+
interface SpawnedProcess {
|
|
530
|
+
control: ContainerProcessControl;
|
|
531
|
+
isPty: boolean;
|
|
532
|
+
pid: number;
|
|
533
|
+
/** `null` under `pty`, where stderr is merged into the terminal output. */
|
|
534
|
+
stderr: ReadableStream<Uint8Array> | null;
|
|
535
|
+
/** A writable stdin when the request asked for `stdin: true`, else `null`. */
|
|
536
|
+
stdin: WritableStream<Uint8Array> | null;
|
|
537
|
+
stdout: ReadableStream<Uint8Array> | null;
|
|
538
|
+
}
|
|
539
|
+
/** What an explicit `start()` chose that later restarts must reuse. */
|
|
540
|
+
interface StartOverride {
|
|
541
|
+
/** Replaces the declared env, `secrets` and `secretsStore` wholesale. */
|
|
542
|
+
envVars?: Record<string, string>;
|
|
543
|
+
/** A key of the definition's `images`, or a managed `cloudflare/…` image. */
|
|
544
|
+
image?: string;
|
|
545
|
+
instanceType?: ContainerRuntimeInstanceType;
|
|
546
|
+
}
|
|
3
547
|
type DurableObjectContext = ConstructorParameters<typeof Container>[0];
|
|
548
|
+
/** The runtime's `ctx.container`, once known to be present. */
|
|
549
|
+
type ContainerRuntime = NonNullable<DurableObjectContext["container"]>;
|
|
550
|
+
/** A running container plus the release for the in-flight count taken on it. See `LunoraContainer.lunoraAcquire`. */
|
|
551
|
+
interface AcquiredContainer {
|
|
552
|
+
container: ContainerRuntime;
|
|
553
|
+
/** Drop the in-flight count. Idempotent. */
|
|
554
|
+
release: () => void;
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* The `start()` options `LunoraContainer` accepts on top of the base's: the
|
|
558
|
+
* `durable_object`-policy image, size and snapshot to restore.
|
|
559
|
+
*/
|
|
560
|
+
type LunoraStartOptions = NonNullable<Parameters<Container["start"]>[0]> & Pick<StartOverride, "image" | "instanceType"> & {
|
|
561
|
+
snapshot?: ContainerSnapshot;
|
|
562
|
+
};
|
|
4
563
|
/**
|
|
5
|
-
* Base class for the generated Container DO classes. Applies a
|
|
6
|
-
* `defineContainer` definition onto `@cloudflare/containers`' `Container`:
|
|
7
|
-
* port, sleep timeout, internet access, and the container environment (static
|
|
8
|
-
* `env` merged with the declared Worker secrets — a declared-but-unset secret
|
|
9
|
-
* fails fast here rather than starting a container without its credential).
|
|
10
|
-
*
|
|
11
|
-
* Generated subclasses stay one line of behavior:
|
|
12
|
-
*
|
|
13
|
-
* ```ts
|
|
14
|
-
* export class TranscoderContainer extends LunoraContainer {
|
|
15
|
-
* constructor(ctx: DurableObjectState, env: Env) {
|
|
16
|
-
* super(ctx, env, transcoder, "transcoder");
|
|
17
|
-
* }
|
|
18
|
-
* }
|
|
19
|
-
* ```
|
|
20
|
-
*/
|
|
564
|
+
* Base class for the generated Container DO classes. Applies a
|
|
565
|
+
* `defineContainer` definition onto `@cloudflare/containers`' `Container`:
|
|
566
|
+
* port, sleep timeout, internet access, and the container environment (static
|
|
567
|
+
* `env` merged with the declared Worker secrets — a declared-but-unset secret
|
|
568
|
+
* fails fast here rather than starting a container without its credential).
|
|
569
|
+
*
|
|
570
|
+
* Generated subclasses stay one line of behavior:
|
|
571
|
+
*
|
|
572
|
+
* ```ts
|
|
573
|
+
* export class TranscoderContainer extends LunoraContainer {
|
|
574
|
+
* constructor(ctx: DurableObjectState, env: Env) {
|
|
575
|
+
* super(ctx, env, transcoder, "transcoder");
|
|
576
|
+
* }
|
|
577
|
+
* }
|
|
578
|
+
* ```
|
|
579
|
+
*/
|
|
21
580
|
declare class LunoraContainer<Env = unknown> extends Container<Env> {
|
|
22
|
-
/** The `lunora/containers.ts` export name, for lifecycle log correlation. */
|
|
23
|
-
|
|
24
|
-
|
|
581
|
+
/** The `lunora/containers.ts` export name, for lifecycle log correlation and error messages. */
|
|
582
|
+
protected readonly lunoraName: string;
|
|
583
|
+
/**
|
|
584
|
+
* Data-residency jurisdiction the app's DOs are pinned to (codegen passes the
|
|
585
|
+
* schema's `.jurisdiction("…")`). Used to pin the best-effort lifecycle report
|
|
586
|
+
* to the same region as the root shard. `undefined` ⇒ un-pinned.
|
|
587
|
+
*/
|
|
588
|
+
private readonly lunoraJurisdiction?;
|
|
589
|
+
/** Default port the readiness probes target when a check omits its own `port`. */
|
|
590
|
+
private readonly lunoraDefaultPort?;
|
|
591
|
+
/** Hard-cap lifetime in whole seconds (from the `hardTimeout` config), or `undefined`. */
|
|
592
|
+
private readonly lunoraHardTimeoutSeconds?;
|
|
593
|
+
/** In-flight `readyOn` gate for the current start; cleared when it fails. See `awaitReadinessGate`. */
|
|
594
|
+
private lunoraReadiness?;
|
|
595
|
+
/** Declarative readiness probes that gate request proxying (from the `readyOn` config). */
|
|
596
|
+
private readonly lunoraReadyOn;
|
|
597
|
+
/** Map of container env-var name → Worker Secrets Store binding name (from the `secretsStore` config). */
|
|
598
|
+
private readonly lunoraSecretsStore?;
|
|
599
|
+
/** The definition's `env` + `secrets`, as resolved at construction — the env a start uses absent an override. */
|
|
600
|
+
private readonly lunoraDeclaredEnv;
|
|
601
|
+
/** The persisted start override, once loaded. See {@link START_OVERRIDE_KEY}. */
|
|
602
|
+
private lunoraOverride?;
|
|
603
|
+
/** Whether the override field reflects storage (read once per DO instance, then kept in step). */
|
|
604
|
+
private lunoraOverrideLoaded;
|
|
605
|
+
/** Memoised Secrets Store resolution: the resolved `name → value` map, fetched once. */
|
|
606
|
+
private lunoraSecretsStoreResolved?;
|
|
607
|
+
/** Whether the definition uses the `durable_object` scheduling policy. */
|
|
608
|
+
private readonly lunoraDurableObjectScheduled;
|
|
609
|
+
/** The definition's default image name and instance size (`durable_object` policy only). */
|
|
610
|
+
private readonly lunoraDefaultSelection;
|
|
611
|
+
/**
|
|
612
|
+
* Count of runs observed to have ENDED, bumped by the `onStop` hook. Read
|
|
613
|
+
* across a start: a bump means the run that start snapshotted is over,
|
|
614
|
+
* whatever the `running` flag said at snapshot time. See `beginStart`.
|
|
615
|
+
*/
|
|
616
|
+
private lunoraStops;
|
|
617
|
+
constructor(context: DurableObjectContext, env: Env, definition: ContainerDefinition, exportName?: string, jurisdiction?: DurableObjectJurisdiction);
|
|
618
|
+
/**
|
|
619
|
+
* Save the running container's filesystem (`durable_object` policy only).
|
|
620
|
+
* The handle is plain data: store it and pass it to `start({ snapshot })` to
|
|
621
|
+
* restore it here or in another instance. Memory and processes are not
|
|
622
|
+
* captured — a restored container runs its entrypoint again.
|
|
623
|
+
*/
|
|
624
|
+
lunoraSnapshot(options?: {
|
|
625
|
+
name?: string;
|
|
626
|
+
}): Promise<ContainerSnapshot>;
|
|
627
|
+
/**
|
|
628
|
+
* HTTP entry for every request to this Durable Object. Refuses the reserved
|
|
629
|
+
* `/__lunora/*` namespace unconditionally: `exec` reaches it only through
|
|
630
|
+
* the {@link lunoraExec} RPC, so no header, path spelling, or inbound request
|
|
631
|
+
* an app forwards as-is (`env.CONTAINER_X.get(id).fetch(request)`) opens it.
|
|
632
|
+
* The client-side path guard is the first line; this is the second.
|
|
633
|
+
*/
|
|
634
|
+
override fetch(request: Request): Promise<Response>;
|
|
635
|
+
/**
|
|
636
|
+
* Proxy entry for every `ctx.containers.<name>` fetch — and a public RPC on
|
|
637
|
+
* the stub in its own right, so it applies the same `/__lunora/*` refusal
|
|
638
|
+
* as {@link fetch} rather than trusting that every caller came through it.
|
|
639
|
+
* The base starts the container for this request through
|
|
640
|
+
* {@link startAndWaitForPorts}, which is where the `secretsStore` resolution
|
|
641
|
+
* lives — a request that finds the container already healthy needs no
|
|
642
|
+
* resolution at all.
|
|
643
|
+
*/
|
|
644
|
+
override containerFetch(...args: Parameters<Container<Env>["containerFetch"]>): Promise<Response>;
|
|
645
|
+
/**
|
|
646
|
+
* The exec entry: `handle.exec` delivers its `POST /__lunora/exec` here, as
|
|
647
|
+
* an RPC, never over {@link fetch}. An RPC can only be invoked by code that
|
|
648
|
+
* holds the Durable Object binding, which is what makes the exec route
|
|
649
|
+
* unreachable from request content. Accepts exactly the exec route and
|
|
650
|
+
* nothing else under the reserved namespace, and honours a `.port(n)`
|
|
651
|
+
* handle's target-port header the way the base `fetch` does.
|
|
652
|
+
*/
|
|
653
|
+
lunoraExec(request: Request): Promise<Response>;
|
|
654
|
+
/**
|
|
655
|
+
* Start a process and stream it (`handle.spawn()`), through the runtime's
|
|
656
|
+
* native `ctx.container.exec()`. Starts the container first when it is not
|
|
657
|
+
* running, and counts the process in flight until it exits, so `sleepAfter`
|
|
658
|
+
* cannot stop the container under it. The process's streams and a control
|
|
659
|
+
* stub (`exitCode` / `kill` / `resize`) cross back over RPC.
|
|
660
|
+
*/
|
|
661
|
+
lunoraSpawn(request: ContainerSpawnRequest): Promise<SpawnedProcess>;
|
|
662
|
+
/**
|
|
663
|
+
* The start path `containerFetch` takes (and the one an app can call itself).
|
|
664
|
+
* Resolves the `secretsStore` bindings into `envVars` first — `doStartContainer`
|
|
665
|
+
* reads `this.envVars`, so a container started this way would otherwise boot
|
|
666
|
+
* without its Secrets Store values.
|
|
667
|
+
*
|
|
668
|
+
* The base's last act is `blockConcurrencyWhile(… onStart())`, so this
|
|
669
|
+
* override resumes on the far side of that gate — which is where
|
|
670
|
+
* {@link afterContainerStart} has to run. See its docblock.
|
|
671
|
+
*/
|
|
672
|
+
override startAndWaitForPorts(...args: Parameters<Container<Env>["startAndWaitForPorts"]>): Promise<void>;
|
|
673
|
+
/**
|
|
674
|
+
* Explicit start (`ctx.containers.<name>.get(id).start()`).
|
|
675
|
+
*
|
|
676
|
+
* A per-instance `start({ envVars })` REPLACES the declared env (`env`,
|
|
677
|
+
* `secrets`, `secretsStore` — the Secrets Store is not even read) and is
|
|
678
|
+
* PERSISTED: every later start of this instance, explicit or implicit (a
|
|
679
|
+
* `fetch`/`exec` after the container slept, crashed or hit `hardTimeout`),
|
|
680
|
+
* boots with the same variables until `destroy()`. That is what makes
|
|
681
|
+
* `start({ envVars: {} })` a credential-free sandbox rather than one that
|
|
682
|
+
* gets its credentials back on the next restart.
|
|
683
|
+
*
|
|
684
|
+
* A start with `envVars` that differ from what the instance is running (or
|
|
685
|
+
* starting) with is REJECTED rather than silently joined: the base would
|
|
686
|
+
* return early on a live container, reporting a start whose env never took
|
|
687
|
+
* effect. `stop()` it first, or `destroy()` it to drop the override.
|
|
688
|
+
*/
|
|
689
|
+
override start(options?: LunoraStartOptions, waitOptions?: Parameters<Container<Env>["start"]>[1]): Promise<void>;
|
|
690
|
+
/**
|
|
691
|
+
* Stop the container and forget this instance's start override, so the next
|
|
692
|
+
* start uses the declared env, image and size again.
|
|
693
|
+
*/
|
|
694
|
+
override destroy(): Promise<void>;
|
|
695
|
+
override onActivityExpired(): Promise<void>;
|
|
25
696
|
override onError(error: unknown): unknown;
|
|
26
697
|
override onStart(): Promise<void>;
|
|
698
|
+
/**
|
|
699
|
+
* Hook run when the container's `hardTimeout` elapses (dispatched by the base
|
|
700
|
+
* scheduler via the run-generation-stamped schedule armed in
|
|
701
|
+
* {@link onStart}). Default: stop the instance. Override to drain/checkpoint
|
|
702
|
+
* first. A stale schedule from a previous run, or an already-stopped
|
|
703
|
+
* instance, is ignored (upstream cloudflare/containers#85).
|
|
704
|
+
*
|
|
705
|
+
* `stop()` sends SIGTERM and returns; nothing escalates to `destroy()`. The
|
|
706
|
+
* cap is therefore a signal, not a bound — a container that traps or ignores
|
|
707
|
+
* SIGTERM keeps running, and the schedule is ONE-SHOT (the base deletes the
|
|
708
|
+
* row once it fires), so nothing signals it a second time either: an ignored
|
|
709
|
+
* SIGTERM means the cap is spent, not retried. Override this hook and follow
|
|
710
|
+
* the stop with a `destroy()` after a grace period if your workload needs a
|
|
711
|
+
* real ceiling.
|
|
712
|
+
*/
|
|
713
|
+
onHardTimeoutExpired(payload?: {
|
|
714
|
+
generation?: number;
|
|
715
|
+
}): Promise<void>;
|
|
27
716
|
override onStop(parameters: StopParams): Promise<void>;
|
|
28
717
|
/**
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
718
|
+
* Get the container running for an operation that talks to it through
|
|
719
|
+
* `ctx.container` rather than over HTTP (`spawn`, and the sandbox helpers),
|
|
720
|
+
* and count the operation in flight so `sleepAfter` cannot stop the
|
|
721
|
+
* container underneath it. Goes through the same readiness gate a proxied
|
|
722
|
+
* request does, and through {@link start} when the container is stopped —
|
|
723
|
+
* `start()` returns once the container runs, so a container that serves no
|
|
724
|
+
* port starts here too. The caller must call `release` when the operation
|
|
725
|
+
* ends, including when the result is a stream that outlives this call.
|
|
726
|
+
*/
|
|
727
|
+
protected lunoraAcquire(operation: string): Promise<AcquiredContainer>;
|
|
728
|
+
/**
|
|
729
|
+
* Runs on every start path after the env and image are settled and before
|
|
730
|
+
* the base starts the container — which is also before the base installs
|
|
731
|
+
* its outbound interception. A subclass that has to register an outbound
|
|
732
|
+
* intercept ahead of the base's catch-all does it here. No-op by default.
|
|
733
|
+
*/
|
|
734
|
+
protected beforeContainerStart(): Promise<void>;
|
|
735
|
+
/** A 403 for a path under the reserved namespace, else `undefined`. */
|
|
736
|
+
private refuseReserved;
|
|
737
|
+
/**
|
|
738
|
+
* Arm the hard timeout and block on the `readyOn` probes — the work that has
|
|
739
|
+
* to happen once per real start, **outside** the base's start gate.
|
|
740
|
+
*
|
|
741
|
+
* It cannot live in `onStart`, which is the obvious home for it: the base
|
|
742
|
+
* invokes that hook as `blockConcurrencyWhile(async () => { … onStart() })`
|
|
743
|
+
* (`@cloudflare/containers`, both `start()` and `startAndWaitForPorts()`),
|
|
744
|
+
* and workerd treats a *rejecting* `blockConcurrencyWhile` closure as
|
|
745
|
+
* unrecoverable — it aborts the Durable Object, discards its in-memory state
|
|
746
|
+
* and every hibernating socket on it, and flattens the error to a plain
|
|
747
|
+
* `Error`. A readiness timeout is an ordinary, diagnosable failure: it must
|
|
748
|
+
* surface as the `LunoraError` naming the check, the port and the budget,
|
|
749
|
+
* not cost the object its life and arrive as an opaque message. (The same
|
|
750
|
+
* reasoning, and the same settle-outside-the-gate remedy, is written up on
|
|
751
|
+
* `ShardHost.runSerialized` in `@lunora/platform-cloudflare`.) A 30-second
|
|
752
|
+
* wait also has no business inside a gate that blocks every other dispatch
|
|
753
|
+
* to the object.
|
|
754
|
+
*
|
|
755
|
+
* Both start entry points call this immediately after `super`, so it runs
|
|
756
|
+
* once per start. It does NOT gate proxying on its own: the base commits the
|
|
757
|
+
* healthy state inside the start gate, before this runs, so a concurrent
|
|
758
|
+
* request would sail past `containerFetch`'s status check. That is what
|
|
759
|
+
* `awaitReadinessGate` is for, and it is the seam the move cost us —
|
|
760
|
+
* the in-gate placement got this for free from `blockConcurrencyWhile`.
|
|
761
|
+
*/
|
|
762
|
+
private afterContainerStart;
|
|
763
|
+
/**
|
|
764
|
+
* Decide — synchronously, before anything is started — whether this start
|
|
765
|
+
* begins a NEW container run, and drop the previous run's readiness gate when
|
|
766
|
+
* it does. Returns whether the container was already running.
|
|
767
|
+
*
|
|
768
|
+
* The gate has to be keyed on the run, and `onStop` alone cannot key it:
|
|
769
|
+
* `@cloudflare/containers` reaches `onStop` only through
|
|
770
|
+
* `syncPendingStoppedEvents`, which `start()` never calls (only
|
|
771
|
+
* `startAndWaitForPorts`, `stop()` and the alarm loop do), while the monitor
|
|
772
|
+
* callback that observes a container exit merely records the state. So a
|
|
773
|
+
* `start()` in the up-to-three-minute window before the next alarm found the
|
|
774
|
+
* finished run's settled gate and skipped BOTH `armHardTimeout` and the
|
|
775
|
+
* `readyOn` probes — run 2 ran uncapped and was proxied to before it reported
|
|
776
|
+
* ready. A `hardTimeout` firing its own SIGTERM lands in exactly that window.
|
|
777
|
+
*
|
|
778
|
+
* The mirror case is why the answer is not "always re-arm": a start that finds
|
|
779
|
+
* the container already up begins no run, and re-arming there moves the cap
|
|
780
|
+
* (see {@link afterContainerStart}).
|
|
781
|
+
*
|
|
782
|
+
* Read with no `await` between it and `super`, so two concurrent starts of a
|
|
783
|
+
* stopped container both observe `false` and the second joins the first's
|
|
784
|
+
* gate instead of arming a second schedule — and so the flag is as fresh as
|
|
785
|
+
* it can be. It is a snapshot either way, and the run can end after it: the
|
|
786
|
+
* base's own pre-start work (`getPortsToCheck`, `syncPendingStoppedEvents`)
|
|
787
|
+
* still runs on the far side of it, and a start that came in on a live
|
|
788
|
+
* container would then arm nothing for the run the base goes on to start.
|
|
789
|
+
* Hence the second half of the answer, in the callers: an `onStop` observed
|
|
790
|
+
* ACROSS the base call ({@link lunoraStops}) demotes the snapshot, because
|
|
791
|
+
* the run it described is over. What that does not cover is an exit inside
|
|
792
|
+
* `start()`'s own base call — that path never syncs pending stop events, so
|
|
793
|
+
* nothing reports the exit until the next alarm or `startAndWaitForPorts`,
|
|
794
|
+
* and the cap for such a run is armed only when one of those arrives.
|
|
795
|
+
*/
|
|
796
|
+
private beginStart;
|
|
797
|
+
/**
|
|
798
|
+
* Block until the `readyOn` probes for the current start have passed.
|
|
799
|
+
*
|
|
800
|
+
* Necessary because the base marks the container healthy *inside* the start
|
|
801
|
+
* gate — `startAndWaitForPorts` runs `setHealthy()` immediately before
|
|
802
|
+
* `onStart()` — while our probes run after it returns. `containerFetch`
|
|
803
|
+
* skips the start path entirely once it observes
|
|
804
|
+
* `container.running && status === "healthy"`, so without this a request
|
|
805
|
+
* arriving mid-probe would proxy to a container that never reported ready,
|
|
806
|
+
* and a request arriving after a *failed* probe would do so permanently.
|
|
807
|
+
* Holding `setHealthy` and the probes together the way the base does would
|
|
808
|
+
* mean putting the probes back inside the gate, which is the defect this
|
|
809
|
+
* whole path exists to avoid.
|
|
810
|
+
*/
|
|
811
|
+
private awaitReadinessGate;
|
|
812
|
+
/**
|
|
813
|
+
* Arm the hard-timeout kill via the base scheduler (so it integrates with
|
|
814
|
+
* the container's own alarm machinery instead of fighting it). Bumps the run
|
|
815
|
+
* generation and stamps the schedule with it, so {@link onHardTimeoutExpired}
|
|
816
|
+
* can tell a fresh schedule from a stale one. No-op without a `hardTimeout`.
|
|
817
|
+
*/
|
|
818
|
+
private armHardTimeout;
|
|
819
|
+
/**
|
|
820
|
+
* Resolve the `secretsStore` bindings (async `.get()`) once and merge the
|
|
821
|
+
* values into `envVars`, so they're present when the base starts the
|
|
822
|
+
* container. Memoised on the first call — every later start reuses the
|
|
823
|
+
* resolved promise. A missing binding or a non-string value fails fast (the
|
|
824
|
+
* start surfaces the error), the same fail-closed stance the static
|
|
825
|
+
* `secrets` resolution takes for a missing Worker secret. No-op without
|
|
826
|
+
* `secretsStore`.
|
|
827
|
+
*/
|
|
828
|
+
private resolveSecretsStoreEnv;
|
|
829
|
+
/** The persisted start override, read from storage once per instance lifetime. */
|
|
830
|
+
private readOverride;
|
|
831
|
+
/**
|
|
832
|
+
* Validate an explicit start's choices and persist them — merged over the
|
|
833
|
+
* stored override, so `start({ instanceType })` alone keeps a chosen image.
|
|
834
|
+
* Everything is checked before the one write, so a rejected start stores
|
|
835
|
+
* nothing. A start whose choices differ from what a running (or starting)
|
|
836
|
+
* container has is REJECTED rather than silently joined: the base would
|
|
837
|
+
* return early on a live container, reporting a start that never took
|
|
838
|
+
* effect. A snapshot restore only applies to a fresh start, so it is refused
|
|
839
|
+
* on a busy one.
|
|
840
|
+
*/
|
|
841
|
+
private recordStartOverride;
|
|
842
|
+
/**
|
|
843
|
+
* Set `envVars` for the start about to happen: the persisted override when
|
|
844
|
+
* there is one (the Secrets Store is not read), else the declared env plus
|
|
845
|
+
* the resolved Secrets Store values.
|
|
846
|
+
*/
|
|
847
|
+
private applyStartEnv;
|
|
848
|
+
/**
|
|
849
|
+
* Resolve the image reference and instance size for the start about to
|
|
850
|
+
* happen (`durable_object` policy only): the persisted explicit choice, else
|
|
851
|
+
* the definition default. A fresh boot with neither an image nor a snapshot
|
|
852
|
+
* would be rejected by the runtime, so it fails here with the fix instead.
|
|
853
|
+
*/
|
|
854
|
+
private applyStartSelection;
|
|
855
|
+
/** Map an image name to the reference `ctx.container.start()` takes, via `ctx.container.images`. */
|
|
856
|
+
private resolveImage;
|
|
857
|
+
/**
|
|
858
|
+
* Block until every `readyOn` probe responds with its expected status, or
|
|
859
|
+
* throw once the readiness budget is spent. Probes run in parallel and hit
|
|
860
|
+
* the container's TCP port directly (NOT `containerFetch`, which would
|
|
861
|
+
* recurse back into the start path). No-op without `readyOn`.
|
|
862
|
+
*/
|
|
863
|
+
private awaitContainerReadiness;
|
|
864
|
+
/** Poll one readiness probe until it returns its expected status or the shared deadline passes. */
|
|
865
|
+
private awaitReadinessCheck;
|
|
866
|
+
/**
|
|
867
|
+
* Best-effort push of `envelope` into the root ShardDO's log buffer so it
|
|
868
|
+
* also appears in the Studio Logs panel (the terminal already has it via
|
|
869
|
+
* `emitContainerLifecycle`). Fire-and-forget and fully swallowed: a missing
|
|
870
|
+
* `SHARD` binding, a missing admin token, or a fetch failure NEVER throws
|
|
871
|
+
* out of a lifecycle hook — the `console` path stays the source of truth.
|
|
872
|
+
*/
|
|
35
873
|
private surfaceInStudioLogs;
|
|
36
874
|
/**
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
875
|
+
* Per-instance correlation id: the Durable Object id, which Cloudflare also
|
|
876
|
+
* injects into the container as `CLOUDFLARE_DURABLE_OBJECT_ID`. Read
|
|
877
|
+
* defensively — the id shape varies and isn't worth crashing a hook over.
|
|
878
|
+
*/
|
|
41
879
|
private instanceId;
|
|
42
880
|
}
|
|
43
|
-
export { LunoraContainer
|
|
881
|
+
export { ContainerProxy, LunoraContainer, type OutboundHandler, type OutboundHandlerContext, type OutboundHandlerParams, type OutboundHandlerParamsOf, type OutboundHandlers, outboundParams };
|