@lunora/container 1.0.0-alpha.5 → 1.0.0-alpha.50

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,324 +1 @@
1
- import { Container } from '../packem_shared/ContainerProxy-DWqUX_re.mjs';
2
- export { ContainerProxy, outboundParams } from '../packem_shared/ContainerProxy-DWqUX_re.mjs';
3
- import { resolveContainerEnvVars as resolveContainerEnvVariables, parseDurationSeconds } from '../packem_shared/containerBindingName-CWmEE_3Y.mjs';
4
-
5
- const LUNORA_EVENT_SOURCE = "lunora";
6
- const buildContainerLifecycleEvent = (container, instance, event, message) => {
7
- return {
8
- container,
9
- event,
10
- instance,
11
- level: event === "error" ? "error" : "info",
12
- message,
13
- source: LUNORA_EVENT_SOURCE,
14
- ts: Date.now(),
15
- type: "container"
16
- };
17
- };
18
- const emitContainerLifecycle = (container, instance, event, message) => {
19
- const envelope = buildContainerLifecycleEvent(container, instance, event, message);
20
- const line = JSON.stringify(envelope);
21
- if (event === "error") {
22
- console.error(line);
23
- } else {
24
- console.log(line);
25
- }
26
- return envelope;
27
- };
28
-
29
- const RECORD_CONTAINER_EVENT_OP = "__lunora_admin__:recordContainerEvent";
30
- const ROOT_SHARD_NAME = "__root__";
31
- const applyJurisdiction = (namespace, jurisdiction) => {
32
- if (jurisdiction === void 0) {
33
- return namespace;
34
- }
35
- if (typeof namespace.jurisdiction !== "function") {
36
- throw new TypeError(
37
- `@lunora/container: Durable Object namespace does not support jurisdiction("${jurisdiction}") — update @cloudflare/workers-types or remove the jurisdiction option`
38
- );
39
- }
40
- return namespace.jurisdiction(jurisdiction);
41
- };
42
- const isShardNamespace = (value) => {
43
- if (value === null || typeof value !== "object") {
44
- return false;
45
- }
46
- const candidate = value;
47
- return typeof candidate.get === "function" && typeof candidate.idFromName === "function";
48
- };
49
- const resolveRootShard = (namespace, jurisdiction) => {
50
- const pinned = applyJurisdiction(namespace, jurisdiction);
51
- if (typeof pinned.getByName === "function") {
52
- return pinned.getByName(ROOT_SHARD_NAME);
53
- }
54
- return pinned.get(pinned.idFromName(ROOT_SHARD_NAME));
55
- };
56
- const reportContainerLifecycle = async (env, envelope, jurisdiction) => {
57
- try {
58
- const envRecord = env ?? {};
59
- const namespace = envRecord["SHARD"];
60
- if (!isShardNamespace(namespace)) {
61
- return;
62
- }
63
- const adminBearer = typeof envRecord["LUNORA_ADMIN_TOKEN"] === "string" ? envRecord["LUNORA_ADMIN_TOKEN"] : void 0;
64
- if (!adminBearer || adminBearer.length === 0) {
65
- return;
66
- }
67
- const request = new Request("https://shard.internal/rpc", {
68
- body: JSON.stringify({ args: { event: envelope }, functionPath: RECORD_CONTAINER_EVENT_OP }),
69
- headers: { authorization: `Bearer ${adminBearer}`, "content-type": "application/json" },
70
- method: "POST"
71
- });
72
- await resolveRootShard(namespace, jurisdiction).fetch(request);
73
- } catch {
74
- }
75
- };
76
-
77
- const READINESS_POLL_INTERVAL_MS = 500;
78
- const READINESS_TIMEOUT_MS = 3e4;
79
- const HARD_TIMEOUT_GENERATION_KEY = "__lunoraHardTimeoutGeneration";
80
- class LunoraContainer extends Container {
81
- /**
82
- * Data-residency jurisdiction the app's DOs are pinned to (codegen passes the
83
- * schema's `.jurisdiction("…")`). Used to pin the best-effort lifecycle report
84
- * to the same region as the root shard. `undefined` ⇒ un-pinned.
85
- */
86
- lunoraJurisdiction;
87
- /** The `lunora/containers.ts` export name, for lifecycle log correlation. */
88
- lunoraName;
89
- /** Default port the readiness probes target when a check omits its own `port`. */
90
- lunoraDefaultPort;
91
- /** Hard-cap lifetime in whole seconds (from the `hardTimeout` config), or `undefined`. */
92
- lunoraHardTimeoutSeconds;
93
- /** Declarative readiness probes that gate request proxying (from the `readyOn` config). */
94
- lunoraReadyOn;
95
- /** Map of container env-var name → Worker Secrets Store binding name (from the `secretsStore` config). */
96
- lunoraSecretsStore;
97
- /** Memoised Secrets Store resolution: run once, then merged into `envVars` before the first start. */
98
- lunoraSecretsStoreResolved;
99
- constructor(context, env, definition, exportName, jurisdiction) {
100
- super(context, env, {
101
- defaultPort: definition.defaultPort,
102
- entrypoint: definition.entrypoint ? [...definition.entrypoint] : void 0,
103
- envVars: resolveContainerEnvVariables(definition, env, exportName),
104
- sleepAfter: definition.sleepAfter
105
- });
106
- if (definition.enableInternet !== void 0) {
107
- this.enableInternet = definition.enableInternet;
108
- }
109
- if (definition.requiredPorts !== void 0) {
110
- this.requiredPorts = [...definition.requiredPorts];
111
- }
112
- if (definition.interceptHttps !== void 0) {
113
- this.interceptHttps = definition.interceptHttps;
114
- }
115
- if (definition.allowedHosts !== void 0) {
116
- this.allowedHosts = [...definition.allowedHosts];
117
- }
118
- if (definition.deniedHosts !== void 0) {
119
- this.deniedHosts = [...definition.deniedHosts];
120
- }
121
- if (definition.pingEndpoint !== void 0) {
122
- this.pingEndpoint = definition.pingEndpoint;
123
- }
124
- if (definition.labels !== void 0) {
125
- this.labels = { ...definition.labels };
126
- }
127
- this.lunoraName = exportName ?? "container";
128
- this.lunoraJurisdiction = jurisdiction;
129
- this.lunoraDefaultPort = definition.defaultPort;
130
- this.lunoraReadyOn = definition.readyOn ? [...definition.readyOn] : [];
131
- this.lunoraHardTimeoutSeconds = definition.hardTimeout === void 0 ? void 0 : parseDurationSeconds(definition.hardTimeout);
132
- this.lunoraSecretsStore = definition.secretsStore;
133
- }
134
- /**
135
- * Proxy entry for every `ctx.containers.<name>` fetch. Resolves the
136
- * `secretsStore` bindings into `envVars` before delegating, so the values
137
- * are present when the base implicitly starts the container for this
138
- * request — a no-op when `secretsStore` is unset.
139
- */
140
- async containerFetch(...args) {
141
- await this.resolveSecretsStoreEnv();
142
- return super.containerFetch(...args);
143
- }
144
- /**
145
- * Explicit start (`ctx.containers.<name>.get(id).start()`). Resolves the
146
- * `secretsStore` bindings into `envVars` first, mirroring
147
- * {@link containerFetch}. A per-instance `start({ envVars })` replaces the
148
- * env set wholesale (base behavior), so the injected values only apply to a
149
- * bare `start()` — same as the static `env`/`secrets`. When the caller
150
- * supplies its own `envVars` we skip resolution entirely: those values would
151
- * be discarded anyway, so a missing/unreadable binding shouldn't fail a start
152
- * that never uses them.
153
- */
154
- async start(...args) {
155
- const [options] = args;
156
- if (options?.envVars === void 0) {
157
- await this.resolveSecretsStoreEnv();
158
- }
159
- return super.start(...args);
160
- }
161
- async onActivityExpired() {
162
- const envelope = emitContainerLifecycle(this.lunoraName, this.instanceId(), "sleep");
163
- this.surfaceInStudioLogs(envelope);
164
- await super.onActivityExpired();
165
- }
166
- onError(error) {
167
- const envelope = emitContainerLifecycle(this.lunoraName, this.instanceId(), "error", error instanceof Error ? error.message : String(error));
168
- this.surfaceInStudioLogs(envelope);
169
- return super.onError(error);
170
- }
171
- async onStart() {
172
- const envelope = emitContainerLifecycle(this.lunoraName, this.instanceId(), "start");
173
- this.surfaceInStudioLogs(envelope);
174
- await super.onStart();
175
- await this.armHardTimeout();
176
- await this.awaitContainerReadiness();
177
- }
178
- /**
179
- * Hook run when the container's `hardTimeout` elapses (dispatched by the base
180
- * scheduler via the run-generation-stamped schedule armed in
181
- * {@link onStart}). Default: stop the instance. Override to drain/checkpoint
182
- * first. A stale schedule from a previous run, or an already-stopped
183
- * instance, is ignored (upstream cloudflare/containers#85).
184
- */
185
- async onHardTimeoutExpired(payload) {
186
- const current = await this.ctx.storage.get(HARD_TIMEOUT_GENERATION_KEY);
187
- if (payload?.generation !== void 0 && payload.generation !== current) {
188
- return;
189
- }
190
- if (this.ctx.container?.running !== true) {
191
- return;
192
- }
193
- const envelope = emitContainerLifecycle(this.lunoraName, this.instanceId(), "stop", "hard timeout reached");
194
- this.surfaceInStudioLogs(envelope);
195
- await this.stop();
196
- }
197
- async onStop(parameters) {
198
- const envelope = emitContainerLifecycle(this.lunoraName, this.instanceId(), "stop", `${parameters.reason} (exit ${String(parameters.exitCode)})`);
199
- this.surfaceInStudioLogs(envelope);
200
- await super.onStop(parameters);
201
- }
202
- /**
203
- * Arm the hard-timeout kill via the base scheduler (so it integrates with
204
- * the container's own alarm machinery instead of fighting it). Bumps the run
205
- * generation and stamps the schedule with it, so {@link onHardTimeoutExpired}
206
- * can tell a fresh schedule from a stale one. No-op without a `hardTimeout`.
207
- */
208
- async armHardTimeout() {
209
- if (this.lunoraHardTimeoutSeconds === void 0) {
210
- return;
211
- }
212
- const generation = (await this.ctx.storage.get(HARD_TIMEOUT_GENERATION_KEY) ?? 0) + 1;
213
- await this.ctx.storage.put(HARD_TIMEOUT_GENERATION_KEY, generation);
214
- await this.schedule(this.lunoraHardTimeoutSeconds, "onHardTimeoutExpired", { generation });
215
- }
216
- /**
217
- * Resolve the `secretsStore` bindings (async `.get()`) once and merge the
218
- * values into `envVars`, so they're present when the base starts the
219
- * container. Memoised on the first call — every later start reuses the
220
- * resolved promise. A missing binding or a non-string value fails fast (the
221
- * start surfaces the error), the same fail-closed stance the static
222
- * `secrets` resolution takes for a missing Worker secret. No-op without
223
- * `secretsStore`.
224
- */
225
- async resolveSecretsStoreEnv() {
226
- const secretsStore = this.lunoraSecretsStore;
227
- if (secretsStore === void 0) {
228
- return;
229
- }
230
- this.lunoraSecretsStoreResolved ??= (async () => {
231
- const workerEnv = this.env;
232
- const resolved = {};
233
- for (const [envName, binding] of Object.entries(secretsStore)) {
234
- const store = workerEnv[binding];
235
- if (store === void 0 || typeof store.get !== "function") {
236
- throw new Error(
237
- `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}".`
238
- );
239
- }
240
- const value = await store.get();
241
- if (typeof value !== "string") {
242
- throw new TypeError(
243
- `container "${this.lunoraName}": Secrets Store binding "${binding}" (env "${envName}") did not resolve to a string value.`
244
- );
245
- }
246
- resolved[envName] = value;
247
- }
248
- this.envVars = { ...this.envVars, ...resolved };
249
- })();
250
- await this.lunoraSecretsStoreResolved;
251
- }
252
- /**
253
- * Block until every `readyOn` probe responds with its expected status, or
254
- * throw once the readiness budget is spent. Probes run in parallel and hit
255
- * the container's TCP port directly (NOT `containerFetch`, which would
256
- * recurse back into the start path). No-op without `readyOn`.
257
- */
258
- async awaitContainerReadiness() {
259
- if (this.lunoraReadyOn.length === 0) {
260
- return;
261
- }
262
- const { container } = this.ctx;
263
- if (container === void 0) {
264
- return;
265
- }
266
- const deadline = Date.now() + READINESS_TIMEOUT_MS;
267
- await Promise.all(this.lunoraReadyOn.map(async (check) => this.awaitReadinessCheck(container, check, deadline)));
268
- }
269
- /** Poll one readiness probe until it returns its expected status or the shared deadline passes. */
270
- async awaitReadinessCheck(container, check, deadline) {
271
- const port = check.port ?? this.lunoraDefaultPort;
272
- if (port === void 0) {
273
- throw new Error(
274
- `container "${this.lunoraName}": readyOn check "${check.path}" has no port — set the check's \`port\` or the container \`defaultPort\`.`
275
- );
276
- }
277
- const expectedStatus = check.status ?? 200;
278
- const path = check.path.startsWith("/") ? check.path : `/${check.path}`;
279
- const tcpPort = container.getTcpPort(port);
280
- for (; ; ) {
281
- try {
282
- const response = await tcpPort.fetch(`http://container${path}`);
283
- if (response.status === expectedStatus) {
284
- return;
285
- }
286
- } catch {
287
- }
288
- if (Date.now() >= deadline) {
289
- throw new Error(
290
- `container "${this.lunoraName}": readiness check "${check.path}" (port ${String(port)}) did not return ${String(expectedStatus)} within ${String(READINESS_TIMEOUT_MS)}ms`
291
- );
292
- }
293
- await new Promise((resolve) => {
294
- setTimeout(resolve, READINESS_POLL_INTERVAL_MS);
295
- });
296
- }
297
- }
298
- /**
299
- * Best-effort push of `envelope` into the root ShardDO's log buffer so it
300
- * also appears in the Studio Logs panel (the terminal already has it via
301
- * `emitContainerLifecycle`). Fire-and-forget and fully swallowed: a missing
302
- * `SHARD` binding, a missing admin token, or a fetch failure NEVER throws
303
- * out of a lifecycle hook — the `console` path stays the source of truth.
304
- */
305
- surfaceInStudioLogs(envelope) {
306
- reportContainerLifecycle(this.env, envelope, this.lunoraJurisdiction).catch(() => {
307
- });
308
- }
309
- /**
310
- * Per-instance correlation id: the Durable Object id, which Cloudflare also
311
- * injects into the container as `CLOUDFLARE_DURABLE_OBJECT_ID`. Read
312
- * defensively — the id shape varies and isn't worth crashing a hook over.
313
- */
314
- instanceId() {
315
- try {
316
- const { id } = this.ctx;
317
- return typeof id?.toString === "function" ? id.toString() : "unknown";
318
- } catch {
319
- return "unknown";
320
- }
321
- }
322
- }
323
-
324
- export { LunoraContainer };
1
+ import{LunoraError as u}from"@lunora/errors";import{a as f}from"../packem_shared/abort-deadline-jwbW9Ala.mjs";import{resolveContainerEnvVars as g,parseDurationSeconds as m}from"../packem_shared/containerBindingName-C7SonAIK.mjs";import{a as y}from"../packem_shared/jurisdiction-DtE9s70w.mjs";import{Container as R}from"../packem_shared/ContainerProxy-fTW_pXWY.mjs";import{ContainerProxy as D,outboundParams as M}from"../packem_shared/ContainerProxy-fTW_pXWY.mjs";const E="lunora",N=(o,t,n,e)=>({container:o,event:n,instance:t,level:n==="error"?"error":"info",message:e,source:E,ts:Date.now(),type:"container"}),i=(o,t,n,e)=>{const r=N(o,t,n,e),s=JSON.stringify(r);return n==="error"?console.error(s):console.log(s),r},T="__lunora_admin__:recordContainerEvent",S="__root__",_=o=>{if(o===null||typeof o!="object")return!1;const t=o;return typeof t.get=="function"&&typeof t.idFromName=="function"},O=(o,t)=>{const n=y(o,t);return typeof n.getByName=="function"?n.getByName(S):n.get(n.idFromName(S))},I=async(o,t,n)=>{try{const e=o??{},r=e.SHARD;if(!_(r))return;const s=typeof e.LUNORA_ADMIN_TOKEN=="string"?e.LUNORA_ADMIN_TOKEN:void 0;if(!s||s.length===0)return;const a=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:{event:t},functionPath:T}),headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},method:"POST"});await O(r,n).fetch(a)}catch{}},v=500,w=3e4,h="__lunoraHardTimeoutGeneration";class L extends R{lunoraJurisdiction;lunoraName;lunoraDefaultPort;lunoraHardTimeoutSeconds;lunoraReadiness;lunoraReadyOn;lunoraSecretsStore;lunoraSecretsStoreResolved;lunoraStops=0;constructor(t,n,e,r,s){super(t,n,{defaultPort:e.defaultPort,entrypoint:e.entrypoint?[...e.entrypoint]:void 0,envVars:g(e,n,r),sleepAfter:e.sleepAfter}),e.enableInternet!==void 0&&(this.enableInternet=e.enableInternet),e.requiredPorts!==void 0&&(this.requiredPorts=[...e.requiredPorts]),e.interceptHttps!==void 0&&(this.interceptHttps=e.interceptHttps),e.allowedHosts!==void 0&&(this.allowedHosts=[...e.allowedHosts]),e.deniedHosts!==void 0&&(this.deniedHosts=[...e.deniedHosts]),e.pingEndpoint!==void 0&&(this.pingEndpoint=e.pingEndpoint),e.labels!==void 0&&(this.labels={...e.labels}),this.lunoraName=r??"container",this.lunoraJurisdiction=s,this.lunoraDefaultPort=e.defaultPort,this.lunoraReadyOn=e.readyOn?[...e.readyOn]:[],this.lunoraHardTimeoutSeconds=e.hardTimeout===void 0?void 0:m(e.hardTimeout),this.lunoraSecretsStore=e.secretsStore}async containerFetch(...t){return await this.awaitReadinessGate(),super.containerFetch(...t)}async startAndWaitForPorts(...t){await this.resolveSecretsStoreEnv();const n=this.lunoraStops,e=this.beginStart();await super.startAndWaitForPorts(...t),await this.afterContainerStart(e&&this.lunoraStops===n)}async start(...t){const[n]=t;n?.envVars===void 0&&await this.resolveSecretsStoreEnv();const e=this.lunoraStops,r=this.beginStart();await super.start(...t),await this.afterContainerStart(r&&this.lunoraStops===e)}async onActivityExpired(){const t=i(this.lunoraName,this.instanceId(),"sleep");this.surfaceInStudioLogs(t),await super.onActivityExpired()}onError(t){const n=i(this.lunoraName,this.instanceId(),"error",t instanceof Error?t.message:String(t));return this.surfaceInStudioLogs(n),super.onError(t)}async onStart(){const t=i(this.lunoraName,this.instanceId(),"start");this.surfaceInStudioLogs(t),await super.onStart()}async onHardTimeoutExpired(t){const n=await this.ctx.storage.get(h);if(t?.generation!==void 0&&t.generation!==n||this.ctx.container?.running!==!0)return;const e=i(this.lunoraName,this.instanceId(),"stop","hard timeout reached");this.surfaceInStudioLogs(e),await this.stop()}async onStop(t){const n=i(this.lunoraName,this.instanceId(),"stop",`${t.reason} (exit ${String(t.exitCode)})`);this.surfaceInStudioLogs(n),this.lunoraReadiness=void 0,this.lunoraStops+=1,await super.onStop(t)}async afterContainerStart(t){const n=this.lunoraReadiness;if(n!==void 0){await n;return}const e=(async()=>{t||await this.armHardTimeout(),await this.awaitContainerReadiness()})();this.lunoraReadiness=e;try{await e}catch(r){throw this.lunoraReadiness===e&&(this.lunoraReadiness=void 0),r}}beginStart(){const t=this.ctx.container?.running===!0;return t||(this.lunoraReadiness=void 0),t}async awaitReadinessGate(){if(this.lunoraReadyOn.length===0)return;if(this.lunoraReadiness===void 0){const{status:n}=await this.getState();if(n!=="healthy")return;this.lunoraReadiness=this.awaitContainerReadiness()}const t=this.lunoraReadiness;try{await t}catch(n){throw this.lunoraReadiness===t&&(this.lunoraReadiness=void 0),n}}async armHardTimeout(){if(this.lunoraHardTimeoutSeconds===void 0)return;const t=(await this.ctx.storage.get(h)??0)+1;await this.ctx.storage.put(h,t),await this.schedule(this.lunoraHardTimeoutSeconds,"onHardTimeoutExpired",{generation:t})}async resolveSecretsStoreEnv(){const t=this.lunoraSecretsStore;t!==void 0&&(this.lunoraSecretsStoreResolved??=(async()=>{const n=this.env,e={};for(const[r,s]of Object.entries(t)){const a=n[s];if(a===void 0||typeof a.get!="function")throw new u("INTERNAL",`container "${this.lunoraName}": secretsStore env "${r}" points at binding "${s}", which is not a Secrets Store binding on the Worker env. Add a \`secrets_store_secrets\` entry binding "${s}".`);const c=await a.get();if(typeof c!="string")throw new TypeError(`container "${this.lunoraName}": Secrets Store binding "${s}" (env "${r}") did not resolve to a string value.`);e[r]=c}this.envVars={...this.envVars,...e}})().catch(n=>{throw this.lunoraSecretsStoreResolved=void 0,n}),await this.lunoraSecretsStoreResolved)}async awaitContainerReadiness(){if(this.lunoraReadyOn.length===0)return;const{container:t}=this.ctx;if(t===void 0)return;const n=Date.now()+w;await Promise.all(this.lunoraReadyOn.map(async e=>this.awaitReadinessCheck(t,e,n)))}async awaitReadinessCheck(t,n,e){const r=n.port??this.lunoraDefaultPort;if(r===void 0)throw new u("INTERNAL",`container "${this.lunoraName}": readyOn check "${n.path}" has no port — set the check's \`port\` or the container \`defaultPort\`.`);const s=n.status??200,a=n.path.startsWith("/")?n.path:`/${n.path}`,c=t.getTcpPort(r);for(;;){const d=Math.max(v,e-Date.now()),l=f(void 0,d,()=>new DOMException(`readiness probe timed out after ${String(d)}ms`,"TimeoutError"));try{if((await c.fetch(`http://container${a}`,{signal:l.signal})).status===s)return}catch{}finally{l.dispose()}if(Date.now()>=e)throw new u("INTERNAL",`container "${this.lunoraName}": readiness check "${n.path}" (port ${String(r)}) did not return ${String(s)} within ${String(w)}ms`);await new Promise(p=>{setTimeout(p,v)})}}surfaceInStudioLogs(t){I(this.env,t,this.lunoraJurisdiction).catch(()=>{})}instanceId(){try{const{id:t}=this.ctx;return typeof t?.toString=="function"?t.toString():"unknown"}catch{return"unknown"}}}export{D as ContainerProxy,L as LunoraContainer,M as outboundParams};