Skip to content

HTTP bindings

An actor’s http slot binds an Effect HttpApiEndpoint to one of its own commands, queries, or jobs. A binding carries no handler. The endpoint’s one path parameter is the actor key, and the request body is the member’s input.

Serve an actor’s members over HTTP⁠

  1. Declare the bindings in ticket.contract.ts. Akter.http names a command, Akter.httpQuery names a query, and Akter.httpStream names a job that declares stream.
ticket.contract.ts
import { Schema } from "effect"
import { HttpApiEndpoint } from "effect/http-api"
import { Akter } from "@akterjs/effect/contract"

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

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

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

export const Closed = Schema.TaggedStruct("Closed", { notes: Schema.Array(Schema.String) })

export const Ticket = Akter.make("Ticket", {
  callers: [Agent],
  commands: {
    close: Akter.command({
      callers: [Agent],
      errors: [],
      from: [Open],
      input: Schema.Void,
      output: Schema.Void,
      to: [Closed],
    }),
  },
  final: [Closed],
  http: [
    Akter.http({
      callers: [Agent],
      command: "close",
      endpoint: HttpApiEndpoint.post("close", "/v1/tickets/:id/close", { params: { id: TicketId } }),
    }),
    Akter.httpQuery({
      callers: [Agent],
      endpoint: HttpApiEndpoint.get("notes", "/v1/tickets/:id/notes", { params: { id: TicketId } }),
      query: "notes",
    }),
    Akter.httpStream({
      callers: [Agent],
      endpoint: HttpApiEndpoint.post("draft", "/v1/tickets/:id/draft", { params: { id: TicketId } }),
      job: "draftReply",
    }),
  ],
  initial: { input: Schema.Struct({}), to: Open },
  jobs: {
    draftReply: Akter.job({
      errors: [],
      from: [Open],
      input: Schema.Struct({ prompt: Schema.String }),
      output: Schema.String,
      patches: [],
      stream: Schema.String,
      to: [Open],
    }),
  },
  key: TicketId,
  parent: Akter.Root,
  queries: {
    notes: Akter.query({
      callers: [Agent],
      errors: [],
      input: Schema.Void,
      output: Schema.Array(Schema.String),
      states: [Open, Closed],
    }),
  },
  states: [Open, Closed],
  tables: [],
})
  1. Emit chunks from the streamed job in draft-reply.job.ts. Ticket.jobs.draftReply.emit sends one chunk to the open stream. The job’s output lands in its result handler as a normal turn.
draft-reply.job.ts
import { Effect } from "effect"
import { Ticket } from "./ticket.contract.ts"

export const DraftReplyLive = Ticket.jobs.draftReply.toLayer(({ prompt }) =>
  Effect.gen(function* () {
    const words = ["Thanks", "for", "asking", "about", prompt]
    yield* Effect.forEach(words, (word) => Ticket.jobs.draftReply.emit(word))
    return words.join(" ")
  }),
)
  1. Implement the commands, the query, and the result handler in ticket.actor.ts. Compose the actor and the job into one layer.
ticket.actor.ts
import { Effect, Exit, Layer } from "effect"
import { Closed, Open, Ticket } from "./ticket.contract.ts"
import { DraftReplyLive } from "./draft-reply.job.ts"

const TicketLive = Ticket.toLayer({
  commands: {
    close: (open) => Effect.succeed({ next: Closed.make({ notes: open.notes }) }),
  },
  initial: () => ({ next: Open.make({ notes: [] }) }),
  queries: {
    notes: (ticket) => Effect.succeed(ticket.notes),
  },
  results: {
    draftReply: (open, exit) =>
      Effect.succeed({ next: Exit.isSuccess(exit) ? Open.make({ notes: [...open.notes, exit.value] }) : open }),
  },
})

export const TicketApp = Layer.mergeAll(TicketLive, DraftReplyLive)
  1. Send requests to the routes. Put the member’s input in the request body as JSON, and leave the body empty for Schema.Void. Send an Idempotency-Key header to retry a command under the same command ID.

Why a binding names a member instead of carrying a handler⁠

A route handler with its own logic would be a second way to change an actor. A binding only routes, so the member’s callers, from states, and errors still decide every outcome. akter verify, the type checker, and the lint rules see each route as the member it names.

Akter.httpStream checks in at the actor in one short step and then streams beside it. The actor keeps running commands while the stream is open. The job changes state only through <Actor>.turn and its result handler, like every other job.

Binding constructors⁠

ConstructorOptionsRuns
Akter.httpcallers, command, endpointThe named command, and replies with its output.
Akter.httpQuerycallers, endpoint, queryThe named query, and replies with its answer.
Akter.httpStreamcallers, endpoint, jobThe named job, and streams each chunk that the job emits.
  • callers: A non-empty list of the actor’s callers that may call the route. The member’s own callers list still applies.
  • endpoint: An HttpApiEndpoint with exactly one path parameter. The parameter’s schema is the actor’s key schema.
  • Method: Akter.http and Akter.httpStream need a POST, PUT, PATCH, or DELETE endpoint. Akter.httpQuery accepts any method, such as GET.
  • Target: command, query, and job are string names of members that the actor declares.
  • Stream: A job that an Akter.httpStream names declares a stream schema. Each emit call encodes one chunk with that schema.

Responses⁠

StatusMeaning
200The member succeeded. The body is its encoded output.
400The request is invalid, such as a body that the input schema rejects.
403The caller is not in the binding’s or the member’s callers list.
404The actor is not created, or no actor is registered for the route.
409The engine refused the call, such as a command in a state that from does not list.
422The member failed with one of its declared errors. The body is the encoded error.
500The member stopped with a defect. The body is a generic message that leaves out the defect.

An Akter.httpStream route answers with text/event-stream. Each chunk is one data: line, and the stream ends when the job settles.

InMemoryRpc.serve holds up to 1,024 unread chunks for each stream. A client that falls further behind loses the rest of the stream. The server sends the chunks it holds and then ends the response, and the job keeps running. A client that disconnects stops the forwarding at once, and the job keeps running.

What you can rely on⁠

  • One path parameter. The type checker rejects an endpoint with no path parameter, more than one, or one whose schema is not the actor key.
  • No state change on a safe method. The type checker rejects an Akter.http or Akter.httpStream endpoint that uses GET, HEAD, or OPTIONS. A browser sends these methods from any site without asking first. InMemoryRpc.serve fails with SafeMethodBindingError when such a binding gets past the type checker.
  • Declared targets. The type checker rejects a binding that names a member the actor does not declare. It also rejects an Akter.httpStream whose job declares no stream.
  • No inline handlers. The akter/declarative-bindings lint rule rejects a function or a computed name in any binding.
  • Streams step aside. Commands on the actor keep committing while an Akter.httpStream job streams (guarantees).
  • Replayed chunks. A job that resumes after a crash replays its journal. The stream skips each chunk key that it has already sent.
  • Reruns can mix attempts. An Activity attempt that crashes before the journal records it runs again with the same chunk keys. The stream skips the keys it already sent. So a non-deterministic activity can show its earlier chunks followed by the rerun’s later chunks.