rays/worker_rpc
Call one Worker from another with Workers RPC, passing and returning ordinary Gleam values.
A method is a public function that takes Params and returns a
Promise. The Worker that serves it binds it, and the Worker that calls
it passes the same function to call, so both ends agree on its argument
and reply types:
// src/app/names.gleam
import gleam/javascript/promise.{type Promise}
import gleam/list
import gleam/string
import rays/app
import rays/worker
import rays/worker_rpc
pub const worker = app.Worker("names", entrypoint: main)
pub fn main() -> worker.Worker {
worker.new(fn(_request, _env, _ctx) { promise.resolve(worker.not_found()) })
|> worker_rpc.bind(search)
}
pub type Search {
Search(query: String, limit: Int)
}
pub fn search(params: worker_rpc.Params(Search)) -> Promise(List(String)) {
let Search(query:, limit:) = params.args
["Ada", "Adam", "Grace"]
|> list.filter(string.starts_with(_, query))
|> list.take(limit)
|> promise.resolve
}
// src/app.gleam, another Worker of the same app (see `rays/app`)
import app/names
import gleam/javascript/promise.{type Promise}
import gleam/string
import rays/app
import rays/worker.{type Context, type Env, type Request, type Response}
import rays/worker_rpc
pub fn handle_request(
_request: Request,
_env: Env,
_ctx: Context,
) -> Promise(Response) {
let call =
app.connect_worker(names.worker)
|> worker_rpc.call(names.search, names.Search("Ad", 2))
use found <- promise.map(call)
case found {
Ok(found) -> worker.ok() |> worker.string_body(string.join(found, ", "))
Error(_) -> worker.response(502)
}
}
This code is compiled and tested in rays’s own test suite.
How it works
Workers RPC can’t send Gleam values as they are, so rays build and the
rays() Vite plugin do two things when they build the project:
- They register every custom type in the project and its dependencies, so values can be encoded on one side and rebuilt as the same types on the other.
- They find every RPC method in the package, and give the Worker’s entry module one Workers RPC method with the same name for each.
So a method must be a public function in the package itself, not a
dependency, whose only argument is a worker_rpc.Params and which
returns a Promise. A Worker that binds anything else fails to start.
Its name is the name of the Workers RPC method, which is what
TypeScript callers and the Cloudflare dashboard see. A Worker built only
with gleam build can still be tested with
rays/worker/simulate.with_rpc_service.
Both Workers must be built from the same code for a method’s types. Each
method has a version, a hash of its argument and reply types and of the
types they contain. A call to a Worker with a different version fails
with VersionMismatch instead of decoding the wrong values, so deploy
both Workers when those types change. Changing a method’s handler doesn’t
change its version.
Functions can’t be sent, and neither can values that only make sense inside one Worker, such as a request body or a stream.
Types
An error that can occur when calling a method on another Worker.
Every variant but NotAMethod has the name of the method called.
pub type CallError {
NotAMethod
NotBound(method: String)
VersionMismatch(method: String)
HandlerFailed(method: String, message: String)
SendFailed(method: String, message: String)
EncodeFailed(method: String, message: String)
DecodeFailed(method: String, message: String)
NotConfigured(method: String, binding: String)
}
Constructors
-
NotAMethodThe function passed to
callisn’t an RPC method that rays found. It must be a public function in this package whose only argument is aParams, and the Worker must be built with rays. -
NotBound(method: String)The other Worker doesn’t bind this method.
-
VersionMismatch(method: String)The other Worker was built from a different version of this method’s argument or reply types. Deploy both Workers.
-
HandlerFailed(method: String, message: String)The method’s handler panicked, or its promise rejected.
-
SendFailed(method: String, message: String)The call didn’t reach the other Worker, or the runtime failed while making it, for example because the binding isn’t a rays Worker.
-
EncodeFailed(method: String, message: String)A value couldn’t be encoded to be sent, such as an argument or reply that holds a function.
-
DecodeFailed(method: String, message: String)A value that was sent couldn’t be decoded, usually because the two Workers were built from different code.
-
NotConfigured(method: String, binding: String)The Worker has no binding for a Worker reached with
rays/app’sconnect_worker, as when its configuration doesn’t come fromraysApp(), or a test didn’t set up the app withapp.simulate.
What a method receives: the argument sent by the caller, and the serving Worker’s bindings and context.
Several values go in a record or a tuple, and Nil stands for none.
Examples
pub fn display_name(params: worker_rpc.Params(Int)) -> Promise(String) {
users.display_name(params.env, params.args)
}
pub type Params(args) {
Params(args: args, env: worker.Env, context: worker.Context)
}
Constructors
-
Params(args: args, env: worker.Env, context: worker.Context)
Values
pub fn bind(
worker: worker.Worker,
method: fn(Params(args)) -> promise.Promise(reply),
) -> worker.Worker
Serve a method from this Worker, so other Workers can call it.
The method is a public function in this package whose only argument is a
Params, or the Worker fails to start when it is built with rays.
The reply is sent back to the caller. If the method panics, or its
promise rejects, the caller gets a HandlerFailed error instead. Errors
the caller should handle belong in the reply type, as in
Promise(Result(User, LookupError)).
Examples
pub fn main() -> worker.Worker {
worker.new(handle_request)
|> worker_rpc.bind(display_name)
|> worker_rpc.bind(search)
}
pub fn call(
service: Service,
method: fn(Params(args)) -> promise.Promise(reply),
args: args,
) -> promise.Promise(Result(reply, CallError))
Call a method on another Worker.
Pass the method’s function itself. The argument and reply types are the method’s own, so they are checked when both Workers are compiled.
The outer Result says whether the call happened. Errors the method
itself returns are part of its reply type.
Examples
use name <- promise.await(worker_rpc.call(names, names.display_name, 42))
case name {
Ok(name) -> worker.ok() |> worker.string_body(name) |> promise.resolve
Error(_) -> worker.response(502) |> promise.resolve
}