Skip to content

Actor grammar

Akter.make declares every actor as a typed state machine in one form. Each slot takes a value, such as a schema, a state, a caller, or an actor. No slot takes a string reference, a shorthand, or a default.

One contract uses every slot⁠

Sale is a root actor with two states, two callers, a table, a command, and a query. Receipt is a child of Sale with a final state.

orders.table.ts
import { Schema } from "effect"
import { Akter } from "@akterjs/effect/contract"

export const OrdersTable = Akter.table("orders", {
  columns: { buyer: Schema.String, id: Schema.String, note: Schema.NullOr(Schema.String), quantity: Schema.Int },
  indexes: [{ columns: ["buyer"], name: "orders_by_buyer", unique: false }],
  primaryKey: ["id"],
})
sale.contract.ts
import { Duration, Schema } from "effect"
import { Akter } from "@akterjs/effect/contract"
import { OrdersTable } from "./orders.table.ts"

export const SaleId = Schema.String.pipe(Schema.brand("SaleId"))

export const OrderId = Schema.String.pipe(Schema.brand("OrderId"))

export const Quantity = Schema.Int.check(Schema.isGreaterThan(0)).pipe(Schema.brand("Quantity"))

export const Stock = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)).pipe(Schema.brand("Stock"))

export class InsufficientStockError extends Schema.TaggedError<InsufficientStockError, { readonly brand: unique symbol }>()(
  "InsufficientStockError",
  { available: Stock },
) {}

export const Buyer = Akter.caller("user", Schema.Struct({ id: Akter.PrincipalId }))

export const Merchant = Akter.caller("apiKey", Schema.Struct({ id: Akter.PrincipalId }))

export const Open = Schema.TaggedStruct("Open", { stock: Stock })

export const SoldOut = Schema.TaggedStruct("SoldOut", { closedByOrder: OrderId })

export const Sale = Akter.make("Sale", {
  callers: [Buyer, Merchant],
  commands: {
    buy: Akter.command({
      callers: [Buyer],
      errors: [InsufficientStockError],
      from: [Open],
      input: Schema.Struct({ quantity: Quantity }),
      output: OrderId,
      to: [Open, SoldOut],
    }),
    restock: Akter.command({
      callers: [Merchant],
      errors: [],
      from: [Open, SoldOut],
      input: Schema.Struct({ stock: Stock }),
      output: Schema.Void,
      to: [Open],
    }),
  },
  initial: { input: Schema.Struct({ stock: Stock }), to: Open },
  key: SaleId,
  parent: Akter.Root,
  queries: {
    stock: Akter.query({
      callers: [Buyer, Merchant],
      errors: [],
      input: Schema.Void,
      output: Stock,
      staleFor: Duration.seconds(2),
      states: [Open, SoldOut],
    }),
  },
  states: [Open, SoldOut],
  tables: [OrdersTable],
})

export const Issued = Schema.TaggedStruct("Issued", { quantity: Quantity })

export const Refunded = Schema.TaggedStruct("Refunded", { quantity: Quantity })

export const Receipt = Akter.make("Receipt", {
  callers: [Akter.ActorCaller, Buyer],
  commands: {
    refund: Akter.command({
      callers: [Akter.ActorCaller],
      errors: [],
      from: [Issued],
      input: Schema.Void,
      output: Schema.Void,
      to: [Refunded],
    }),
  },
  final: [Refunded],
  initial: { input: Schema.Struct({ quantity: Quantity }), to: Issued },
  key: OrderId,
  parent: Sale,
  queries: {
    quantity: Akter.query({
      callers: [Buyer],
      errors: [],
      input: Schema.Void,
      output: Quantity,
      states: [Issued, Refunded],
    }),
  },
  states: [Issued, Refunded],
  tables: [],
})
sale.actor.ts
import { Effect } from "effect"
import { Akter } from "@akterjs/effect/contract"
import { OrdersTable } from "./orders.table.ts"
import { InsufficientStockError, Open, OrderId, Sale, SoldOut, Stock } from "./sale.contract.ts"

