On this pageFunctions
ManagedResource
/**
* Low-level builder for a ManagedResource registry. The Model and Message
* generics are provided up front; the callback builds a record with `entry`.
*
* Application features create accessors through their named Block's
* `resource` and registries through their definition's `managedResources`.
* Pass the registry as `managedResources` and its local handler recipes through
* `EffectsLayer` when calling `Composition.prepareBlock`; registered child bindings
* collect their own registries and derive independent occurrence lifetimes.
*
* Use this when a resource is expensive or stateful and should only exist while
* the model is in a particular state: a camera stream during a video call, a
* WebSocket connection while on a chat page, or a Web Worker pool during a
* computation. For services that live for the entire application lifetime,
* supply a Layer through the completed application's `provide` method instead.
*
* `aggregate` and `lift` transform standalone records. Application Blocks
* use registered `bind` or `bindEach` placements to collect their resources,
* handler recipes, and other lifecycle registrations together.
*
* Pass a handler name before the requirements schema. An attached lifecycle
* handler supplies both functions and exposes its Layer as `layer`. The
* handler name identifies the Layer requirement;
* the record key continues to identify the lifecycle the runtime watches.
*
* **Lifecycle** — The runtime watches each entry's `modelToMaybeRequirements`
* after every model update, structurally comparing the result against the
* previous value:
*
* - `Option.none()` → `Option.some(params)`: calls `acquire(params)`, then
* dispatches `onAcquired(value)`.
* - `Option.some(paramsA)` → `Option.some(paramsB)` (structurally different):
* releases the old resource, then acquires a new one with `paramsB`.
* - `Option.some(params)` → `Option.none()`: calls `release(value)`, then
* dispatches `onReleased()`. No re-acquisition occurs.
*
* If `acquire` fails, `onAcquireError` is dispatched and the resource daemon
* continues watching for the next requirements change: a failed acquisition
* does not crash the application.
*
* **Entry and handler fields:**
*
* - `resource` — The identity tag created with `ManagedResource.tag`. Appears
* in the Effect R channel so commands that call `.get` are type-checked.
* - `modelToMaybeRequirements` — Extracts requirements from the model.
* `Option.none()` means "release", `Option.some(params)` means
* "acquire/re-acquire if params changed". For resources with no
* parameters, use `Schema.Option(Schema.Null)` and return `Option.some(null)`.
* - `acquire` — Creates the resource from the unwrapped params. The returned
* Effect should fail when acquisition fails: errors in the error channel
* flow to `onAcquireError` as a message instead of crashing the runtime.
* `acquire` runs with the resource-lifetime `Scope.Scope` in its context, so
* it can build an Effect `Layer` with `Layer.build` or register finalizers
* with `Effect.addFinalizer` whose teardown is tied to the resource. Those
* finalizers run when the resource is released or re-acquired, after the
* explicit `release` callback. Finalizers registered during a partially
* completed acquisition also run if `acquire` fails or is interrupted. A
* `Layer`-built resource therefore needs only `release: () => Effect.void`:
* the `Layer` finalizers run automatically when the scope closes.
* - `release` — Tears down the resource. Errors thrown here are silently
* swallowed, but the runtime still clears the resource reference and
* dispatches `onReleased()` so bookkeeping completes. Resources that
* register their teardown as scope finalizers in `acquire` leave this as
* `() => Effect.void`.
* - `handler`: An Effect generator for the `acquire` and `release`
* callbacks. When present, the entry exposes the resulting Layer as `layer`.
* - `onAcquired` — Message dispatched when `acquire` succeeds.
* - `onAcquireError` — Message dispatched when `acquire` fails.
* - `onReleased` — Message dispatched after `release` and the activation scope's
* finalizers complete.
*/
<Model, Message>(): (build: (entry: EntryBuilder<Model, Message>) => Entries) => Entries/** Creates a managed resource identity with a `.get` accessor for use in commands. */
<Value>(): (key: Key) => ManagedResource<Value, ManagedResourceService<Key>>/**
* A single ManagedResource entry produced by `ManagedResource.make`,
* `ManagedResource.lift`, or `ManagedResource.aggregate`. A private function
* brand prevents application code from manually constructing one, so an entry
* must come from a Foldkit constructor.
*
* The `Value` parameter is the type the resource holds while active: what
* `acquire` produces, what `release` and `onAcquired` receive, and what the
* tag's `.get` yields to commands. It is inferred from the `resource` tag.
*
* The `Service` parameter carries the resource tag's identity so `make`,
* `lift`, and `aggregate` can union the services a record requires. Read the
* union off a finished record with `ManagedResource.ServicesOf`.
*
* The `OnAcquired` parameter preserves the arity of the `onAcquired` handler:
* an entry whose handler ignores the acquired value keeps that fact in its
* type, so callers that replay the handler (the Scene test steps) only demand
* the value when the handler consumes it.
*/
type Entry = {
acquire: (params: Params) => Effect.Effect<Value, unknown, Scope.Scope | LifecycleServices>
modelToMaybeRequirements: (model: Model) => Requirements
onAcquired: OnAcquired
onAcquireError: (error: unknown) => Message
onReleased: () => Message
release: (value: Value) => Effect.Effect<void, unknown, Scope.Scope | LifecycleServices>
resource: ManagedResource<Value, Service>
schema: Schema.Schema<Requirements>
} & EntryBrand<Model, Message>/**
* Extracts the exact lifecycle handler requirement carried by a
* ManagedResource entry.
*/
type HandlerOf = ExtractHandler<Effect.Services<ReturnType<Entry["acquire"]>>>/** A ManagedResource entry whose lifecycle implementation is supplied by a Layer. */
type LayeredEntry = Entry<Model, Message, Requirements, Value, Service, OnAcquired, Handler<Name, Params, Value>, Params> & Readonly<{
name: Name
toLayer: ToLayer<Name, Params, Value>
}>/**
* Runtime-ready contract for one ManagedResource lifecycle. Applications
* normally create this through make; custom integrations may inspect
* the completed entry.
*/
type ManagedResourceConfig = {
acquire: (params: any) => Effect.Effect<any, unknown, Scope.Scope | LifecycleServices>
modelToMaybeRequirements: (model: Model) => any
onAcquired: (value: any) => Message
onAcquireError: (error: unknown) => Message
onReleased: () => Message
release: (value: any) => Effect.Effect<void, unknown, Scope.Scope | LifecycleServices>
resource: ManagedResource<any>
schema: Schema.Schema<any>
}/** A record of named ManagedResource configurations, keyed by resource name. */
type ManagedResources = Record<string, ManagedResourceConfig<Model, Message, any>> & {
__managedResourceServices: Services
}/** Type-level utility to extract the service identity type from a ManagedResource. */
type ServiceOf = T extends ManagedResource<any, infer S>
? S
: never/** Type-level utility to extract the service union from a ManagedResources record. */
type ServicesOf = {
[Key in keyof Resources]: Resources[Key] extends {
resource: ManagedResource<any, infer Service>
}
? Service
: never
}[keyof Resources]/** Type-level utility to extract the value type from a ManagedResource. */
type Value = T extends ManagedResource<infer V, any>
? V
: never/**
* The service required by a ManagedResource whose lifecycle is supplied by a
* Layer. Its name, decoded acquire params, and resource value identify the
* handler contract.
*/
interface Handler {
[HandlerTypeId]: Readonly<{
name: Invariant<Name>
params: Invariant<Params>
value: Invariant<Value>
}>
}/**
* A model-driven resource with acquire/release lifecycle. Access the resource
* value in commands via `.get`, which fails with `ResourceNotAvailable` when
* the resource is not currently active. The service identity appears in the
* Effect R channel, providing compile-time enforcement that the resource is
* registered.
*/
interface ManagedResource {
[ManagedResourceTypeId]: typeof ManagedResourceTypeId
get: Effect<Value, ResourceNotAvailable, Service>
key: string
}/** Branded identity type for a managed resource, used in the Effect R channel. */
interface ManagedResourceService {
[ManagedResourceBrand]: Key
}/**
* Creates a Layer recipe from an Effect that constructs a ManagedResource
* lifecycle handler. The constructor runs once when the application Layer
* is built and may capture shared services. The returned acquire and release
* functions manage each handle according to Model state. Acquire scoped
* resources inside acquire so their finalizers follow the handle's lifetime.
* Provide test services before building the same lifecycle handler Layer.
* Captured services retain their identity; service lookups during acquire and
* release use the invocation context over the construction context.
*/
interface ToLayer unknown/**
* Combines multiple ManagedResources records into one. Throws on duplicate
* keys so a misconfigured aggregate fails loudly at startup rather than
* silently overriding.
*
* Pass the records directly and the Model and Message are read off them. The
* Model of the first record is the one every later record is checked against,
* so a record from another Model universe fails at its own argument position.
* Message widens to the union across all records.
*
* The result keeps each record's keys, each entry's requirements schema and
* resource service, and the arity of each `onAcquired` handler. Read the
* service union off the result with ServicesOf.
*
* The curried form remains available for a record that has to be typed before
* its entries exist, such as a value annotated at a module boundary.
*/
const aggregate: () => (records: Records) => MergeRecords<Records>