Skip to Content
Views

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.

examples/views-shop/src/streams.ts
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:

examples/views-shop/src/streams.ts
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 throws ViewFault at 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. With outputs, group views under the same route names as outputs.
  • Parameters and discovered inputs: View.circuit automatically discovers every input Streamsy.state stream referenced via View.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 by generation or routeBy) must be a subset of the circuit's params with identical decoded types. Projection supplies the wrapped generation parameter from the circuit's generation. Pass views: (params) => ({ ... }) to use decoded JSON-valued binding parameters in expressions; see Binding parameter expressions.
  • Generation: generation defaults to 1. Raise it whenever a plan or collection codec changes; see Lifecycle and rebuilds.
  • Retry policy: Optional retry accepts the standard projection binding retry policy.
  • Fan-out limit: Optional maxAffectedKeys caps distinct changed relation keys per unit. See Bounding fan-out with maxAffectedKeys.
  • Wake deadlines: Optional wakeAt: (unit) => Projection.wakeAt(deadline) records a wake deadline with the unit; returning void clears 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 by expressions must supply exactly the declared routeBy parameter names with matching decoded types (string, finite number, or boolean).
  • Add row: (row) => row.value when 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 ViewDataFault identifying the row.
  • When rebuilding, use Projection.caughtUp on 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 with ProjectionWakeup.attach(circuit).
  • Follow the one-writer rule: do not call Projection.run or Projection.follow on a binding that is already attached. Use registry.awaitOffset for 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.

HostStorage layerViews backendNotes
SQLiteBunStorage or DurableObjectStorageViewBackend.layerSqlSupports StateTable on the same SQLite owner
PostgresSqlStorage with @effect/sql-pgViewBackend.layerSqlShared server database; StateTable is SQLite-only
MySQLSqlStorage with @effect/sql-mysql2ViewBackend.layerSqlRequires MySQL 8.0.17+ and READ COMMITTED
MemoryMemoryStorageViewBackend.layerMemoryHeap-only, no migration; useful for tests and prototypes
Live snapshotsPrivate heap host created by View.liveManaged internallyReads committed snapshots directly without output streams

On this page