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
17 changes: 9 additions & 8 deletions plugins/github-watcher/hooks-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const SUBSCRIBE_BATCH = 100;
* separate because reading a repository does not entitle a token to its
* alerts (bb-gate/docs/hooks.md).
*/
export type LeaseKind = "issue" | "repo" | "dependabot_repo";
export type LeaseKind = "issue" | "repo" | "dependabot_repo" | "deployment_repo";
export type Lease = { kind: LeaseKind; id: string };

// ---- server-sent events ----------------------------------------------------
Expand Down 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() }).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() }).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,11 +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` or `dependabot_alert`), the entity id, and
* the unit (the repository) when the service named one. The caller decides
* what to look at.
* 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.
*/
onDoorbell: (kind: string, id: string, unit: string | null) => void;
onDoorbell: (kind: string, id: string, unit: string | null, deployment?: 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 @@ -426,10 +427,10 @@ 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")) {
if (doorbell.success && doorbell.data.source === SOURCE && (doorbell.data.kind === "issue" || doorbell.data.kind === "dependabot_alert" || doorbell.data.kind === "deployment")) {
doorbells.push();
const unit = doorbell.data.unit?.trim() ?? "";
deps.onDoorbell(doorbell.data.kind, doorbell.data.id, unit === "" ? null : unit);
deps.onDoorbell(doorbell.data.kind, doorbell.data.id, unit === "" ? null : unit, doorbell.data.deployment);
}
}
}
Expand Down
26 changes: 25 additions & 1 deletion plugins/github-watcher/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -582,7 +582,7 @@ describe("stewards' source contract", () => {
expect(w.hooks.subscribes).toEqual([]);

expect(await w.harness.callRpc("sourceSetInterest", { units: ["acme/gadgets"], entities: ["https://github.com/Acme/Widgets/pull/12"] }, STEWARDS)).toEqual({ ok: true });
expect(await w.bb.storage.kv.get("stewards/interest")).toEqual({ units: ["acme/gadgets"], entities: ["Acme/Widgets#12"], dependabot: [] });
expect(await w.bb.storage.kv.get("stewards/interest")).toEqual({ units: ["acme/gadgets"], entities: ["Acme/Widgets#12"], dependabot: [], deployment: [] });
type Interest = { units: string[]; entities: Array<{ key: string; url: string | null }>; unleased: Array<{ key: string; reason: string }> };
const interestOf = async () => ((await w.harness.callRpc("watches", null)) as { interest: Interest }).interest;
expect(await interestOf()).toMatchObject({ units: ["acme/gadgets"], entities: [{ key: "Acme/Widgets#12", url: "https://github.com/Acme/Widgets/issues/12" }], unleased: [] });
Expand Down Expand Up @@ -640,6 +640,30 @@ describe("stewards' source contract", () => {
await service.done;
});

it("leases deployment repositories and hands stewards a deployment doorbell's object", 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 deployment = { id: 7, environment: "production", ref: "main", sha: "abc123", state: "success", url: "https://github.com/acme/bb-gate/actions/runs/9" };
w.hooks.last().send(`event: doorbell\ndata: ${JSON.stringify({ source: "github", kind: "deployment", id: "Acme/bb-gate#7", unit: "Acme/bb-gate", deployment })}\n\n`);
w.hooks.last().send(`event: doorbell\ndata: ${JSON.stringify({ source: "github", kind: "deployment", id: "Acme/Other#7", unit: "Acme/Other", deployment })}\n\n`);
await tick(3000);
expect(w.rpcs()).toEqual([{ pluginId: "stewards", method: "stewardsRing", input: { source: "github", id: "Acme/bb-gate#7", deployment } }]);
// 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);
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" }]);
service.controller.abort();
await service.done;
});

it("leases what stewards asked for after a restart, beside the watches", async () => {
const w = await setup({ ...WITH_HOOKS, kv: { "stewards/interest": { units: ["acme/gadgets"], entities: ["acme/widgets#12"] } } });
await w.tool({ ref: "Acme/Widgets#12" });
Expand Down
69 changes: 62 additions & 7 deletions plugins/github-watcher/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ import {
type Target,
} from "./github.js";
import { createHooksLoop, HOOKS_URL_ENV, type Lease, type Rejection } from "./hooks-client.js";
import { ringStewards, sourceContract, STEWARDS_PLUGIN_ID, type AdoptableEntity } from "./source-contract.js";
import { deploymentSchema, ringStewards, sourceContract, STEWARDS_PLUGIN_ID, type AdoptableEntity, type Deployment } 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 All @@ -70,7 +70,7 @@ export const rpcContract = defineRpcContract({

/** Where the units and entities stewards wants to hear about are kept, so a restart keeps leasing them. */
export const INTEREST_KEY = "stewards/interest";
const interestSchema = z.object({ units: z.array(z.string()), entities: z.array(z.string()), dependabot: z.array(z.string()).default([]) });
const interestSchema = z.object({ units: z.array(z.string()), entities: z.array(z.string()), dependabot: z.array(z.string()).default([]), deployment: z.array(z.string()).default([]) });
type Interest = z.infer<typeof interestSchema>;

/** How long a token read from gh is reused before gh is asked again. */
Expand Down Expand Up @@ -263,12 +263,13 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
// Kept in kv so a restart leases them again before stewards next says.

const storedInterest = interestSchema.safeParse(await bb.storage.kv.get(INTEREST_KEY));
let interest: Interest = storedInterest.success ? storedInterest.data : { units: [], entities: [], dependabot: [] };
let interest: Interest = storedInterest.success ? storedInterest.data : { units: [], entities: [], dependabot: [], deployment: [] };
// GitHub's names are case-insensitive, and a doorbell spells them as
// GitHub does, which need not be how a project file does.
let interestRepos = new Set(interest.units.map((u) => u.toLowerCase()));
let interestEntities = new Set(interest.entities.map((e) => e.toLowerCase()));
let interestDependabot = new Set(interest.dependabot.map((r) => r.toLowerCase()));
let interestDeployment = new Set(interest.deployment.map((r) => r.toLowerCase()));
/** Stewards' leases bb-gate-hooks refused, by `<kind> <lowercased id>`. */
const refusals = createRefusals(deps.now);

Expand All @@ -286,13 +287,15 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
for (const key of interest.entities) add("issue", key);
for (const repo of interest.units) add("repo", repo);
for (const repo of interest.dependabot) add("dependabot_repo", repo);
for (const repo of interest.deployment) add("deployment_repo", repo);
return out;
}

/** Whether stewards cares about a doorbell for this key, in this repository. */
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());
if (interestEntities.has(key.toLowerCase())) return true;
return repo !== null && interestRepos.has(repo.toLowerCase());
}
Expand All @@ -304,6 +307,22 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
const rings = createCheckQueue((key) => ringStewards(callStewards, { source: "github", id: key }, warn), { onError: (key, error) => warn(`ringing stewards for ${key} failed: ${errorMessage(error)}`) });
bb.onDispose(() => rings.stop());

// A deployment doorbell carries its deployment object, which a plain ring
// does not; the queue holds the latest per deployment id and the ring
// hands it on. A doorbell with no readable object is dropped: there is
// nothing to decide carries from.
const pendingDeployments = new Map<string, Deployment>();
const deploymentRings = createCheckQueue(
(id) => {
const deployment = pendingDeployments.get(id);
pendingDeployments.delete(id);
if (deployment === undefined) return Promise.resolve();
return ringStewards(callStewards, { source: "github", id, deployment }, warn);
},
{ onError: (id, error) => warn(`ringing stewards for deployment ${id} failed: ${errorMessage(error)}`) },
);
bb.onDispose(() => deploymentRings.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 All @@ -316,14 +335,29 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
async function onRejected(rejected: Rejection[]): Promise<void> {
for (const r of rejected) {
const watching = r.kind === "issue" ? watches.forKey(r.id) : [];
if (r.kind === "repo" ? interestRepos.has(r.id.toLowerCase()) : r.kind === "dependabot_repo" ? interestDependabot.has(r.id.toLowerCase()) : interestEntities.has(r.id.toLowerCase())) refusals.add(`${r.kind} ${r.id.toLowerCase()}`, r.reason);
const leased =
r.kind === "repo"
? interestRepos.has(r.id.toLowerCase())
: r.kind === "dependabot_repo"
? interestDependabot.has(r.id.toLowerCase())
: r.kind === "deployment_repo"
? interestDeployment.has(r.id.toLowerCase())
: interestEntities.has(r.id.toLowerCase());
if (leased) refusals.add(`${r.kind} ${r.id.toLowerCase()}`, r.reason);
if (r.kind === "dependabot_repo") {
// A login that cannot read alerts gets `forbidden` here. That is a
// skip, not an error: the server keeps running without Dependabot
// doorbells, and `bb stewards check` says which repos it skips.
if (interestDependabot.has(r.id.toLowerCase())) bb.log.info(`bb-gate-hooks refused a dependabot_repo lease on ${r.id} (${r.reason}); this server skips Dependabot alerts there`);
continue;
}
if (r.kind === "deployment_repo") {
// 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`);
continue;
}
if (r.kind === "repo" || (watching.length === 0 && interestEntities.has(r.id.toLowerCase()))) {
bb.log.warn(`bb-gate-hooks refused a lease on ${r.kind === "repo" ? `repository ${r.id}` : r.id} for stewards (${r.reason}); stewards will not be rung for it`);
continue;
Expand Down Expand Up @@ -352,8 +386,19 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
token: accessToken,
refreshToken: () => refreshToken("was refused by bb-gate-hooks"),
watchIds: leases,
onDoorbell: (kind, key, unit) => {
onDoorbell: (kind, key, unit, deployment) => {
if (kind === "issue") checks.ring(key);
if (kind === "deployment") {
if (!interesting(kind, key, unit)) return;
const parsed = deploymentSchema.safeParse(deployment);
if (!parsed.success) {
bb.log.warn(`GitHub deployment doorbell ${key} carried no readable deployment; nothing to hand stewards`);
return;
}
pendingDeployments.set(key, parsed.data);
deploymentRings.ring(key);
return;
}
if (interesting(kind, key, unit)) rings.ring(key);
},
onRejected,
Expand Down Expand Up @@ -410,10 +455,15 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
const reason = refused.get(`dependabot_repo ${repo.toLowerCase()}`);
if (reason !== undefined) unleased.push({ key: repo, reason: `refused by bb-gate-hooks (${reason}); Dependabot alerts are skipped` });
}
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` });
}
return {
nouns: { unit: ["repository", "repositories"], entity: ["pull request", "pull requests"] },
units: interest.units,
dependabot: [...interest.dependabot].sort((a, b) => a.localeCompare(b)),
deployment: [...interest.deployment].sort((a, b) => a.localeCompare(b)),
entities: [...interest.entities].sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).map((key) => {
const ref = parseRefKey(key);
// GitHub sends /issues/N on to the pull request when it is one.
Expand Down Expand Up @@ -541,17 +591,19 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>

// Replaces the previous set. Anything new is leased right away; what
// was dropped is simply not renewed and lapses within the hour.
async sourceSetInterest({ units, entities, dependabot }, { experimental_caller: caller }) {
async sourceSetInterest({ units, entities, dependabot, deployment }, { experimental_caller: caller }) {
if (caller.kind !== "plugin" || caller.pluginId !== STEWARDS_PLUGIN_ID) throw new Error(`sourceSetInterest is for the ${STEWARDS_PLUGIN_ID} plugin only`);
const badUnits = units.filter((u) => parseRepo(u) === null);
const badEntities = entities.filter((e) => parseRef(e) === null);
const badDependabot = dependabot.filter((r) => parseRepo(r) === null);
if (badUnits.length > 0 || badEntities.length > 0 || badDependabot.length > 0) {
const badDeployment = deployment.filter((r) => parseRepo(r) === null);
if (badUnits.length > 0 || badEntities.length > 0 || badDependabot.length > 0 || badDeployment.length > 0) {
throw new Error(
`not GitHub names: ${[
...badUnits.map((u) => `${JSON.stringify(u)} (want owner/repo)`),
...badEntities.map((e) => `${JSON.stringify(e)} (want owner/repo#12)`),
...badDependabot.map((r) => `${JSON.stringify(r)} (want owner/repo)`),
...badDeployment.map((r) => `${JSON.stringify(r)} (want owner/repo)`),
]
.slice(0, 10)
.join(", ")}`,
Expand All @@ -562,12 +614,14 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
units: [...new Set(units.map((u) => u.trim()))],
entities: [...new Set(entities.map((e) => refKey(parseRef(e)!)))],
dependabot: [...new Set(dependabot.map((r) => r.trim()))],
deployment: [...new Set(deployment.map((r) => r.trim()))],
};
await bb.storage.kv.set(INTEREST_KEY, next);
interest = next;
interestRepos = new Set(next.units.map((u) => u.toLowerCase()));
interestEntities = new Set(next.entities.map((e) => e.toLowerCase()));
interestDependabot = new Set(next.dependabot.map((r) => r.toLowerCase()));
interestDeployment = new Set(next.deployment.map((r) => r.toLowerCase()));
announceWatches();
const fresh = leases().filter((l) => !before.has(`${l.kind} ${l.id.toLowerCase()}`));
const lease = (kind: Lease["kind"]) => {
Expand All @@ -577,6 +631,7 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
lease("repo");
lease("issue");
lease("dependabot_repo");
lease("deployment_repo");
return { ok: true };
},
});
Expand Down
Loading
Loading