Skip to content

Schema services and worker imports

Experimental. The layers that move a service live in Experimental.Rpc, an experimental module. A release can change or remove it. The declaration, the worker import and Experimental.Rpc need no opt-in in tsconfig.json or vibe.config.json.

A schema service is a service whose calls can cross a boundary: every parameter, result and error of every member has a schema. The code that calls the service stays the same wherever the implementation runs. A layer decides the place: the calling thread, a pool of worker threads, or another machine. Use a schema service to move CPU-bound work off the main thread, or to call code on a server through a typed interface. VIP-57 defines the forms.

export schema Summary { mean: number; max: number }
export schema error EmptySample {}
 
export schema service Stats {
  summarize(values: readonly number[]): Summary!EmptySample
  countdown(from: number): Stream<number>
}
 
export const StatsLive = Layer.succeed(Stats, {
  summarize: effect (values) => {
    if (values.length === 0) throw new EmptySample()
    return { mean: values.reduce((a, b) => a + b, 0) / values.length, max: Math.max(...values) }
  },
  countdown: (from) => Stream.fromIterable(Array.from({ length: from }, (_, index) => from - index))
})
 
effect function local() {
  provide StatsLive {
    const stats = try Stats
    const summary = try stats.summarize([1, 2, 3])
    const empty = stats.summarize([]) catch { when EmptySample: "empty" }
    const ticks = Array.from(try Stream.runCollect(stats.countdown(3)))
    return `${summary.mean} ${summary.max} ${empty} ${ticks.join(",")}`
  }
}
// Run in an effect function: try Console.log(try local())
// Output: 2 3 empty 3,2,1

Stats is an ordinary service. You request it with try Stats, and Layer.succeed(Stats, ...) implements it. With a local layer such as StatsLive, calls run in the calling fiber and nothing is serialized.

Declare a schema service

export schema Job { id: string; attempts: number }
export schema error JobMissing { id: string }
 
export schema service Jobs {
  find(id: string): Job!JobMissing
  list(limit?: number): readonly Job[]!!
  watch(id: string): Stream<Job, JobMissing>
  cancel(id: string): void!!
}
// Run in an effect function: try Console.log(Array.from(JobsRpcs.requests.keys()).join(", "))
// Output: find, list, watch, cancel

The following rules apply to the members of a schema service:

  • Every member is a method that returns an Effect or a Stream. Write the return type in full, as A!E, Effect<A, E> or Stream<A, E>. The compiler reads the schemas from the written type, so a type alias for the return type is an error.
  • Every parameter type, success type and error type has a schema form: a primitive, an array, a record, a union, a schema declaration, a schema error, or schema data. A plain error, an interface, a function type and unknown have none.
  • An optional parameter (limit?: number) is an optional field of the request.
  • A member declares no requirements. Services that the implementation needs come from the layer on the side where it runs.
  • The declaration has a body. schema service Name: Type and a static readonly defaultValue are errors.

For each schema service, the compiler also writes an Effect RpcGroup named after the service with the suffix Rpcs, here JobsRpcs. It holds one Rpc per member, with the parameters as the request fields. An RpcGroup is Effect's description of a set of remote calls. The compiler exports the group when you export the service.

Run a service in worker threads

A worker import binds a handle to a module that runs in worker threads. The module's default export is a Layer, and every service that the layer provides is a schema service that the module exports.

// stats.vibe
export schema Summary { mean: number; max: number }
export schema error EmptySample {}
 
export schema service Stats {
  summarize(values: readonly number[]): Summary!EmptySample
}
 
export default Layer.succeed(Stats, {
  summarize: effect (values) => {
    if (values.length === 0) throw new EmptySample()
    return { mean: values.reduce((a, b) => a + b, 0) / values.length, max: Math.max(...values) }
  }
})
// main.vibe
import { ExperimentalNodeRpc } from "vibelang-runtime/experimental/platform-node"
import { EmptySample, Stats } from "./stats.vibe"
import statsWorker from "./stats.vibe" with { type: "worker" }
 
const StatsPool = Layer.provide(Experimental.Rpc.workers(statsWorker, { size: 2 }), ExperimentalNodeRpc.layer)
 
export effect function main() {
  provide StatsPool {
    const stats = try Stats
    const summaries = try forEach([[1, 2, 3], [4, 6]], (values) => stats.summarize(values), { concurrency: "unbounded" })
    const empty = stats.summarize([]) catch { when EmptySample: "empty" }
    try Console.log(summaries.map((summary) => summary.mean).join(" "), empty)
  }
}
 
await runPromise(main())
2 5 empty

import statsWorker from "./stats.vibe" with { type: "worker" } imports no code into the calling thread. statsWorker is a handle of type Experimental.Rpc.WorkerHandle, not the layer. Experimental.Rpc.workers(statsWorker, { size: 2 }) is a layer that starts two threads and provides Stats from them. The pool's scope owns the threads and ends them when it closes. The ordinary import in the line above gives the calling thread the service key and the schemas.

