Skip to Content
Reference

@streamsy/views

Reference for every public export of @streamsy/views, including View, Relation, TypedExpression, ViewBackend, faults, and types.

import {
  PlanChanged,
  PlanCheckFailed,
  View,
  ViewBackend,
  ViewDataFault,
  ViewFault,
} from "@streamsy/views";
import type {
  BooleanExpression,
  CircuitBinding,
  CircuitDeclaration,
  CircuitError,
  Input,
  LiveReader,
  LiveSnapshot,
  ParameterExpressions,
  Reference,
  Relation,
  RoutedView,
  State,
  TypedAggregateExpression,
  TypedExpression,
} from "@streamsy/views";

Install with bun add @streamsy/views @streamsy/projection @streamsy/core effect. All public APIs are exported from the package root. Views supports SQLite, Postgres, MySQL, and memory backends, plus scoped in-memory live snapshots.

Root exports

ExportKindPurpose
ViewNamespaceRelation builders, routing, aggregates, expressions, circuit, live, and migrate
ViewBackendServiceHost-selected operator storage
LiveReaderTypeScoped reader returned by View.live's at(params)
LiveSnapshotTypeCommitted rows and input offsets with initial catch-up status
PlanChangedClass (Schema.TaggedError)Non-retryable fault (_tag: "ViewPlanChanged") when a namespace's plan hash changes
ViewFaultClass (Schema.TaggedError)Operational or setup fault (_tag: "ViewFault")
ViewDataFaultClass (Schema.TaggedError)Non-retryable row-level or maxAffectedKeys fault (_tag: "ViewDataFault")
PlanCheckFailedClass (Schema.TaggedError)Compile-time plan check error (_tag: "PlanCheckFailed") with issues
CircuitDeclarationTypeProjection Declaration returned by View.circuit
CircuitBindingTypeBound projection returned by declaration.at(params)
CircuitErrorTypeUnion PlanChanged | ViewFault | ViewDataFault | ProjectionFault
ParameterExpressionsTypeMap of JSON-valued binding parameters to TypedExpression values
StateTypeStructural contract of a Streamsy.state class
InputTypeExistential input State class boundary used in Relation and View.circuit
RelationTypeTyped relation handle returned by View.from and relation operators
RoutedViewTypeRouted circuit view returned by View.routed
TypedExpressionTypeTyped expression node with fluent comparison, boolean, numeric, sort, optional, and field operations
ReferenceTypeAlias for TypedExpression<T> passed to operator callbacks
BooleanExpressionTypeAlias for TypedExpression<boolean>
TypedAggregateExpressionTypeExpression returned by the View aggregate functions

View namespace

View exports these values and types:

MemberKindPurpose
View.fromFunctionStart a Relation from a Streamsy.state class and collection name
View.routedFunctionAttach explicit route expressions (and optional row selector) for a routed output
View.circuitFunctionCompile views and generation-addressed outputs into a CircuitDeclaration
View.liveFunctionCompile named views for a scoped heap reader
View.migrateFunctionCreate operator tables on SQLite, Postgres, or MySQL
View.countFunctionCount rows in a groupBy group
View.sumFunctionSum a numeric expression in a groupBy group
View.minFunctionMinimum ordered (number | string) expression in a groupBy group
View.maxFunctionMaximum ordered (number | string) expression in a groupBy group
View.listFunctionAll values of an ordered expression in a groupBy group, with duplicates
View.fieldFunctionSelect a field whose name overlaps an expression method or member
View.fnFunctionDeclare a named, versioned, pure synchronous expression function
View.literalFunctionWrap a JSON value as a TypedExpression
View.keyFunctionBuild a composite key expression or use View.key.asc() to sort by the relation key
View.StateTypeSame as root State
View.InputTypeSame as root Input
View.RelationTypeSame as root Relation
View.RoutedViewTypeSame as root RoutedView
View.CircuitDeclarationTypeSame as root CircuitDeclaration
View.CircuitBindingTypeSame as root CircuitBinding

View.from

declare function from<
  Codecs extends StreamRoute.ParamCodecs,
  C extends StreamAddress.Collections,
  R,
  K extends keyof C & string,
>(state: State<Codecs, C, R>, collection: K): Relation<C[K]["schema"]["Type"], State<Codecs, C, R>>;

Creates a source relation for collection on state. Throws RangeError if collection is not declared on state.

View.routed

declare function routed<Row, Inputs extends Input, const By extends RouteFields>(
  source: Relation<Row, Inputs>,
  spec: { readonly by: (row: Reference<Row>) => By; readonly row?: never },
): RoutedView<Row, Inputs, By>;

declare function routed<
  Row,
  Inputs extends Input,
  const By extends RouteFields,
  Result extends JsonObject,
