@lunora/container 0.0.0 → 1.0.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +131 -0
- package/README.md +249 -9
- package/__assets__/package-og.svg +14 -0
- package/dist/bridge.d.mts +90 -0
- package/dist/bridge.d.ts +90 -0
- package/dist/bridge.mjs +79 -0
- package/dist/do/index.d.mts +597 -0
- package/dist/do/index.d.ts +597 -0
- package/dist/do/index.mjs +321 -0
- package/dist/index.d.mts +277 -0
- package/dist/index.d.ts +277 -0
- package/dist/index.mjs +2 -0
- package/dist/otel.d.mts +95 -0
- package/dist/otel.d.ts +95 -0
- package/dist/otel.mjs +203 -0
- package/dist/packem_shared/ContainerProxy-DWqUX_re.mjs +1474 -0
- package/dist/packem_shared/containerBindingName-BiTrAF1J.mjs +224 -0
- package/dist/packem_shared/createContainerContext-CIVzsY5m.mjs +220 -0
- package/dist/packem_shared/jurisdiction-CuPNcLDt.mjs +13 -0
- package/dist/packem_shared/jurisdiction.d-TwTGkgTg.d.mts +266 -0
- package/dist/packem_shared/jurisdiction.d-TwTGkgTg.d.ts +266 -0
- package/package.json +50 -15
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { D as DurableObjectJurisdiction, C as ContainerConfig, a as ContainerDefinition, b as ContainerImageSource, N as NormalizedContainerImage } from "./packem_shared/jurisdiction.d-TwTGkgTg.js";
|
|
2
|
+
export type { B as BuildImageSource, c as ContainerInstanceType, d as ContainerReadinessCheck, e as ContainerRollout, f as CustomContainerInstanceType, g as NamedContainerInstanceType, R as RegistryImageSource } from "./packem_shared/jurisdiction.d-TwTGkgTg.js";
|
|
3
|
+
/** Options for explicitly starting an instance (mirrors `@cloudflare/containers`). */
|
|
4
|
+
interface ContainerStartOptions {
|
|
5
|
+
/** Override outbound internet access for this start. */
|
|
6
|
+
enableInternet?: boolean;
|
|
7
|
+
/** Override the container entrypoint. */
|
|
8
|
+
entrypoint?: string[];
|
|
9
|
+
/** Per-instance environment, merged over the definition's `env`/secrets. */
|
|
10
|
+
envVars?: Record<string, string>;
|
|
11
|
+
/** Metadata labels attached for metrics/observability. */
|
|
12
|
+
labels?: Record<string, string>;
|
|
13
|
+
}
|
|
14
|
+
/** A container instance's runtime state, as returned by `getState()`. Structural — the platform adds fields over time. */
|
|
15
|
+
interface ContainerInstanceState {
|
|
16
|
+
[key: string]: unknown;
|
|
17
|
+
/** Process exit code, present once the instance has `stopped_with_code`. */
|
|
18
|
+
exitCode?: number;
|
|
19
|
+
/** Epoch-ms of the last state transition. */
|
|
20
|
+
lastChange?: number;
|
|
21
|
+
/** Lifecycle status. Widening union — Cloudflare adds values over time. */
|
|
22
|
+
status?: "healthy" | "running" | "stopped" | "stopped_with_code" | "stopping";
|
|
23
|
+
}
|
|
24
|
+
/** What a handle needs from a Durable Object stub — `fetch` plus the optional lifecycle/egress RPCs the container DO exposes. */
|
|
25
|
+
interface ContainerStubLike {
|
|
26
|
+
allowHost?: (hostname: string) => Promise<void>;
|
|
27
|
+
denyHost?: (hostname: string) => Promise<void>;
|
|
28
|
+
destroy?: () => Promise<void>;
|
|
29
|
+
fetch: (input: Request) => Promise<Response>;
|
|
30
|
+
getState?: () => Promise<ContainerInstanceState>;
|
|
31
|
+
removeAllowedHost?: (hostname: string) => Promise<void>;
|
|
32
|
+
removeDeniedHost?: (hostname: string) => Promise<void>;
|
|
33
|
+
renewActivityTimeout?: () => Promise<void>;
|
|
34
|
+
setAllowedHosts?: (hosts: string[]) => Promise<void>;
|
|
35
|
+
setDeniedHosts?: (hosts: string[]) => Promise<void>;
|
|
36
|
+
start?: (options?: ContainerStartOptions) => Promise<void>;
|
|
37
|
+
stop?: (signal?: number | string) => Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
/** What the client needs from a Durable Object namespace binding. */
|
|
40
|
+
interface ContainerNamespaceLike {
|
|
41
|
+
get: (id: unknown) => ContainerStubLike;
|
|
42
|
+
idFromName: (name: string) => unknown;
|
|
43
|
+
/**
|
|
44
|
+
* Derive a jurisdiction-restricted subnamespace. Optional because older
|
|
45
|
+
* workers-types releases (and test doubles) may not expose it.
|
|
46
|
+
*/
|
|
47
|
+
jurisdiction?: (jurisdiction: DurableObjectJurisdiction) => ContainerNamespaceLike;
|
|
48
|
+
}
|
|
49
|
+
/** A handle on one container instance (one Durable Object). */
|
|
50
|
+
interface ContainerHandle {
|
|
51
|
+
/**
|
|
52
|
+
* Send an HTTP (or WebSocket-upgrade) request to the container. A path
|
|
53
|
+
* string (`"/transcode"`) is resolved against a synthetic origin; a full
|
|
54
|
+
* `Request`/URL passes through unchanged.
|
|
55
|
+
*/
|
|
56
|
+
fetch: (input: Request | string, init?: RequestInit) => Promise<Response>;
|
|
57
|
+
/**
|
|
58
|
+
* Return a handle that routes every request to `targetPort` on the
|
|
59
|
+
* container instead of the definition's `defaultPort` — for multi-port
|
|
60
|
+
* containers (declare the ports in `requiredPorts`). Sets the
|
|
61
|
+
* `cf-container-target-port` header the way `@cloudflare/containers`'
|
|
62
|
+
* `switchPort` does, so it composes with `.get()`, `.any()`, and `.pool()`:
|
|
63
|
+
* `ctx.containers.app.get("u1").port(9090).fetch("/admin")`.
|
|
64
|
+
*/
|
|
65
|
+
port: (targetPort: number) => ContainerHandle;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* A handle on a *named* instance (from `.get(name)`) — `fetch` plus explicit
|
|
69
|
+
* lifecycle control. The per-entity pattern (a sandbox per user, a room per
|
|
70
|
+
* game, a job runner per id) often needs to tear down or inspect the instance
|
|
71
|
+
* rather than wait for `sleepAfter`, so these wrap the container DO's
|
|
72
|
+
* `start`/`stop`/`destroy`/`getState`.
|
|
73
|
+
*/
|
|
74
|
+
interface ContainerInstanceHandle extends ContainerHandle {
|
|
75
|
+
/** Stop and discard the instance (its ephemeral disk is lost). */
|
|
76
|
+
destroy: () => Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* Adjust this instance's egress allow/deny lists at runtime — the dynamic
|
|
79
|
+
* counterpart to the static `allowedHosts`/`deniedHosts` config. Useful for
|
|
80
|
+
* per-tenant egress policy. Requires the worker to export `ContainerProxy`
|
|
81
|
+
* (codegen re-exports it from the generated container file whenever any
|
|
82
|
+
* container is defined, so the runtime controls always work).
|
|
83
|
+
*/
|
|
84
|
+
egress: ContainerEgressControls;
|
|
85
|
+
/** Read the instance's current runtime state. */
|
|
86
|
+
getState: () => Promise<ContainerInstanceState>;
|
|
87
|
+
/**
|
|
88
|
+
* Reset the instance's `sleepAfter` idle timer. The platform renews it on
|
|
89
|
+
* each proxied request, and because `@lunora/container` proxies WebSocket
|
|
90
|
+
* frames through the Durable Object, message traffic on an open socket
|
|
91
|
+
* renews it too (the WebSocket-keepalive gap of cloudflare/containers#147 is
|
|
92
|
+
* closed in the bundled base). This manual control is the escape hatch for
|
|
93
|
+
* keeping a container awake during activity that is neither an HTTP request
|
|
94
|
+
* nor a WS message — e.g. a long out-of-band job running inside it.
|
|
95
|
+
*/
|
|
96
|
+
renewActivityTimeout: () => Promise<void>;
|
|
97
|
+
/** Explicitly start the instance, optionally with per-instance env/entrypoint. */
|
|
98
|
+
start: (options?: ContainerStartOptions) => Promise<void>;
|
|
99
|
+
/** Stop the instance (optionally with a signal); it can start again on the next request. */
|
|
100
|
+
stop: (signal?: number | string) => Promise<void>;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Runtime egress-firewall controls for a named instance (`handle.egress.*`).
|
|
104
|
+
* Each maps to the corresponding `@cloudflare/containers` `Container` RPC, so
|
|
105
|
+
* an app can tighten or relax a single instance's allowed/denied hosts after
|
|
106
|
+
* start without redeploying.
|
|
107
|
+
*/
|
|
108
|
+
interface ContainerEgressControls {
|
|
109
|
+
/** Add one hostname (or glob) to the allow-list. */
|
|
110
|
+
allow: (hostname: string) => Promise<void>;
|
|
111
|
+
/** Add one hostname (or glob) to the deny-list. */
|
|
112
|
+
deny: (hostname: string) => Promise<void>;
|
|
113
|
+
/** Remove one hostname from the allow-list. */
|
|
114
|
+
removeAllowed: (hostname: string) => Promise<void>;
|
|
115
|
+
/** Remove one hostname from the deny-list. */
|
|
116
|
+
removeDenied: (hostname: string) => Promise<void>;
|
|
117
|
+
/** Replace the entire allow-list. */
|
|
118
|
+
setAllowed: (hosts: ReadonlyArray<string>) => Promise<void>;
|
|
119
|
+
/** Replace the entire deny-list. */
|
|
120
|
+
setDenied: (hosts: ReadonlyArray<string>) => Promise<void>;
|
|
121
|
+
}
|
|
122
|
+
/** The per-definition accessor exposed as `ctx.containers.<exportName>`. */
|
|
123
|
+
interface ContainerAccessor {
|
|
124
|
+
/**
|
|
125
|
+
* A random instance from a fixed pool of `count` (defaults to the
|
|
126
|
+
* definition's `maxInstances`, else 3 — mirroring `getRandom` from
|
|
127
|
+
* `@cloudflare/containers`). For stateless, interchangeable workloads.
|
|
128
|
+
*
|
|
129
|
+
* Like `.get()`, a path/URL-string fetch transparently retries the
|
|
130
|
+
* cold-start "instance is provisioning" transients (cloudflare/containers#45,
|
|
131
|
+
* #139); pass {@link InstanceRetryOptions} to tune or disable it.
|
|
132
|
+
*/
|
|
133
|
+
any: (count?: number, options?: InstanceRetryOptions) => ContainerHandle;
|
|
134
|
+
/**
|
|
135
|
+
* The instance for `name` — one container per entity (user, room, job…),
|
|
136
|
+
* with lifecycle control.
|
|
137
|
+
*
|
|
138
|
+
* A path/URL-string fetch transparently retries the platform's cold-start
|
|
139
|
+
* transients — "there is no Container instance available" / "container is
|
|
140
|
+
* not listening" while an instance is still provisioning
|
|
141
|
+
* (cloudflare/containers#45, #139) — on the *same* instance with backoff,
|
|
142
|
+
* since the request never reached the app. Pass {@link InstanceRetryOptions}
|
|
143
|
+
* to tune attempts/backoff or disable it (`{ attempts: 1 }`). A pre-built
|
|
144
|
+
* `Request` (possibly a one-shot stream body) is sent once, never retried.
|
|
145
|
+
*/
|
|
146
|
+
get: (name: string, options?: InstanceRetryOptions) => ContainerInstanceHandle;
|
|
147
|
+
/**
|
|
148
|
+
* A resilient handle over the pool: each `fetch` picks a random instance and,
|
|
149
|
+
* on a thrown error or a retryable response (5xx by default), retries on a
|
|
150
|
+
* freshly-picked instance with exponential backoff. Until Cloudflare ships
|
|
151
|
+
* native autoscaling + health-aware routing this is the recommended way to
|
|
152
|
+
* call a stateless container pool — it rides over a single cold/unhealthy
|
|
153
|
+
* instance instead of failing the whole request.
|
|
154
|
+
*
|
|
155
|
+
* Because a retry re-issues the request, pass a **replayable** body — a path
|
|
156
|
+
* string plus an `init.body` string/`ArrayBuffer` (re-created each attempt).
|
|
157
|
+
* A pre-built `Request` carrying a stream body can only be sent once, so it
|
|
158
|
+
* is not retry-safe here; use `.get()`/`.any()` for those.
|
|
159
|
+
*/
|
|
160
|
+
pool: (options?: PoolOptions) => ContainerHandle;
|
|
161
|
+
}
|
|
162
|
+
/** Tuning for a pooled, retrying container handle. See {@link ContainerAccessor.pool}. */
|
|
163
|
+
interface PoolOptions {
|
|
164
|
+
/** Total attempts before giving up (each on a freshly-picked instance). Default 3. */
|
|
165
|
+
attempts?: number;
|
|
166
|
+
/** Base backoff in ms between attempts; doubles each retry (0 disables the wait). Default 100. */
|
|
167
|
+
backoffMs?: number;
|
|
168
|
+
/**
|
|
169
|
+
* Upper bound on a single backoff sleep, in ms. The doubling delay is clamped
|
|
170
|
+
* to this ceiling so a large `attempts` count can't produce an unboundedly
|
|
171
|
+
* long wait. Default {@link DEFAULT_MAX_BACKOFF_MS} (30s).
|
|
172
|
+
*/
|
|
173
|
+
maxBackoffMs?: number;
|
|
174
|
+
/**
|
|
175
|
+
* Whether a *returned* response should be retried on another instance.
|
|
176
|
+
* Defaults to retrying any `5xx`. A thrown error (network/start failure) is
|
|
177
|
+
* always retried regardless of this predicate.
|
|
178
|
+
*/
|
|
179
|
+
retryOn?: (response: Response) => boolean;
|
|
180
|
+
/** Pool size to spread picks across. Defaults to the definition's `maxInstances`, else 3. */
|
|
181
|
+
size?: number;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Tuning for the cold-start retry on a `.get()`/`.any()` handle. The retry fires
|
|
185
|
+
* only on the platform's provisioning transients (no-instance / not-listening /
|
|
186
|
+
* rate-limited — see {@link isColdStartTransient}), which is why it's safe by
|
|
187
|
+
* default: those responses mean the request never reached the container.
|
|
188
|
+
*/
|
|
189
|
+
interface InstanceRetryOptions {
|
|
190
|
+
/**
|
|
191
|
+
* Total attempts on a cold-start transient before the last outcome is
|
|
192
|
+
* surfaced as-is. `1` disables the retry. Default
|
|
193
|
+
* {@link DEFAULT_COLD_START_ATTEMPTS}.
|
|
194
|
+
*/
|
|
195
|
+
attempts?: number;
|
|
196
|
+
/** Base backoff in ms between attempts; doubles each retry (0 disables the wait). Default {@link DEFAULT_COLD_START_BACKOFF_MS}. */
|
|
197
|
+
backoffMs?: number;
|
|
198
|
+
/** Upper bound on a single backoff sleep, in ms. Default {@link DEFAULT_MAX_BACKOFF_MS} (30s). */
|
|
199
|
+
maxBackoffMs?: number;
|
|
200
|
+
}
|
|
201
|
+
/** Wiring info for one definition, emitted by codegen into the generated DO. */
|
|
202
|
+
interface ContainerBindingSpec {
|
|
203
|
+
/** Durable Object binding name, e.g. `CONTAINER_TRANSCODER`. */
|
|
204
|
+
binding: string;
|
|
205
|
+
/** The `lunora/containers.ts` export name, e.g. `transcoder`. */
|
|
206
|
+
exportName: string;
|
|
207
|
+
/** Pool size default for `.any()`. */
|
|
208
|
+
maxInstances?: number;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Build the `ctx.containers` record from the Worker `env`. Called by the
|
|
212
|
+
* generated ShardDO with the specs codegen derived from
|
|
213
|
+
* `lunora/containers.ts`. A missing binding doesn't throw here — only when the
|
|
214
|
+
* handle is actually used — so one unprovisioned container never breaks
|
|
215
|
+
* unrelated functions.
|
|
216
|
+
*/
|
|
217
|
+
declare const createContainerContext: (env: Record<string, unknown>, specs: ReadonlyArray<ContainerBindingSpec>, jurisdiction?: DurableObjectJurisdiction) => Record<string, ContainerAccessor>;
|
|
218
|
+
/** A test handler: receives the request plus the targeted instance name. */
|
|
219
|
+
type ContainerTestHandler = (request: Request, instance: {
|
|
220
|
+
name: string;
|
|
221
|
+
}) => Promise<Response> | Response;
|
|
222
|
+
/**
|
|
223
|
+
* Docker-free test double for `ctx.containers`: each export name maps to a
|
|
224
|
+
* fetch handler that plays the container. Mirrors the real shape exactly, so
|
|
225
|
+
* action handlers under test can't tell the difference.
|
|
226
|
+
*
|
|
227
|
+
* ```ts
|
|
228
|
+
* const containers = createContainerTestContext({
|
|
229
|
+
* transcoder: (request) => new Response("ok"),
|
|
230
|
+
* });
|
|
231
|
+
* ```
|
|
232
|
+
*/
|
|
233
|
+
declare const createContainerTestContext: (handlers: Record<string, ContainerTestHandler>) => Record<string, ContainerAccessor>;
|
|
234
|
+
/**
|
|
235
|
+
* Normalize a `ContainerImageSource` into the shape wrangler wants: a
|
|
236
|
+
* Dockerfile path + build context for local builds, or a fully-qualified
|
|
237
|
+
* reference for pre-built images.
|
|
238
|
+
*
|
|
239
|
+
* A local-path string whose basename starts with `Dockerfile` (so
|
|
240
|
+
* `Dockerfile.dev` also counts) is used as-is with its directory as the build
|
|
241
|
+
* context; any other path is treated as the build-context directory and the
|
|
242
|
+
* Dockerfile is expected at `<dir>/Dockerfile`.
|
|
243
|
+
*/
|
|
244
|
+
declare const normalizeContainerImage: (image: ContainerImageSource) => NormalizedContainerImage;
|
|
245
|
+
/**
|
|
246
|
+
* The generated Container DO class name for a `lunora/containers.ts` export:
|
|
247
|
+
* `transcoder` → `TranscoderContainer`. wrangler's `containers[].class_name`
|
|
248
|
+
* and the Durable Object binding's `class_name` both reference it, so codegen
|
|
249
|
+
* and the config layer MUST derive it identically — always via this helper.
|
|
250
|
+
*/
|
|
251
|
+
declare const containerClassName: (exportName: string) => string;
|
|
252
|
+
/**
|
|
253
|
+
* The Durable Object binding name for a container export: `transcoder` →
|
|
254
|
+
* `CONTAINER_TRANSCODER`, `imageResizer` → `CONTAINER_IMAGE_RESIZER`. The
|
|
255
|
+
* `CONTAINER_` prefix namespaces these away from `SHARD`/`SESSION`/`SCHEDULER`
|
|
256
|
+
* so a container export can never collide with the built-in bindings.
|
|
257
|
+
*/
|
|
258
|
+
declare const containerBindingName: (exportName: string) => string;
|
|
259
|
+
/**
|
|
260
|
+
* The local image tag a Railpack `{ build }` container is built and pushed
|
|
261
|
+
* under: `transcoder` → `lunora-transcoder:build`. The config reconciler writes
|
|
262
|
+
* it as the wrangler `containers[].image`, and `lunora deploy` builds that tag
|
|
263
|
+
* with Railpack and `wrangler containers push`es it before deploying — so all
|
|
264
|
+
* three derive the tag from this one helper and can never disagree.
|
|
265
|
+
*/
|
|
266
|
+
declare const containerBuildTag: (exportName: string) => string;
|
|
267
|
+
declare const defineContainer: (config: ContainerConfig) => ContainerDefinition;
|
|
268
|
+
/** True when a value is a `defineContainer` result (the runtime brand check). */
|
|
269
|
+
declare const isContainerDefinition: (value: unknown) => value is ContainerDefinition;
|
|
270
|
+
/**
|
|
271
|
+
* The container's full environment at instance start: the static `env` block
|
|
272
|
+
* plus every declared secret resolved from the Worker `env`. A declared secret
|
|
273
|
+
* missing from the Worker env fails fast — starting the container without a
|
|
274
|
+
* credential it was promised yields far worse errors downstream.
|
|
275
|
+
*/
|
|
276
|
+
declare const resolveContainerEnvVariables: (definition: ContainerDefinition, workerEnv: Record<string, unknown>, exportName?: string) => Record<string, string>;
|
|
277
|
+
export { type ContainerAccessor, type ContainerBindingSpec, type ContainerConfig, type ContainerDefinition, type ContainerEgressControls, type ContainerHandle, type ContainerImageSource, type ContainerInstanceHandle, type ContainerInstanceState, type ContainerNamespaceLike, type ContainerStartOptions, type ContainerTestHandler, type DurableObjectJurisdiction, type InstanceRetryOptions, type NormalizedContainerImage, type PoolOptions, containerBindingName, containerBuildTag, containerClassName, createContainerContext, createContainerTestContext, defineContainer, isContainerDefinition, normalizeContainerImage, resolveContainerEnvVariables as resolveContainerEnvVars };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { createContainerContext, createContainerTestContext } from './packem_shared/createContainerContext-CIVzsY5m.mjs';
|
|
2
|
+
export { containerBindingName, containerBuildTag, containerClassName, defineContainer, isContainerDefinition, normalizeContainerImage, resolveContainerEnvVars } from './packem_shared/containerBindingName-BiTrAF1J.mjs';
|
package/dist/otel.d.mts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/** An attribute value carried on a span or log. */
|
|
2
|
+
type ContainerAttributeValue = boolean | number | string;
|
|
3
|
+
/**
|
|
4
|
+
* A `fetch` implementation — defaults to the runtime global. The exporter passes
|
|
5
|
+
* an abort `signal` (for the per-request timeout) and, once the promise settles,
|
|
6
|
+
* cancels the response `body` so Node/undici can release the socket for
|
|
7
|
+
* keep-alive reuse instead of leaving it occupied by an unread stream. It reads
|
|
8
|
+
* `ok`/`status` to detect a rejected export and nothing else from the response.
|
|
9
|
+
*/
|
|
10
|
+
type OtelFetchLike = (input: string, init: {
|
|
11
|
+
body: string;
|
|
12
|
+
headers: Record<string, string>;
|
|
13
|
+
method: string;
|
|
14
|
+
signal?: AbortSignal;
|
|
15
|
+
}) => Promise<{
|
|
16
|
+
body?: {
|
|
17
|
+
cancel: () => Promise<void>;
|
|
18
|
+
} | null;
|
|
19
|
+
ok: boolean;
|
|
20
|
+
status: number;
|
|
21
|
+
}>;
|
|
22
|
+
/** A single span the container process asks the exporter to record. */
|
|
23
|
+
interface ContainerSpanInput {
|
|
24
|
+
/** Attributes attached to the span (rendered under the OTLP `attributes` list). */
|
|
25
|
+
attributes?: Record<string, ContainerAttributeValue>;
|
|
26
|
+
/** Wall-clock millis when the operation ended. */
|
|
27
|
+
endMs: number;
|
|
28
|
+
/** When set, the span is marked errored with this message (and optional `error.type`). */
|
|
29
|
+
error?: {
|
|
30
|
+
message: string;
|
|
31
|
+
type?: string;
|
|
32
|
+
};
|
|
33
|
+
/** Span name — the operation being timed, e.g. `"transcode"`. */
|
|
34
|
+
name: string;
|
|
35
|
+
/** Wall-clock millis when the operation started. */
|
|
36
|
+
startMs: number;
|
|
37
|
+
}
|
|
38
|
+
/** A single log line the container process asks the exporter to record. */
|
|
39
|
+
interface ContainerLogInput {
|
|
40
|
+
/** Attributes attached to the log record. */
|
|
41
|
+
attributes?: Record<string, ContainerAttributeValue>;
|
|
42
|
+
/** Severity — defaults to `"info"`. */
|
|
43
|
+
level?: "debug" | "error" | "info" | "warn";
|
|
44
|
+
/** The log message body. */
|
|
45
|
+
message: string;
|
|
46
|
+
/** Wall-clock millis the line was emitted; defaults to now. */
|
|
47
|
+
ts?: number;
|
|
48
|
+
}
|
|
49
|
+
/** Options for {@link createContainerTelemetry}. */
|
|
50
|
+
interface ContainerTelemetryOptions {
|
|
51
|
+
/** Base OTLP collector endpoint; defaults to the `LUNORA_OTLP_ENDPOINT` env var. */
|
|
52
|
+
endpoint?: string;
|
|
53
|
+
/** Injectable `fetch` (tests / non-global runtimes). Defaults to `globalThis.fetch`. */
|
|
54
|
+
fetch?: OtelFetchLike;
|
|
55
|
+
/** Extra headers merged onto every POST — e.g. deployment/org correlation. `content-type` is set by default. */
|
|
56
|
+
headers?: Record<string, string>;
|
|
57
|
+
/** Called with any send failure so the caller can surface it; the export itself always swallows. */
|
|
58
|
+
onError?: (error: unknown) => void;
|
|
59
|
+
/** `service.name` resource attribute; defaults to the `LUNORA_SERVICE_NAME` env var then `"lunora-container"`. */
|
|
60
|
+
serviceName?: string;
|
|
61
|
+
/** Per-POST timeout in ms; a collector that never responds aborts after this so a stuck send can't stall `flush()`. Defaults to {@link DEFAULT_TIMEOUT_MS} (10s). */
|
|
62
|
+
timeoutMs?: number;
|
|
63
|
+
/** Bearer token sent as an `Authorization: Bearer` header; defaults to the `LUNORA_OTLP_TOKEN` env var. */
|
|
64
|
+
token?: string;
|
|
65
|
+
}
|
|
66
|
+
/** The exporter handle {@link createContainerTelemetry} returns. */
|
|
67
|
+
interface ContainerTelemetry {
|
|
68
|
+
/** Record one log line (no-op when disabled). */
|
|
69
|
+
emitLog: (log: ContainerLogInput) => void;
|
|
70
|
+
/** Record one span (no-op when disabled). */
|
|
71
|
+
emitSpan: (span: ContainerSpanInput) => void;
|
|
72
|
+
/** True when an endpoint resolved and exports are actually sent. */
|
|
73
|
+
readonly enabled: boolean;
|
|
74
|
+
/** Await all in-flight sends — call before the process exits. */
|
|
75
|
+
flush: () => Promise<void>;
|
|
76
|
+
/** Time `run()`, recording a span named `name` (ok, or errored if it throws). Always runs `run()`, even when disabled. */
|
|
77
|
+
trace: <T>(name: string, run: () => Promise<T>, attributes?: Record<string, ContainerAttributeValue>) => Promise<T>;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Create a zero-config OTLP exporter for the container process.
|
|
81
|
+
*
|
|
82
|
+
* ```ts
|
|
83
|
+
* const telemetry = createContainerTelemetry(); // reads LUNORA_OTLP_ENDPOINT / _TOKEN
|
|
84
|
+
* await telemetry.trace("transcode", () => transcode(job), { jobId: job.id });
|
|
85
|
+
* telemetry.emitLog({ level: "info", message: "done", attributes: { jobId: job.id } });
|
|
86
|
+
* await telemetry.flush(); // before the process exits
|
|
87
|
+
* ```
|
|
88
|
+
*
|
|
89
|
+
* With no endpoint resolvable the returned exporter is disabled (`enabled ===
|
|
90
|
+
* false`): `emitSpan`/`emitLog` no-op and `trace` still runs its work but records
|
|
91
|
+
* nothing — so the same code runs unchanged locally and in the cloud.
|
|
92
|
+
* @param options Exporter options; every field falls back to a `LUNORA_*` env var.
|
|
93
|
+
*/
|
|
94
|
+
declare const createContainerTelemetry: (options?: ContainerTelemetryOptions) => ContainerTelemetry;
|
|
95
|
+
export { type ContainerAttributeValue, type ContainerLogInput, type ContainerSpanInput, type ContainerTelemetry, type ContainerTelemetryOptions, type OtelFetchLike, createContainerTelemetry };
|
package/dist/otel.d.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/** An attribute value carried on a span or log. */
|
|
2
|
+
type ContainerAttributeValue = boolean | number | string;
|
|
3
|
+
/**
|
|
4
|
+
* A `fetch` implementation — defaults to the runtime global. The exporter passes
|
|
5
|
+
* an abort `signal` (for the per-request timeout) and, once the promise settles,
|
|
6
|
+
* cancels the response `body` so Node/undici can release the socket for
|
|
7
|
+
* keep-alive reuse instead of leaving it occupied by an unread stream. It reads
|
|
8
|
+
* `ok`/`status` to detect a rejected export and nothing else from the response.
|
|
9
|
+
*/
|
|
10
|
+
type OtelFetchLike = (input: string, init: {
|
|
11
|
+
body: string;
|
|
12
|
+
headers: Record<string, string>;
|
|
13
|
+
method: string;
|
|
14
|
+
signal?: AbortSignal;
|
|
15
|
+
}) => Promise<{
|
|
16
|
+
body?: {
|
|
17
|
+
cancel: () => Promise<void>;
|
|
18
|
+
} | null;
|
|
19
|
+
ok: boolean;
|
|
20
|
+
status: number;
|
|
21
|
+
}>;
|
|
22
|
+
/** A single span the container process asks the exporter to record. */
|
|
23
|
+
interface ContainerSpanInput {
|
|
24
|
+
/** Attributes attached to the span (rendered under the OTLP `attributes` list). */
|
|
25
|
+
attributes?: Record<string, ContainerAttributeValue>;
|
|
26
|
+
/** Wall-clock millis when the operation ended. */
|
|
27
|
+
endMs: number;
|
|
28
|
+
/** When set, the span is marked errored with this message (and optional `error.type`). */
|
|
29
|
+
error?: {
|
|
30
|
+
message: string;
|
|
31
|
+
type?: string;
|
|
32
|
+
};
|
|
33
|
+
/** Span name — the operation being timed, e.g. `"transcode"`. */
|
|
34
|
+
name: string;
|
|
35
|
+
/** Wall-clock millis when the operation started. */
|
|
36
|
+
startMs: number;
|
|
37
|
+
}
|
|
38
|
+
/** A single log line the container process asks the exporter to record. */
|
|
39
|
+
interface ContainerLogInput {
|
|
40
|
+
/** Attributes attached to the log record. */
|
|
41
|
+
attributes?: Record<string, ContainerAttributeValue>;
|
|
42
|
+
/** Severity — defaults to `"info"`. */
|
|
43
|
+
level?: "debug" | "error" | "info" | "warn";
|
|
44
|
+
/** The log message body. */
|
|
45
|
+
message: string;
|
|
46
|
+
/** Wall-clock millis the line was emitted; defaults to now. */
|
|
47
|
+
ts?: number;
|
|
48
|
+
}
|
|
49
|
+
/** Options for {@link createContainerTelemetry}. */
|
|
50
|
+
interface ContainerTelemetryOptions {
|
|
51
|
+
/** Base OTLP collector endpoint; defaults to the `LUNORA_OTLP_ENDPOINT` env var. */
|
|
52
|
+
endpoint?: string;
|
|
53
|
+
/** Injectable `fetch` (tests / non-global runtimes). Defaults to `globalThis.fetch`. */
|
|
54
|
+
fetch?: OtelFetchLike;
|
|
55
|
+
/** Extra headers merged onto every POST — e.g. deployment/org correlation. `content-type` is set by default. */
|
|
56
|
+
headers?: Record<string, string>;
|
|
57
|
+
/** Called with any send failure so the caller can surface it; the export itself always swallows. */
|
|
58
|
+
onError?: (error: unknown) => void;
|
|
59
|
+
/** `service.name` resource attribute; defaults to the `LUNORA_SERVICE_NAME` env var then `"lunora-container"`. */
|
|
60
|
+
serviceName?: string;
|
|
61
|
+
/** Per-POST timeout in ms; a collector that never responds aborts after this so a stuck send can't stall `flush()`. Defaults to {@link DEFAULT_TIMEOUT_MS} (10s). */
|
|
62
|
+
timeoutMs?: number;
|
|
63
|
+
/** Bearer token sent as an `Authorization: Bearer` header; defaults to the `LUNORA_OTLP_TOKEN` env var. */
|
|
64
|
+
token?: string;
|
|
65
|
+
}
|
|
66
|
+
/** The exporter handle {@link createContainerTelemetry} returns. */
|
|
67
|
+
interface ContainerTelemetry {
|
|
68
|
+
/** Record one log line (no-op when disabled). */
|
|
69
|
+
emitLog: (log: ContainerLogInput) => void;
|
|
70
|
+
/** Record one span (no-op when disabled). */
|
|
71
|
+
emitSpan: (span: ContainerSpanInput) => void;
|
|
72
|
+
/** True when an endpoint resolved and exports are actually sent. */
|
|
73
|
+
readonly enabled: boolean;
|
|
74
|
+
/** Await all in-flight sends — call before the process exits. */
|
|
75
|
+
flush: () => Promise<void>;
|
|
76
|
+
/** Time `run()`, recording a span named `name` (ok, or errored if it throws). Always runs `run()`, even when disabled. */
|
|
77
|
+
trace: <T>(name: string, run: () => Promise<T>, attributes?: Record<string, ContainerAttributeValue>) => Promise<T>;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Create a zero-config OTLP exporter for the container process.
|
|
81
|
+
*
|
|
82
|
+
* ```ts
|
|
83
|
+
* const telemetry = createContainerTelemetry(); // reads LUNORA_OTLP_ENDPOINT / _TOKEN
|
|
84
|
+
* await telemetry.trace("transcode", () => transcode(job), { jobId: job.id });
|
|
85
|
+
* telemetry.emitLog({ level: "info", message: "done", attributes: { jobId: job.id } });
|
|
86
|
+
* await telemetry.flush(); // before the process exits
|
|
87
|
+
* ```
|
|
88
|
+
*
|
|
89
|
+
* With no endpoint resolvable the returned exporter is disabled (`enabled ===
|
|
90
|
+
* false`): `emitSpan`/`emitLog` no-op and `trace` still runs its work but records
|
|
91
|
+
* nothing — so the same code runs unchanged locally and in the cloud.
|
|
92
|
+
* @param options Exporter options; every field falls back to a `LUNORA_*` env var.
|
|
93
|
+
*/
|
|
94
|
+
declare const createContainerTelemetry: (options?: ContainerTelemetryOptions) => ContainerTelemetry;
|
|
95
|
+
export { type ContainerAttributeValue, type ContainerLogInput, type ContainerSpanInput, type ContainerTelemetry, type ContainerTelemetryOptions, type OtelFetchLike, createContainerTelemetry };
|
package/dist/otel.mjs
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
const OTLP_SEVERITY = {
|
|
2
|
+
debug: 5,
|
|
3
|
+
// DEBUG
|
|
4
|
+
error: 17,
|
|
5
|
+
// ERROR
|
|
6
|
+
info: 9,
|
|
7
|
+
// INFO
|
|
8
|
+
log: 9,
|
|
9
|
+
// INFO
|
|
10
|
+
warn: 13
|
|
11
|
+
// WARN
|
|
12
|
+
};
|
|
13
|
+
const otlpUnixNano = (ms) => `${String(Math.round(ms))}000000`;
|
|
14
|
+
const otlpRandomHex = (bytes) => {
|
|
15
|
+
const buffer = new Uint8Array(bytes);
|
|
16
|
+
crypto.getRandomValues(buffer);
|
|
17
|
+
let hex = "";
|
|
18
|
+
for (const byte of buffer) {
|
|
19
|
+
hex += byte.toString(16).padStart(2, "0");
|
|
20
|
+
}
|
|
21
|
+
return hex;
|
|
22
|
+
};
|
|
23
|
+
const encodeAttribute = (key, value) => {
|
|
24
|
+
if (typeof value === "boolean") {
|
|
25
|
+
return { key, value: { boolValue: value } };
|
|
26
|
+
}
|
|
27
|
+
if (typeof value === "number") {
|
|
28
|
+
if (!Number.isFinite(value)) {
|
|
29
|
+
return { key, value: { stringValue: String(value) } };
|
|
30
|
+
}
|
|
31
|
+
return Number.isSafeInteger(value) ? { key, value: { intValue: String(value) } } : { key, value: { doubleValue: value } };
|
|
32
|
+
}
|
|
33
|
+
return { key, value: { stringValue: value } };
|
|
34
|
+
};
|
|
35
|
+
const encodeAttributes = (attributes) => {
|
|
36
|
+
if (attributes === void 0) {
|
|
37
|
+
return [];
|
|
38
|
+
}
|
|
39
|
+
return Object.entries(attributes).map(([key, value]) => encodeAttribute(key, value));
|
|
40
|
+
};
|
|
41
|
+
const mergeHeaders = (defaults, overrides, token) => {
|
|
42
|
+
const merged = {};
|
|
43
|
+
const seen = /* @__PURE__ */ new Map();
|
|
44
|
+
const put = (name, value) => {
|
|
45
|
+
const lower = name.toLowerCase();
|
|
46
|
+
const existing = seen.get(lower);
|
|
47
|
+
if (existing === void 0) {
|
|
48
|
+
seen.set(lower, name);
|
|
49
|
+
merged[name] = value;
|
|
50
|
+
} else {
|
|
51
|
+
merged[existing] = value;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
for (const [name, value] of Object.entries(defaults)) {
|
|
55
|
+
put(name, value);
|
|
56
|
+
}
|
|
57
|
+
for (const [name, value] of Object.entries(overrides ?? {})) {
|
|
58
|
+
put(name, value);
|
|
59
|
+
}
|
|
60
|
+
if (token !== void 0 && token.length > 0) {
|
|
61
|
+
put("authorization", `Bearer ${token}`);
|
|
62
|
+
}
|
|
63
|
+
return merged;
|
|
64
|
+
};
|
|
65
|
+
const wrapResourceSpans = (span, scopeName, serviceName) => {
|
|
66
|
+
return {
|
|
67
|
+
resourceSpans: [
|
|
68
|
+
{
|
|
69
|
+
resource: { attributes: [encodeAttribute("service.name", serviceName)] },
|
|
70
|
+
scopeSpans: [{ scope: { name: scopeName }, spans: [span] }]
|
|
71
|
+
}
|
|
72
|
+
]
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
const wrapResourceLogs = (logRecord, scopeName, serviceName) => {
|
|
76
|
+
return {
|
|
77
|
+
resourceLogs: [
|
|
78
|
+
{
|
|
79
|
+
resource: { attributes: [encodeAttribute("service.name", serviceName)] },
|
|
80
|
+
scopeLogs: [{ logRecords: [logRecord], scope: { name: scopeName } }]
|
|
81
|
+
}
|
|
82
|
+
]
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const DEFAULT_TIMEOUT_MS = 1e4;
|
|
87
|
+
const readEnv = (name) => {
|
|
88
|
+
return process.env[name];
|
|
89
|
+
};
|
|
90
|
+
const resolveFetch = (injected) => {
|
|
91
|
+
if (injected !== void 0) {
|
|
92
|
+
return injected;
|
|
93
|
+
}
|
|
94
|
+
if (typeof globalThis.fetch === "function") {
|
|
95
|
+
return globalThis.fetch;
|
|
96
|
+
}
|
|
97
|
+
return void 0;
|
|
98
|
+
};
|
|
99
|
+
const traceBody = (span, serviceName) => {
|
|
100
|
+
const attributes = encodeAttributes(span.attributes);
|
|
101
|
+
if (span.error?.type !== void 0) {
|
|
102
|
+
attributes.push(encodeAttribute("error.type", span.error.type));
|
|
103
|
+
}
|
|
104
|
+
const otlpSpan = {
|
|
105
|
+
attributes,
|
|
106
|
+
endTimeUnixNano: otlpUnixNano(span.endMs),
|
|
107
|
+
// SPAN_KIND_INTERNAL — the container's own work, not a server/client edge.
|
|
108
|
+
kind: 1,
|
|
109
|
+
name: span.name,
|
|
110
|
+
spanId: otlpRandomHex(8),
|
|
111
|
+
startTimeUnixNano: otlpUnixNano(span.startMs),
|
|
112
|
+
// STATUS_CODE_OK (1) / STATUS_CODE_ERROR (2).
|
|
113
|
+
status: span.error === void 0 ? { code: 1 } : { code: 2, message: span.error.message },
|
|
114
|
+
traceId: otlpRandomHex(16)
|
|
115
|
+
};
|
|
116
|
+
return wrapResourceSpans(otlpSpan, "@lunora/container", serviceName);
|
|
117
|
+
};
|
|
118
|
+
const logBody = (log, serviceName, nowMs) => {
|
|
119
|
+
const level = log.level ?? "info";
|
|
120
|
+
const record = {
|
|
121
|
+
attributes: encodeAttributes(log.attributes),
|
|
122
|
+
body: { stringValue: log.message },
|
|
123
|
+
severityNumber: OTLP_SEVERITY[level],
|
|
124
|
+
severityText: level.toUpperCase(),
|
|
125
|
+
timeUnixNano: otlpUnixNano(log.ts ?? nowMs)
|
|
126
|
+
};
|
|
127
|
+
return wrapResourceLogs(record, "@lunora/container", serviceName);
|
|
128
|
+
};
|
|
129
|
+
const createContainerTelemetry = (options = {}) => {
|
|
130
|
+
const endpoint = options.endpoint ?? readEnv("LUNORA_OTLP_ENDPOINT");
|
|
131
|
+
const enabled = endpoint !== void 0 && endpoint.length > 0;
|
|
132
|
+
const token = options.token ?? readEnv("LUNORA_OTLP_TOKEN");
|
|
133
|
+
const serviceName = options.serviceName ?? readEnv("LUNORA_SERVICE_NAME") ?? "lunora-container";
|
|
134
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
135
|
+
const fetchImpl = resolveFetch(options.fetch);
|
|
136
|
+
const headers = mergeHeaders({ "content-type": "application/json" }, options.headers, token);
|
|
137
|
+
let base = endpoint ?? "";
|
|
138
|
+
while (base.endsWith("/")) {
|
|
139
|
+
base = base.slice(0, -1);
|
|
140
|
+
}
|
|
141
|
+
const tracesUrl = `${base}/v1/traces`;
|
|
142
|
+
const logsUrl = `${base}/v1/logs`;
|
|
143
|
+
const inflight = /* @__PURE__ */ new Set();
|
|
144
|
+
const send = (url, body) => {
|
|
145
|
+
if (fetchImpl === void 0) {
|
|
146
|
+
options.onError?.(new TypeError("createContainerTelemetry: no `fetch` available — pass `fetch` in options for this runtime."));
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
const dispatch = async () => {
|
|
150
|
+
try {
|
|
151
|
+
const response = await fetchImpl(url, { body: JSON.stringify(body), headers, method: "POST", signal: AbortSignal.timeout(timeoutMs) });
|
|
152
|
+
if (!response.ok) {
|
|
153
|
+
options.onError?.(new Error(`createContainerTelemetry: OTLP export to ${url} failed with status ${String(response.status)}.`));
|
|
154
|
+
}
|
|
155
|
+
try {
|
|
156
|
+
await response.body?.cancel();
|
|
157
|
+
} catch {
|
|
158
|
+
}
|
|
159
|
+
} catch (error) {
|
|
160
|
+
options.onError?.(error);
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
const settled = dispatch().finally(() => {
|
|
164
|
+
inflight.delete(settled);
|
|
165
|
+
});
|
|
166
|
+
inflight.add(settled);
|
|
167
|
+
};
|
|
168
|
+
const emitSpan = (span) => {
|
|
169
|
+
if (!enabled) {
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
send(tracesUrl, traceBody(span, serviceName));
|
|
173
|
+
};
|
|
174
|
+
const emitLog = (log) => {
|
|
175
|
+
if (!enabled) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
send(logsUrl, logBody(log, serviceName, Date.now()));
|
|
179
|
+
};
|
|
180
|
+
const trace = async (name, run, attributes) => {
|
|
181
|
+
const startMs = Date.now();
|
|
182
|
+
try {
|
|
183
|
+
const result = await run();
|
|
184
|
+
emitSpan({ attributes, endMs: Date.now(), name, startMs });
|
|
185
|
+
return result;
|
|
186
|
+
} catch (error) {
|
|
187
|
+
emitSpan({
|
|
188
|
+
attributes,
|
|
189
|
+
endMs: Date.now(),
|
|
190
|
+
error: { message: error instanceof Error ? error.message : String(error), type: error instanceof Error ? error.name : void 0 },
|
|
191
|
+
name,
|
|
192
|
+
startMs
|
|
193
|
+
});
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
const flush = async () => {
|
|
198
|
+
await Promise.allSettled(inflight);
|
|
199
|
+
};
|
|
200
|
+
return { emitLog, emitSpan, enabled, flush, trace };
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
export { createContainerTelemetry };
|