Experimental.Rpc.workers needs a host that can start threads. ExperimentalNodeRpc.layer provides it on Node, and ExperimentalNodeServices.layer includes it. The Bun and browser equivalents are ExperimentalBunRpc.layer and ExperimentalBrowserRpc.layer, in vibelang-runtime/experimental/platform-bun and vibelang-runtime/experimental/platform-browser.

The following table lists the pool options.

OptionMeaning
sizeA fixed number of threads.
minSize, maxSize, timeToLiveA pool that grows to maxSize threads and ends an idle thread after timeToLive. Use these three instead of size.
concurrencyOptional. The number of calls each thread runs at once.

Call a service on another machine

import { FetchHttpClient } from "effect/http"
import { RpcClient, RpcSerialization, RpcServer } from "effect/rpc"
 
export schema service Greeter {
  greet(name: string): string!!
}
 
const GreeterLive = Layer.succeed(Greeter, {
  greet: effect (name) => `hello ${name}`
})
 
// On the server: needs an HttpRouter from the HTTP server you run.
export const GreeterServer = Experimental.Rpc.serve(Greeter)
  |> Layer.provide(%, GreeterLive)
  |> Layer.provide(%, RpcServer.layerProtocolHttp({ path: "/rpc" }))
  |> Layer.provide(%, RpcSerialization.layerNdjson)
 
// On the caller: provides Greeter.
export const GreeterRemote = Experimental.Rpc.client(Greeter)
  |> Layer.provide(%, RpcClient.layerProtocolHttp({ url: "https://greeter.internal/rpc" }))
  |> Layer.provide(%, RpcSerialization.layerNdjson)
  |> Layer.provide(%, FetchHttpClient.layer)
 
export effect function greetRemote(name: string) {
  provide GreeterRemote {
    const greeter = try Greeter
    return try greeter.greet(name)
  }
}

Experimental.Rpc.serve(Greeter) is a layer that answers calls with the Greeter implementation in its context. Experimental.Rpc.client(Greeter) is a layer that provides Greeter by calling a server. The transport and the wire format are Effect's: you provide a protocol layer and a serialization layer from effect/rpc on each side. This sample compiles but does not run on this page, because it needs a network.

The following table lists the Experimental.Rpc layers.

CallProvidesNeeds
Experimental.Rpc.workers(handle, options)Every schema service of the worker moduleExperimental.Rpc.WorkerHost
Experimental.Rpc.client(Service)ServiceRpcClient.Protocol
Experimental.Rpc.serve(Service, ...more)Nothing: it serves calls while its scope is openEach service, and RpcServer.Protocol

One serve layer cannot answer two services that share a member name: building the layer is a defect. A worker pool has no such limit.

Values that cross the boundary

Only the arguments, results and errors of the declared members cross the boundary. Each value is encoded and decoded with its schema, so the far side receives a copy. Nothing from the caller's context crosses: the worker module or the server builds its own layers, with its own module state.

A worker thread is not a security boundary. To isolate code that you do not trust, use a sandbox.

A transport failure, such as a lost connection, is a defect by default. That keeps the error type of a member the same for local, worker and remote layers. To handle transport failures as typed errors, add Effect's RpcClientError to the member's error type:

import { RpcClientError } from "effect/rpc"
 
export schema service Health {
  probe(): boolean!RpcClientError.RpcClientError
}

Bundler worker entries

Run unbundled on Node, a worker pool starts the runtime's own worker entry, which imports the compiled module and serves its default layer. A bundler needs the worker as a separate chunk, and the Vibe plugins emit it. The following table lists what each bundler does with a worker import.

BundlerWorker entry
Vite build, Rollup, RolldownA chunk of the same build, named after the module, such as stats.worker.
webpack, RspackThe bundler's own worker chunk.
Vite dev serverServed from the dev server for the browser. In a server environment, the runtime starts the module itself.
esbuild, Bun.buildNone. The build fails and names the import.

The plugins are vibelang-vite and vibelang-unplugin. Both take a workerPlatform option, "node", "bun" or "browser", for the cases where the bundler does not state the platform. Rollup is one such case.

Rules and diagnostics

// expect-error: EK5701 EK2109
interface Point { x: number; y: number }
 
export schema service Geometry {
  readonly unit: string
  area(points: readonly Point[]): number!!
}

unit is a property, so the compiler reports EK5701. Point is an interface with no schema form, so the compiler reports EK2109. The following table lists the diagnostics for schema services and worker imports.

CodeCondition
EK2109A parameter, success or error type of a member has no schema form.
EK5701A member is a property, an accessor, an overload or a generic method. A member returns neither an Effect nor a Stream, names its return type through an alias, or declares requirements. A parameter is a rest or destructured parameter. The service declares defaultValue, or uses the schema service Name: Type form.
EK5702The module of a worker import has no default export, its default export is not a Layer, or the layer provides a service that is not a schema service or that the module does not export.
EK5703A worker import has named bindings, a namespace binding or no binding. Bind one default name.