@lunora/container 1.0.0-alpha.15 → 1.0.0-alpha.17
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/bridge.mjs +1 -79
- package/dist/do/index.mjs +1 -321
- package/dist/index.mjs +1 -2
- package/dist/otel.mjs +1 -296
- package/dist/packem_shared/ContainerProxy-BsQAwSNX.mjs +27 -0
- package/dist/packem_shared/containerBindingName-DP2NqQV-.mjs +1 -0
- package/dist/packem_shared/createContainerContext-Df9Ev-Fp.mjs +1 -0
- package/dist/packem_shared/jurisdiction-BKRNOTip.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/ContainerProxy-DWqUX_re.mjs +0 -1474
- package/dist/packem_shared/containerBindingName-BiTrAF1J.mjs +0 -224
- package/dist/packem_shared/createContainerContext-Cg53QGdf.mjs +0 -223
- package/dist/packem_shared/jurisdiction-CuPNcLDt.mjs +0 -13
package/dist/bridge.mjs
CHANGED
|
@@ -1,79 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
const RPC_PATH = "/_lunora/rpc";
|
|
4
|
-
class ContainerBridgeError extends LunoraError {
|
|
5
|
-
constructor(code, message) {
|
|
6
|
-
super(code, message, { name: "ContainerBridgeError" });
|
|
7
|
-
}
|
|
8
|
-
}
|
|
9
|
-
const joinUrl = (baseUrl, path) => {
|
|
10
|
-
let base = baseUrl;
|
|
11
|
-
while (base.endsWith("/")) {
|
|
12
|
-
base = base.slice(0, -1);
|
|
13
|
-
}
|
|
14
|
-
return `${base}${path}`;
|
|
15
|
-
};
|
|
16
|
-
const statusError = (functionPath, response) => new Error(
|
|
17
|
-
`createContainerBridge: request to "${functionPath}" failed (status ${String(response.status)}${response.statusText ? ` ${response.statusText}` : ""})`
|
|
18
|
-
);
|
|
19
|
-
const parseResponseBody = async (response, functionPath) => {
|
|
20
|
-
try {
|
|
21
|
-
return await response.json();
|
|
22
|
-
} catch {
|
|
23
|
-
if (!response.ok) {
|
|
24
|
-
throw statusError(functionPath, response);
|
|
25
|
-
}
|
|
26
|
-
throw new LunoraError(
|
|
27
|
-
"INTERNAL",
|
|
28
|
-
`createContainerBridge: request to "${functionPath}" returned a non-JSON response (status ${String(response.status)})`
|
|
29
|
-
);
|
|
30
|
-
}
|
|
31
|
-
};
|
|
32
|
-
const createContainerBridge = (options) => {
|
|
33
|
-
if (typeof options.baseUrl !== "string" || options.baseUrl.length === 0) {
|
|
34
|
-
throw new TypeError("createContainerBridge: `baseUrl` must be a non-empty Worker URL (e.g. https://my-app.workers.dev) — is the URL env var set?");
|
|
35
|
-
}
|
|
36
|
-
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
37
|
-
const call = async (functionPath, args = {}, shardKey) => {
|
|
38
|
-
if (typeof fetchImpl !== "function") {
|
|
39
|
-
throw new TypeError("createContainerBridge: no `fetch` available — pass `fetch` in options for this runtime.");
|
|
40
|
-
}
|
|
41
|
-
const headers = { "content-type": "application/json" };
|
|
42
|
-
if (options.token !== void 0) {
|
|
43
|
-
headers.authorization = `Bearer ${options.token}`;
|
|
44
|
-
}
|
|
45
|
-
const response = await fetchImpl(joinUrl(options.baseUrl, RPC_PATH), {
|
|
46
|
-
body: JSON.stringify({ args, functionPath, shardKey }),
|
|
47
|
-
headers,
|
|
48
|
-
method: "POST"
|
|
49
|
-
});
|
|
50
|
-
const body = await parseResponseBody(response, functionPath);
|
|
51
|
-
if (typeof body === "object" && body !== null && "error" in body) {
|
|
52
|
-
const { error } = body;
|
|
53
|
-
if (typeof error === "object" && error !== null) {
|
|
54
|
-
const { code, message } = error;
|
|
55
|
-
if (typeof code === "string" && typeof message === "string") {
|
|
56
|
-
throw new ContainerBridgeError(code, message);
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
let detail;
|
|
60
|
-
try {
|
|
61
|
-
detail = JSON.stringify(error);
|
|
62
|
-
} catch {
|
|
63
|
-
detail = String(error);
|
|
64
|
-
}
|
|
65
|
-
throw new LunoraError(
|
|
66
|
-
"INTERNAL",
|
|
67
|
-
`createContainerBridge: request to "${functionPath}" returned a malformed error envelope (status ${String(response.status)}): ${detail}`
|
|
68
|
-
);
|
|
69
|
-
}
|
|
70
|
-
if (!response.ok) {
|
|
71
|
-
throw statusError(functionPath, response);
|
|
72
|
-
}
|
|
73
|
-
return body.result;
|
|
74
|
-
};
|
|
75
|
-
const run = async (reference, args, shardKey) => call(reference.__lunoraRef, args, shardKey);
|
|
76
|
-
return { action: call, call, mutation: call, query: call, run };
|
|
77
|
-
};
|
|
78
|
-
|
|
79
|
-
export { ContainerBridgeError, createContainerBridge };
|
|
1
|
+
import{LunoraError as f}from"@lunora/errors";const g="/_lunora/rpc";class y extends f{constructor(r,e){super(r,e,{name:"ContainerBridgeError"})}}const w=(t,r)=>{let e=t;for(;e.endsWith("/");)e=e.slice(0,-1);return`${e}${r}`},d=(t,r)=>new Error(`createContainerBridge: request to "${t}" failed (status ${String(r.status)}${r.statusText?` ${r.statusText}`:""})`),m=async(t,r)=>{try{return await t.json()}catch{throw t.ok?new f("INTERNAL",`createContainerBridge: request to "${r}" returned a non-JSON response (status ${String(t.status)})`):d(r,t)}},b=t=>{if(typeof t.baseUrl!="string"||t.baseUrl.length===0)throw new TypeError("createContainerBridge: `baseUrl` must be a non-empty Worker URL (e.g. https://my-app.workers.dev) — is the URL env var set?");const r=t.fetch??globalThis.fetch,e=async(n,i={},c)=>{if(typeof r!="function")throw new TypeError("createContainerBridge: no `fetch` available — pass `fetch` in options for this runtime.");const l={"content-type":"application/json"};t.token!==void 0&&(l.authorization=`Bearer ${t.token}`);const s=await r(w(t.baseUrl,g),{body:JSON.stringify({args:i,functionPath:n,shardKey:c}),headers:l,method:"POST"}),o=await m(s,n);if(typeof o=="object"&&o!==null&&"error"in o){const{error:a}=o;if(typeof a=="object"&&a!==null){const{code:h,message:p}=a;if(typeof h=="string"&&typeof p=="string")throw new y(h,p)}let u;try{u=JSON.stringify(a)}catch{u=String(a)}throw new f("INTERNAL",`createContainerBridge: request to "${n}" returned a malformed error envelope (status ${String(s.status)}): ${u}`)}if(!s.ok)throw d(n,s);return o.result};return{action:e,call:e,mutation:e,query:e,run:async(n,i,c)=>e(n.__lunoraRef,i,c)}};export{y as ContainerBridgeError,b as createContainerBridge};
|
package/dist/do/index.mjs
CHANGED
|
@@ -1,321 +1 @@
|
|
|
1
|
-
import {
|
|
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';
|
|
6
|
-
|
|
7
|
-
const LUNORA_EVENT_SOURCE = "lunora";
|
|
8
|
-
const buildContainerLifecycleEvent = (container, instance, event, message) => {
|
|
9
|
-
return {
|
|
10
|
-
container,
|
|
11
|
-
event,
|
|
12
|
-
instance,
|
|
13
|
-
level: event === "error" ? "error" : "info",
|
|
14
|
-
message,
|
|
15
|
-
source: LUNORA_EVENT_SOURCE,
|
|
16
|
-
ts: Date.now(),
|
|
17
|
-
type: "container"
|
|
18
|
-
};
|
|
19
|
-
};
|
|
20
|
-
const emitContainerLifecycle = (container, instance, event, message) => {
|
|
21
|
-
const envelope = buildContainerLifecycleEvent(container, instance, event, message);
|
|
22
|
-
const line = JSON.stringify(envelope);
|
|
23
|
-
if (event === "error") {
|
|
24
|
-
console.error(line);
|
|
25
|
-
} else {
|
|
26
|
-
console.log(line);
|
|
27
|
-
}
|
|
28
|
-
return envelope;
|
|
29
|
-
};
|
|
30
|
-
|
|
31
|
-
const RECORD_CONTAINER_EVENT_OP = "__lunora_admin__:recordContainerEvent";
|
|
32
|
-
const ROOT_SHARD_NAME = "__root__";
|
|
33
|
-
const isShardNamespace = (value) => {
|
|
34
|
-
if (value === null || typeof value !== "object") {
|
|
35
|
-
return false;
|
|
36
|
-
}
|
|
37
|
-
const candidate = value;
|
|
38
|
-
return typeof candidate.get === "function" && typeof candidate.idFromName === "function";
|
|
39
|
-
};
|
|
40
|
-
const resolveRootShard = (namespace, jurisdiction) => {
|
|
41
|
-
const pinned = applyJurisdiction(namespace, jurisdiction);
|
|
42
|
-
if (typeof pinned.getByName === "function") {
|
|
43
|
-
return pinned.getByName(ROOT_SHARD_NAME);
|
|
44
|
-
}
|
|
45
|
-
return pinned.get(pinned.idFromName(ROOT_SHARD_NAME));
|
|
46
|
-
};
|
|
47
|
-
const reportContainerLifecycle = async (env, envelope, jurisdiction) => {
|
|
48
|
-
try {
|
|
49
|
-
const envRecord = env ?? {};
|
|
50
|
-
const namespace = envRecord["SHARD"];
|
|
51
|
-
if (!isShardNamespace(namespace)) {
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
const adminBearer = typeof envRecord["LUNORA_ADMIN_TOKEN"] === "string" ? envRecord["LUNORA_ADMIN_TOKEN"] : void 0;
|
|
55
|
-
if (!adminBearer || adminBearer.length === 0) {
|
|
56
|
-
return;
|
|
57
|
-
}
|
|
58
|
-
const request = new Request("https://shard.internal/rpc", {
|
|
59
|
-
body: JSON.stringify({ args: { event: envelope }, functionPath: RECORD_CONTAINER_EVENT_OP }),
|
|
60
|
-
headers: { authorization: `Bearer ${adminBearer}`, "content-type": "application/json" },
|
|
61
|
-
method: "POST"
|
|
62
|
-
});
|
|
63
|
-
await resolveRootShard(namespace, jurisdiction).fetch(request);
|
|
64
|
-
} catch {
|
|
65
|
-
}
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
const READINESS_POLL_INTERVAL_MS = 500;
|
|
69
|
-
const READINESS_TIMEOUT_MS = 3e4;
|
|
70
|
-
const HARD_TIMEOUT_GENERATION_KEY = "__lunoraHardTimeoutGeneration";
|
|
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;
|
|
78
|
-
/** The `lunora/containers.ts` export name, for lifecycle log correlation. */
|
|
79
|
-
lunoraName;
|
|
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) {
|
|
91
|
-
super(context, env, {
|
|
92
|
-
defaultPort: definition.defaultPort,
|
|
93
|
-
entrypoint: definition.entrypoint ? [...definition.entrypoint] : void 0,
|
|
94
|
-
envVars: resolveContainerEnvVariables(definition, env, exportName),
|
|
95
|
-
sleepAfter: definition.sleepAfter
|
|
96
|
-
});
|
|
97
|
-
if (definition.enableInternet !== void 0) {
|
|
98
|
-
this.enableInternet = definition.enableInternet;
|
|
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
|
-
}
|
|
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();
|
|
156
|
-
}
|
|
157
|
-
onError(error) {
|
|
158
|
-
const envelope = emitContainerLifecycle(this.lunoraName, this.instanceId(), "error", error instanceof Error ? error.message : String(error));
|
|
159
|
-
this.surfaceInStudioLogs(envelope);
|
|
160
|
-
return super.onError(error);
|
|
161
|
-
}
|
|
162
|
-
async onStart() {
|
|
163
|
-
const envelope = emitContainerLifecycle(this.lunoraName, this.instanceId(), "start");
|
|
164
|
-
this.surfaceInStudioLogs(envelope);
|
|
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();
|
|
187
|
-
}
|
|
188
|
-
async onStop(parameters) {
|
|
189
|
-
const envelope = emitContainerLifecycle(this.lunoraName, this.instanceId(), "stop", `${parameters.reason} (exit ${String(parameters.exitCode)})`);
|
|
190
|
-
this.surfaceInStudioLogs(envelope);
|
|
191
|
-
await super.onStop(parameters);
|
|
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
|
-
}
|
|
295
|
-
/**
|
|
296
|
-
* Best-effort push of `envelope` into the root ShardDO's log buffer so it
|
|
297
|
-
* also appears in the Studio Logs panel (the terminal already has it via
|
|
298
|
-
* `emitContainerLifecycle`). Fire-and-forget and fully swallowed: a missing
|
|
299
|
-
* `SHARD` binding, a missing admin token, or a fetch failure NEVER throws
|
|
300
|
-
* out of a lifecycle hook — the `console` path stays the source of truth.
|
|
301
|
-
*/
|
|
302
|
-
surfaceInStudioLogs(envelope) {
|
|
303
|
-
reportContainerLifecycle(this.env, envelope, this.lunoraJurisdiction).catch(() => {
|
|
304
|
-
});
|
|
305
|
-
}
|
|
306
|
-
/**
|
|
307
|
-
* Per-instance correlation id: the Durable Object id, which Cloudflare also
|
|
308
|
-
* injects into the container as `CLOUDFLARE_DURABLE_OBJECT_ID`. Read
|
|
309
|
-
* defensively — the id shape varies and isn't worth crashing a hook over.
|
|
310
|
-
*/
|
|
311
|
-
instanceId() {
|
|
312
|
-
try {
|
|
313
|
-
const { id } = this.ctx;
|
|
314
|
-
return typeof id?.toString === "function" ? id.toString() : "unknown";
|
|
315
|
-
} catch {
|
|
316
|
-
return "unknown";
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
export { LunoraContainer };
|
|
1
|
+
import{Container as f}from"../packem_shared/ContainerProxy-BsQAwSNX.mjs";import{ContainerProxy as b,outboundParams as A}from"../packem_shared/ContainerProxy-BsQAwSNX.mjs";import{LunoraError as u}from"@lunora/errors";import{resolveContainerEnvVars as S,parseDurationSeconds as m}from"../packem_shared/containerBindingName-DP2NqQV-.mjs";import{e as v}from"../packem_shared/jurisdiction-BKRNOTip.mjs";const g="lunora",y=(i,t,n,e)=>({container:i,event:n,instance:t,level:n==="error"?"error":"info",message:e,source:g,ts:Date.now(),type:"container"}),a=(i,t,n,e)=>{const r=y(i,t,n,e),o=JSON.stringify(r);return n==="error"?console.error(o):console.log(o),r},w="__lunora_admin__:recordContainerEvent",h="__root__",N=i=>{if(i===null||typeof i!="object")return!1;const t=i;return typeof t.get=="function"&&typeof t.idFromName=="function"},$=(i,t)=>{const n=v(i,t);return typeof n.getByName=="function"?n.getByName(h):n.get(n.idFromName(h))},E=async(i,t,n)=>{try{const e=i??{},r=e.SHARD;if(!N(r))return;const o=typeof e.LUNORA_ADMIN_TOKEN=="string"?e.LUNORA_ADMIN_TOKEN:void 0;if(!o||o.length===0)return;const s=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:{event:t},functionPath:w}),headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},method:"POST"});await $(r,n).fetch(s)}catch{}},I=500,l=3e4,d="__lunoraHardTimeoutGeneration";class _ extends f{lunoraJurisdiction;lunoraName;lunoraDefaultPort;lunoraHardTimeoutSeconds;lunoraReadyOn;lunoraSecretsStore;lunoraSecretsStoreResolved;constructor(t,n,e,r,o){super(t,n,{defaultPort:e.defaultPort,entrypoint:e.entrypoint?[...e.entrypoint]:void 0,envVars:S(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=o,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.resolveSecretsStoreEnv(),super.containerFetch(...t)}async start(...t){const[n]=t;return n?.envVars===void 0&&await this.resolveSecretsStoreEnv(),super.start(...t)}async onActivityExpired(){const t=a(this.lunoraName,this.instanceId(),"sleep");this.surfaceInStudioLogs(t),await super.onActivityExpired()}onError(t){const n=a(this.lunoraName,this.instanceId(),"error",t instanceof Error?t.message:String(t));return this.surfaceInStudioLogs(n),super.onError(t)}async onStart(){const t=a(this.lunoraName,this.instanceId(),"start");this.surfaceInStudioLogs(t),await super.onStart(),await this.armHardTimeout(),await this.awaitContainerReadiness()}async onHardTimeoutExpired(t){const n=await this.ctx.storage.get(d);if(t?.generation!==void 0&&t.generation!==n||this.ctx.container?.running!==!0)return;const e=a(this.lunoraName,this.instanceId(),"stop","hard timeout reached");this.surfaceInStudioLogs(e),await this.stop()}async onStop(t){const n=a(this.lunoraName,this.instanceId(),"stop",`${t.reason} (exit ${String(t.exitCode)})`);this.surfaceInStudioLogs(n),await super.onStop(t)}async armHardTimeout(){if(this.lunoraHardTimeoutSeconds===void 0)return;const t=(await this.ctx.storage.get(d)??0)+1;await this.ctx.storage.put(d,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,o]of Object.entries(t)){const s=n[o];if(s===void 0||typeof s.get!="function")throw new u("INTERNAL",`container "${this.lunoraName}": secretsStore env "${r}" points at binding "${o}", which is not a Secrets Store binding on the Worker env. Add a \`secrets_store_secrets\` entry binding "${o}".`);const c=await s.get();if(typeof c!="string")throw new TypeError(`container "${this.lunoraName}": Secrets Store binding "${o}" (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()+l;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 o=n.status??200,s=n.path.startsWith("/")?n.path:`/${n.path}`,c=t.getTcpPort(r);for(;;){try{if((await c.fetch(`http://container${s}`)).status===o)return}catch{}if(Date.now()>=e)throw new u("INTERNAL",`container "${this.lunoraName}": readiness check "${n.path}" (port ${String(r)}) did not return ${String(o)} within ${String(l)}ms`);await new Promise(p=>{setTimeout(p,I)})}}surfaceInStudioLogs(t){E(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{b as ContainerProxy,_ as LunoraContainer,A as outboundParams};
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { containerBindingName, containerBuildTag, containerClassName, defineContainer, isContainerDefinition, normalizeContainerImage, resolveContainerEnvVars } from './packem_shared/containerBindingName-BiTrAF1J.mjs';
|
|
1
|
+
import{createContainerContext as t,createContainerTestContext as a}from"./packem_shared/createContainerContext-Df9Ev-Fp.mjs";import{containerBindingName as o,containerBuildTag as r,containerClassName as C,defineContainer as m,isContainerDefinition as s,normalizeContainerImage as c,resolveContainerEnvVars as f}from"./packem_shared/containerBindingName-DP2NqQV-.mjs";export{o as containerBindingName,r as containerBuildTag,C as containerClassName,t as createContainerContext,a as createContainerTestContext,m as defineContainer,s as isContainerDefinition,c as normalizeContainerImage,f as resolveContainerEnvVars};
|