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
27 changes: 26 additions & 1 deletion plugins/github-watcher/github.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { parseDependabotAlerts, parseOpenPulls, parseRef, parseRefKey, parseRepo, parseRepoCheck, parseSnapshot, parseTarget, refKey, TARGET_QUERY } from "./github.js";
import { parseDependabotAlerts, parseDeploymentStatus, parseDeployments, parseOpenPulls, parseRef, parseRefKey, parseRepo, parseRepoCheck, parseSnapshot, parseTarget, refKey, TARGET_QUERY } from "./github.js";
import { entitySnapshotSchema, SNAPSHOT_COMMENT_CHARS, SNAPSHOT_COMMENTS_MAX, SNAPSHOT_DESCRIPTION_CHARS } from "./source-contract.js";

describe("refs", () => {
Expand Down Expand Up @@ -308,3 +308,28 @@ describe("Dependabot alerts", () => {
expect(() => parseDependabotAlerts({ message: "Not Found" }, "Acme/Widgets")).toThrow(/Dependabot alert list/u);
});
});

describe("deployments", () => {
const node = (over: Record<string, unknown> = {}) => ({ id: 7, environment: "production", ref: "main", sha: "bbbbbbb2", url: "https://github.com/Acme/Widgets/actions/runs/9", ...over });

it("reads a page newest first, tolerating a bare deployment", () => {
expect(parseDeployments([node({ id: 6 }), node({ id: 7 })])).toEqual([
{ id: 7, environment: "production", ref: "main", sha: "bbbbbbb2", url: "https://github.com/Acme/Widgets/actions/runs/9" },
{ id: 6, environment: "production", ref: "main", sha: "bbbbbbb2", url: "https://github.com/Acme/Widgets/actions/runs/9" },
]);
expect(parseDeployments([node({ environment: null, ref: null, sha: null, url: null })])[0]).toEqual({ id: 7, environment: "", ref: "", sha: "", url: null });
});

it("throws on anything that is not a deployment list", () => {
expect(() => parseDeployments({ message: "Not Found" })).toThrow(/deployment list/u);
});

it("reads the newest status's state and the best link, with the doorbell's fallbacks", () => {
expect(parseDeploymentStatus([{ state: "success", log_url: "https://github.com/Acme/Widgets/actions/runs/9" }, { state: "in_progress" }])).toEqual({ state: "success", url: "https://github.com/Acme/Widgets/actions/runs/9" });
expect(parseDeploymentStatus([{ state: "success", environment_url: "https://preview.example.com/7" }])).toEqual({ state: "success", url: "https://preview.example.com/7" });
expect(parseDeploymentStatus([{ state: "failure", target_url: "https://target.example.com/7" }])).toEqual({ state: "failure", url: "https://target.example.com/7" });
expect(parseDeploymentStatus([{ state: "failure", url: "https://api.github.com/repos/Acme/Widgets/deployments/7/statuses/9" }])).toEqual({ state: "failure", url: "https://api.github.com/repos/Acme/Widgets/deployments/7/statuses/9" });
expect(parseDeploymentStatus([])).toEqual({ state: "", url: null });
expect(() => parseDeploymentStatus({ message: "Not Found" })).toThrow(/deployment status list/u);
});
});
56 changes: 56 additions & 0 deletions plugins/github-watcher/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -542,3 +542,59 @@ export function parseDependabotAlerts(payload: unknown, repo: string): Dependabo
updatedAt: a.updated_at ?? null,
}));
}

// ---- deployments, for stewards ----------------------------------------------------

/**
* The REST path for a repository's recent deployments, newest first. The
* environment is filtered client-side because GitHub's `environment` query is
* an exact match; a page of 100 is assumed wide enough that the newest
* deployment for any one environment sits in it, which holds while a repo
* does not interleave a busier second environment.
*/
export const deploymentsPath = (repo: string, perPage = 100): string => `/repos/${repo}/deployments?per_page=${perPage}`;

/** The REST path for one deployment's statuses, newest first. */
export const deploymentStatusesPath = (repo: string, id: number, perPage = 1): string => `/repos/${repo}/deployments/${id}/statuses?per_page=${perPage}`;

const deploymentNode = z.object({
id: z.number(),
environment: z.string().nullish(),
ref: z.string().nullish(),
sha: z.string().nullish(),
url: z.string().nullish(),
});

