Capabilities & providers
A capability is a typed interface to the outside world; a provider
implements one. Handlers receive capabilities through a given clause. All three
live inside a context.
Declaring a capability
Section titled “Declaring a capability”capability Logger { fn info(message: String) -> Effect[()]}A capability is a set of operation signatures (no bodies). Each operation
returns Effect[T] (capabilities are how effectful work reaches the outside).
Providing a capability
Section titled “Providing a capability”provides Logger = ConsoleLogger { fn info(message: String) -> Effect[()] { Effect.pure(()) }}provides Cap = Impl { … } implements every operation of Cap. The signatures
must match exactly (bynk.provider.signature_mismatch,
bynk.provider.missing_operation, bynk.provider.extra_operation). There is one
provider per capability in a context.
A capability a context declares and requires with given needs a provider in
that context when you build for Workers: a Worker’s composition root builds
every capability its handlers are given (bynk.capability.not_provided). On the
bundle target a capability with no provider is left to the host, which supplies
it through __makeSurface(deps), unless the bundle has a composition root
(composeApp). A bundle has one once any context consumes another context’s
service or capability, emits events, or derives a capability, and composeApp
builds every context itself, so each required capability then needs a provider
there too. A test stub doesn’t count: it replaces the provider only in the
cases that stub it.
Using a capability
Section titled “Using a capability”A handler lists the capabilities it needs with given, then calls them:
service hello { on call() -> Effect[String] by Caller given Logger { let _ <- Logger.info("hi") "ok" }}A given name must be a declared capability (bynk.given.unknown_capability); a
call to a capability not in given is an error (bynk.given.undeclared_capability);
a declared-but-unused capability is a warning (bynk.given.unused_capability).
Capabilities in functions
Section titled “Capabilities in functions”A free function in a context may declare given after its return type, and use
those capabilities in its body (a lambda there included):
fn warn(what: String) -> Effect[()] given Logger { Logger.error("warning: \(what)")}- Where. Only a free function that returns
Effect[T], in a context. A function in acommonsor a suite cannot: those are shared by contexts that may consume different capabilities, so they keep the function-value style (log: (String) -> Effect[()]). A method cannot, andEventscannot be named (bynk.given.fn_outside_context,bynk.given.fn_unsupported). - Calling it. The caller’s
givenMUST include the callee’s. A call, or a reference to the function as a value, from a body that lacks one isbynk.given.missing_for_call, naming the capabilities missing. This is checked at every call, so it holds transitively; recursion needs no special case. A call counts as a use of the callee’s capabilities in the caller’sgiven. - Tests. A
casemay call it directly and gets the target’s capabilities as its handlers do.stubandexpect … calledobserve the calls made inside it. - Generics. The function may be generic. Capability operations keep their own type arguments.
- Emission. The function takes a hidden trailing
depsparameter that carries exactly the capabilities it names (before the execution context ofdetach,withinandrace), and every call passes the caller’sdepson.
Joining independent effects — par
Section titled “Joining independent effects — par”Every <- waits for its effect, so two independent calls cost the sum of their
latencies. A par block issues several effects together and waits for all of them:
service dashboard { on call(id: Int) -> Effect[String] by Caller given Users, Orders { par { let user <- Users.get(id) let orders <- Orders.forUser(id) } Effect.pure("\(user): \(orders)") }}Both effects are issued, in source order, before either is awaited. The block
completes when every binding has settled, and the names it binds are in scope after
the closing brace, not inside it. par is contextual: it opens a statement only
before {, and is an ordinary identifier everywhere else.
A par block holds only let x <- e (optionally let x: T <- e) and do e, and is
legal wherever a <- is: an effectful body, an agent handler included. It has no
value; it is a statement. These are refused:
| In the block | Code | Why |
|---|---|---|
a plain let, := or a store write, expect, advance, a nested par, a let … else, or nothing at all | bynk.par.invalid_statement | each has no effect to overlap, nothing to join, or must stay sequential |
? in a binding | bynk.par.question_in_join | ? takes a Result, not an effect: bind the Result in the block and apply ? after it (let user = userR?), where the first Err in source order propagates; compute a ? on an argument before the block |
| a binding that mentions a name another binding of the block binds, or two bindings of one name | bynk.par.sibling_name | the bindings run together, so none can read a sibling’s result; the rule holds even where the name would resolve to an outer binding |
A block with one binding is the warning bynk.par.single_binding: it is a plain
let x <- e with extra syntax.
Store writes stay sequential in parTraverse too. The closure given to
parForEach, parTraverse, parTraverseAll or parTraverseTry runs once per element, all at
once, so it follows the same rule: it may not write a store field
(bynk.par.store_write_in_closure). That covers put, remove, update, upsert,
add, append and :=, in the closure, in a lambda nested in it, or in a lambda
bound to a name and passed by name. Reads, a store used as the receiver
(conns.parTraverse(…)), and calls to other agents are fine. A get then a put in
a closure loses updates, because every <- is an await point and the branches
interleave between the two; run the loop with forEach instead, where a single-call
update or upsert is atomic per key.
If an effect faults, the block waits for the others to settle, then raises the
first fault in source order, not the first in time. A fast failure waits for a
slow sibling; that is what keeps every effect inside the handler’s lifetime and the
fault a program sees independent of timing. Effects that completed before the fault
keep their effects, exactly as in a sequence of <-s. See
what a join guarantees on failure.
Bounding an effect — within
Section titled “Bounding an effect — within”e.within(d) bounds how long an effect may take. It is a method of every
Effect[T], d is a Duration, and the result is Effect[Result[T, TimedOut]]:
// the unit has: consumes bynk { TimedOut }let r <- Pricing.quote(id).within(2.seconds)match r { Ok(q) => Effect.pure("quoted \(q)") Err(TimedOut { after, .. }) => Effect.pure("late") // the quote may still complete}TimedOut { after: Duration } is bynk’s, so the unit needs consumes bynk { TimedOut }
(or TimedOut in its existing consumes bynk { … } list); without it the call is
bynk.within.timed_out_not_in_scope. When the
deadline passes first, the effect is not cancelled: it is handed to the
platform’s waitUntil and may still complete after the handler returns, with its side
effects. A tie goes to the effect. FetchOptions.timeout is the tool when the work must
actually stop. An effect that already returns a Result gains a second layer.
| Where | Code | Why |
|---|---|---|
| an agent handler, a lambda in one included | bynk.within.in_agent_handler | no execution context to hand the abandoned effect to |
a provider operation, a WebSocket handler or a test case body | bynk.within.outside_handler | none of them has an execution context (a WebSocket handler runs in the connection’s Durable Object). An effectful fn or method is allowed: it takes the context from its caller (#2719) |
a call to, or a reference to, a function that uses within, race or detach, from an agent handler, a WebSocket handler or a provider operation | bynk.exec.unavailable | the note names the chain of calls down to the construct |
| a pure body | bynk.within.in_pure_context | it needs an effectful body |
a unit that does not consume bynk | bynk.within.timed_out_not_in_scope | TimedOut is bynk’s |
A deadline that is not over zero and at most 2,147,483,647 ms faults the call. See bound how long a call may take.
Racing two effects — race
Section titled “Racing two effects — race”a.race(b) takes whichever of two effects succeeds first. It is a method of every
Effect[T], b is an Effect[T] too, and the result is Effect[T]. It chains:
a.race(b).race(c) is the first of three.
let p <- Prices.get("east", sku).race(Prices.get("west", sku))- First to succeed. A side that faults does not win while another may still
succeed. If every side faults, the first fault in source order is raised, with the
others attached as
suppressed. AnErrreturned by anEffect[Result[T, E]]is a value, so it is a success and can win. - A tie goes to the receiver: the side written first.
- The loser is not cancelled. It is handed to the platform’s
waitUntiland runs to completion, so its side effects still happen.raceis for idempotent work, and the work is done twice.FetchOptions.timeoutis the tool when the work must stop. - A mismatched
Tis an ordinary type error; map each side into a shared type first.
It is legal exactly where within is, and refused in the same places:
| Where | Code | Why |
|---|---|---|
| an agent handler, a lambda in one included | bynk.race.in_agent_handler | no execution context to hand the loser to |
a provider operation, a WebSocket handler or a test case body | bynk.race.outside_handler | none of them has an execution context. An effectful fn or method is allowed (#2719), as for within |
| a pure body | bynk.race.in_pure_context | it needs an effectful body |
See ask two sources and take the first answer.
Detaching an effect — detach
Section titled “Detaching an effect — detach”e.detach() on any Effect[T] stops waiting for e. It returns an Effect[()] that completes at
once: the effect is already running (an effect is an eager promise, started where the expression
is evaluated), and detach hands that running promise to the platform’s waitUntil so it can finish
after the handler has answered. It never starts anything and never delays one.
fn notify(req: Request) -> Effect[()] given Fetch { Fetch.send(req).detach() // an `Err` reply is reported, never lost}
fn notifyAll(reqs: List[Request]) -> Effect[()] given Fetch { reqs.forEach((r) => Fetch.send(r).detach())}A detached reply is never silently lost. A failure is reported by the runtime, not by Logger:
- A fault (the effect’s promise rejects) is passed to the platform’s exception path unchanged, so the platform records an exception, labelled with the detach site.
- An
Err(whenTis aResult) is one structuredconsole.errorrecord naming the site, the error’s type and, for a sum, its variant tag. The payload is not reported, because it can hold a credential. Ok, and anyTthat is not aResult, report nothing.
Detaching is immediate and best-effort: it is not retried. On Workers, waitUntil work can run for up to
30 seconds after the response is sent or the client disconnects, shared across the request; promises still
unsettled then are cancelled (local workerd does not enforce this). In a test, the harness records each report and does not fail the case, as on
Workers.
It is legal exactly where within is, and an agent handler or a pure body is refused:
| Where | Code | Why |
|---|---|---|
| an agent handler, a lambda in one included | bynk.detach.in_agent_handler | no execution context to keep the effect alive |
| a store operation in an agent handler | bynk.detach.store_op | a store write is part of the handler’s atomic commit |
| a pure body | bynk.detach.in_pure_context | it needs an effectful body |
Generic operations
Section titled “Generic operations”A capability operation may declare its own type parameter (v0.235, ADR 0281) —
useful when the value it hands back is of whatever type the calling handler
determines, not a type the capability’s author can know ahead of time. The
example below is also the real shape of the first-party Idempotency
capability this mechanism was built for — see
First-party bynk capabilities
for its actual, shipped two-operation form (dedup plus a remember to write
a value back):
capability Idempotency { fn dedup[T](key: String) -> Effect[Option[T]]}T is resolved from an explicit call-site type argument, or inferred from the
arguments when they determine it (Idempotency.remember(key, value, ttl), Events.emit(event)).
dedup has no argument that mentions T, so it is written, as Json.decode[T](s) is, and
T is never inferred from the expected type:
service reserve { on call() -> Effect[Option[ReserveOutcome]] by Caller given Idempotency { let cached <- Idempotency.dedup[ReserveOutcome]("order-key-1") cached }}Omitting [T] when no parameter’s type mentions it is
bynk.generics.uninferable_type_arg; the wrong number of type arguments is
bynk.generics.type_arg_mismatch. The operation is emitted as a genuine
generic TypeScript interface method (dedup<T>(key: string): Promise<Option<T>>)
— no monomorphisation, no erasure — and the call site names the type argument
explicitly in the emitted TypeScript too, since nothing else at the call site
lets tsc infer a return-position-only parameter.
Two restrictions follow directly from there being no runtime codec to
specialise a generic operation’s T against:
- A capability with a generic operation requires an external
provider (
bynk.provider.generic_op_requires_external) — a Bynk-bodied provider would needTrigid through its own body checker for no expressive gain, since it can only ever return a value it already has. This means a capability with a generic operation can only be declared inside anadapter, never a plaincontext(whose provider must have a Bynk body). - A generic operation cannot be stubbed in a test (
bynk.stub.generic_op) — astubclause’s body has no way to construct a value of an unconstrainedT. Stubbing another, non-generic operation of the same capability is unaffected.
A generic operation is called the same way through a cross-context capability,
both flattened (consumes Adapter { Cap } → Cap.op[T](…)) and qualified
(consumes Adapter → Adapter.Cap.op[T](…)).
Provider composition (provides … given)
Section titled “Provider composition (provides … given)”A provider may itself depend on other capabilities — declare them with given
after the provider name, and call them in the bodies:
context demo
capability Logger { fn info(message: String) -> Effect[()]}
capability Greeter { fn greet() -> Effect[()]}
provides Logger = ConsoleLogger { fn info(message: String) -> Effect[()] { Effect.pure(()) }}
provides Greeter = PoliteGreeter given Logger { fn greet() -> Effect[()] { let _ <- Logger.info("hello") Effect.pure(()) }}The same given discipline applies (unknown / undeclared-use are errors). The
providers form a dependency graph over capabilities; the composition root
instantiates them in dependency order, injecting each provider’s dependencies.
A capability may not depend on itself, directly or transitively
(bynk.provider.dependency_cycle) — including the trivial provides X = … given X.
Derived capabilities (capability X = K)
Section titled “Derived capabilities (capability X = K)”A derived capability is a distinct instance of a platform resource, such as a second KV namespace:
context shop.cart
consumes bynk.cloudflare { Kv }
capability Sessions = Kv
capability PriceCache = Kv
service remember { on call(k: String, v: String) -> Effect[Option[String]] by Caller given Sessions { let _ <- Sessions.put(k, v) Sessions.get(k) }}Sessions has Kv’s operations, but its own storage. PriceCache is another
instance, and the bare Kv, if used, a third. It is not an alias: a key written
through Sessions is absent through PriceCache, just as type Id = Int is a
distinct type over Int. Write no provides. The base’s platform provider
serves each instance, bound to the instance’s own resource. In every other way
an instance is an ordinary capability: given, calls, stub and expect work
on it unchanged.
- The base must be a capability the context selects with
consumes U { K }(bynk.capability.unknown_base), and a resource kind with instances (bynk.capability.base_not_instantiable). Today that isbynk.cloudflare’sKv,Service,R2,RateLimit,Queue,Analytics,EdgeCache,StoredSecret,Email,PostgresandMySql.Versionis not: a Worker has one Version metadata binding, so it is used bare, withgiven Version. - Options follow the base as
@annotations, from the kind’s own set (bynk.capability.unknown_option), each one literal of the option’s kind, given once (bynk.capability.invalid_option).Kvtakes none.Servicerequires@worker("name"), the Worker it reaches (bynk.capability.missing_option), which must not be one of the project’s own contexts’ Workers.R2takes an optional@jurisdiction("eu").RateLimitrequires@limit(n), a positiveInt, and@period(d),10.secondsor60.seconds(Rate limiting).Queuerequires@name("queue"), the queue it sends to (Sending to a queue).Analyticstakes none:bynk deploynames its dataset (Writing events).D1takes none:bynk deploynames and creates its database (SQL databases).StoredSecretrequires@store("name")and@secret("name"), the Secrets Store and the secret in it, whichbynk deploylinks and never creates (Account secrets).Emailtakes@to("addr"),@allowedRecipients([…])and@allowedSenders([…]), each optional: deploy-time policy written into[[send_email]], whose sendersbynk deploychecks and never configures (Outbound email).Postgrestakes none: it binds asHYPERDRIVE_<NAME>, a[[hyperdrive]]entry whoseidis a placeholderbynk deployreplaces with the Hyperdrive configuration it makes from a connection string in an environment variablebynk.tomlnames (Postgres databases).MySqltakes an optional@tls("required"),"verify-ca"or"verify-identity"(how Hyperdrive secures its connection to the database; anything else isbynk.capability.invalid_option), and binds asHYPERDRIVE_<NAME>likePostgres(MySQL databases).EdgeCachetakes none, and a context declares at most one (bynk.cloudflare.edge_cache_duplicate): it turns on the Worker’s edge cache and has no binding (Edge caching).Service,R2,RateLimit,Queue,Analytics,D1,Postgres,MySqlandEdgeCacheare used only through instances (bynk.capability.instance_only). - Only a context declares one (
bynk.capability.derived_outside_context), and it cannot be exported (bynk.exports.derived_capability). The data belongs to the context, so another context reaches it through the context’s services.
On Workers, each instance gets its own binding, named from the kind and the
capability (Sessions → KV_SESSIONS, PriceCache → KV_PRICE_CACHE), with an
Env member and a [[kv_namespaces]] stanza of its own. The bare KV stanza is
emitted only for a context that uses the bare Kv. Under bynk test, each
instance has its own fresh in-memory double. bynk deploy provisions each
instance’s namespace and records its id, titled <worker>-<capability>
(Several KV namespaces). See Use more than one KV namespace.
A Service instance (capability Billing = Service @worker("legacy-billing"))
binds as SERVICE_BILLING, a [[services]] entry naming its Worker. Under
bynk test its double faults until send is stubbed; bynk deploy binds it
without provisioning anything. See Call a Worker outside the project.
Cross-context capabilities (exports capability)
Section titled “Cross-context capabilities (exports capability)”A context can offer a capability for other contexts to consume — the pattern
behind platform / framework contexts (a Clock, an Http client, a
Random source) that application contexts depend on without re-declaring.
The providing context lists the capability in an exports capability { … }
clause; each name must be a capability the context both declares and
provides:
context platform.time
exports capability { Clock }
capability Clock { fn now() -> Effect[Int]}
provides Clock = SystemClock { fn now() -> Effect[Int] { 0 }}A consumer consumes that context and depends on the capability through a
qualified given — given B.Cap, or given Alias.Cap when the consumes
clause introduces an alias. The capability call uses the same prefix:
context ops.jobs
consumes platform.time
service tick { on call() -> Effect[Int] by Caller given platform.time.Clock { let t <- platform.time.Clock.now() t }}The capability contract is imported for type-checking; the provider is
instantiated in the consumer’s own composition and the call runs in-process
(no Worker hop) — each consuming Worker gets its own provider instance, exactly
as platform capabilities intend. A consumer’s provider may also depend on a
cross-context capability (provides X = Impl given B.Cap); the composition root
wires the provider across the boundary.
Errors:
bynk.exports.undeclared_capability—exports capabilitynames something the context does not declare as a capability.bynk.exports.capability_not_provided— an exported capability has no provider (a consumer could not instantiate it).bynk.given.cross_context_unknown_capability—given B.CapwhereBdoes not exportCap.- A
given B.CapwhoseBis notconsumes-d is the ordinarybynk.resolve.unconsumed_context.
Out of scope (deferred): remote routing of capability calls to the providing Worker, capabilities backed by another context’s private agent state, and transitive re-export of a consumed capability.
Emission
Section titled “Emission”Providers compile to classes implementing the capability interface; a composed
provider gains a constructor that receives its dependencies, and the generated
compose instantiates providers in topological order. A cross-context
capability is instantiated locally in the consumer’s composition (its provider
class imported from the providing context), so the call lowers to an ordinary
deps.<Cap>.op(…). See emission.