Declare and run a circuit
Wire input and output State classes into View.circuit, route output rows across streams, and choose a host to run or attach the circuit.
A Views circuit reads one or more Streamsy.state collections, maintains relational views incrementally, and writes generation-addressed Streamsy.state outputs. Install it with bun add @streamsy/views @streamsy/projection @streamsy/core effect.
To learn the relational operators (where, select, selectRow, join, leftJoin, groupBy, top, concat, closure, and View.fn), see Build relations.
Declare input and output State classes
Declare your input and output streams with Streamsy.state. Every output State route used by a circuit needs a numeric generation parameter in its path so each generation writes to its own stream address.
import { Schema } from "effect";
import { Streamsy } from "@streamsy/core";
import { Projection } from "@streamsy/projection";
import { View } from "@streamsy/views";
const Order = Schema.Struct({
orderId: Schema.String,
customerId: Schema.String,
total: Schema.Finite,
});
export class Orders extends Streamsy.state<Orders>()("ViewsShop/Orders", "shop/:shopId/orders", {
params: { shopId: Schema.String },
collections: { order: { schema: Order, key: "orderId" } },
}) {}
export class ShopViews extends Streamsy.state<ShopViews>()(
"ViewsShop/Views",
"shop/:shopId/views/g/:generation",
{
params: { shopId: Schema.String, generation: Schema.FiniteFromString },
collections: {
customerTotals: {
schema: Schema.Struct({
customerId: Schema.String,
orders: Schema.Finite,
revenue: Schema.Finite,
}),
key: "customerId",
},
topOrder: { schema: Order, key: "orderId" },
},
},
) {}View.from derives the row type, schema, and key directly from the input State class, and View.circuit checks each view's row type against its output collection at compile time and validates rows when encoding at runtime.
Declare a circuit
Pass your views and generation-wrapped output(s) to View.circuit:
export const shopCircuit = (generation: number, minimumTotal?: number) => {
const orders = View.from(Orders, "order");
const selected =
minimumTotal === undefined ? orders : orders.where((row) => row.total.gte(minimumTotal));
return View.circuit({
id: "views-shop",
params: Orders.paramCodecs,
generation,
output: Projection.perGeneration(ShopViews, "generation"),
views: {
customerTotals: selected
.groupBy((row) => ({ customerId: row.customerId }))
.aggregate((row) => ({ orders: View.count(), revenue: View.sum(row.total) })),
topOrder: selected.top({
partitionBy: (row) => row.customerId,
by: (row) => [row.total.desc(), row.orderId.asc()],
limit: 1,
}),
},
});
};View.circuit accepts either a single wrapped output under output or a record of wrapped outputs under outputs:
- Generation-wrapped outputs: Every output route must be wrapped with
Projection.perGeneration(StateClass, param). Passing an unwrapped output throwsViewFaultat declaration time. - Exact collection coverage: Each collection on an output State class must have exactly one view. Missing collections, unknown collection names, and duplicate output State classes throw
RangeError. Withoutputs, groupviewsunder the same route names asoutputs. - Parameters and discovered inputs:
View.circuitautomatically discovers every inputStreamsy.statestream referenced viaView.from, whether views pull from one stream or join across several distinct streams. Each input stream's route parameters (and any output route parameters not supplied bygenerationorrouteBy) must be a subset of the circuit'sparamswith identical decoded types. Projection supplies the wrapped generation parameter from the circuit'sgeneration. Passviews: (params) => ({ ... })to use decoded JSON-valued binding parameters in expressions; see Binding parameter expressions. - Generation:
generationdefaults to1. Raise it whenever a plan or collection codec changes; see Lifecycle and rebuilds. - Retry policy: Optional
retryaccepts the standard projection binding retry policy. - Fan-out limit: Optional
maxAffectedKeyscaps distinct changed relation keys per unit. See Bounding fan-out withmaxAffectedKeys. - Wake deadlines: Optional
wakeAt: (unit) => Projection.wakeAt(deadline)records a wake deadline with the unit; returningvoidclears it.
View.circuit returns a projection declaration with .at(params) and .parse(id), like other projection declarations.
Route output rows
One circuit binding can fan output rows out to multiple streams based on row values. Declare routeBy on Projection.perGeneration and wrap each view for that output in View.routed:
import { Projection } from "@streamsy/projection";
import { View } from "@streamsy/views";
import { DayRows, Events } from "./streams.ts";
const events = View.from(Events, "event");
export const byDay = View.circuit({
id: "events-by-day",
params: {},
output: Projection.perGeneration(DayRows, "generation", { routeBy: ["workspace", "date"] }),
views: {
event: View.routed(events, {
by: (row) => ({ workspace: row.workspace, date: row.date }),
}),
},
});Rules for routed outputs:
- The
byexpressions must supply exactly the declaredrouteByparameter names with matching decoded types (string, finitenumber, orboolean). - Add
row: (row) => row.valuewhen the emitted row is nested inside the relation row. - The collection key is unique within each routed stream, so different streams can hold the same collection key. A route change deletes the key in the old stream and upserts it in the new stream in the same transaction with the same
txid. Readers following individual streams observe separate notifications. - A route that has never received an emitted row returns
StreamNotFound. The first emitted row creates the stream in the checkpoint transaction, and streams that have held rows remain readable after those rows are deleted. - If a route value fails to encode, the unit fails with a
ViewDataFaultidentifying the row. - When rebuilding, use
Projection.caughtUpon the binding to check whether it has caught up to its inputs before switching readers.
Run and attach
A circuit is a standard @streamsy/projection declaration:
- Run a single binding to catch up once with
Projection.run(circuit.at(params)). - Attach a declaration to a long-lived process with
Projection.attach(circuit, { durable: true }), or to a Cloudflare Durable Object withProjectionWakeup.attach(circuit). - Follow the one-writer rule: do not call
Projection.runorProjection.followon a binding that is already attached. Useregistry.awaitOffsetfor read-your-writes; see Observe attached runners.
In the first unit, the circuit uses Commit.transaction to create each non-routed generation output and check that it starts empty and open. Every declared output must share the storage owner of the checkpoint and Transaction. Input streams use normal projection stream services and do not need an input StateTable.
Choose a host
Every host provides CheckpointStore.layer, Transaction.layer, and a ViewBackend layer over the storage owner. SQL hosts also call View.migrate(sql) at startup.
| Host | Storage layer | Views backend | Notes |
|---|---|---|---|
| SQLite | BunStorage or DurableObjectStorage | ViewBackend.layerSql | Supports StateTable on the same SQLite owner |
| Postgres | SqlStorage with @effect/sql-pg | ViewBackend.layerSql | Shared server database; StateTable is SQLite-only |
| MySQL | SqlStorage with @effect/sql-mysql2 | ViewBackend.layerSql | Requires MySQL 8.0.17+ and READ COMMITTED |
| Memory | MemoryStorage | ViewBackend.layerMemory | Heap-only, no migration; useful for tests and prototypes |
| Live snapshots | Private heap host created by View.live | Managed internally | Reads committed snapshots directly without output streams |