A ZIO / Effect style effect type for PureScript: typed environment, typed errors, resource safety, layers, and structured concurrency.
newtype RIO r e a = RIO (Op r e a)ris a row of services the computation needs.eis a row of typed failures it may raise.ais the success value on the happy path.
Both rows are open by default, so requirements aggregate automatically on composition and shrink as services are provided and failures are handled.
This repository ships two runtimes for the same
three-channel design. They share vocabulary, layer algebra,
service convention, and almost every combinator name. What
differs is how RIO r e a is interpreted at the bottom.
rio-fiber (default, recommended) |
rio-aff (ecosystem alternative) |
|
|---|---|---|
| Runtime | Custom hand-rolled fiber interpreter | Sits on top of Effect.Aff |
| Module prefix | RIO.Fiber.* |
RIO.Aff.* |
| Fiber identity | Numeric id with Supervisor registration hooks (every fork notifies listeners) |
Numeric id only (no supervisor surface; can't observe arbitrary forks from outside) |
| Per-fiber state | FiberRef baked into the runtime; eager snapshot-on-fork |
RIO.Aff.FiberRef with the same snapshot-on-fork semantics, opt-in via a fiberRefs env service and forkFiber; RIO.Aff.Local is the simpler shared-Effect.Ref model |
| Failure model | First-class Cause e everywhere |
Single Variant e (or Cause reified at boundaries) |
| Virtual time | TestClock wakes sleeping fibers directly |
Discipline-based via Clock service |
| STM semantics | Optimistic concurrency: version-checked commits under a global commit lock; retry parks on TVar change via the fiber scheduler |
Event-loop atomicity: the whole transaction commits in one synchronous step (no version checks); retry parks on TRef change via an AVar waiter |
| Bind hot path | ~10 ns per bind (BIND fuses common leaf ops) |
~90 ns per bind |
| Array fan-out | forkAll x16 + joinAll runs ~5x faster than forkAff x16 + joinFiber |
Same as Aff |
rio-fiber is the default because it owns the runtime end-to-end
and unlocks behaviour the Aff foundation structurally cannot
give us (a fiber Supervisor registration surface, native
FiberRef baked into every fork, full Cause tree, a TestClock
that actually wakes parked fibers, and structured concurrency
in the proper sense). rio-aff exists for codebases that want the
three-channel design without leaving the Effect.Aff ecosystem,
and for the interop story: an Aff program can call into a
rio-fiber subroutine at the boundary via
RIO.Fiber.Aff.
The "why" for each runtime is spelled out in
Why rio-fiber is the default and
When rio-aff is the right choice
below; the precise cost analysis for the Aff ceiling is in
docs/aff-constraints.md.
If you've used ZIO in Scala or Effect in TypeScript, you
already know the shape. PureScript's row types let the same
three-channel design feel native: the requirements channel is
a record row, the error channel is a Variant row, and the
type inferer aggregates and shrinks both as your program
composes.
If you have not used those libraries, the short version: RIO
is a description of an asynchronous computation that knows what
it needs, what it can fail with, and what it produces, and
gives you uniform plumbing to wire those together. You write
handlers, services, and tests against typed interfaces; you
provide implementations once at the edge.
import Prelude
import Effect (Effect)
import Effect.Aff (launchAff_)
import Effect.Console as Console
import RIO.Fiber.Aff (runAff)
import RIO.Fiber.Core (RIO, asks, liftEffect)
type Logger = { log :: String -> Effect Unit }
greet
:: forall e
. String
-> RIO (logger :: Logger) e Unit
greet name = do
log <- asks _.logger.log
liftEffect (log ("hello, " <> name))
main :: Effect Unit
main = launchAff_ do
let consoleLogger = { log: Console.log }
_ <- runAff (greet "world") { logger: consoleLogger }
pure unitA handler that may fail picks up its tag automatically:
import RIO.Fiber.Core (RIO, asks, fail, liftEffect)
import Data.Maybe (Maybe(..))
import Data.Variant as Variant
import Type.Proxy (Proxy(..))
notFound :: Proxy "notFound"
notFound = Proxy
findTodo
:: Int
-> RIO (store :: TodoStore) (notFound :: { id :: Int }) Todo
findTodo tid = do
store <- asks _.store
row <- liftEffect (store.get tid)
case row of
Nothing -> fail (Variant.inj notFound { id: tid })
Just todo -> pure todoThe notFound tag flows up through callers until a
catchTag (Proxy :: _ "notFound") removes it from the row,
or a runner surfaces it on the Outcome value the entry
point inspects.
These are not "we haven't written them yet" features: each one
is either impossible to add on top of Aff without rewriting
its interpreter, or has been tried and found to be unworkable
inside Aff's canceler protocol.
- First-class
Cause e. Every failure carries a structured cause tree (Empty,Fail,Die,Interrupt,Then,Both) that distinguishes typed failures from defects from interrupts, and composes sequential / parallel error trees losslessly.Affcollapses everything into one error channel; you cannot ask "was this failure also accompanied by an interrupt?" or "did both branches of aracefail?". - Supervisor registration hooks. Both packages give every
fiber a stable numeric
FiberId, butrio-fiberadditionally exposes aSupervisorregistration point so an observer can see every fiber start, end, and link without instrumenting call sites. Cross-cutting tracing, metrics, and structured logging hook into that surface.rio-affhas the id but no registration surface; you can correlate a span to a known fiber, but you cannot watch arbitrary forks from outside. FiberRefwith snapshot-on-fork semantics, baked into every fork. Per-fiber state that is eagerly cloned into the child at fork time; subsequent writes on either side stay local to that fiber. This is what makes scoped log annotations, span context inheritance, and trace propagation work without threading them through every signature.rio-affships the same semantics viaRIO.Aff.FiberRef, but each fork must useforkFiber(orforkFiberScoped) and the env row must carry afiberRefsservice for the storage map;rio-fiber's version is native, so plainforkalready snapshots correctly.RIO.Aff.Localis the separate shared-Effect.Refmodel for the simple "ambient context" use case.- Structured concurrency via
Scope.forkScopedties a child's lifetime to a scope;forkSupervisedties it to the nearestsupervisedblock via an ambientFiberRef. When the scope closes (success, failure, or interrupt), every child is interrupted and every finalizer runs in LIFO order.Affforks are detached by default and there is no protocol to attach them to a parent's lifetime. - A
TestClockthat actually drives sleeping fibers.TestClock.advance nfinds every fiber that registered a sleep with a deadline<= now + nand resumes it. Deterministic simulation of timers, retries, debounces, and schedules drops out for free. AnAff-style simulated clock cannot wake a fiber that is parked insideAff.delay; the harness has to fake the parked state itself. - STM with version-checked commits and
TVar-park retry.TVar/TMVar/TChan/TQueue/TArraywithatomically,retry,orElse,check. A transaction stages its writes and, at commit time, briefly takes a global commit lock to validate that noTVarit read has changed, re-running on a conflict, so a transaction never observes another fiber's half-write.retryparks the fiber on the set ofTVars it read and resumes only when one of them changes. - Bounded-concurrency parallel traversal.
parTraverseN nviaSemaphore, plusHub,Queue,Latch,Deferred,Layer, andPoolas proper first-class concurrent primitives instead of ad-hocMVarrecipes. Stream/Sink/Pipewith structured concurrency. Pull-based streams withmapPar,merge,broadcast,share,throttle,debounce,timeoutPerPull, plusSinkandPipeas composable terminals and transducers. Each pulls under a realScopeso leaked producers are interrupted automatically.Schedule-drivenrepeat/retry.recurs,spaced,exponential,jittered,intersect,andThen,whileInput, all driven by the activeClockso the same policy runs against real time in production and virtual time in tests.- Tracing / metrics / logging with span context propagation.
withSpan, counter / gauge / histogram metrics, scoped log annotations. Each ships a noop and at least one recording or live backend, and child fibers inherit the active span by virtue ofFiberRefcopy-on-write. - An interruption model that distinguishes "asked to stop"
from "in the middle of stopping" from "finalizer running".
uninterruptible,ensuring, andbracketcompose at the Cause layer, so a finalizer that itself fails is visible in the resultingCause.Then.Aff's canceler protocol cannot represent a finalizer-failed-while-cleaning-up scenario.
On the workspace benchmarks the bind hot path is roughly 9x
faster than Aff; fork x16 + join each is at parity with
forkAff once V8's JIT is warm; and the specialised
forkAll x16 + joinAll array fan-out runs at roughly 5x the
speed of forkAff x16 + joinFiber (it walks the array in a
single op dispatch instead of the per-element bind chain that
traverse fork builds). See
rio-fiber/README.md for the full
surface and the side-by-side comparison table.
rio-aff is a complete implementation of the same three-channel
design that delegates the runtime to Effect.Aff. It is the
right pick when:
- You're already on
Aff. Existing code, libraries you depend on, and frameworks you target are written againstAff. Picking theAff-backed runtime keeps your effect graph homogeneous: no boundary conversions, norunAffThrowbridges, no two-runtime composition story. - You want the smallest possible surface to learn first.
rio-affis backed byEffect.Aff, so it shares its vocabulary and mental model with thepurescript-affmany users already know; you can lean on that familiarity instead of learning a custom fiber runtime first. - You're embedding into a host that hands you
Aff. Some PureScript HTTP servers, GraphQL frameworks, and SDKs accept anAff ahandler.rio-afflets you write that handler in the three-channel style and discharge toAffat the call boundary withrunRIO/runRIO'.
What you give up by staying on Aff is documented in detail in
docs/aff-constraints.md; the
short version is the column on the right of the table at the
top of this README. Specifically: no fiber Supervisor
registration surface, no native per-fiber state, no full
Cause tree, no test clock that wakes
sleeping fibers, no first-class structured concurrency, and a
~9x bind hot path overhead relative to rio-fiber.
Note that rio-aff still ships its own Cause reifier
(attemptCause, parTraverseCause, prettyCauseWithStack) and
its own simulated Clock (RIO.Aff.Test.Clock), so most of the
ZIO-shaped vocabulary survives the trip. But Cause exists at
the boundaries, not as the native failure carrier the way it
does in rio-fiber.
The two runtimes interop at the boundary via
RIO.Fiber.Aff. A common
production shape is a top-level Aff program that calls
RIO.Fiber.Aff.runAffThrow to run a fiber-backed subroutine,
keeping the host on Aff while taking advantage of the fiber
runtime inside.
purescript-rio is not yet published to the PureScript registry. To try it
out, clone the repository and use it as a local workspace package,
or point your spago.yaml at the git remote directly. Pick
rio-fiber for new code; pick rio-aff only if one of the
considerations in the previous section applies.
Programs are written against RIO.Fiber.*.
RIO.Fiber.Core: the entry point.RIO r e aplus the primitives every program needs (pure,bind,liftEffect,ask,asks,fail,catchAll,async,fork,forkInline,forkAll,forkAllInline,join,joinAll,interrupt,uninterruptible,bracket,ensuring,race,raceAll,parTraverse,zipPar,validatePar,timeout) and three runners (runRIO,runRIO',runRIOCallback).RIO.Fiber.Aff: bridge topurescript-aff.fromAfflifts anAffintoRIO;runAff,runAffEither, andrunAffThrowrun anRIOinsideAffat three projection levels.RIO.Fiber.Cause: the failure algebra and its introspection set (firstFailure,firstDefect,interruptCount,stripInterrupts,mapFailures,flatten,squash,fold,prettyPrint/prettyCause).RIO.Fiber.Scope: resource scopes with LIFO finalizers, plus the structured-concurrency primitivesforkScopedandforkSupervised.RIO.Fiber.Ref:FiberRefwith copy-on-write fork semantics, plusRIO.Fiber.Ref.Synchronizedfor atomic effectful updates over anEffect.Ref.RIO.Fiber.Deferred: one-shot write-once cell.RIO.Fiber.Semaphore,RIO.Fiber.Latch: counting semaphore withwithPermitandparTraverseN, and a one-shot count-down latch.RIO.Fiber.Queue,RIO.Fiber.Hub: async queue and pub/sub hub.RIO.Fiber.STMplusSTM.TArray,STM.TChan,STM.TDeferred,STM.TMap,STM.TMVar,STM.TPubSub,STM.TQueue,STM.TSemaphore,STM.TSet: software transactional memory withretry/orElse/check.TPubSubis the transactional pub/sub primitive (STM.THubon the aff side).RIO.Fiber.Stream,RIO.Fiber.Sink,RIO.Fiber.Pipe: pull-based stream, composable terminating consumers, and stream-to-stream transducers.RIO.Fiber.Layer,RIO.Fiber.Pool: layered service composition and a fixed-size object pool.RIO.Fiber.Schedule: recursion policies driven by the activeClock.RIO.Fiber.Clock,RIO.Fiber.TestClock: real wall clock and virtual-time clock that wakes sleeping fibers.RIO.Fiber.Tracer,RIO.Fiber.Metrics,RIO.Fiber.Logger: observability services with span context propagation, counter / gauge / histogram metrics, and scoped log annotations.RIO.Fiber.ConfigplusConfig.Rotatingfor refreshable cells.RIO.Fiber.Memo,RIO.Fiber.Cache,RIO.Fiber.RateLimiter,RIO.Fiber.CircuitBreaker,RIO.Fiber.WorkerPool: higher-level resilience primitives built on the fiber runtime.RIO.Fiber.Supervisor: global supervisor registration for observability.RIO.Fiber.Random: randomness service with a seeded deterministic backend.
Programs are written against RIO.Aff.*.
RIO.Aff.Core: the type, runners, and the most common re-exports.RIO.Aff.Env:ask/asksto read services,provide/provideAllto inject them.RIO.Aff.Error:fail,catchTag,catchAll,mapError, plusdie/sandbox/unsandboxfor the defect channel.RIO.Aff.Cause: parallel + sequential failure trees,attemptCause,parTraverseCause,raceCause,acquireReleaseCause,prettyCause/prettyCauseWithStack. Reified at boundaries rather than carried natively.RIO.Aff.Resource:acquireRelease,bracket,ensuring, andScopewith LIFO finalizers.RIO.Aff.Layer:Layer rIn e rOutwith sequential (>>>) and horizontal (<+>) composition.RIO.Aff.Concurrency:fork,forkScoped,forkSupervised,forkAll,join,joinAll,interrupt,uninterruptible,timeout,parTraverse,parTraverseN,parSequence,validatePar,zipPar,race,raceAll. Cancellation is cooperative (Aff-style).RIO.Aff.Deferred,RIO.Aff.Semaphore,RIO.Aff.Latch,RIO.Aff.Queue,RIO.Aff.Hub: async coordination primitives overEffect.Aff.AVarandEffect.Ref.RIO.Aff.Clock,RIO.Aff.Random: the service shapes plus live and seeded backends.RIO.Aff.ConfigplusRIO.Aff.Config.Rotating: the Config DSL and a refreshable cell.RIO.Aff.Schedule: pure scheduling policies that sleep throughClockso the virtual-time test clock can drive them.RIO.Aff.STMplusSTM.TArray,STM.TChan,STM.TDeferred,STM.THub,STM.TMap,STM.TMVar,STM.TQueue,STM.TSemaphore,STM.TSet: software-transactional memory derived from single-event-loop atomicity.RIO.Aff.Stream,RIO.Aff.Stream.Par,RIO.Aff.Stream.Concurrent,RIO.Aff.Stream.Resource,RIO.Aff.Stream.Timed,RIO.Aff.Pipe,RIO.Aff.Sink,RIO.Aff.Channel: pull-based effectful streams, parallel stream combinators, stream-to-stream transducers, composable sinks, and the unified Channel primitive.RIO.Aff.Tracer,RIO.Aff.Metrics,RIO.Aff.Logger: observability services (each with noop, live, and recording backends).RIO.Aff.Local: ambient state with scoped overrides (process-global, not per-fiber). For true per-fiber snapshot-on-fork state seeRIO.Aff.FiberRef.RIO.Aff.Spec,RIO.Aff.Test.*:itRIO/itRIO_adapters forpurescript-spec, plus recording test backends.
Foundational reading:
docs/aff-constraints.md: the precise cost analysis forrio-aff'sEffect.Afffoundation. What it gives us for free, what it cannot give us, and whyrio-fiberexists. Read this before adoptingrio-afffor anything load-bearing.
Walkthrough docs (the shared three-channel design; examples
mostly use RIO.Aff.* because the docs predate rio-fiber,
but the concepts apply to both):
docs/01-core-type.md: the three parameters, how the channels compose.docs/02-services.md: service convention and idiomatic provision.docs/03-errors.md: typed failures, catching, and the defect channel.docs/04-layers.md: theLayertype, vertical (>>>) and horizontal (<+>) composition.docs/05-resources.md:acquireRelease,ensuring,Scope/scoped.docs/06-concurrency.md: fork, race, parallel traversal, cancellation caveats.docs/07-testing.md: the spec adapters and the virtual-time clock.docs/08-scheduling.md: retry and repeat policies, combinators, and how to drive them deterministically in tests.docs/09-stm.md: STM primitives, transactional atomicity,retry/orElse.docs/10-tracing.md: tracing and metrics services.docs/11-fiber-local.md: ambient state, scoped overrides, and the fork-inheritance trade-off relative to ZIOFiberRef.docs/12-logging.md: structured logging.docs/13-streams.md: pull-based streams.docs/14-causes.md: theCausealgebra and the cause-collecting combinators.docs/15-config.md: theConfigdescriptor type, theSourceadapter set,Secretredaction.docs/performance.md: benchmark baselines and dominant costs.
rio-fiber-specific tour:
rio-fiber/README.md: the full fiber-runtime surface, the bridge toAff, and the side-by-side comparison table.rio-fiber/docs/ecosystem.md: guided tour of howStream/Pipe/SinkandSTMcompose into pipelines.
Migration guides for users coming from other ecosystems:
Worked examples (each example targets one of the two runtimes;
the package's spago.yaml makes the choice explicit):
examples/logger/: the smallest end-to-end demo. A tinyLoggerservice run withprovideAll+runRIO.examples/notify/: exercisesRIO.Aff.Postgres.Notifyend-to-end against the workspace's docker-compose Postgres: subscribes viawithListen, firesNOTIFYpayloads on the pool, and lets the scope finalizer drain both clients on exit.examples/otel-demo/: wiresRIO.Aff.Tracer.OTel.Adapter.makeOTelTracerinto a real OpenTelemetry SDK with an in-memory exporter.examples/todo-api/: a small HTTPurple service demonstrating layers, typed failures, real Postgres persistence, middleware that stampsrequest.id/request.method/request.pathon every emission, bearer-token auth, and JSON codec bridging.examples/worker-pool/: a producer + bounded queue + fan-out of N workers + per-job retry schedule + spans + metrics.examples/stream-pipeline/: three partition sources merged viamergeAlland fanned out to two consumers viabroadcast.examples/sink-analytics/: one stream pass over an HTTP request log computes five summaries viaSink.zipPar.examples/config-loader/: loads typed configuration from a sample.envfile, showing theConfigDSL end-to-end withSecretredaction.examples/batch-import/: a row-typed pipeline exercisingmemoize,validatePar,orElse,option, andfoldRIO.examples/typed-error-workflow/: a flakyuserApisurvived via retries, aCircuitBreakerthat fail-fasts after a streak, andcatchTagrouting.examples/showcase/: wiresSchema,Logger.withFields,Tracer, amockSqlstore, andHttpStream.fromChunksinto an in-process HTTP application.examples/production-app/: the canonical long-running daemon wire-up:Layerfor the service graph,Runtimefor the resolved environment,withSpanper heartbeat, andwithShutdownracing the worker againstSIGINT/SIGTERM.
npm install
npx spago build
npx spago testBuild or test a single package:
npx spago build -p rio-fiber
npx spago test -p rio-fiber
npx spago test -p rio-affRun the example:
npx spago run -p rio-example-todo-apiRun the benchmark suite (compares rio-fiber, rio-aff, and
raw Aff head-to-head):
npx spago run -p rio-benchmarksPre-release. Nothing has been published to the PureScript
registry or Pursuit yet; the surface is being developed on
main. Treat any version string in any spago.yaml as a
placeholder.
rio-fiber is the active development target: its
interpreter is stable, its surface in RIO.Fiber.* is
unlikely to shift in shape, and the test suite covers each
module end-to-end (880+ tests at time of writing). rio-aff
is maintained as the ecosystem-friendly alternative and
receives bug fixes plus selective forward-ports of new
surface, but new design work happens in rio-fiber first.
Companion adapter packages (rio-fiber-node, rio-fiber-http,
rio-fiber-otel, rio-fiber-config-file, rio-fiber-postgres,
rio-fiber-postgres-json, rio-fiber-postgres-migrate) sit on
top of rio-fiber; the matching rio-aff-* packages do the
same for rio-aff. See FUTURE_WORK.md
for the open work list.
MIT. See LICENSE.