/**
* The deployments GitHub returned, newest first. The list has no `state`;
* the latest status of each carries it, read separately.
*/
export function parseDeployments(payload: unknown): Array<{ id: number; environment: string; ref: string; sha: string; url: string | null }> {
const parsed = z.array(deploymentNode).safeParse(payload);
if (!parsed.success) throw new Error("GitHub answered with something that is not a deployment list");
return parsed.data.map((d) => ({ id: d.id, environment: d.environment ?? "", ref: d.ref ?? "", sha: d.sha ?? "", url: d.url ?? null })).sort((a, b) => b.id - a.id);
}

const deploymentStatusNode = z.object({
state: z.string(),
url: z.string().nullish(),
log_url: z.string().nullish(),
environment_url: z.string().nullish(),
target_url: z.string().nullish(),
});

/**
* The newest deployment status's state and the best link a person can open,
* exactly as bb-gate-hooks builds a `deployment` doorbell's `url`: the
* status's `log_url`, then `environment_url`, then `target_url`, then the
* status's own API URL; null when it set none (the caller then falls back to
* the deployment's API URL). "" state when no status has been reported.
*/
export function parseDeploymentStatus(payload: unknown): { state: string; url: string | null } {
const parsed = z.array(deploymentStatusNode).safeParse(payload);
if (!parsed.success) throw new Error("GitHub answered with something that is not a deployment status list");
const status = parsed.data[0];
if (status === undefined) return { state: "", url: null };
const url = [status.log_url, status.environment_url, status.target_url, status.url].find((u): u is string => typeof u === "string" && u !== "") ?? null;
return { state: status.state, url };
}
42 changes: 41 additions & 1 deletion plugins/github-watcher/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,22 @@ const comment = (body: string, createdAt: string, who = "bob") => ({ author: { l
// A GitHub whose GraphQL endpoint a test scripts: one repository with one
// pull request, whose bb-managed label validates.
function fakeGitHub() {
const state = { node: pullNode() as Record<string, unknown> | null, fail: false, valid: (token: string) => token.startsWith("gho_"), openPulls: [] as Array<Record<string, unknown>>, dependabotAlerts: [] as unknown[], dependabotPage2: [] as unknown[], dependabotStatus: 200, dependabotMessage: "Forbidden" };
const state = { node: pullNode() as Record<string, unknown> | null, fail: false, valid: (token: string) => token.startsWith("gho_"), openPulls: [] as Array<Record<string, unknown>>, dependabotAlerts: [] as unknown[], dependabotPage2: [] as unknown[], dependabotStatus: 200, dependabotMessage: "Forbidden", deployments: [] as unknown[], deploymentStatuses: {} as Record<number, unknown[]> };
const calls: Array<{ token: string; variables: Record<string, unknown> }> = [];
const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit) => {
const token = ((init?.headers as Record<string, string>).authorization ?? "").replace(/^Bearer /u, "");
const u = String(url);
const deployments = /\/repos\/([^/]+)\/([^/]+)\/deployments(?:\?|$)/u.exec(u);
if (deployments !== null) {
if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 });
if (`${deployments[1]}/${deployments[2]}`.toLowerCase() !== "acme/widgets") return Response.json({ message: "Not Found" }, { status: 404 });
return Response.json(state.deployments);
}
const statuses = /\/repos\/([^/]+)\/([^/]+)\/deployments\/(\d+)\/statuses(?:\?|$)/u.exec(u);
if (statuses !== null) {
if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 });
return Response.json(state.deploymentStatuses[Number(statuses[3])] ?? []);
}
const dependabot = /\/repos\/([^/]+)\/([^/]+)\/dependabot\/alerts(?:\?|$)/u.exec(u);
if (dependabot !== null) {
if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 });
Expand Down Expand Up @@ -564,6 +575,35 @@ describe("stewards' source contract", () => {
expect(out.errors).toEqual([]);
});