>(
  source: Relation<Row, Inputs>,
  spec: {
    readonly by: (row: Reference<Row>) => By;
    readonly row: (row: Reference<Row>) => TypedExpression<Result>;
  },
): RoutedView<Result, Inputs, By>;

Wraps a Relation for an output declared with Projection.perGeneration(StateClass, param, { routeBy: [...] }). by must return an expression (string, finite number, or boolean) for every parameter listed in routeBy with matching decoded types. Pass row when the emitted JSON object row is nested inside the relation row.

Passing a RoutedView to a non-routed circuit output or to View.live throws RangeError. See Route output rows.

View.circuit

// Single output form
declare function circuit<
  C extends StreamRoute.ParamCodecs,
  const V extends Views,
  O extends Projection.PerGeneration<Input, string, string>,
  HE = never,
  HR = never,
>(definition: {
  readonly id: string;
  readonly generation?: number;
  readonly params: C;
  readonly retry?: CircuitDeclaration<C, { output: V }, { output: O }, HE, HR>["retry"];
  readonly maxAffectedKeys?: number;
  readonly wakeAt?: (unit: Unit<StreamRoute.Params<NoInfer<C>>>) => void | WakeAt;
  readonly output: O;
  readonly views: V | ((params: ParameterExpressions<NoInfer<C>>) => V);
}): CircuitDeclaration<C, { output: V }, { output: O }, HE, HR>;

// Multiple outputs form
declare function circuit<
  C extends StreamRoute.ParamCodecs,
  const V extends ViewMap,
  const O extends Readonly<Record<string, Projection.PerGeneration<Input, string, string>>>,
  HE = never,
  HR = never,
>(definition: {
  readonly id: string;
  readonly generation?: number;
  readonly params: C;
  readonly retry?: CircuitDeclaration<C, V, O, HE, HR>["retry"];
  readonly maxAffectedKeys?: number;
  readonly wakeAt?: (unit: Unit<StreamRoute.Params<NoInfer<C>>>) => void | WakeAt;
  readonly outputs: O;
  readonly views: V | ((params: ParameterExpressions<NoInfer<C>>) => V);
}): CircuitDeclaration<C, V, O, HE, HR>;

Compiles the declared views and returns a Declaration backed by Projection.process and a transactional cleanup commit.

Declaration-time checks:

  • Throws ViewFault if any output is not wrapped in Projection.perGeneration.
  • Throws RangeError for missing circuit parameters, duplicate output State classes, missing or unknown output collections, empty outputs, mismatched View.routed route fields, an invalid maxAffectedKeys, or a defined version option.
  • Throws PlanCheckFailed if the compiled plan fails static validation.

View.live

View.live({ id, params, views, maxAffectedKeys?, retry? }) compiles named relations and returns a declaration with at(params). Pass a record of relations or a function from typed parameter expressions to that record. The declaration uses the same input parameter checks and affected-key limit as View.circuit. Routed relations throw RangeError. An invalid compiled plan throws PlanCheckFailed.

MemberResultBehavior
at(params)Effect of LiveReader<V>, with CircuitErrorOpens a reader with a private heap host. Requires Scope and the input State services
snapshotEffect<LiveSnapshot<V>>Reads the latest committed rows of all views, their input offsets, and catch-up status
snapshotsStream<LiveSnapshot<V>, CircuitError>Starts with the latest snapshot and emits after commits and when initial catch-up succeeds. Slow subscribers can skip intermediate snapshots
caughtUpEffect<void, CircuitError>Waits for the first snapshot that reaches the startup tails. Interrupts its caller if the reader ends without a fault before that

Open a reader outside any transaction. A terminal startup or follower fault fails snapshots, including ViewDataFault from a bad input row and ProjectionFault with reason history-unavailable when required history is missing. A caughtUp wait that is still waiting for the first caught-up snapshot gets the same fault. Offsets are scoped to their input streams. A follower parked when an input closes without data can take up to 30 seconds to notice the close. See Read live snapshots.

View.migrate

declare const migrate: (
  sql: SqlClient.SqlClient,
) => Effect.Effect<void, ViewFault | SqlError.SqlError>;

Creates streamsy_view_integrals, streamsy_view_arrangements, streamsy_view_accumulators, streamsy_view_key_owners, and streamsy_view_circuits if they do not exist. On Postgres and MySQL it also creates and checks streamsy_view_layout. An unsupported SQL dialect fails with ViewFault. See the migration rules for SQLite, Postgres, and MySQL.

Aggregates

declare const count: () => TypedAggregateExpression<number>;
declare const sum: (expression: TypedExpression<number>) => TypedAggregateExpression<number>;
declare const min: <T extends number | string>(
  expression: TypedExpression<T>,
) => TypedAggregateExpression<T>;
declare const max: <T extends number | string>(
  expression: TypedExpression<T>,
) => TypedAggregateExpression<T>;
declare const list: <T extends number | string>(
  expression: TypedExpression<T>,
) => TypedAggregateExpression<readonly T[]>;

