Published foldkit API declarations for managedResource.
./managedResource
@wsagency/wseffect-foldkit · MIT · source · MIT license · WS-AGENCY-NOTICE · THIRD-PARTY-NOTICES
This entry point is published in @wsagency/wseffect-foldkit@0.1.0-rc.1. Import it from the package subpath shown below; the signatures and documentation are read from the installed package declarations.
import * as Wseffect from '@wsagency/wseffect-foldkit/managedResource'
Exported declarations
aggregate
aggregate: {
<Model, Message>(): <Records extends ReadonlyArray<Record<string, Entry<Model, Message, any, any, any>>>>(...records: Records) => MergeRecords<Records>;
<Records extends AnyResourcesList>(...records: CompatibleResources<Records>): MergeRecords<Records>;
}
Entry
A single Managed Resource entry produced by `ManagedResource.make`,
`ManagedResource.lift`, or `ManagedResource.aggregate`. The brand field is
`never`, so application code cannot manually construct one: it must go
through a 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.
export type Entry<Model, Message, Requirements, Value, Service = unknown, OnAcquired extends (...args: any) => Message = (value: Value) => Message> = {
readonly schema: Schema.Schema<Requirements>;
readonly resource: ManagedResource<Value, Service>;
readonly modelToMaybeRequirements: (model: Model) => Requirements;
readonly acquire: (params: AcquireParams<Requirements>) => Effect.Effect<Value, unknown, Scope.Scope>;
readonly release: (value: Value) => Effect.Effect<void>;
readonly onAcquired: OnAcquired;
readonly onReleased: () => Message;
readonly onAcquireError: (error: unknown) => Message;
} & EntryBrand<Model, Message>;
lift
Lifts a record of child Managed Resources into a parent's Model and Message
context, applying a Model accessor and a Message wrapper uniformly to every
entry. Per-entry requirements schemas and resource services are preserved.
`read` returns `Some(childModel)` while the child exists and `None` while
it is absent.
An absent child releases its resources without reading their requirements.
Use `Option.some` for a child that is always present. Each child's
requirements must be `Schema.Option`-wrapped so child absence and the
child's own release condition follow the same acquire/release lifecycle.
lift: <Resources extends Record<string, Entry<any, any, Option.Option<any>, any, any>>>(resources: Resources) => <ParentModel, ParentMessage>(config: {
readonly read: (parentModel: ParentModel) => Option.Option<ChildModelOf<Resources>>;
readonly toParentMessage: (message: ChildMessageOf<Resources>) => ParentMessage;
}) => { readonly [Key in keyof Resources]: Resources[Key] extends Entry<any, any, infer Requirements, infer Value, infer Service, infer OnAcquired extends (...args: ReadonlyArray<any>) => any> ? Entry<ParentModel, ParentMessage, Requirements, Value, Service, (...args: Parameters<OnAcquired>) => ParentMessage> : never; }
make
Declares a Managed Resources record. The Model and Message generics are
provided up front; the entries record follows, built from calls to the
`entry` builder passed into the inner function.
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 resources that live for the entire application lifetime, use
the static `resources` config instead.
Reach for `ManagedResource.aggregate` to combine multiple records, and
`ManagedResource.lift` to translate a child Submodel's record into a parent
context.
**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.
**Config 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 (scope finalizers run in last-in-first-out
order, and the runtime registers `release` after `acquire` completes). 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`.
- `onAcquired` — Message dispatched when `acquire` succeeds.
- `onAcquireError` — Message dispatched when `acquire` fails.
- `onReleased` — Message dispatched after `release` is attempted.
make: <Model, Message>() => <Entries extends Record<string, EntryBrand<Model, Message>>>(build: (entry: EntryBuilder<Model, Message>) => Entries) => Entries
ManagedResource
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.
export interface ManagedResource<in out Value, out Service = unknown> {
readonly [ManagedResourceTypeId]: ManagedResourceTypeId;
readonly key: string;
readonly get: Effect.Effect<Value, ResourceNotAvailable, Service>;
/** @internal */
readonly _tag: Context.Service<any, any>;
}
ManagedResourceConfig
Internal configuration for a single Managed Resource, used by the runtime.
export type ManagedResourceConfig<Model, Message> = {
readonly schema: Schema.Schema<any>;
readonly resource: ManagedResource<any>;
readonly modelToMaybeRequirements: (model: Model) => any;
readonly acquire: (params: any) => Effect.Effect<any, unknown, Scope.Scope>;
readonly release: (value: any) => Effect.Effect<void>;
readonly onAcquired: (value: any) => Message;
readonly onReleased: () => Message;
readonly onAcquireError: (error: unknown) => Message;
};
ManagedResources
A record of named Managed Resource configurations, keyed by resource name.
export type ManagedResources<Model, Message, Services = never> = Record<string, ManagedResourceConfig<Model, Message>> & {
readonly __managedResourceServices?: Services;
};
ManagedResourceService
Branded identity type for a managed resource, used in the Effect R channel.
export interface ManagedResourceService<Key extends string> {
readonly [ManagedResourceBrand]: Key;
}
ResourceNotAvailable
Typed error raised when a command accesses a managed resource that is not currently acquired.
export declare class ResourceNotAvailable extends ResourceNotAvailable_base<{
readonly resource: string;
}> {
}
ServiceOf
Type-level utility to extract the service identity type from a ManagedResource.
export type ServiceOf<T> = T extends ManagedResource<any, infer S> ? S : never;
ServicesOf
Type-level utility to extract the service union from a Managed Resources record.
export type ServicesOf<Resources> = {
[Key in keyof Resources]: Resources[Key] extends {
readonly resource: ManagedResource<any, infer Service>;
} ? Service : never;
}[keyof Resources];
tag
Creates a managed resource identity with a `.get` accessor for use in commands.
tag: <Value>() => <const Key extends string>(key: Key) => ManagedResource<Value, ManagedResourceService<Key>>
Value
Type-level utility to extract the value type from a ManagedResource.
export type Value<T> = T extends ManagedResource<infer V, any> ? V : never;