Skip to content

Streams and rooms

Keep an extension UI current with a one-way stream of the repo's events, or let its users work together in a room.

Updated

An extension UI can stay current without polling. It has two realtime modes, and a page uses whichever it needs:

Mode Direction What the page gets Extension code on the path
Stream One way Every event of the repo it asks for, in order, as each write commits None
Room Both ways Messages between the people on the page, each one’s state, and the repo events the room follows The room’s handlers, when it declares any

Both read one event log per repo. Every write appends its events in the same transaction as the change, so an event exists exactly when its change does, and the log numbers its events in the order their writes committed.

The log keeps each repo’s newest 10,000 events. It’s how changes reach a page, not their history: commits and record versions are the history. A stream or a room that falls behind the oldest event that the log keeps gets a gap instead of what it missed, and the page reads what it shows afresh.

Events in the log

The engine appends these events itself:

Type When Data
records.changed A working write of a branch: records created, updated, or deleted branch, table, idPrefix, and changes, each a recordId and its operation. A write of more than 1,000 records sends count and truncated: true instead of changes
branch.advanced A commit, a merge, or a fast-forward of a branch branch, fromCommitId, toCommitId, and kind: commit, merge, or fast_forward
repo.member_removed A member leaves the repo userId
repo.share_revoked A public share of one of the repo’s extension UIs is revoked share
repo.policies_changed An org policy, or one of the repo’s policies, changes none

An extension adds its own with ctx.events.publish, from a tool or a workflow step. An event named pricing.progress in the extension integrations.estimates, named by its repo’s slug and its own name, has the type ext.integrations.estimates.pricing.progress:

// index.ts, inside a workflow step
await s.events.publish("pricing.progress", { estimateId, step: i + 1, of: n }, { branch: "main" });

Name the branch the event is about when it’s about one, so a stream that follows that branch keeps it. An event without a branch is about the whole repo, and every stream keeps it.

Publishing an event takes the update action on the extension, and so does broadcasting into a room from a tool or a workflow step. Neither the default Editor policy nor an extension’s built-in policy grants it. So a tool that a member without it calls, and a schedule’s run, reject with Forbidden at the publish until an org policy allows update on the extension. A room’s handlers broadcast without it.

Streams

A stream is the cheapest way for a page to hear about changes. The Forge server pushes each event to the page’s socket as soon as the write commits, with no other object and no extension code in between.

// ui/web/main.ts
import { context, stream } from "@buildr/sdk/client";

const feed = stream({
  types: ["records.changed", "branch.advanced", "ext.integrations.estimates.*"],
  branch: context.branch,
});

feed.on("event", (event) => {
  // { seq, type, branch, data, actorId, at }
  if (event.type === "records.changed") reloadEstimates();
});
feed.on("gap", () => reloadEverything());
feed.on("status", (status) => showStatus(status)); // connecting | open | reconnecting | closed

for await (const event of feed) console.log(event.seq, event.type);
  • types: Each entry is a type, or a prefix ending in *. Without types, the stream keeps every type.
  • branch: Keeps events about that branch and events about no branch. Without it, the stream keeps every branch’s events.
  • since: Starts after an event that an earlier stream delivered. A stream that reconnects resumes after the last event it delivered, so event sees each event once, in order, across reconnects.
  • for await: Yields each event as it arrives, and ends once the stream closes, after the events the stream delivered before it closed. A loop that breaks closes the stream.
  • gap: Fires when a resumed stream asks for events older than the log keeps. Read what the page shows afresh.

Rooms

A room is a realtime space that the people on a page share, one per set of params, such as one per branch or one per estimate. An extension declares its rooms in index.ts, and a page joins one with rooms.<name>.join(params).

// index.ts
import { branchEvents, defineExtension, object, ownEvents, room, string } from "@buildr/sdk";
import type { RoomConnection } from "@buildr/sdk";

