Skip to content

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.

Terminal window
pnpm add https://pkg.alchemy.run/@alchemy.run/github/9c58f00

A reply on an issue is a third command:

src/Board/CommentOnIssue.command.ts
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: [],
}) {}
src/Board/Issue.aggregate.ts
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,
src/Board/IssueDetail.view.ts
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],
}),
},

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:

src/Board/IssueWork.policy.ts
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.

src/Board/IssueWork.policy.ts
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.

src/Board/Board.model.ts
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],
}) {}

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:

src/Triage.process.ts
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.

The board reads its policy as it loads, so it takes its members as a thunk too:

src/Board/Board.model.ts
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.

Board.layer takes what the board’s policies do:

src/Sessions.ts
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.

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:

src/Sessions.ts
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.

src/Triage.process.ts
${() => 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.
`;
src/Repo.ts
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,
});

GitHub.consumeRepositoryEvents registers a webhook on the repository and verifies each delivery. An opened issue is reported, and a reply is recorded:

src/GitHubIssues.ts
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.

The Worker no longer starts sessions. It consumes the events and shows the board:

src/Worker.ts
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)),
) {}
alchemy.run.ts
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 };
}),
Terminal window
pnpm alchemy deploy

Open an issue on the repository, then read it from the board:

Terminal window
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.

  • 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.