@lunora/container 1.0.0-alpha.6 → 1.0.0-alpha.60

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.
@@ -1,5 +1,5 @@
1
+ import { C as ContainerDefinition, D as DurableObjectJurisdiction } from "../packem_shared/jurisdiction.d-DPvNG2h5.js";
1
2
  import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
2
- import { a as ContainerDefinition } from "../packem_shared/types.d-BlNwNY44.js";
3
3
  /**
4
4
  * ContainerStartOptions as they come from worker types
5
5
  */
@@ -119,7 +119,7 @@ type OutboundHandler<E = Cloudflare.Env, P = unknown> = {
119
119
  type OutboundHandlerParams = Record<string, unknown>;
120
120
  type OutboundHandlerParamsOf<THandler> = THandler extends ((req: Request, env: unknown, ctx: OutboundHandlerContext<infer Params>) => Promise<Response> | Response) ? Params : never;
121
121
  declare function outboundParams<THandler extends OutboundHandler<unknown, unknown>>(_handler: THandler, params: OutboundHandlerParamsOf<THandler>): OutboundHandlerParamsOf<THandler>;
122
- type OutboundHandlers<ParamsByMethod extends OutboundHandlerParams, E = Cloudflare.Env> = { [Method in keyof ParamsByMethod]?: OutboundHandler<E, ParamsByMethod[Method]> };
122
+ type OutboundHandlers<ParamsByMethod extends OutboundHandlerParams, E = Cloudflare.Env> = { [Method in keyof ParamsByMethod]?: OutboundHandler<E, ParamsByMethod[Method]>; };
123
123
  type OutboundHandlerOverride<Params = unknown> = {
124
124
  method: string;
125
125
  } & ([Params] extends [undefined] ? {
@@ -483,44 +483,30 @@ declare class Container<Env = Cloudflare.Env> extends DurableObject<Env> {
483
483
  getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined>;
484
484
  private isActivityExpired;
485
485
  }
486
- /**
487
- * Cloudflare Durable Object data-residency jurisdiction. Widening union —
488
- * Cloudflare adds values over time.
489
- * @see https://developers.cloudflare.com/durable-objects/reference/data-location/
490
- */
491
- type DurableObjectJurisdiction = "eu" | "fedramp" | "us";
492
- /**
493
- * Forward one lifecycle envelope to the root ShardDO's log buffer, best-effort.
494
- *
495
- * `env` is the Container DO's worker `env`: we read the `SHARD` namespace and
496
- * the `LUNORA_ADMIN_TOKEN` from it. Returns a promise that NEVER rejects — every
497
- * failure path (missing binding, missing token, fetch error) resolves to
498
- * `undefined` — so the caller can `void` it from a lifecycle hook safely.
499
- */
500
486
  type DurableObjectContext = ConstructorParameters<typeof Container>[0];
501
487
  /**
502
- * Base class for the generated Container DO classes. Applies a
503
- * `defineContainer` definition onto `@cloudflare/containers`' `Container`:
504
- * port, sleep timeout, internet access, and the container environment (static
505
- * `env` merged with the declared Worker secrets — a declared-but-unset secret
506
- * fails fast here rather than starting a container without its credential).
507
- *
508
- * Generated subclasses stay one line of behavior:
509
- *
510
- * ```ts
511
- * export class TranscoderContainer extends LunoraContainer {
512
- * constructor(ctx: DurableObjectState, env: Env) {
513
- * super(ctx, env, transcoder, "transcoder");
514
- * }
515
- * }
516
- * ```
517
- */
488
+ * Base class for the generated Container DO classes. Applies a
489
+ * `defineContainer` definition onto `@cloudflare/containers`' `Container`:
490
+ * port, sleep timeout, internet access, and the container environment (static
491
+ * `env` merged with the declared Worker secrets — a declared-but-unset secret
492
+ * fails fast here rather than starting a container without its credential).
493
+ *
494
+ * Generated subclasses stay one line of behavior:
495
+ *
496
+ * ```ts
497
+ * export class TranscoderContainer extends LunoraContainer {
498
+ * constructor(ctx: DurableObjectState, env: Env) {
499
+ * super(ctx, env, transcoder, "transcoder");
500
+ * }
501
+ * }
502
+ * ```
503
+ */
518
504
  declare class LunoraContainer<Env = unknown> extends Container<Env> {
519
505
  /**
520
- * Data-residency jurisdiction the app's DOs are pinned to (codegen passes the
521
- * schema's `.jurisdiction("…")`). Used to pin the best-effort lifecycle report
522
- * to the same region as the root shard. `undefined` ⇒ un-pinned.
523
- */
506
+ * Data-residency jurisdiction the app's DOs are pinned to (codegen passes the
507
+ * schema's `.jurisdiction("…")`). Used to pin the best-effort lifecycle report
508
+ * to the same region as the root shard. `undefined` ⇒ un-pinned.
509
+ */
524
510
  private readonly lunoraJurisdiction?;
525
511
  /** The `lunora/containers.ts` export name, for lifecycle log correlation. */
526
512
  private readonly lunoraName;
@@ -528,84 +514,238 @@ declare class LunoraContainer<Env = unknown> extends Container<Env> {
528
514
  private readonly lunoraDefaultPort?;
529
515
  /** Hard-cap lifetime in whole seconds (from the `hardTimeout` config), or `undefined`. */
530
516
  private readonly lunoraHardTimeoutSeconds?;
517
+ /** In-flight `readyOn` gate for the current start; cleared when it fails. See `awaitReadinessGate`. */
518
+ private lunoraReadiness?;
531
519
  /** Declarative readiness probes that gate request proxying (from the `readyOn` config). */
532
520
  private readonly lunoraReadyOn;
533
521
  /** Map of container env-var name → Worker Secrets Store binding name (from the `secretsStore` config). */
534
522
  private readonly lunoraSecretsStore?;
535
- /** Memoised Secrets Store resolution: run once, then merged into `envVars` before the first start. */
523
+ /** The definition's `env` + `secrets`, as resolved at construction — the env a start uses absent an override. */
524
+ private readonly lunoraDeclaredEnv;
525
+ /** The persisted `start({ envVars })` override, once loaded. See {@link ENV_OVERRIDE_KEY}. */
526
+ private lunoraEnvOverride?;
527
+ /** Whether the override field reflects storage (read once per DO instance, then kept in step). */
528
+ private lunoraEnvOverrideLoaded;
529
+ /** Memoised Secrets Store resolution: the resolved `name → value` map, fetched once. */
536
530
  private lunoraSecretsStoreResolved?;
531
+ /**
532
+ * Count of runs observed to have ENDED, bumped by the `onStop` hook. Read
533
+ * across a start: a bump means the run that start snapshotted is over,
534
+ * whatever the `running` flag said at snapshot time. See `beginStart`.
535
+ */
536
+ private lunoraStops;
537
537
  constructor(context: DurableObjectContext, env: Env, definition: ContainerDefinition, exportName?: string, jurisdiction?: DurableObjectJurisdiction);
538
538
  /**
539
- * Proxy entry for every `ctx.containers.&lt;name>` fetch. Resolves the
540
- * `secretsStore` bindings into `envVars` before delegating, so the values
541
- * are present when the base implicitly starts the container for this
542
- * request — a no-op when `secretsStore` is unset.
543
- */
539
+ * HTTP entry for every request to this Durable Object. Refuses the reserved
540
+ * `/__lunora/*` namespace unconditionally: `exec` reaches it only through
541
+ * the {@link lunoraExec} RPC, so no header, path spelling, or inbound request
542
+ * an app forwards as-is (`env.CONTAINER_X.get(id).fetch(request)`) opens it.
543
+ * The client-side path guard is the first line; this is the second.
544
+ */
545
+ override fetch(request: Request): Promise<Response>;
546
+ /**
547
+ * Proxy entry for every `ctx.containers.<name>` fetch — and a public RPC on
548
+ * the stub in its own right, so it applies the same `/__lunora/*` refusal
549
+ * as {@link fetch} rather than trusting that every caller came through it.
550
+ * The base starts the container for this request through
551
+ * {@link startAndWaitForPorts}, which is where the `secretsStore` resolution
552
+ * lives — a request that finds the container already healthy needs no
553
+ * resolution at all.
554
+ */
544
555
  override containerFetch(...args: Parameters<Container<Env>["containerFetch"]>): Promise<Response>;
545
556
  /**
546
- * Explicit start (`ctx.containers.&lt;name>.get(id).start()`). Resolves the
547
- * `secretsStore` bindings into `envVars` first, mirroring
548
- * {@link containerFetch}. A per-instance `start({ envVars })` replaces the
549
- * env set wholesale (base behavior), so the injected values only apply to a
550
- * bare `start()` — same as the static `env`/`secrets`. When the caller
551
- * supplies its own `envVars` we skip resolution entirely: those values would
552
- * be discarded anyway, so a missing/unreadable binding shouldn't fail a start
553
- * that never uses them.
554
- */
557
+ * The exec entry: `handle.exec` delivers its `POST /__lunora/exec` here, as
558
+ * an RPC, never over {@link fetch}. An RPC can only be invoked by code that
559
+ * holds the Durable Object binding, which is what makes the exec route
560
+ * unreachable from request content. Accepts exactly the exec route and
561
+ * nothing else under the reserved namespace, and honours a `.port(n)`
562
+ * handle's target-port header the way the base `fetch` does.
563
+ */
564
+ lunoraExec(request: Request): Promise<Response>;
565
+ /**
566
+ * The start path `containerFetch` takes (and the one an app can call itself).
567
+ * Resolves the `secretsStore` bindings into `envVars` first — `doStartContainer`
568
+ * reads `this.envVars`, so a container started this way would otherwise boot
569
+ * without its Secrets Store values.
570
+ *
571
+ * The base's last act is `blockConcurrencyWhile(… onStart())`, so this
572
+ * override resumes on the far side of that gate — which is where
573
+ * {@link afterContainerStart} has to run. See its docblock.
574
+ */
575
+ override startAndWaitForPorts(...args: Parameters<Container<Env>["startAndWaitForPorts"]>): Promise<void>;
576
+ /**
577
+ * Explicit start (`ctx.containers.<name>.get(id).start()`).
578
+ *
579
+ * A per-instance `start({ envVars })` REPLACES the declared env (`env`,
580
+ * `secrets`, `secretsStore` — the Secrets Store is not even read) and is
581
+ * PERSISTED: every later start of this instance, explicit or implicit (a
582
+ * `fetch`/`exec` after the container slept, crashed or hit `hardTimeout`),
583
+ * boots with the same variables until `destroy()`. That is what makes
584
+ * `start({ envVars: {} })` a credential-free sandbox rather than one that
585
+ * gets its credentials back on the next restart.
586
+ *
587
+ * A start with `envVars` that differ from what the instance is running (or
588
+ * starting) with is REJECTED rather than silently joined: the base would
589
+ * return early on a live container, reporting a start whose env never took
590
+ * effect. `stop()` it first, or `destroy()` it to drop the override.
591
+ */
555
592
  override start(...args: Parameters<Container<Env>["start"]>): Promise<void>;
593
+ /**
594
+ * Stop the container and forget this instance's `start({ envVars })`
595
+ * override, so the next start uses the declared env again.
596
+ */
597
+ override destroy(): Promise<void>;
556
598
  override onActivityExpired(): Promise<void>;
557
599
  override onError(error: unknown): unknown;
558
600
  override onStart(): Promise<void>;
559
601
  /**
560
- * Hook run when the container's `hardTimeout` elapses (dispatched by the base
561
- * scheduler via the run-generation-stamped schedule armed in
562
- * {@link onStart}). Default: stop the instance. Override to drain/checkpoint
563
- * first. A stale schedule from a previous run, or an already-stopped
564
- * instance, is ignored (upstream cloudflare/containers#85).
565
- */
602
+ * Hook run when the container's `hardTimeout` elapses (dispatched by the base
603
+ * scheduler via the run-generation-stamped schedule armed in
604
+ * {@link onStart}). Default: stop the instance. Override to drain/checkpoint
605
+ * first. A stale schedule from a previous run, or an already-stopped
606
+ * instance, is ignored (upstream cloudflare/containers#85).
607
+ *
608
+ * `stop()` sends SIGTERM and returns; nothing escalates to `destroy()`. The
609
+ * cap is therefore a signal, not a bound — a container that traps or ignores
610
+ * SIGTERM keeps running, and the schedule is ONE-SHOT (the base deletes the
611
+ * row once it fires), so nothing signals it a second time either: an ignored
612
+ * SIGTERM means the cap is spent, not retried. Override this hook and follow
613
+ * the stop with a `destroy()` after a grace period if your workload needs a
614
+ * real ceiling.
615
+ */
566
616
  onHardTimeoutExpired(payload?: {
567
617
  generation?: number;
568
618
  }): Promise<void>;
569
619
  override onStop(parameters: StopParams): Promise<void>;
570
- /**
571
- * Arm the hard-timeout kill via the base scheduler (so it integrates with
572
- * the container's own alarm machinery instead of fighting it). Bumps the run
573
- * generation and stamps the schedule with it, so {@link onHardTimeoutExpired}
574
- * can tell a fresh schedule from a stale one. No-op without a `hardTimeout`.
575
- */
620
+ /** A 403 for a path under the reserved namespace, else `undefined`. */
621
+ private refuseReserved;
622
+ /**
623
+ * Arm the hard timeout and block on the `readyOn` probes — the work that has
624
+ * to happen once per real start, **outside** the base's start gate.
625
+ *
626
+ * It cannot live in `onStart`, which is the obvious home for it: the base
627
+ * invokes that hook as `blockConcurrencyWhile(async () => { … onStart() })`
628
+ * (`@cloudflare/containers`, both `start()` and `startAndWaitForPorts()`),
629
+ * and workerd treats a *rejecting* `blockConcurrencyWhile` closure as
630
+ * unrecoverable — it aborts the Durable Object, discards its in-memory state
631
+ * and every hibernating socket on it, and flattens the error to a plain
632
+ * `Error`. A readiness timeout is an ordinary, diagnosable failure: it must
633
+ * surface as the `LunoraError` naming the check, the port and the budget,
634
+ * not cost the object its life and arrive as an opaque message. (The same
635
+ * reasoning, and the same settle-outside-the-gate remedy, is written up on
636
+ * `ShardHost.runSerialized` in `@lunora/platform-cloudflare`.) A 30-second
637
+ * wait also has no business inside a gate that blocks every other dispatch
638
+ * to the object.
639
+ *
640
+ * Both start entry points call this immediately after `super`, so it runs
641
+ * once per start. It does NOT gate proxying on its own: the base commits the
642
+ * healthy state inside the start gate, before this runs, so a concurrent
643
+ * request would sail past `containerFetch`'s status check. That is what
644
+ * `awaitReadinessGate` is for, and it is the seam the move cost us —
645
+ * the in-gate placement got this for free from `blockConcurrencyWhile`.
646
+ */
647
+ private afterContainerStart;
648
+ /**
649
+ * Decide — synchronously, before anything is started — whether this start
650
+ * begins a NEW container run, and drop the previous run's readiness gate when
651
+ * it does. Returns whether the container was already running.
652
+ *
653
+ * The gate has to be keyed on the run, and `onStop` alone cannot key it:
654
+ * `@cloudflare/containers` reaches `onStop` only through
655
+ * `syncPendingStoppedEvents`, which `start()` never calls (only
656
+ * `startAndWaitForPorts`, `stop()` and the alarm loop do), while the monitor
657
+ * callback that observes a container exit merely records the state. So a
658
+ * `start()` in the up-to-three-minute window before the next alarm found the
659
+ * finished run's settled gate and skipped BOTH `armHardTimeout` and the
660
+ * `readyOn` probes — run 2 ran uncapped and was proxied to before it reported
661
+ * ready. A `hardTimeout` firing its own SIGTERM lands in exactly that window.
662
+ *
663
+ * The mirror case is why the answer is not "always re-arm": a start that finds
664
+ * the container already up begins no run, and re-arming there moves the cap
665
+ * (see {@link afterContainerStart}).
666
+ *
667
+ * Read with no `await` between it and `super`, so two concurrent starts of a
668
+ * stopped container both observe `false` and the second joins the first's
669
+ * gate instead of arming a second schedule — and so the flag is as fresh as
670
+ * it can be. It is a snapshot either way, and the run can end after it: the
671
+ * base's own pre-start work (`getPortsToCheck`, `syncPendingStoppedEvents`)
672
+ * still runs on the far side of it, and a start that came in on a live
673
+ * container would then arm nothing for the run the base goes on to start.
674
+ * Hence the second half of the answer, in the callers: an `onStop` observed
675
+ * ACROSS the base call ({@link lunoraStops}) demotes the snapshot, because
676
+ * the run it described is over. What that does not cover is an exit inside
677
+ * `start()`'s own base call — that path never syncs pending stop events, so
678
+ * nothing reports the exit until the next alarm or `startAndWaitForPorts`,
679
+ * and the cap for such a run is armed only when one of those arrives.
680
+ */
681
+ private beginStart;
682
+ /**
683
+ * Block until the `readyOn` probes for the current start have passed.
684
+ *
685
+ * Necessary because the base marks the container healthy *inside* the start
686
+ * gate — `startAndWaitForPorts` runs `setHealthy()` immediately before
687
+ * `onStart()` — while our probes run after it returns. `containerFetch`
688
+ * skips the start path entirely once it observes
689
+ * `container.running && status === "healthy"`, so without this a request
690
+ * arriving mid-probe would proxy to a container that never reported ready,
691
+ * and a request arriving after a *failed* probe would do so permanently.
692
+ * Holding `setHealthy` and the probes together the way the base does would
693
+ * mean putting the probes back inside the gate, which is the defect this
694
+ * whole path exists to avoid.
695
+ */
696
+ private awaitReadinessGate;
697
+ /**
698
+ * Arm the hard-timeout kill via the base scheduler (so it integrates with
699
+ * the container's own alarm machinery instead of fighting it). Bumps the run
700
+ * generation and stamps the schedule with it, so {@link onHardTimeoutExpired}
701
+ * can tell a fresh schedule from a stale one. No-op without a `hardTimeout`.
702
+ */
576
703
  private armHardTimeout;
577
704
  /**
578
- * Resolve the `secretsStore` bindings (async `.get()`) once and merge the
579
- * values into `envVars`, so they're present when the base starts the
580
- * container. Memoised on the first call — every later start reuses the
581
- * resolved promise. A missing binding or a non-string value fails fast (the
582
- * start surfaces the error), the same fail-closed stance the static
583
- * `secrets` resolution takes for a missing Worker secret. No-op without
584
- * `secretsStore`.
585
- */
705
+ * Resolve the `secretsStore` bindings (async `.get()`) once and merge the
706
+ * values into `envVars`, so they're present when the base starts the
707
+ * container. Memoised on the first call — every later start reuses the
708
+ * resolved promise. A missing binding or a non-string value fails fast (the
709
+ * start surfaces the error), the same fail-closed stance the static
710
+ * `secrets` resolution takes for a missing Worker secret. No-op without
711
+ * `secretsStore`.
712
+ */
586
713
  private resolveSecretsStoreEnv;
714
+ /** The persisted `start({ envVars })` override, read from storage once per instance lifetime. */
715
+ private readEnvOverride;
587
716
  /**
588
- * Block until every `readyOn` probe responds with its expected status, or
589
- * throw once the readiness budget is spent. Probes run in parallel and hit
590
- * the container's TCP port directly (NOT `containerFetch`, which would
591
- * recurse back into the start path). No-op without `readyOn`.
592
- */
717
+ * Record a `start({ envVars })` override, refusing one that differs from
718
+ * the env a running (or starting) container already has — see {@link start}.
719
+ */
720
+ private persistEnvOverride;
721
+ /**
722
+ * Set `envVars` for the start about to happen: the persisted override when
723
+ * there is one (the Secrets Store is not read), else the declared env plus
724
+ * the resolved Secrets Store values.
725
+ */
726
+ private applyStartEnv;
727
+ /**
728
+ * Block until every `readyOn` probe responds with its expected status, or
729
+ * throw once the readiness budget is spent. Probes run in parallel and hit
730
+ * the container's TCP port directly (NOT `containerFetch`, which would
731
+ * recurse back into the start path). No-op without `readyOn`.
732
+ */
593
733
  private awaitContainerReadiness;
594
734
  /** Poll one readiness probe until it returns its expected status or the shared deadline passes. */
595
735
  private awaitReadinessCheck;
596
736
  /**
597
- * Best-effort push of `envelope` into the root ShardDO's log buffer so it
598
- * also appears in the Studio Logs panel (the terminal already has it via
599
- * `emitContainerLifecycle`). Fire-and-forget and fully swallowed: a missing
600
- * `SHARD` binding, a missing admin token, or a fetch failure NEVER throws
601
- * out of a lifecycle hook — the `console` path stays the source of truth.
602
- */
737
+ * Best-effort push of `envelope` into the root ShardDO's log buffer so it
738
+ * also appears in the Studio Logs panel (the terminal already has it via
739
+ * `emitContainerLifecycle`). Fire-and-forget and fully swallowed: a missing
740
+ * `SHARD` binding, a missing admin token, or a fetch failure NEVER throws
741
+ * out of a lifecycle hook — the `console` path stays the source of truth.
742
+ */
603
743
  private surfaceInStudioLogs;
604
744
  /**
605
- * Per-instance correlation id: the Durable Object id, which Cloudflare also
606
- * injects into the container as `CLOUDFLARE_DURABLE_OBJECT_ID`. Read
607
- * defensively — the id shape varies and isn't worth crashing a hook over.
608
- */
745
+ * Per-instance correlation id: the Durable Object id, which Cloudflare also
746
+ * injects into the container as `CLOUDFLARE_DURABLE_OBJECT_ID`. Read
747
+ * defensively — the id shape varies and isn't worth crashing a hook over.
748
+ */
609
749
  private instanceId;
610
750
  }
611
751
  export { ContainerProxy, LunoraContainer, type OutboundHandler, type OutboundHandlerContext, type OutboundHandlerParams, type OutboundHandlerParamsOf, type OutboundHandlers, outboundParams };