Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions plugins/github-watcher/hooks-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,8 @@ describe("the loop", () => {
const doorbells: string[] = [];
const doorbellKinds: string[] = [];
const units: Array<string | null> = [];
const deployments: unknown[] = [];
const workflowRuns: unknown[] = [];
const rejected: Rejection[][] = [];
let token = "tok-1";
let refreshes = 0;
Expand All @@ -180,10 +182,12 @@ describe("the loop", () => {
return token;
},
watchIds: over.watchIds ?? (() => [{ kind: "issue", id: "i-1" }, { kind: "issue", id: "i-2" }]),
onDoorbell: (kind, id, unit) => {
onDoorbell: (kind, id, unit, deployment, workflowRun) => {
doorbellKinds.push(kind);
doorbells.push(id);
units.push(unit);
deployments.push(deployment);
workflowRuns.push(workflowRun);
},
onRejected: async (r) => {
rejected.push(r);
Expand All @@ -195,7 +199,7 @@ describe("the loop", () => {
});
const controller = new AbortController();
const done = loop.run(controller.signal);
return { loop, logs, sweeps, doorbells, doorbellKinds, units, rejected, controller, done, setToken: (t: string) => (token = t), refreshes: () => refreshes };
return { loop, logs, sweeps, doorbells, doorbellKinds, units, deployments, workflowRuns, rejected, controller, done, setToken: (t: string) => (token = t), refreshes: () => refreshes };
}

it("subscribes every watch on hello with the current token, sweeps, then rings on doorbells for issues only", async () => {
Expand All @@ -214,14 +218,17 @@ describe("the loop", () => {
hooks.last().send(hooks.doorbell("i-1"));
hooks.last().send(hooks.doorbell("acme/widgets", { kind: "repo" }));
hooks.last().send(hooks.doorbell("acme/widgets#4", { kind: "dependabot_alert" }));
const workflowRun = { workflow: ".github/workflows/bb-server.yaml", name: "bb-server", conclusion: "failure", url: "https://github.com/acme/bb-gate/actions/runs/42", sha: "abc123", run_attempt: 1 };
hooks.last().send(hooks.doorbell("acme/bb-gate#42", { kind: "workflow_run", unit: "acme/bb-gate", workflow_run: workflowRun }));
hooks.last().send(hooks.doorbell("i-9", { source: "linear" }));
hooks.last().send("event: doorbell\ndata: not json\n\n");
hooks.last().send(hooks.doorbell("i-2", { action: "remove", unit: "" }));
await tick();
expect(s.doorbells).toEqual(["i-1", "acme/widgets#4", "i-2"]);
expect(s.doorbellKinds).toEqual(["issue", "dependabot_alert", "issue"]);
// The unit comes along when the service names one.
expect(s.units).toEqual(["acme/widgets", "acme/widgets", null]);
expect(s.doorbells).toEqual(["i-1", "acme/widgets#4", "acme/bb-gate#42", "i-2"]);
expect(s.doorbellKinds).toEqual(["issue", "dependabot_alert", "workflow_run", "issue"]);
// The unit comes along when the service names one, and the run object with it.
expect(s.units).toEqual(["acme/widgets", "acme/widgets", "acme/bb-gate", null]);
expect(s.workflowRuns).toEqual([undefined, undefined, workflowRun, undefined]);
expect(s.logs.join("\n")).not.toContain("tok-1");

s.controller.abort();
Expand Down
20 changes: 12 additions & 8 deletions plugins/github-watcher/hooks-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export async function* readSse(body: ReadableStream<Uint8Array>, signal: AbortSi
// ---- the wire shapes ---------------------------------------------------------

export const helloSchema = z.object({ connection: z.string().min(1), leaseSeconds: z.number().positive().optional() });
export const doorbellSchema = z.object({ source: z.string(), kind: z.string(), id: z.string().min(1), unit: z.string().optional(), deployment: z.unknown().optional() }).loose();
export const doorbellSchema = z.object({ source: z.string(), kind: z.string(), id: z.string().min(1), unit: z.string().optional(), deployment: z.unknown().optional(), workflow_run: z.unknown().optional() }).loose();
export const subscribeResponseSchema = z.object({
leases: z.array(z.object({ kind: z.string(), id: z.string() }).loose()).default([]),
rejected: z.array(z.object({ kind: z.string(), id: z.string(), reason: z.string() }).loose()).default([]),
Expand Down Expand Up @@ -217,12 +217,12 @@ export interface HooksLoopDeps {
/** Every lease to hold, right now: watched issues, and whatever stewards asked for. */
watchIds: () => Lease[];
/**
* A doorbell: the kind (`issue`, `dependabot_alert` or `deployment`), the
* entity id, the unit (the repository) when the service named one, and, on
* a `deployment` doorbell, the deployment object the doorbell carries. The
* caller decides what to look at.
* A doorbell: the kind (`issue`, `dependabot_alert`, `deployment` or
* `workflow_run`), the entity id, the unit (the repository) when the
* service named one, and, on a `deployment` or `workflow_run` doorbell, the
* object the doorbell carries. The caller decides what to look at.
*/
onDoorbell: (kind: string, id: string, unit: string | null, deployment?: unknown) => void;
onDoorbell: (kind: string, id: string, unit: string | null, deployment?: unknown, workflowRun?: unknown) => void;
/** Leases the service refused. The caller decides what that means for each watch. */
onRejected: (rejected: Rejection[]) => Promise<void>;
/** Check every watch against its cursor. */
Expand Down Expand Up @@ -427,10 +427,14 @@ export function createHooksLoop(deps: HooksLoopDeps): HooksLoop {
// `action` and `at` are for the service's logs; the reaction to any
// doorbell is the same check. The unit is passed on so a repository
// lease can tell which of its doorbells it was rung for.
if (doorbell.success && doorbell.data.source === SOURCE && (doorbell.data.kind === "issue" || doorbell.data.kind === "dependabot_alert" || doorbell.data.kind === "deployment")) {
if (
doorbell.success &&
doorbell.data.source === SOURCE &&
(doorbell.data.kind === "issue" || doorbell.data.kind === "dependabot_alert" || doorbell.data.kind === "deployment" || doorbell.data.kind === "workflow_run")
) {
doorbells.push();
const unit = doorbell.data.unit?.trim() ?? "";
deps.onDoorbell(doorbell.data.kind, doorbell.data.id, unit === "" ? null : unit, doorbell.data.deployment);
deps.onDoorbell(doorbell.data.kind, doorbell.data.id, unit === "" ? null : unit, doorbell.data.deployment, doorbell.data.workflow_run);
}
}
}
Expand Down
22 changes: 20 additions & 2 deletions plugins/github-watcher/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -697,9 +697,27 @@ describe("stewards' source contract", () => {
// A refused deployment_repo lease is a skip, logged as one.
w.hooks.state.answer = (body) => Response.json({ leases: [], rejected: body.watches.map((x) => ({ ...x, reason: "forbidden" })) });
await tick(30 * 60_000);
expect(w.harness.logEntries.some((l) => l.message.includes("this server skips deployment doorbells there"))).toBe(true);
expect(w.harness.logEntries.some((l) => l.message.includes("this server skips deployment and workflow-run doorbells there"))).toBe(true);
const interest = ((await w.harness.callRpc("watches", null)) as { interest: { unleased: Array<{ key: string; reason: string }> } }).interest;
expect(interest.unleased).toEqual([{ key: "acme/bb-gate", reason: "refused by bb-gate-hooks (forbidden); deployment doorbells are skipped" }]);
expect(interest.unleased).toEqual([{ key: "acme/bb-gate", reason: "refused by bb-gate-hooks (forbidden); deployment and workflow-run doorbells are skipped" }]);
service.controller.abort();
await service.done;
});

it("hands stewards a workflow_run doorbell's run object for a leased deployment repository (BB-61)", async () => {
const w = await setup(WITH_HOOKS);
const service = w.harness.runService("watches");
await tick();
w.hooks.last().send(w.hooks.hello("c_1"));
await tick();
expect(await w.harness.callRpc("sourceSetInterest", { units: [], entities: [], dependabot: [], deployment: ["acme/bb-gate"] }, STEWARDS)).toEqual({ ok: true });
await tick();
expect(w.hooks.subscribes.map((s) => s.watches)).toEqual([[{ kind: "deployment_repo", id: "acme/bb-gate" }]]);
const workflow_run = { workflow: ".github/workflows/bb-server.yaml", name: "bb-server", conclusion: "failure", url: "https://github.com/acme/bb-gate/actions/runs/42", sha: "abc123", run_attempt: 1 };
w.hooks.last().send(`event: doorbell\ndata: ${JSON.stringify({ source: "github", kind: "workflow_run", id: "Acme/bb-gate#42", unit: "Acme/bb-gate", workflow_run })}\n\n`);
w.hooks.last().send(`event: doorbell\ndata: ${JSON.stringify({ source: "github", kind: "workflow_run", id: "Acme/Other#42", unit: "Acme/Other", workflow_run })}\n\n`);
await tick(3000);
expect(w.rpcs()).toEqual([{ pluginId: "stewards", method: "stewardsRing", input: { source: "github", id: "Acme/bb-gate#42", workflow_run } }]);
service.controller.abort();
await service.done;
});
Expand Down
39 changes: 34 additions & 5 deletions plugins/github-watcher/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import {
type Target,
} from "./github.js";
import { createHooksLoop, HOOKS_URL_ENV, type Lease, type Rejection } from "./hooks-client.js";
import { deploymentSchema, ringStewards, sourceContract, STEWARDS_PLUGIN_ID, type AdoptableEntity, type Deployment } from "./source-contract.js";
import { deploymentSchema, ringStewards, sourceContract, STEWARDS_PLUGIN_ID, workflowRunSchema, type AdoptableEntity, type Deployment, type WorkflowRun } from "./source-contract.js";
import { buildUsage, createRefusals, formatUsage, usageViewSchema, type InterestView } from "./usage.js";
import { compare, createCheckQueue, createWatchStore, initialCursors, snapshotOf, WATCH_MIGRATIONS, type WatchRow } from "./watch.js";

Expand Down Expand Up @@ -299,7 +299,9 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
function interesting(kind: string, key: string, unit: string | null): boolean {
const repo = unit ?? parseRefKey(key)?.repo ?? null;
if (kind === "dependabot_alert") return repo !== null && interestDependabot.has(repo.toLowerCase());
if (kind === "deployment") return repo !== null && interestDeployment.has(repo.toLowerCase());
// A workflow_run doorbell shares the deployment_repo lease: only a
// project that names a deployment target cares about a failed run.
if (kind === "deployment" || kind === "workflow_run") return repo !== null && interestDeployment.has(repo.toLowerCase());
if (interestEntities.has(key.toLowerCase())) return true;
return repo !== null && interestRepos.has(repo.toLowerCase());
}
Expand Down Expand Up @@ -327,6 +329,21 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
);
bb.onDispose(() => deploymentRings.stop());

// A workflow_run doorbell carries its run object the same way. It is keyed
// by the run id and attempt, so a re-run that fails again is its own ring
// rather than being coalesced into the first.
const pendingWorkflowRuns = new Map<string, { id: string; run: WorkflowRun }>();
const workflowRunRings = createCheckQueue(
(eventKey) => {
const pending = pendingWorkflowRuns.get(eventKey);
pendingWorkflowRuns.delete(eventKey);
if (pending === undefined) return Promise.resolve();
return ringStewards(callStewards, { source: "github", id: pending.id, workflow_run: pending.run }, warn);
},
{ onError: (eventKey, error) => warn(`ringing stewards for workflow run ${eventKey} failed: ${errorMessage(error)}`) },
);
bb.onDispose(() => workflowRunRings.stop());

// The service refusing a lease is not proof the developer lost access:
// with GitHub rate-limiting the service, or briefly down, every watch
// would come back `forbidden`. The developer's own read is the ground
Expand Down Expand Up @@ -359,7 +376,7 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
// Reading a repository's deployments needs `deployments:read` (or
// the `repo` scope); a token without it is refused here, which is a
// skip: the server keeps running without deployment doorbells.
if (interestDeployment.has(r.id.toLowerCase())) bb.log.info(`bb-gate-hooks refused a deployment_repo lease on ${r.id} (${r.reason}); this server skips deployment doorbells there`);
if (interestDeployment.has(r.id.toLowerCase())) bb.log.info(`bb-gate-hooks refused a deployment_repo lease on ${r.id} (${r.reason}); this server skips deployment and workflow-run doorbells there`);
continue;
}
if (r.kind === "repo" || (watching.length === 0 && interestEntities.has(r.id.toLowerCase()))) {
Expand Down Expand Up @@ -390,8 +407,20 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
token: accessToken,
refreshToken: () => refreshToken("was refused by bb-gate-hooks"),
watchIds: leases,
onDoorbell: (kind, key, unit, deployment) => {
onDoorbell: (kind, key, unit, deployment, workflowRun) => {
if (kind === "issue") checks.ring(key);
if (kind === "workflow_run") {
if (!interesting(kind, key, unit)) return;
const parsed = workflowRunSchema.safeParse(workflowRun);
if (!parsed.success) {
bb.log.warn(`GitHub workflow_run doorbell ${key} carried no readable run; nothing to hand stewards`);
return;
}
const eventKey = `${key.toLowerCase()}#${parsed.data.run_attempt}`;
pendingWorkflowRuns.set(eventKey, { id: key, run: parsed.data });
workflowRunRings.ring(eventKey);
return;
}
if (kind === "deployment") {
if (!interesting(kind, key, unit)) return;
const parsed = deploymentSchema.safeParse(deployment);
Expand Down Expand Up @@ -461,7 +490,7 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
}
for (const repo of interest.deployment) {
const reason = refused.get(`deployment_repo ${repo.toLowerCase()}`);
if (reason !== undefined) unleased.push({ key: repo, reason: `refused by bb-gate-hooks (${reason}); deployment doorbells are skipped` });
if (reason !== undefined) unleased.push({ key: repo, reason: `refused by bb-gate-hooks (${reason}); deployment and workflow-run doorbells are skipped` });
}
return {
nouns: { unit: ["repository", "repositories"], entity: ["pull request", "pull requests"] },
Expand Down
35 changes: 30 additions & 5 deletions plugins/github-watcher/source-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,29 @@ export const deploymentSchema = z
.loose();
export type Deployment = z.infer<typeof deploymentSchema>;

/**
* A GitHub Actions workflow run, as bb-gate-hooks forwards it on a
* `workflow_run` doorbell (bb-gate/docs/hooks.md). The doorbell's entity id
* is `owner/repo#<run id>` and its unit is the repository, leased the same
* way as a deployment (`deployment_repo`). `workflow` is the workflow's file
* path and `name` its name, either of which a playbook may match;
* `conclusion` is failure, cancelled or timed_out -- the only conclusions
* that ring the doorbell. `sha` is the run's head commit, which is usually
* the deploying repository's commit, not the merge's, so a subscriber must
* not match on it. `run_attempt` tells a re-run from the first attempt.
*/
export const workflowRunSchema = z
.object({
workflow: z.string().default(""),
name: z.string().default(""),
conclusion: z.string().default(""),
url: z.string().nullable().default(null),
sha: z.string().default(""),
run_attempt: z.number().int().positive().default(1),
})
.loose();
export type WorkflowRun = z.infer<typeof workflowRunSchema>;

/** How much of a comment or description crosses the contract. */
export const SNAPSHOT_COMMENT_CHARS = 4000;
export const SNAPSHOT_DESCRIPTION_CHARS = 20_000;
Expand Down Expand Up @@ -275,7 +298,9 @@ export const sourceContract = {
* stewards wants: the deployment targets the project's playbooks name. It
* is separate from `units` for the same reason as `dependabot`: a
* repository lease does not receive deployment doorbells, so the github
* plugin leases each as a `deployment_repo`. Linear ignores it.
* plugin leases each as a `deployment_repo`. A `workflow_run` doorbell
* shares that lease, because only a project that names a deployment target
* cares about a workflow run. Linear ignores it.
*/
sourceSetInterest: {
input: z.object({
Expand Down Expand Up @@ -373,11 +398,11 @@ export const stewardsContract = {
/** Something about this entity may have changed. Cheap: debounced, then compared with the last snapshot. */
stewardsRing: {
/**
* A `deployment` doorbell carries its deployment object, which is the one
* doorbell whose ref and state are not in the entity name. Every other
* doorbell leaves it out.
* A `deployment` doorbell carries its deployment object, and a
* `workflow_run` doorbell its run object: the two doorbells whose facts
* are not in the entity name. Every other doorbell leaves both out.
*/
input: z.object({ source: sourceSchema, id: z.string().min(1).max(300), deployment: deploymentSchema.optional() }),
input: z.object({ source: sourceSchema, id: z.string().min(1).max(300), deployment: deploymentSchema.optional(), workflow_run: workflowRunSchema.optional() }),
output: z.object({ ok: z.boolean() }),
},
/**
Expand Down
35 changes: 30 additions & 5 deletions plugins/linear/source-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,29 @@ export const deploymentSchema = z
.loose();
export type Deployment = z.infer<typeof deploymentSchema>;

/**
* A GitHub Actions workflow run, as bb-gate-hooks forwards it on a
* `workflow_run` doorbell (bb-gate/docs/hooks.md). The doorbell's entity id
* is `owner/repo#<run id>` and its unit is the repository, leased the same
* way as a deployment (`deployment_repo`). `workflow` is the workflow's file
* path and `name` its name, either of which a playbook may match;
* `conclusion` is failure, cancelled or timed_out -- the only conclusions
* that ring the doorbell. `sha` is the run's head commit, which is usually
* the deploying repository's commit, not the merge's, so a subscriber must
* not match on it. `run_attempt` tells a re-run from the first attempt.
*/
export const workflowRunSchema = z
.object({
workflow: z.string().default(""),
name: z.string().default(""),
conclusion: z.string().default(""),
url: z.string().nullable().default(null),
sha: z.string().default(""),
run_attempt: z.number().int().positive().default(1),
})
.loose();
export type WorkflowRun = z.infer<typeof workflowRunSchema>;

/** How much of a comment or description crosses the contract. */
export const SNAPSHOT_COMMENT_CHARS = 4000;
export const SNAPSHOT_DESCRIPTION_CHARS = 20_000;
Expand Down Expand Up @@ -275,7 +298,9 @@ export const sourceContract = {
* stewards wants: the deployment targets the project's playbooks name. It
* is separate from `units` for the same reason as `dependabot`: a
* repository lease does not receive deployment doorbells, so the github
* plugin leases each as a `deployment_repo`. Linear ignores it.
* plugin leases each as a `deployment_repo`. A `workflow_run` doorbell
* shares that lease, because only a project that names a deployment target
* cares about a workflow run. Linear ignores it.
*/
sourceSetInterest: {
input: z.object({
Expand Down Expand Up @@ -373,11 +398,11 @@ export const stewardsContract = {
/** Something about this entity may have changed. Cheap: debounced, then compared with the last snapshot. */
stewardsRing: {
/**
* A `deployment` doorbell carries its deployment object, which is the one
* doorbell whose ref and state are not in the entity name. Every other
* doorbell leaves it out.
* A `deployment` doorbell carries its deployment object, and a
* `workflow_run` doorbell its run object: the two doorbells whose facts
* are not in the entity name. Every other doorbell leaves both out.
*/
input: z.object({ source: sourceSchema, id: z.string().min(1).max(300), deployment: deploymentSchema.optional() }),
input: z.object({ source: sourceSchema, id: z.string().min(1).max(300), deployment: deploymentSchema.optional(), workflow_run: workflowRunSchema.optional() }),
output: z.object({ ok: z.boolean() }),
},
/**
Expand Down
Loading
Loading