it("reads a repository's deployments for one environment, newest first, each with its latest status and a person's link (BB-59)", async () => {
const w = await setup();
// GitHub's deployment object carries its own API URL; the link a person
// opens is on the status (`log_url`), exactly as bb-gate-hooks builds a
// doorbell.
w.github.state.deployments = [
{ id: 6, environment: "production", ref: "main", sha: "aaaaaaa1", url: "https://api.github.com/repos/Acme/Widgets/deployments/6" },
{ id: 7, environment: "production", ref: "main", sha: "bbbbbbb2", url: "https://api.github.com/repos/Acme/Widgets/deployments/7" },
];
w.github.state.deploymentStatuses = {
7: [{ state: "success", url: "https://api.github.com/repos/Acme/Widgets/deployments/7/statuses/9", log_url: "https://github.com/Acme/Widgets/actions/runs/9" }],
6: [{ state: "failure", environment_url: "https://preview.example.com/6" }],
};
expect(await w.harness.callRpc("sourceDeployments", { repo: "Acme/Widgets", environment: "production", limit: 10 }, STEWARDS)).toEqual({
deployments: [
{ id: 7, environment: "production", ref: "main", sha: "bbbbbbb2", state: "success", url: "https://github.com/Acme/Widgets/actions/runs/9" },
{ id: 6, environment: "production", ref: "main", sha: "aaaaaaa1", state: "failure", url: "https://preview.example.com/6" },
],
error: null,
});
// The environment filter is case-insensitive, as the doorbell path is, and
// a limit keeps the newest.
const limited = (await w.harness.callRpc("sourceDeployments", { repo: "acme/widgets", environment: "Production", limit: 1 }, STEWARDS)) as { deployments: Array<{ id: number; state: string }> };
expect(limited.deployments).toEqual([expect.objectContaining({ id: 7, state: "success" })]);
expect(await w.harness.callRpc("sourceDeployments", { repo: "Acme/Widgets", environment: "staging", limit: 10 }, STEWARDS)).toMatchObject({ deployments: [], error: null });
expect(await w.harness.callRpc("sourceDeployments", { repo: "acme/gone", environment: "production", limit: 10 }, STEWARDS)).toMatchObject({ deployments: [], error: "acme/gone: GitHub answered HTTP 404: Not Found" });
expect(await w.harness.callRpc("sourceDeployments", { repo: "widgets", environment: "production", limit: 10 }, STEWARDS)).toMatchObject({ deployments: [], error: "widgets: not owner/repo" });
});

describe("interest", () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
Expand Down
40 changes: 40 additions & 0 deletions plugins/github-watcher/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,13 @@ import {
TARGET_QUERY,
VIEWER_QUERY,
dependabotAlertsPath,
deploymentStatusesPath,
deploymentsPath,
graphql,
kindName,
parseDependabotAlerts,
parseDeploymentStatus,
parseDeployments,
parseOpenPulls,
parseRef,
parseRefKey,
Expand Down Expand Up @@ -589,6 +593,42 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
return { viewer, alerts, errors };
},

// A repository's recent deployments, newest first, read with the token
// through the REST API (GraphQL does not expose deployments) and
// filtered to the requested environment here: GitHub's `environment`
// query is an exact match, while the playbook's environment and the
// doorbell path match ignoring case. Each deployment's latest status is
// its `state` and its `url`, as a `deployment` doorbell builds them; a
// repository the token cannot read is named in `error` rather than
// failing the call. Stewards uses this to confirm a merge carried by a
// deployment that already exists, not only by a doorbell (BB-59).
async sourceDeployments({ repo, environment, limit }) {
const parsed = parseRepo(repo);
if (parsed === null) return { deployments: [], error: `${repo}: not owner/repo` };
const name = `${parsed.owner}/${parsed.name}`;
try {
const page = await restPage(deploymentsPath(name), checkSignal());
const nodes = parseDeployments(page.body)
.filter((d) => d.environment.toLowerCase() === environment.toLowerCase())
.slice(0, limit);
const deployments: Deployment[] = [];
for (const node of nodes) {
const status = parseDeploymentStatus((await restPage(deploymentStatusesPath(name, node.id), checkSignal())).body);
deployments.push({
id: node.id,
environment: node.environment === "" ? environment : node.environment,
ref: node.ref,
sha: node.sha,
state: status.state,
url: status.url ?? node.url,
});
}
return { deployments, error: null };
} catch (error) {
return { deployments: [], error: `${repo}: ${errorMessage(error)}` };
}
},

// 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, deployment }, { experimental_caller: caller }) {
Expand Down
20 changes: 20 additions & 0 deletions plugins/github-watcher/source-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,26 @@ export const sourceContract = {
errors: z.array(z.string()),
}),
},
/**
* A repository's recent GitHub Deployments for one environment, newest
* first, each with its latest status as `state` (BB-59). Stewards reads
* this to confirm a merge carried by a deployment that already exists, not
* only by a `deployment` doorbell; the plugin never evaluates the
* playbook's `carries` rule. Linear has no deployments and answers with an
* error. `limit` caps how many are returned.
*/
sourceDeployments: {
input: z.object({
repo: z.string().min(1).max(200),
environment: z.string().min(1).max(200),
limit: z.number().int().min(1).max(100).default(10),
}),
output: z.object({
deployments: z.array(deploymentSchema),
/** Set when the repository could not be read (not visible, no access). */
error: z.string().nullable(),
}),
},
} as const;