Used inside relation.groupBy(fields).aggregate(aggregates).

View.list returns values in ascending order, using numeric order for finite numbers and UTF-16 code-unit order for strings. Numbers precede strings, duplicates are kept, and absent operands are skipped. Empty groups have no output row. When a member changes the list, the aggregate emits the whole array. maxAffectedKeys does not bound group size.

Expression helpers

declare function field<T, K extends keyof Exclude<T, undefined> & string>(
  expression: TypedExpression<T>,
  name: K,
): TypedExpression<Exclude<T, undefined>[K] | Extract<T, undefined>>;

declare function fn<
  Args extends readonly (JsonValue | undefined)[],
  Result extends JsonValue | undefined,
>(
  name: string,
  version: number,
  implementation: (...args: Args) => Result,
): (
  ...operands: { readonly [K in keyof Args]: TypedExpression<Args[K]> }
) => TypedExpression<Result>;

declare const literal: <T extends JsonValue>(value: T) => TypedExpression<T>;

declare const key: ((
  ...parts: readonly (
    TypedExpression<boolean> | TypedExpression<number> | TypedExpression<string>
  )[]
) => TypedExpression<readonly (boolean | number | string)[]>) & {
  asc: () => SortTerm;
};

View.fn throws RangeError if name is blank or version is not a positive safe integer.

Relation

interface Relation<Row, Inputs extends Input = Input> {
  readonly rowType?: Row;
  readonly expression: RelationExpression<Row>;
  readonly inputs: ReadonlyMap<string, { readonly state: Inputs; readonly collection: string }>;
  readonly where: (predicate: (row: Reference<Row>) => BooleanExpression) => Relation<Row, Inputs>;
  readonly select: <F extends Readonly<Record<string, Expression>>>(
    fields: (row: Reference<Row>) => F,
  ) => Relation<Selected<F>, Inputs>;
  readonly selectRow: <Result extends JsonObject>(
    expression: (row: Reference<Row>) => TypedExpression<Result>,
  ) => Relation<Result, Inputs>;
  readonly concat: <Other, OtherInputs extends Input>(
    other: Relation<Other, OtherInputs>,
  ) => Relation<Row | Other, Inputs | OtherInputs>;
  readonly closure: <Part extends JsonValue | undefined = undefined>(spec: {
    readonly parent: (row: Reference<Row>) => ValueExpression<string | undefined>;
    readonly part?: (row: Reference<Row>) => ValueExpression<Part>;
    readonly maxDepth: number;
  }) => Relation<
    {
      readonly node: string;
      readonly ancestor: string;
      readonly depth: number;
      readonly path?: readonly Exclude<Part, undefined>[];
    },
    Inputs
  >;
  readonly join: <Right, Other extends Input, Alias extends string>(
    other: Relation<Right, Other>,
    spec: {
      readonly as: Alias;
      readonly on: (left: Reference<Row>, right: Reference<Right>) => BooleanExpression;
    },
  ) => Relation<Row & Record<Alias, Right>, Inputs | Other>;
  readonly leftJoin: <Right, Other extends Input, Alias extends string>(
    other: Relation<Right, Other>,
    spec: {
      readonly as: Alias;
      readonly on: (left: Reference<Row>, right: Reference<Right>) => BooleanExpression;
    },
  ) => Relation<Row & Partial<Record<Alias, Right>>, Inputs | Other>;
  readonly groupBy: <F extends Readonly<Record<string, Expression>>>(
    fields: (row: Reference<Row>) => F,
  ) => {
    readonly aggregate: <A extends Readonly<Record<string, TypedAggregateExpression<unknown>>>>(
      aggregates: (row: Reference<Row>) => A,
    ) => Relation<Selected<F> & { readonly [K in keyof A]: AggregateValue<A[K]> }, Inputs>;
  };
  readonly top: (spec: {
    readonly partitionBy?: (row: Reference<Row>) => Expression | readonly Expression[];
    readonly by: (row: Reference<Row>) => readonly SortTerm[];
    readonly limit: number;
  }) => Relation<Row, Inputs>;
}
  • selectRow projects the whole row from one expression that returns a JSON object. It keeps the input relation key, as select does. A circuit uses its output State collection's declared key when writing the row.
  • concat preserves all input values and prefixes each encoded relation key with its side as ["l", encodedKey] or ["r", encodedKey].
  • closure follows one parent per string relation key for at most maxDepth edges. A missing parent row is a final ancestor. Cycles stop before an ancestor repeats or the walk returns to its starting node. Each output key contains the encoded node and ancestor keys. Pass part to include the path values from the row below the ancestor down to the node. If any part on an emitted path is absent, the unit fails with ViewDataFault. Use View.field(row, "path") to read the path. The selectors accept typed expressions, including optional parent values.