export const SaleLive = Sale.toLayer({
  commands: {
    buy: (sale, { quantity }) =>
      Effect.gen(function* () {
        if (quantity > sale.stock) {
          return yield* InsufficientStockError.make({ available: sale.stock })
        }
        const order = OrderId.make(yield* Akter.id)
        const buyer = yield* Akter.principal
        const db = yield* Akter.db
        yield* db.insert(OrdersTable).values({ buyer: buyer.id, id: order, note: null, quantity })
        const left = Stock.make(sale.stock - quantity)
        const next = left === 0 ? SoldOut.make({ closedByOrder: order }) : Open.make({ stock: left })
        return { next, output: order }
      }),
    restock: (_sale, { stock }) => Effect.succeed({ next: Open.make({ stock }) }),
  },
  initial: ({ stock }) => ({ next: Open.make({ stock }) }),
  queries: {
    stock: (sale) => Effect.succeed(sale._tag === "Open" ? sale.stock : Stock.make(0)),
  },
})
sale.story.ts
import { Effect } from "effect"
import { Akter } from "@akterjs/effect/contract"
import { Story } from "@akterjs/effect/testing"
import { Buyer, Merchant, Quantity, Sale, SaleId, Stock } from "./sale.contract.ts"
import { SaleLive } from "./sale.actor.ts"

const drop = SaleId.make("drop")

const buyer = { caller: Buyer, principal: { id: Akter.PrincipalId.make("ada") } }

const merchant = { caller: Merchant, principal: { id: Akter.PrincipalId.make("shop") } }

const program = Story.run(SaleLive, function* (story) {
  yield* story.create(Sale, drop, { as: merchant, input: { stock: Stock.make(2) } })

  const sale = yield* story.actor(Sale, drop, { as: buyer })
  yield* sale.buy({ quantity: Quantity.make(2) })

  const closed = yield* Effect.flip(sale.buy({ quantity: Quantity.make(1) }))
  console.log(closed._tag)

  const shop = yield* story.actor(Sale, drop, { as: merchant })
  yield* shop.restock({ stock: Stock.make(5) })
  console.log(yield* sale.stock())
})

Effect.runPromise(program)
Text
StateNotAllowedError
5

Akter.make slots⁠

Every options object lists its keys in alphabetical order.

SlotTakesPresence
callersA non-empty list of Akter.caller values, Akter.ActorCaller, and Akter.System.Required.
channelOne Akter.channel declaration (Channels).Only when the actor has a live room.
commandsA map of member names to Akter.command declarations.Required. Write {} when the actor has no commands.
droppedTablesA non-empty list of table names that the actor drops.Only when the actor drops a table.
finalA non-empty list of states that no command or job leaves.Only when the actor has such states.
fsOne Akter.fs declaration.Only when the actor’s handlers use a file system.
httpA non-empty list of Akter.http, Akter.httpQuery, and Akter.httpStream bindings (HTTP bindings).Only when the actor serves routes.
initial{ input, to }, the creation input schema and the first state.Required.
jobsA map of job names to Akter.job declarations.Only when the actor has jobs.
keyA schema whose encoded form is a string, usually a branded Schema.String.Required.
parentAnother actor, or Akter.Root.Required.
queriesA map of member names to Akter.query declarations.Required. Write {} when the actor has no queries.
schedulesA non-empty list of Akter.schedule bindings.Only when the actor runs commands on a cron schedule.
secretsA non-empty list of secret names that the actor’s jobs read.Only when the jobs read secrets.
statesA non-empty list of Schema.TaggedStruct values.Required.
tablesA list of Akter.table values.Required. Write [] when the actor has no tables.
timeoutsA non-empty list of Akter.timeout bindings.Only when a state times out.

A table appears once in tables, and a name in droppedTables names no table in tables. The type checker rejects a repeated table or a name in both slots. At runtime they fail with DuplicateTableError and DroppedTableDeclaredError.

A command and a query cannot share a name. Names such as client, create, ensure, fork, state, and states are reserved for the actor client.

Akter.table options⁠

Akter.table(name, options) declares one table.

OptionTakesPresence
columnsA map of column names to schemas.Required.
droppedColumnsA non-empty list of column names that the table drops.Only when the table drops a column.
indexesA list of { columns, name, unique } indexes. columns is a non-empty list of column names.Required. Write [] when the table has no indexes.
primaryKeyA non-empty list of column names.Required.
  • Names: Table, column, and index names match ^[a-z][a-z0-9_]*$. They do not start with akter_ or sqlite_. A bad or repeated name throws InvalidTableNameError.
  • Column references: The type checker rejects a name in indexes or primaryKey that columns does not declare, and a name in both columns and droppedColumns. At runtime both throw InvalidTableColumnError.
  • Strict tables: Every table is a SQLite STRICT table.
  • Reads: A stored value that its column schema rejects on read is a defect.
  • Changes: The host migrates additive changes and refuses the rest (Changing tables and state).

