Part 3: Events start the work
In Part 2 the Worker reported an issue and then sent its session a message by hand. This part moves that decision into the board: a policy hands an issue to its session 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/9c58f00bun add https://pkg.alchemy.run/@alchemy.run/github/9c58f00npm install https://pkg.alchemy.run/@alchemy.run/github/9c58f00yarn add https://pkg.alchemy.run/@alchemy.run/github/9c58f00Record 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], }), },Hand a reported issue to its session
Section titled “Hand a reported issue to its session”A policy reacts to events. Inside it, yield* Triage gives the process’s client, the same one the Worker had, and get reaches the session of the issue:
import * as Domain from "@alchemy.run/domain";import * as Effect from "effect/Effect";import * as Match from "effect/Match";import { Triage } from "../Triage.process.ts";import { Issue } from "./Issue.aggregate.ts";import { IssueReported } from "./ReportIssue.command.ts";
export class IssueWork extends Domain.Policy("IssueWork", { from: Issue, on: [IssueReported],}) {}
export const IssueWorkLive = IssueWork.toLayer( Effect.gen(function* () { const triage = yield* Triage; return ({ source, event }) => Match.valueTags(event, { IssueReported: () => triage.get(source.id).send(`The issue is ${source.id}.`, { requestId: "start" }), }).pipe(Effect.orDie); }),);The process is not a member of the board, and the board’s policy uses it all the same: IssueWorkLive requires Triage. send returns once the message is stored, so the policy never waits for a model. A policy can run more than once for one event, and requestId keeps the message from reaching the session twice.
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],
triage.get(source.id).send(`The issue is ${source.id}.`, { requestId: "start" }), IssueCommented: ({ body, commentId }) => triage .get(source.id) .send(`A reply on the issue: ${body}`, { requestId: commentId }),The reply’s id is the message’s, so a reply delivered twice is read once.
Add the policy to the board
Section titled “Add the policy to the board”import { IssueDetail } from "./IssueDetail.view.ts";import { IssueWork } from "./IssueWork.policy.ts";
export class Board extends Domain.Model("Board", { aggregates: [Issue], views: [IssueDetail], policies: [IssueWork],}) {}Break the import cycle in the prose
Section titled “Break the import cycle in the prose”The files now import each other in a circle: the prose imports the board, the board imports the policy, and the policy imports Triage. Whichever loads first reads another before it exists. A thunk delays the read until it is used:
import { Board } from "./Board/Board.model.ts";
Get the issue with ${Board.IssueDetail}: its key is the issue. Then send ${Board.LabelIssue}: bug when something is broken, feature when something new is asked for, question otherwise. Get the issue with ${() => Board.IssueDetail}: its key is the issue. Then send ${() => Board.LabelIssue}: bug when something is broken, feature when something new is asked for, question otherwise.The prose reads the board when a session first runs, once every file has loaded.
Give the board its members as a thunk
Section titled “Give the board its members as a thunk”The board reads its policy as it loads, so it takes its members as a thunk too:
import { IssueWork } from "./IssueWork.policy.ts";
export class Board extends Domain.Model("Board", {export class Board extends Domain.Model("Board", () => ({ aggregates: [Issue], views: [IssueDetail], policies: [IssueWork],}) {}})) {}With both lazy, the files load in any order. The board’s type is the same as before. Break the cycle with thunks says when a declaration needs one.
Give the board its policy
Section titled “Give the board its policy”Board.layer takes what the board’s policies do:
import { Board } from "./Board/Board.model.ts";import { IssueWorkLive } from "./Board/IssueWork.policy.ts";import { Smart, SmartLlama } from "./Models.ts";
export const BoardLive = Board.layer(Layer.empty).pipe(const BoardLive = Board.layer(IssueWorkLive).pipe( Layer.provide(DomainCloudflare.layerDurableObjects()),);The policy holds Triage, so BoardLive now needs one. It is no longer exported: on its own it is incomplete.
Give the board its process
Section titled “Give the board its process”The sessions need the board and the board needs the sessions. TriageSessions already takes the board. Provide it back to the board, and export the two together:
export const TriageSessions = AICloudflare.ProcessSessions(const TriageSessions = AICloudflare.ProcessSessions( TriageLive.pipe(Layer.provide(Layer.mergeAll(Harness, BoardLive))),);
export const Live = BoardLive.pipe(Layer.provideMerge(TriageSessions));The host closes the loop: the Layer it is given may need the process it provides, and the host supplies it, inside each session’s object and outside. The policy and the session each run in an object of their own. The policy’s call to session.send is a call from one to the other, and neither file says so.
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 { 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";import { Live as BoardLive } from "./Sessions.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 policy that hands each issue to its session, and passes replies on.
- A board and a process that use each other by name: the policy holds the process’s client, and the prose mentions the board.
- 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.