const board = room({
  params: object({ branch: string() }),
  message: object({ kind: string(), text: string().optional() }),
  follows: ({ branch }) => [branchEvents(branch), ownEvents()],

  async onConnect(conn, ctx) {
    conn.setState({ name: nameOf(conn), cursor: null });
    ctx.room.broadcast({ kind: "system", text: `${nameOf(conn)} joined` }, { without: [conn.id] });
  },
  async onMessage(conn, message, ctx) {
    ctx.room.broadcast({ kind: "chat", text: message.text ?? "", by: nameOf(conn) });
  },
  async onEvent(event, ctx) {
    ctx.room.broadcast({ kind: "activity", type: event.type });
  },
  async onClose(conn, ctx) {
    ctx.room.broadcast({ kind: "system", text: `${nameOf(conn)} left` });
  },
});

// A member's name, or "A guest" for a public share's guest, who has none.
const nameOf = (conn: RoomConnection) =>
  conn.principal.kind === "member" ? conn.principal.name : "A guest";

export default defineExtension({}, { rooms: { board } });
// ui/web/main.ts
import { context, rooms } from "@buildr/sdk/client";

const board = rooms.board.join({ branch: context.branch });
board.on("message", ({ from, data }) => render(from, data)); // from is null for the room's own
board.on("connections", (connections) => drawCursors(connections)); // everyone's state
board.on("event", (event) => refetch(event)); // a followed event, when the room has no onEvent
board.on("gap", () => refetchEverything()); // the room missed events the log no longer keeps
board.send({ kind: "chat", text: "On it" });
board.setState({ name: "Ada", cursor: { x: 0.4, y: 0.2 } });

What a room declares

  • params: What names one room. Every page of the same UI on the same branch that joins with equal params is in the same room, whichever build of the extension served it. A branch’s page never shares a room with the main branch’s page, so a branch’s handlers never act for the people on the main branch. Params that don’t fit refuse the join.
  • message: What a page may send. A message that doesn’t fit never reaches onMessage, and the sender gets an error.
  • follows: The repo events the room hears: branchEvents(branch) for a branch’s records.changed and branch.advanced, and ownEvents() for what the extension publishes. A room always hears its own broadcasts.
  • state: The type of the room’s own state, which ctx.room.setState checks and ctx.room.state reads. See Room state and alarms.
  • connectionState: The type of each connection’s state, which conn.setState checks.

Handlers

Each handler is optional. A room without handlers runs no extension code: it relays each message to every other connection, naming its sender, and hands each followed event to every connection.

Handler Runs Without it
onConnect(conn, ctx) Each time a connection’s page connects: when it joins, and when it reconnects Nothing runs
onMessage(conn, message, ctx) For each message a connection sends The room relays the message to everyone else
onEvent(event, ctx) For each event the room follows The room hands the event to every connection
onClose(conn, ctx) Once a connection leaves: its page closes the room, or its socket drops and doesn’t come back within 15 seconds Nothing runs
onAlarm(ctx) When the alarm that ctx.room.setAlarm set goes off, also with no one in the room Nothing runs

A handler works through what it’s given:

  • conn.principal: Who holds the connection: { kind: "member", userId, name }, or { kind: "guest" } for a public share’s guest, who signs in as no one and is known only by conn.id.
  • conn.setState(state): Sets the connection’s state, which every connection sees in connections. A page sets its own state with setState, which runs no handler, so cursors and presence cost no extension code. A state that connectionState refuses, or one larger than 16 KB as JSON, throws in the handler. Connection state lives only on the server that runs the room, so it starts over when the room moves to another server.
  • conn.send(data) and conn.close(code, reason): Reach that connection alone. A close code is 1000, or 3000 through 4999.
  • ctx.room.broadcast(data, { without }): Reaches every connection except those named in without.
  • ctx.room.connections() and ctx.room.getConnection(id): Read who is in the room.
  • ctx.room.state and ctx.room.setState(state): Read and replace the room’s own state.
  • ctx.room.alarm and ctx.room.setAlarm(at): Read and set the room’s one alarm, which runs onAlarm.
  • ctx.forge: Calls Forge as whoever holds the connection the handler runs for, with exactly the access that holder’s page has, without waiting. For a guest, that’s only the installation’s tools that the org’s policies open to guests. A call answers nothing: the room sends it once the handler has returned, so the next message runs at once. See Calling Forge from a room.
  • ctx.waitForForge: Makes the same calls as the same member and answers each one, while the handler, and every message behind it, waits. Use it only for what the handler can’t do without, such as reading the state a room rebuilds from.