See Build relations for worked examples of every operator.

TypedExpression operations

Methods available on TypedExpression<T> depend on T:

GroupCondition on TMethods
CommonAll typeseq(right), ne(right), in(...values)
OrderedExclude<T, undefined> is number | stringgt(right), gte(right), lt(right), lte(right)
SortNon-optional number | stringasc(), desc()
BooleanExclude<T, undefined> is booleanand(...right), or(...right), not()
NumberExclude<T, undefined> is numberadd(right)
Optionalundefined is assignable to TisPresent(), unwrap(), orElse(fallback)
Object fieldsExclude<T, undefined> is an objectProperty access expr.prop for each field, propagating optionality; use View.field when a name overlaps a method

ViewBackend

ViewBackend is an opaque Effect service. Supply it through a layer.

LayerProvidesRequiresLayer error
ViewBackend.layerSqlViewBackendSqlClient.SqlClientViewFault for an unsupported dialect
ViewBackend.layerMemoryViewBackendCommitBoundarynever

layerSql uses the storage owner's SqlClient. Run View.migrate with that client before running the circuit. If the transaction for that client is absent, the fault message is The Views SQL client is outside the storage owner's transaction.

layerMemory requires an active memory owner transaction on the running fiber when the circuit uses the store. If the transaction is absent or belongs to another owner, the fault message is Views memory state requires the active memory owner transaction on this fiber.

For either transaction check, a circuit unit fails with a non-retryable ViewFault. During Projection.forget or Projection.retire, the same check fails cleanup with a ProjectionFault with phase checkpoint and reason unsupported-composition. The cleanup fault keeps the same message.

Faults

PlanChanged

interface PlanChanged {
  readonly _tag: "ViewPlanChanged";
  readonly namespace: string;
  readonly stored: string;
  readonly requested: string;
  readonly [NonRetryable]: true;
}

ViewDataFault

interface ViewDataFault {
  readonly _tag: "ViewDataFault";
  readonly view: string;
  readonly node: string;
  readonly key: string | number | boolean | readonly (string | number | boolean)[] | null;
  readonly reason: string;
  readonly [NonRetryable]: true;
}

ViewFault

interface ViewFault {
  readonly _tag: "ViewFault";
  readonly message: string;
  readonly cause?: unknown;
}

PlanCheckFailed

interface PlanCheckFailed {
  readonly _tag: "PlanCheckFailed";
  readonly issues: ReadonlyArray<{
    readonly code:
      | "invalid-expression-scope"
      | "non-boolean-predicate"
      | "join-alias-conflict"
      | "join-condition-not-boolean"
      | "aggregate-shape-mismatch"
      | "undeclared-parameter"
      | "invalid-top-limit"
      | "invalid-closure-depth"
      | "invalid-closure-key"
      | "unstable-top-order"
      | "unsupported-sql-plan";
    readonly view: string;
    readonly nodeId?: string;
    readonly path: string;
    readonly message: string;
  }>;
}

Types

LiveReader and LiveSnapshot

interface LiveSnapshot<V> {
  readonly rows: {
    readonly [K in keyof V]: ReadonlyArray<V[K] extends Relation<infer Row> ? Row : never>;
  };
  readonly offsets: Readonly<Record<string, Offset>>;
  readonly caughtUp: boolean;
}

interface LiveReader<V> {
  readonly snapshot: Effect.Effect<LiveSnapshot<V>>;
  readonly snapshots: Stream.Stream<LiveSnapshot<V>, CircuitError>;
  readonly caughtUp: Effect.Effect<void, CircuitError>;
}

The snapshot and its rows are read-only. Use a State input's key to look up its committed offset. caughtUp records completion of the initial replay. Rows within each view are ordered by the encoded relation key. Select a key as a row field when the caller needs it.

CircuitError

type CircuitError = PlanChanged | ViewFault | ViewDataFault | ProjectionFault;

CircuitBinding and CircuitDeclaration

CircuitDeclaration<C, V, O, HE, HR> extends @streamsy/projection's Declaration<C, CircuitBinding<V, O>, HE, HR>. Calling declaration.at(params) returns a CircuitBinding<V, O> that Projection.pass, Projection.run, Projection.follow, and Projection.forget accept. Projection.attach, ProjectionWakeup.attach, and Projection.retire accept the CircuitDeclaration. The binding uses Commit.TransactionCommit<void | WakeAt, CheckpointStore | Transaction | ViewBackend>. Its handler requires ViewBackend and the output State services.

On this page