Part 3: Events start the work
In Part 2 the Worker reported an issue and then started its session by hand. This part moves that decision into the board: a policy asks for an issue to be looked after whenever one is reported, and passes on every reply. The Worker then only turns GitHub’s events into commands.
Install
Section titled “Install”pnpm add https://pkg.alchemy.run/@alchemy.run/github/pr:3743:56b4873bun add https://pkg.alchemy.run/@alchemy.run/github/pr:3743:56b4873npm install https://pkg.alchemy.run/@alchemy.run/github/pr:3743:56b4873yarn add https://pkg.alchemy.run/@alchemy.run/github/pr:3743:56b4873Record a reply
Section titled “Record a reply”A reply on an issue is a third command:
import * as Domain from "@alchemy.run/domain";import * as Schema from "effect/Schema";import { IssueId } from "./Issue.id.ts";
export class IssueCommented extends Domain.Event("IssueCommented", { commentId: Schema.String, body: Schema.String,}) {}
export class CommentOnIssue extends Domain.Command("CommentOnIssue", { input: { issueId: IssueId, commentId: Schema.String, body: Schema.String }, events: [IssueCommented], rejects: [],}) {}Take it on the aggregate
Section titled “Take it on the aggregate”import * as Schema from "effect/Schema";import { CommentOnIssue, IssueCommented } from "./CommentOnIssue.command.ts";import { IssueId } from "./Issue.id.ts";
commands: [ReportIssue, LabelIssue], commands: [ReportIssue, LabelIssue, CommentOnIssue],
LabelIssue: (_, command) => [new IssueLabeled({ label: command.label })], CommentOnIssue: (_, command) => [ new IssueCommented({ commentId: command.commentId, body: command.body }), ],
IssueLabeled: (issue) => issue, IssueCommented: (issue) => issue,Show replies on the issue
Section titled “Show replies on the issue”import { Label } from "./LabelIssue.command.ts";
label: Schema.NullOr(Label), comments: Schema.Array(Schema.String), }), initial: { title: "", body: "", label: null }, initial: { title: "", body: "", label: null, comments: [] }, evolve: { IssueReported: (detail, event) => ({ ...detail, title: event.title, body: event.body }), IssueLabeled: (detail, event) => ({ ...detail, label: event.label }), IssueCommented: (detail, event) => ({ ...detail, comments: [...detail.comments, event.body], }), },Say what the board asks for
Section titled “Say what the board asks for”The board should not know that a model does this work. It declares what it asks of whatever does: start on an issue, and pass on what was said about it.
import * as Domain from "@alchemy.run/domain";import * as Schema from "effect/Schema";import { IssueId } from "./Issue.id.ts";
export class Triager extends Domain.ExternalSystem("Triager", { start: { args: { issue: IssueId } }, tell: { args: { issue: IssueId, text: Schema.String, id: Schema.String } },}) {}See External systems.
Ask for it when an issue is reported
Section titled “Ask for it when an issue is reported”A policy reacts to events. IssueWork hands each reported issue to the triager:
import * as Domain from "@alchemy.run/domain";import * as Effect from "effect/Effect";import * as Match from "effect/Match";import { Issue } from "./Issue.aggregate.ts";import { IssueReported } from "./ReportIssue.command.ts";import { Triager } from "./Triager.external.ts";
export class IssueWork extends Domain.Policy("IssueWork", { from: Issue, on: [IssueReported],}) {}
export const IssueWorkLive = IssueWork.toLayer( Effect.gen(function* () { const triager = yield* Triager; return Effect.fn(function* ({ source, event }) { yield* Match.valueTags(event, { IssueReported: () => triager.start({ issue: source.id }), }); }); }),);Pass replies on
Section titled “Pass replies on”import * as Match from "effect/Match";import { IssueCommented } from "./CommentOnIssue.command.ts";import { Issue } from "./Issue.aggregate.ts";
on: [IssueReported], on: [IssueReported, IssueCommented],
IssueReported: () => triager.start({ issue: source.id }), IssueCommented: ({ body, commentId }) => triager.tell({ issue: source.id, text: `A reply on the issue: ${body}`, id: commentId }),The reply’s id goes with it, so the triager can tell a reply it has already seen.
Add the policy to the model
Section titled “Add the policy to the model”import { IssueDetail } from "./IssueDetail.view.ts";import { IssueWork } from "./IssueWork.policy.ts";
views: [IssueDetail], policies: [IssueWork],Say what an issue’s object answers
Section titled “Say what an issue’s object answers”The triager will be the Durable Object of each issue. Write down what one answers, and what the objects are, as plain types:
import * as PiCloudflare from "@alchemy.run/pi/Cloudflare";import type { RuntimeContext } from "alchemy/RuntimeContext";import * as Effect from "effect/Effect";
import { Triage } from "./Triage.process.ts";
interface Agent { readonly start: (issue: IssueId) => Effect.Effect<void, never, RuntimeContext>; readonly tell: ( issue: IssueId, text: string, id: string, ) => Effect.Effect<void, never, RuntimeContext>;}
interface Agents { readonly getByName: (issue: string) => Agent;}Host the board over the objects
Section titled “Host the board over the objects”The board is hosted in two places: in the Worker, and in each object, so a session can reach it. Both need a triager, and both have a handle on the objects. boardOver takes that handle. It replaces src/Board.ts, which you can delete.
import * as Cloudflare from "@alchemy.run/cloudflare";import * as DomainCloudflare from "@alchemy.run/domain/Cloudflare";import * as Pi from "@alchemy.run/pi";
import { BoardLive } from "./Board.ts";import { Board } from "./Board/Board.model.ts";import type { IssueId } from "./Board/Issue.id.ts";import { IssueWorkLive } from "./Board/IssueWork.policy.ts";import { Triager } from "./Board/Triager.external.ts";
interface Agents { readonly getByName: (issue: string) => Agent;}
const boardOver = <R>(agents: Effect.Effect<Agents, never, R>) => Board.layer(IssueWorkLive).pipe( Layer.provide( Layer.mergeAll( DomainCloudflare.layerDurableObjects(), Triager.toLayer( Effect.map(agents, (agents) => ({ start: ({ issue }) => agents.getByName(issue).start(issue), tell: ({ issue, text, id }) => agents.getByName(issue).tell(issue, text, id), })), ), ), ), );Triager.toLayer is the adapter: each thing the board asks becomes a call to the object named after the issue.
Give an object the board
Section titled “Give an object the board”Inside an object, the handle on the objects is its own namespace:
const HarnessLive = Pi.HarnessLive.pipe(Layer.provide(PiCloudflare.DurableObjectStorage));
const Live = Layer.mergeAll(HarnessLive, AI.DefaultModel(Smart), BoardLive).pipe(const own = Effect.map( Cloudflare.DurableObjectScope, (self) => self as Cloudflare.DurableObject<Agent>,);
const Live = Layer.mergeAll(HarnessLive, AI.DefaultModel(Smart), boardOver(own)).pipe( Layer.provide(SmartLlama),);Answer the board
Section titled “Answer the board”The object answers start and tell:
export default class IssueAgents extends Cloudflare.DurableObject<IssueAgents>()( return Effect.succeed({ start: (issue: IssueId) => start: (issue) => triage .get(issue) .send(`The issue is ${issue}.`, { requestId: "start" }) .pipe(Effect.orDie), }); tell: (issue, text, id) => triage.get(issue).send(text, { requestId: id }).pipe(Effect.orDie), } satisfies Agent);send returns once the message is stored, so the policy never waits for a model. requestId keeps a message from reaching the session twice: a policy can run more than once for one event.
Using a session requires the runtime context, which is why Agent says so. A policy’s handler and an external system’s operations carry the same requirement, so the call type-checks all the way from the board to the session.
Export the board for the Worker
Section titled “Export the board for the Worker”Outside the objects, the handle on them is the class:
}).pipe(Effect.provide(Live)),) {}
export const BoardLive = boardOver(IssueAgents);Tell the session about replies
Section titled “Tell the session about replies” ${Board.LabelIssue}: bug when something is broken, feature when something new is asked for, question otherwise.
Later messages are replies on the issue. Send ${Board.LabelIssue} again when a reply changes what kind of issue it is.` {}Declare the repository
Section titled “Declare the repository”import * as GitHub from "@alchemy.run/github";
export const owner = "my-org";export const repository = "issue-board";
export const Repo = GitHub.Repository("Repo", { owner, name: repository, visibility: "public", autoInit: true,});Turn GitHub’s events into commands
Section titled “Turn GitHub’s events into commands”GitHub.consumeRepositoryEvents registers a webhook on the repository and verifies each delivery. An opened issue is reported, and a reply is recorded:
import * as GitHub from "@alchemy.run/github";import * as Effect from "effect/Effect";import * as Match from "effect/Match";import { CommentOnIssue } from "./Board/CommentOnIssue.command.ts";import { Issue } from "./Board/Issue.aggregate.ts";import { IssueId } from "./Board/Issue.id.ts";import { ReportIssue } from "./Board/ReportIssue.command.ts";import { owner, repository } from "./Repo.ts";
export const GitHubIssues = Effect.gen(function* () { const issues = yield* Issue;
yield* GitHub.consumeRepositoryEvents( { owner, repository, events: ["issues", "issue_comment"] }, Effect.fn(function* (event) { const issueId = IssueId.make(String(event.payload.issue.number)); const once = { commandId: event.id }; yield* Match.value(event).pipe( Match.when({ name: "issues", payload: { action: "opened" } }, ({ payload }) => issues.send( new ReportIssue({ issueId, title: payload.issue.title, body: payload.issue.body ?? "", }), once, ), ), Match.when({ name: "issue_comment", payload: { action: "created" } }, ({ payload }) => issues.send( new CommentOnIssue({ issueId, commentId: String(payload.comment.id), body: payload.comment.body, }), once, ), ), Match.orElse(() => Effect.void), ); }, Effect.orDie), );});GitHub’s delivery id is the command id, so a delivery that arrives twice changes nothing. Nothing in this file knows a process exists.
Serve the events from the Worker
Section titled “Serve the events from the Worker”The Worker no longer starts sessions. It consumes the events and shows the board:
import * as Cloudflare from "@alchemy.run/cloudflare";import * as GitHub from "@alchemy.run/github";import * as Effect from "effect/Effect";import { HttpServerRequest } from "effect/http/HttpServerRequest";import * as HttpServerResponse from "effect/http/HttpServerResponse";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import { BoardLive } from "./Agents.ts";import { Issue } from "./Board/Issue.aggregate.ts";import { IssueId } from "./Board/Issue.id.ts";import { IssueDetail } from "./Board/IssueDetail.view.ts";import { GitHubIssues } from "./GitHubIssues.ts";
const Live = Layer.mergeAll(BoardLive, GitHub.RepositoryEventSourceLive);
export default class Worker extends Cloudflare.Worker<Worker>()( "Worker", { main: import.meta.url }, Effect.gen(function* () { const details = yield* IssueDetail; yield* GitHubIssues;
return { // GET /issues/<number> shows the issue as the board has it. fetch: Effect.gen(function* () { const request = yield* HttpServerRequest; const [, area, number] = new URL(request.url, "http://board").pathname.split("/"); if (area !== "issues" || number === undefined) { return HttpServerResponse.text("not found", { status: 404 }); } const detail = yield* details.get(Issue.ref(IssueId.make(number))); return yield* HttpServerResponse.json(Option.getOrNull(detail)); }).pipe(Effect.orDie), }; }).pipe(Effect.provide(Live)),) {}Add the repository to the Stack
Section titled “Add the repository to the Stack”import * as DomainCloudflare from "@alchemy.run/domain/Cloudflare";import * as GitHub from "@alchemy.run/github";import * as Alchemy from "alchemy";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import { Repo } from "./src/Repo.ts";import Worker from "./src/Worker.ts";
providers: Layer.mergeAll(Cloudflare.providers(), DomainCloudflare.providers()), providers: Layer.mergeAll( Cloudflare.providers(), DomainCloudflare.providers(), GitHub.providers(), ),
Effect.gen(function* () { const repo = yield* Repo; const worker = yield* Worker; return { url: worker.url }; return { url: worker.url, repository: repo.htmlUrl }; }),pnpm alchemy deploybun alchemy deploynpx alchemy deployyarn alchemy deployTry it
Section titled “Try it”Open an issue on the repository, then read it from the board:
gh issue create -R my-org/issue-board --title "The build fails on Windows" --body "npm run build exits with code 1."
curl "$URL/issues/1"# {"title":"The build fails on Windows","body":"npm run build exits with code 1.","label":"bug","comments":[]}Reply on the issue that it was your own mistake, and the label changes to question.
What you have
Section titled “What you have”- A board that says what it asks for, and a policy that asks.
- An object for each issue that answers, by starting its session or sending it a message.
- GitHub’s events as commands, with no knowledge of processes.
The session labels an issue it has never read the code for. Part 4 gives it the repository and lets it answer.