send returns true once the room has the message. While the room connects or reconnects, send returns false and the message goes nowhere, so a page that must not lose one sends it again when status returns to open. setState needs no resend: a room that reconnects sets the page’s newest state again.

A page that reconnects resumes its connection. conn.id and the page’s connectionId stay the same, the connection keeps its state, and the room runs onConnect again, but not onClose, and the other pages see no left and no new connection. So a room can key what a player holds, such as a seat, by conn.id, and the player keeps it through a dropped socket. Until it comes back, the connection stays in connections and ctx.room.connections(), for pages that join meanwhile too, but nothing sent reaches it. A connection whose socket drops and doesn’t come back within 15 seconds leaves then, and onClose runs. A connection leaves at once when its page calls close or the room refuses it. A reloaded page, or another join, is a new connection.

Connections live only on the server that runs the room. When the room moves to another server, as on a deploy or when its server fails, every page gets code 1012 and rejoins as a new connection: onConnect runs again, each connection’s state starts over, and onClose doesn’t run for a connection whose page never comes back. Keep what must outlast that, such as who holds a seat, in ctx.room.state.

A page that reconnects to a room is sent what it missed of what the room hands every connection unchanged: tools’ broadcasts, and the events the room follows when it has no onEvent. A handler’s own messages, including what onEvent made of an event, go out once, live. A page that shows them reads its state afresh when the room’s status returns to open.

A room fires gap when what it missed is older than what the log keeps: on a page that reconnects from before the oldest event that the log still holds, and on every page when the room itself fell that far behind. When the room fell behind, it also closes every connection with code 1012, and each page rejoins at once, so the room checks each member against the repo again. The rejoined page’s replay starts with the gap. Read what the page shows afresh.

A room runs one handler at a time, and applies what each one asked for in order once it returns, so the room sees its messages in the order they arrived. Handlers run in the extension’s sandbox. Its module memory is a cache that the room may lose between any two handlers, so keep what the room must remember in ctx.room.state. A room’s sandbox has no network: it reaches Forge only through ctx.forge and ctx.waitForForge. Each handler may run for 10 seconds.

When a new build publishes

A room runs one build of the extension at a time. A UI serves a new build when a commit to its branch publishes one, or when its repo installs another version. The first page that joins on the new build moves the room to it: the room closes every connection of the old build with code 4410, joins the new build, and runs only the new build’s handlers from then on. Two rooms with the same params never run side by side.

A page’s code comes from its build, so a page on the old build can’t stay: its messages have the old build’s shape, and the room refuses it. A page learns that its build was replaced when the room closes it, or by itself: an open room asks every minute which build its UI serves. Either way the room’s status becomes superseded, and the room doesn’t reconnect. With no superseded listener, the client reloads the page, which loads the new build and joins the room again. A page that mustn’t reload in the middle of something listens, and reloads when it’s ready:

board.on("superseded", () => {
  showBanner("A new version is ready");
  finishTurn().then(() => location.reload());
});

What the old build’s handlers kept in module memory goes with its sandbox, as it does whenever a room’s sandbox is replaced. ctx.room.state stays, so the new build’s handlers read it, as the new build’s state type decodes it: a saved state that type refuses reads as null.

Room state and alarms