Each column’s SQLite type comes from the encoded side of its schema:

Encoded schemaSQLite type
A string or a template literalTEXT
An integer, such as Schema.IntINTEGER
Any other numberREAL
A bigintINTEGER
A booleanINTEGER, stored as 0 or 1
A Uint8ArrayBLOB
Any other schemaTEXT, stored as JSON

Schema.NullOr(...) makes a column nullable. Every other column is NOT NULL.

Akter.db queries⁠

Akter.db is a Drizzle ORM SQLite database whose queries are Effects. Import operators such as eq, desc, and and from drizzle-orm.

  • Commands: db.insert, db.update, db.delete, and db.select run inside the turn’s savepoint.
  • Queries: A query handler gets the same database. The host refuses its write statements.
  • Transport: Every statement travels to the host as a host call of the turn worker ABI.

Akter.command options⁠

OptionTakes
callersA non-empty list of the actor’s callers that may send the command.
errorsA list of Schema.TaggedError classes. Write [] when the command cannot fail with a domain error.
fromA non-empty list of states in which the command runs.
inputA schema, such as Schema.Struct({ ... }). Write Schema.Void for no input.
outputA schema. Write Schema.Void for no output.
toA non-empty list of states that the command can move to.

Akter.query options⁠

OptionTakes
callersA non-empty list of the actor’s callers that may run the query.
errorsA list of Schema.TaggedError classes, or [].
inputA schema, or Schema.Void.
outputA schema.
staleForA Duration, such as Duration.seconds(2). Optional. An engine may serve a cached answer up to this age.
statesA non-empty list of states in which the query runs.

Akter.job options⁠

OptionTakes
errorsA list of Schema.TaggedError classes, or [].
fromA non-empty list of states in which the job’s result can land.
inputA Schema.Struct({ ... }).
outputA schema, or Schema.Void.
patchesA list of workflow patch names, or [].
streamA schema for each chunk that the job emits with <Actor>.jobs.<name>.emit. Optional. An Akter.httpStream binding needs it.
toA non-empty list of states that the result turn can move to.

Bindings name a member⁠

timeouts, schedules, and http bind a declared member to a state, a clock, or a route. Each binding names its member as a string and carries no handler.

ConstructorOptions
Akter.timeoutafter, a Duration. command, the name of a command. state, a state from states.
Akter.schedulecommand, the name of a command. cron, an Effect Cron value, such as Cron.parseUnsafe("0 * * * *").
Akter.httpcallers, command, and endpoint, a POST, PUT, PATCH, or DELETE HttpApiEndpoint.
Akter.httpQuerycallers, endpoint with any method, and query, the name of a query.
Akter.httpStreamcallers, endpoint with POST, PUT, PATCH, or DELETE, and job, the name of a job that declares stream.
Akter.fscallers, the callers whose handlers reach the actor’s files.
Akter.channelcallers, event, and presence, the schemas of broadcasts and of each connection’s presence.
  • Timeout and schedule commands: The command lists Akter.System in callers and takes Schema.Void. A timeout’s command lists the timeout’s state in from.
  • Endpoints: An endpoint declares exactly one path parameter, and its schema is the actor’s key.
  • Timing: The host arms a timeout when the actor enters its state and cancels it when the actor leaves. It runs a schedule’s command at each due time of the cron expression (State timeouts and schedules).
  • Schedules run in UTC: The host reads each cron expression in UTC. Akter.schedule throws InvalidScheduleError for a Cron with a time zone.

<Actor>.turn options⁠

A job body changes its actor’s state only through <Actor>.turn. Each call runs one jobStep turn in the actor’s turn line and returns the turn’s output.

OptionTakes
errorsA list of Schema.TaggedError classes, or []. A typed failure rolls the turn back and fails the call.
fromA non-empty list of states in which the turn runs. Another state fails the call with StateNotAllowedError.
outputA schema, or Schema.Void.
run(state) => Effect<{ next, output }>, or { next } when output is Schema.Void. It reads and writes tables with Akter.db and makes no network calls.
toA non-empty list of states that the turn can move to.

