Skip to content

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.

Terminal window
pnpm add https://pkg.alchemy.run/@alchemy.run/github/pr:3743:56b4873

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],
}),
},

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.

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

A policy reacts to events. IssueWork hands each reported issue to the triager:

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 { 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 }),
});
});
}),
);
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],
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.

src/Board/Board.model.ts
import { IssueDetail } from "./IssueDetail.view.ts";
import { IssueWork } from "./IssueWork.policy.ts";
views: [IssueDetail],
policies: [IssueWork],

The triager will be the Durable Object of each issue. Write down what one answers, and what the objects are, as plain types:

src/Agents.ts
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;
}

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.

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

Inside an object, the handle on the objects is its own namespace:

src/Agents.ts
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),
);

The object answers start and tell:

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

Outside the objects, the handle on them is the class:

src/Agents.ts
}).pipe(Effect.provide(Live)),
) {}
export const BoardLive = boardOver(IssueAgents);
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 { 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)),
) {}
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 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.