ctx.room.state is the room’s storage. ctx.room.setState(state) replaces it, and the handler reads the new state at once. The room saves it before any message of that handler goes out, so it survives a new build, a deploy, and a server that fails over, as module memory doesn’t. It is null until a handler sets it. A state that the room’s state type refuses, or one larger than 64 KB as JSON, throws in the handler. Keep larger data in records. A room that no page joins for 30 days is deleted with its state and alarm, however often its alarm ran meanwhile; keep what must outlast that in records.

ctx.room.setAlarm(at) sets the room’s one alarm, at a Date or a time in epoch milliseconds, and replaces any other; null clears it. The room runs onAlarm when it goes off, whether or not anyone is in the room, and keeps the alarm through deploys and a server that fails: an alarm stays set until a run of onAlarm is saved, so one that a failing server cut short runs again. An onAlarm that throws clears its alarm and saves nothing it set, so a handler that wants another try catches the error, sets the alarm again, and returns normally. An alarm less than 10 seconds ahead goes off 10 seconds ahead. ctx.room.alarm reads the alarm set, or null.

const auction = room({
  params: object({ lot: string() }),
  message: object({ bid: number() }),
  state: object({ high: number(), endsAt: number() }),

  async onMessage(conn, message, ctx) {
    const endsAt = ctx.room.state?.endsAt ?? Date.now() + 60_000;
    if (message.bid <= (ctx.room.state?.high ?? 0)) return conn.send({ refused: message.bid });
    ctx.room.setState({ high: message.bid, endsAt });
    ctx.room.setAlarm(endsAt);
    ctx.room.broadcast({ high: message.bid });
  },
  async onAlarm(ctx) {
    ctx.room.broadcast({ sold: ctx.room.state?.high ?? null });
  },
});

A page built with a @buildr/sdk from before rooms moved between builds takes the 4410 close as a refusal: it emits error, sets status to closed, and stays closed until someone reloads it.

Calling Forge from a room

A room runs one handler at a time, so a handler that waits on Forge holds up every message behind it. That is why a room handler’s ctx.forge, unlike a tool’s, queues its calls and answers nothing. A room that saves as it goes, such as a game that commits its state every few seconds, writes without slowing anyone down:

async onMessage(conn, message, ctx) {
  const save = game.advance(message);
  if (save !== undefined) {
    const branch = `games/${ctx.room.params.game}`;
    ctx.forge.customRecords.upsertRepoCustomRecords({
      repo_id: ctx.repo.id,
      branch,
      model_api_name: "rail__train",
      match_on: "key",
      body: { records: save.trains },
    });
    ctx.forge.commits.createRepoCommit({
      repo_id: ctx.repo.id,
      branch,
      body: { message: `Month ${save.month}` },
    });
  }
  ctx.room.broadcast(game.events());
}
  • Order: The room sends one handler’s calls in the order it made them, one at a time, and every earlier handler’s calls before them. A save never lands after a later one.
  • Failure: A call that fails skips the rest of its handler’s calls, which may depend on it, such as a commit after its writes. The room tells the connection the handler ran for with an error, if it is still open. Nothing retries, so a handler that must know a write landed awaits it with ctx.waitForForge. A room acts with the access token its member joined with. An OAuth access token expires, and the room closes its socket with 1012 once it has, so its client rejoins with a fresh one. A page’s token lasts as long as its session, and a call refused because that session ended stays failed. Either way, keep what a later save needs in ctx.room.state or records, not only in the lost call.
  • Limits: A handler may queue 50 calls. Its input must be JSON, which the call checks at once, so a bad input throws in the handler.
  • Who calls: A handler that runs for a connection calls Forge as that connection’s member, or as the extension’s guest for a share’s guest. onEvent, onAlarm, and the onClose of a connection whose socket never came back run for no connection, so they call Forge as the extension itself, as its schedules and triggers do: under its built-in policy, with its own tools and its peers’ and no other extension’s. The room sends their queued calls the same way, once, after the turn’s state is saved, and a failure reaches no page.

