Skip to content

Channels

A channel gives each actor key a live room. Clients join it over a WebSocket, share presence, and receive events. Nothing in a room touches the actor’s database or disk.

Broadcast events and presence from an actor⁠

  1. Declare the channel on the actor in board.contract.ts. event is the schema of every broadcast. presence is the schema each connection carries.
board.contract.ts
import { Schema } from "effect"
import { Akter } from "@akterjs/effect/contract"

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

export const Moved = Schema.TaggedStruct("Moved", { x: Schema.Number, y: Schema.Number })

export const Renamed = Schema.TaggedStruct("Renamed", { title: Schema.String })

export const Viewer = Schema.Struct({ name: Schema.String })

export const Open = Schema.TaggedStruct("Open", { title: Schema.String })

export const Board = Akter.make("Board", {
  callers: [Member],
  channel: Akter.channel({ callers: [Member], event: Schema.Union([Moved, Renamed]), presence: Viewer }),
  commands: {
    rename: Akter.command({
      callers: [Member],
      errors: [],
      from: [Open],
      input: Schema.Struct({ title: Schema.String }),
      output: Schema.Void,
      to: [Open],
    }),
  },
  initial: { input: Schema.Void, to: Open },
  key: Schema.String,
  parent: Akter.Root,
  queries: {
    viewers: Akter.query({
      callers: [Member],
      errors: [],
      input: Schema.Void,
      output: Schema.Array(Schema.String),
      states: [Open],
    }),
  },
  states: [Open],
  tables: [],
})
  1. Publish from a command and read the room from a query in board.actor.ts. Board.channel.publish holds the event until the turn commits.
board.actor.ts
import { Effect } from "effect"
import { Board, Open, Renamed } from "./board.contract.ts"

export const BoardLive = Board.toLayer({
  commands: {
    rename: (_board, { title }) =>
      Effect.as(Board.channel.publish(Renamed.make({ title })), { next: Open.make({ title }) }),
  },
  initial: () => ({ next: Open.make({ title: "Untitled" }) }),
  queries: {
    viewers: () =>
      Effect.map(Board.channel.members, (members) => members.map((member) => member.presence.name)),
  },
})
  1. Connect from an Effect client in watch.ts. The connection stays open until its scope closes.
watch.ts
import { Effect, Stream } from "effect"
import { akterClient } from "@akterjs/client/effect"
import { Board, Moved } from "./board.contract.ts"

export const watchBoard = (url: string) =>
  Effect.gen(function* () {
    const board = yield* Board.client("plan")
    const connection = yield* board.channel.connect({ name: "Ada" })

    console.log(`connection ${connection.connection} sees ${connection.welcome.members.length} members`)

    yield* connection.publish(Moved.make({ x: 10, y: 20 }))
    yield* connection.setPresence({ name: "Ada (away)" })
    yield* board.rename({ title: "Roadmap" })
    yield* connection.events.pipe(
      Stream.take(1),
      Stream.runForEach((message) => Effect.sync(() => console.log(message._tag))),
    )
  }).pipe(Effect.scoped, Effect.provide(akterClient({ url })))
  1. Connect from a browser with the Promise client in browser.ts. Call close to leave the room.
browser.ts
import { createClient } from "@akterjs/client"
import { Board, Moved } from "./board.contract.ts"

export const joinBoard = async (url: string) => {
  const akter = createClient({ actors: [Board], url })
  const connection = await akter.Board("plan").channel.connect(
    { name: "Bob" },
    {
      onEvent: (message) => {
        console.log(message._tag)
      },
    },
  )

  await connection.publish(Moved.make({ x: 3, y: 4 }))
  await connection.close()
  await akter.close()
}

Channel rules⁠

  • One room per actor key. A room exists while at least one connection is open to that (Actor, key). The actor does not need to exist yet.
  • Zero disk. Rooms, presence, and events live only in the host’s memory. They never enter the actor’s SQL tables, state, or file system.
  • Publish after commit. A command, a result handler, or a job turn calls <Actor>.channel.publish(event). The host holds the event and broadcasts it after the turn commits. A typed failure, a defect, a cancel, or a host crash drops it.
  • Every connection receives a turn’s event. A committed event reaches every open connection of the room once, in publish order.
  • Queries read but never publish. A query may read <Actor>.channel.members. A publish from a query stops the turn with a defect. The defect says the host answered channel.publish with unsupported, because a query turn never publishes.
  • Client publish skips the turn. connection.publish broadcasts at once to every other connection. It never runs a handler and is never stored.
  • Presence belongs to the connection. connection.setPresence replaces the presence of that connection only. Every other connection receives a Presence message.
  • A closed connection leaves. When a connection’s stream ends for any reason, the host removes its presence. Every other connection receives a Left message.
  • A host restart drops every room. Every connection’s stream ends, and clients connect again.
  • The caller gate. Only callers in channel.callers connect, read members, publish, or set presence. A connection’s publish and setPresence also require the caller that opened it.

Channel client API⁠

<Actor>.client(key) returns a channel member when the actor declares a channel.

MemberTypeBehavior
channel.connect(presence)Effect<ChannelConnection, StateFailure, Scope>Joins the room and waits for the Welcome message. Closing the scope leaves the room.
connection.connectionstringThe connection id that the host assigned.
connection.welcomeWelcomeThe connection id and every member at join time, including this connection.
connection.eventsStream<Joined | Left | Presence | Event>Every room message after the welcome.
connection.membersEffect<readonly ChannelMember[]>The room’s current members.
connection.publish(event)Effect<void>Broadcasts event to every other connection.
connection.setPresence(presence)Effect<void>Replaces this connection’s presence.

The Promise client from @akterjs/client takes connect(presence, { onEvent, onError, onEnd }). It resolves to the same members as promises, plus close(). onEnd runs when the server ends the stream, such as on a host restart.

Channel wire protocol⁠

Each channel actor adds four RPCs to its RpcGroup. Every RPC carries the actor key and runs the caller gate.

RPCPayloadReply
<Actor>/channel{ key, presence }A stream that starts with Welcome, then Joined, Left, Presence, and Event messages
<Actor>/channel/members{ key }The list of current members
<Actor>/channel/presence{ connection, key, presence }void
<Actor>/channel/publish{ connection, event, key }void
MessageFieldsSent when
Welcomeconnection, membersThe connection joins. members includes the new connection.
JoinedmemberAnother connection joins.
LeftconnectionAnother connection’s stream ends.
PresencememberAnother connection sets its presence.
EventeventA turn commits a publish, or another connection publishes.

A member is { caller, connection, presence, principal }. caller is the caller kind, and principal is the caller’s principal. channelMessagesOf(channel) from @akterjs/effect/contract/channel returns the schemas of these messages.

Channel guarantees⁠

The host conformance suite checks three channel guarantees:

Hosts that serve channels⁠

Akter Cloud’s akterd answers every channel host call with unsupported today. A turn that reads members or publishes there stops with a defect. The in-memory test host in @akterjs/effect/testing serves channel calls, so Story, InMemoryRpc, and akter dev run channels.