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.
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"],
})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: [],
})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)),
},
})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)StateNotAllowedError
5Akter.make slots
Every options object lists its keys in alphabetical order.
| Slot | Takes | Presence |
|---|---|---|
callers | A non-empty list of Akter.caller values, Akter.ActorCaller, and Akter.System. | Required. |
channel | One Akter.channel declaration (Channels). | Only when the actor has a live room. |
commands | A map of member names to Akter.command declarations. | Required. Write {} when the actor has no commands. |
droppedTables | A non-empty list of table names that the actor drops. | Only when the actor drops a table. |
final | A non-empty list of states that no command or job leaves. | Only when the actor has such states. |
fs | One Akter.fs declaration. | Only when the actor’s handlers use a file system. |
http | A 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. |
jobs | A map of job names to Akter.job declarations. | Only when the actor has jobs. |
key | A schema whose encoded form is a string, usually a branded Schema.String. | Required. |
parent | Another actor, or Akter.Root. | Required. |
queries | A map of member names to Akter.query declarations. | Required. Write {} when the actor has no queries. |
schedules | A non-empty list of Akter.schedule bindings. | Only when the actor runs commands on a cron schedule. |
secrets | A non-empty list of secret names that the actor’s jobs read. | Only when the jobs read secrets. |
states | A non-empty list of Schema.TaggedStruct values. | Required. |
tables | A list of Akter.table values. | Required. Write [] when the actor has no tables. |
timeouts | A 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.
| Option | Takes | Presence |
|---|---|---|
columns | A map of column names to schemas. | Required. |
droppedColumns | A non-empty list of column names that the table drops. | Only when the table drops a column. |
indexes | A list of { columns, name, unique } indexes. columns is a non-empty list of column names. | Required. Write [] when the table has no indexes. |
primaryKey | A non-empty list of column names. | Required. |
- Names: Table, column, and index names match
^[a-z][a-z0-9_]*$. They do not start withakter_orsqlite_. A bad or repeated name throwsInvalidTableNameError. - Column references: The type checker rejects a name in
indexesorprimaryKeythatcolumnsdoes not declare, and a name in bothcolumnsanddroppedColumns. At runtime both throwInvalidTableColumnError. - Strict tables: Every table is a SQLite
STRICTtable. - 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 schema | SQLite type |
|---|---|
| A string or a template literal | TEXT |
An integer, such as Schema.Int | INTEGER |
| Any other number | REAL |
A bigint | INTEGER |
| A boolean | INTEGER, stored as 0 or 1 |
A Uint8Array | BLOB |
| Any other schema | TEXT, 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, anddb.selectrun 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
| Option | Takes |
|---|---|
callers | A non-empty list of the actor’s callers that may send the command. |
errors | A list of Schema.TaggedError classes. Write [] when the command cannot fail with a domain error. |
from | A non-empty list of states in which the command runs. |
input | A schema, such as Schema.Struct({ ... }). Write Schema.Void for no input. |
output | A schema. Write Schema.Void for no output. |
to | A non-empty list of states that the command can move to. |
Akter.query options
| Option | Takes |
|---|---|
callers | A non-empty list of the actor’s callers that may run the query. |
errors | A list of Schema.TaggedError classes, or []. |
input | A schema, or Schema.Void. |
output | A schema. |
staleFor | A Duration, such as Duration.seconds(2). Optional. An engine may serve a cached answer up to this age. |
states | A non-empty list of states in which the query runs. |
Akter.job options
| Option | Takes |
|---|---|
errors | A list of Schema.TaggedError classes, or []. |
from | A non-empty list of states in which the job’s result can land. |
input | A Schema.Struct({ ... }). |
output | A schema, or Schema.Void. |
patches | A list of workflow patch names, or []. |
stream | A schema for each chunk that the job emits with <Actor>.jobs.<name>.emit. Optional. An Akter.httpStream binding needs it. |
to | A 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.
| Constructor | Options |
|---|---|
Akter.timeout | after, a Duration. command, the name of a command. state, a state from states. |
Akter.schedule | command, the name of a command. cron, an Effect Cron value, such as Cron.parseUnsafe("0 * * * *"). |
Akter.http | callers, command, and endpoint, a POST, PUT, PATCH, or DELETE HttpApiEndpoint. |
Akter.httpQuery | callers, endpoint with any method, and query, the name of a query. |
Akter.httpStream | callers, endpoint with POST, PUT, PATCH, or DELETE, and job, the name of a job that declares stream. |
Akter.fs | callers, the callers whose handlers reach the actor’s files. |
Akter.channel | callers, event, and presence, the schemas of broadcasts and of each connection’s presence. |
- Timeout and schedule commands: The command lists
Akter.Systemincallersand takesSchema.Void. A timeout’s command lists the timeout’s state infrom. - 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.schedulethrowsInvalidScheduleErrorfor aCronwith 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.
| Option | Takes |
|---|---|
errors | A list of Schema.TaggedError classes, or []. A typed failure rolls the turn back and fails the call. |
from | A non-empty list of states in which the turn runs. Another state fails the call with StateNotAllowedError. |
output | A 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. |
to | A non-empty list of states that the turn can move to. |
States and transitions
- States: Each state is a
Schema.TaggedStructwith a unique tag. Two states with one tag fail withDuplicateStateError. - Lifecycles: A lifecycle is a set of states. A state struct never carries a string-literal
status,phase,state, orstagefield, and theakter/state-machine-statuslint rule rejects that field. - Edges: Each command and job adds an edge from every state in
fromto every state into.initial.tois the start state. - Narrowing: A command handler receives the state narrowed to
from. A query handler receives the state narrowed tostates. - 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.
| Key | Handler | Presence |
|---|---|---|
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. |
upgrade | Akter.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.inputisSchema.Voidstarts ininitial.toon its first command. - Typed input: Any other
initial.inputneeds an explicitcreateorensurecall. 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 asuserorapiKey. The schema decodes the principal. - Actor caller: Messages from other actors arrive as
Akter.ActorCaller. The nameactoris reserved, andAkter.caller("actor", ...)fails withReservedCallerError. - System caller: State timeouts and cron schedules run their commands as
Akter.System. The namesystemis 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 listsAkter.Systemincallersand takesAkter.ChildFaultas 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:
| File | Holds |
|---|---|
*.contract.ts | Akter.make, Akter.command, Akter.query, Akter.job, and Akter.caller declarations, with their states and errors. |
*.table.ts | Akter.table declarations. |
*.actor.ts | One actor’s toLayer handlers. |
*.job.ts | One job’s layer. |
*.layer.ts | Layer 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, orinitial.to. - A table listed twice in
tables, or a table in bothtablesanddroppedTables. - A column in
indexesorprimaryKeythatcolumnsdoes not declare, or a column in bothcolumnsanddroppedColumns. - An object literal of fields in place of a schema in
input,output, orinitial.input. - An omitted
input,output,errors, orparent. - A caller or state on a member that the actor does not declare.
- A
nextstate outside the member’stolist, or a missingoutputin 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, orhttpbinding. - A timeout or schedule command that omits
Akter.Systemor takes input, or a timeout command whosefromomits the timeout’s state. - A binding that names a member the actor does not declare, or an
Akter.httpStreamjob withoutstream. - An endpoint whose path parameters are not exactly one parameter with the actor’s
keyschema. - An
Akter.httporAkter.httpStreamendpoint that usesGET,HEAD, orOPTIONS.