States and transitions⁠

  • States: Each state is a Schema.TaggedStruct with a unique tag. Two states with one tag fail with DuplicateStateError.
  • Lifecycles: A lifecycle is a set of states. A state struct never carries a string-literal status, phase, state, or stage field, and the akter/state-machine-status lint rule rejects that field.
  • Edges: Each command and job adds an edge from every state in from to every state in to. initial.to is the start state.
  • Narrowing: A command handler receives the state narrowed to from. A query handler receives the state narrowed to states.
  • Refusal: The engine refuses a command or query in a state it does not list with StateNotAllowedError. The handler does not run.

Handlers⁠

toLayer takes one handler object.

KeyHandlerPresence
commands(state, input) => Effect<{ next, output }>. A command whose output is Schema.Void returns { next }.Required.
initial(input) => ({ next }). Pure and synchronous.Required.
queries(state, input) => Effect<output>.Required. Write {} when the actor has no queries.
results(state, exit, job) => Effect<{ next }>, one per job.Required exactly when the actor has jobs.
upgradeAkter.migrateState(from, migrate).Optional.

next is a state from the member’s to list, built with .make(...). A handler can return the received state as next when to lists that state.

Creation⁠

  • Void input: An actor whose initial.input is Schema.Void starts in initial.to on its first command.
  • Typed input: Any other initial.input needs an explicit create or ensure call. The client has these methods only for such an actor.

Callers⁠

  • Declared callers: Akter.caller(name, schema) declares a caller. The name is the wire kind, such as user or apiKey. The schema decodes the principal.
  • Actor caller: Messages from other actors arrive as Akter.ActorCaller. The name actor is reserved, and Akter.caller("actor", ...) fails with ReservedCallerError.
  • System caller: State timeouts and cron schedules run their commands as Akter.System. The name system is reserved. A client principal can never claim it.
  • Member lists: Every command and query lists its callers. A caller outside the list fails with CallerNotAllowedError.

Parents form a supervision tree⁠

parent names another actor, or Akter.Root for a top-level actor. The tree is part of the published contract, and akterd uses it:

  • Supervision: A parent that declares onChildFault: Akter.onChildFault({ command: "childFaulted" }) runs that command when the host quarantines a child’s envelope. The command lists Akter.System in callers and takes Akter.ChildFault as its input.
  • Authorization: A parent’s relations extend to its children.
  • Erasure: Erasing a parent erases its children.
  • Placement: A child is placed on its parent’s shard.

Final states⁠

final lists every reachable state that no command or job lists in from. Receipt lists Refunded, because no command lists Refunded in from. An actor without such states omits final. akter verify reports any dead end that final does not list.

File names are a convention⁠

Akter reads each construct from its code, not from its file name. A small actor fits in one plain .ts file with its contract, tables, handlers, and jobs. A larger app can split each construct into its own file with these names:

FileHolds
*.contract.tsAkter.make, Akter.command, Akter.query, Akter.job, and Akter.caller declarations, with their states and errors.
*.table.tsAkter.table declarations.
*.actor.tsOne actor’s toLayer handlers.
*.job.tsOne job’s layer.
*.layer.tsLayer wiring that composes actors and jobs.

A client bundle that imports only a contract file leaves out the handlers and their server dependencies.

Rejected forms⁠

The type checker rejects each of these forms:

  • A string in callers, states, from, to, errors, parent, tables, or initial.to.
  • A table listed twice in tables, or a table in both tables and droppedTables.
  • A column in indexes or primaryKey that columns does not declare, or a column in both columns and droppedColumns.
  • An object literal of fields in place of a schema in input, output, or initial.input.
  • An omitted input, output, errors, or parent.
  • A caller or state on a member that the actor does not declare.
  • A next state outside the member’s to list, or a missing output in a command’s transition.
  • An initial state other than initial.to.
  • A function, or a name that is not a string literal, in a timeouts, schedules, or http binding.
  • A timeout or schedule command that omits Akter.System or takes input, or a timeout command whose from omits the timeout’s state.
  • A binding that names a member the actor does not declare, or an Akter.httpStream job without stream.
  • An endpoint whose path parameters are not exactly one parameter with the actor’s key schema.
  • An Akter.http or Akter.httpStream endpoint that uses GET, HEAD, or OPTIONS.