Skip to content

Consume another context's services with `consumes`

Goal: call a service that belongs to another context.

A context declares the contexts it depends on with consumes, then calls their services. Suppose a payment context offers an authorise service:

context payment
service authorise {
on call(amount: Int) -> Effect[Result[Int, Int]] {
Ok(amount)
}
}

Declare the dependency and call the service

Section titled “Declare the dependency and call the service”

In the consuming context, declare consumes <context> and call the service by its qualified name. Service calls are effectful, so bind the result with <-:

context orders
consumes payment
service placeOrder {
on call(total: Int) -> Effect[Result[Int, Int]] {
let _ <- payment.authorise(total)
Ok(total)
}
}

Add as <Alias> to call through a shorter name:

context orders
consumes payment as Pay
service placeOrder {
on call(total: Int) -> Effect[Result[Int, Int]] {
let _ <- Pay.authorise(total)
Ok(total)
}
}

Each context commits its own work. When a handler calls several, nothing rolls the earlier calls back if a later one fails, so the handler undoes them itself. let <pattern> <- <call> else { … } puts each step’s undo beside the step (let … else):

context orders
consumes inventory as Stock
consumes payment as Pay
service placeOrder {
on call(sku: String, total: Int) -> Effect[Result[Int, String]] {
let Ok(_) <- Stock.reserve(sku) else { Err("out of stock") }
let Ok(receipt) <- Pay.authorise(total) else {
let _ <- Stock.release(sku)
Err("payment declined")
}
Ok(receipt)
}
}

If reserve fails, nothing has happened yet, so the handler answers at once. If authorise fails, it releases the stock it reserved first. Either else produces the handler’s result, in place of the rest of its body.

The call is the same Bynk code on both targets, but the emitted wiring differs:

  • bundle (default) — a direct in-process function call through a composed surface.
  • workers — a JSON call over a Cloudflare Service Binding, with the arguments and result validated as they cross the boundary.

See Target Cloudflare Workers for the target details.