// ---- what stewards serves ---------------------------------------------------
Expand Down
5 changes: 5 additions & 0 deletions plugins/linear/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,11 @@ export function createLinearPlugin(deps: LinearPluginDeps): (bb: BbPluginApi) =>
async sourceDependabotAlerts() {
return { viewer: null, alerts: [], errors: ["Dependabot alerts are read from github, not linear"] };
},
// Deployments are a GitHub thing; linear has none. Stewards only asks
// github, so this is a plain answer rather than a throw.
async sourceDeployments() {
return { deployments: [], error: "deployments are read from github, not linear" };
},
async sourceSetInterest({ units, entities }, { experimental_caller: caller }) {
// The interest decides what this server leases and whom it rings, so
// only stewards itself may set it; the app and the CLI are clients.
Expand Down
20 changes: 20 additions & 0 deletions plugins/linear/source-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,26 @@ export const sourceContract = {
errors: z.array(z.string()),
}),
},
/**
* A repository's recent GitHub Deployments for one environment, newest
* first, each with its latest status as `state` (BB-59). Stewards reads
* this to confirm a merge carried by a deployment that already exists, not
* only by a `deployment` doorbell; the plugin never evaluates the
* playbook's `carries` rule. Linear has no deployments and answers with an
* error. `limit` caps how many are returned.
*/
sourceDeployments: {
input: z.object({
repo: z.string().min(1).max(200),
environment: z.string().min(1).max(200),
limit: z.number().int().min(1).max(100).default(10),
}),
output: z.object({
deployments: z.array(deploymentSchema),
/** Set when the repository could not be read (not visible, no access). */
error: z.string().nullable(),
}),
},
} as const;

// ---- what stewards serves ---------------------------------------------------
Expand Down
18 changes: 17 additions & 1 deletion plugins/stewards/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -745,6 +745,19 @@ deployment: # where a merge is confirmed live (BB-53); omi
comment once every pull request is merged and deployed. A failure/error
deployment or a timeout wakes the steward with the run URL. No `deployment`
is exactly today's behaviour.
- **A deployment that predates its watch is read, not waited for (BB-59).**
A doorbell can be missed, most obviously across the server restart every
`bb-plugins` merge causes, and a deployment that landed before the watch was
recorded never rings. So when a `merged` watch is first recorded, and on
every sweep for a watch still in `merged` or `deploying`, the plugin reads
the target repo's recent deployments for the playbook's environment through
the github plugin's source contract (`sourceDeployments`, never `gh` in the
server). The newest one is applied exactly as a doorbell would be: a success
moves the watch to `deploying` with its id, ref, sha and URL and wakes the
steward with the playbook's rule; a failure or error gives the failure wake.
A read that repeats what a watch already recorded is not news, so the sweep
does not re-wake for the same deployment. No deployments leaves the deadline
and the timeout path untouched. The plugin still never evaluates `carries`.
- **Stages** — `spec`, `build`, `review` — are what the plugin acts on (the
ready gate blocks `build`). State names are what a person sees.
- **Validation.** Phases must be workflow states of every listed team, labels
Expand Down Expand Up @@ -1411,7 +1424,10 @@ own server behind bb-gate, so it is per developer in practice.
deployment; a GitHub Deployment doorbell wakes the binding, and the steward
decides from the playbook's rule whether it carries the merge. A project
that names no target keeps "merged" as the terminal state and follows
through as before.
through as before. A deployment that already exists is read through the
github plugin's source contract on the first watch and on the sweep
(BB-59), so a missed doorbell costs a sweep, not the timeout; the read
never evaluates `carries`.
- **One developer's server and machine watch production.** An ops binding
runs on the server of the developer who runs the project's stewards, and
looks with kubectl on their machine, as them, like everything else here
Expand Down
Loading
Loading