A handler that needs an answer waits for it with ctx.waitForForge, which takes the same operations and answers as a tool’s ctx.forge:

const branch = await ctx.waitForForge.branches.getRepoBranch({ repo_id: ctx.repo.id, branch: "main" });

Broadcasting from tools and workflows

A tool or a workflow step reaches a room with ctx.rooms.<name>(params).broadcast(data). Every connection in a room with those params gets the broadcast as a message whose from is null, whichever UI and branch its page is on:

const announce = tool(
  { description: "Announces something on a branch's board", input: object({ branch: string(), text: string() }) },
  (ctx, { branch, text }) => ctx.rooms.board({ branch }).broadcast({ kind: "announcement", text }),
);

Guests from a public share

A public share of an installation’s UI lets its guests join that UI’s rooms, beside its members, once an org policy lets the extension’s guests join the room. No built-in policy does, so every room starts closed to guests:

import { orgPolicy, allow, extension, room } from "@forge/policies";

export const guestsVisitTheLobby = orgPolicy({
  name: "Guests visit the lobby",
  principals: [extension("integrations.lobby")],
  statements: [
    allow({
      actions: ["join"],
      resource: room("integrations.lobby/lobby"),
      when: ({ request }) => request.principal === "guest",
    }),
  ],
});

rooms("integrations.lobby") names every room of an extension, and allRooms every room. A policy names a room by an identifier, so a room whose name isn’t one never admits guests. A guest in a room is held apart from what only members see:

  • Who’s there: A guest’s page sees each member as { kind: "member", userId: null, name: null }. A member’s page that wants to show its name to guests sets it in its own state. Members and handlers see a guest as { kind: "guest" }.
  • Events: A guest hears the room’s broadcasts and what handlers send it, but never a followed event as the log wrote it, whose data can name members and records. A room that wants guests to hear about changes says so from onEvent.
  • Calls: A handler that runs for a guest’s connection calls Forge as the extension’s guest, as the share’s page does. It may call only the installation’s own tools, through callRepoExtensionInstallationTool, and only those that an org policy opens to guests. Each call counts against the guest’s rate limit for the share.
  • Revoking: Every guest join checks the share and the policies. As a member’s removal closes their sockets, a repo.share_revoked event closes that share’s guests with 4404, and a repo.policies_changed event asks every guest to rejoin with 1012, so each rejoin checks the policies again and one they now refuse closes with 4403.

A guest has no stream.

Who may connect

A page opens a stream or joins a room as the member its UI signs in, or a room as a public share’s guest, and only from its own address. Each connect asks Forge for a short-lived socket ticket first, which @buildr/sdk/client does for you. A stream or a room that the page is refused closes with a code from 4400 through 4499 and a reason: 4401 for a ticket that doesn’t hold, 4403 for a member who can’t read the repo, and 4422 for a join the room refused or params that don’t fit. The client emits the reason as an error, sets status to closed, and stops reconnecting. A room also closes with 4410 when a newer build replaced the page’s, which sets status to superseded instead. See When a new build publishes. When a member leaves the repo, their open streams and rooms close with code 4403.

The client pings each socket every 30 seconds. When two pings in a row go unanswered, the connection is gone, and the client reconnects.

Reading the log without a page

Any client reads the same log a page at a time, after a cursor, as an agent or a script might:

forge events list-events --repo "$REPO" --types "ext.integrations.estimates.*" --branch main --after-seq 120

GET /repos/:repo_id/events?after_seq=&types=&branch= answers the page’s events, latest_seq, the cursor to pass as after_seq to read on, and oldest_seq, the oldest event that the log still keeps. When after_seq is below oldest_seq - 1, the log no longer holds some of the events after it: read state afresh, then read on from latest_seq. forge events publish-extension-event and forge events create-extension-room-broadcast publish an extension’s event and broadcast into one of its rooms.

Type to search…

↑↓ navigate↵ selectEsc close