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: 7 additions & 10 deletions plugins/github-watcher/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ copy shared with stewards and linear; edit all three or none):
`errors` and the rest are still returned.
- `sourceSetInterest`: the repositories, entities and Dependabot
repositories stewards wants to hear about. Only stewards may call it. Kept
in kv, leased on bb-gate-hooks beside the watches (`repo` leases for
in kv, leased on the hooks service beside the watches (`repo` leases for
repositories, `issue` leases for entities, `dependabot_repo` leases for
Dependabot repositories; a `repo` lease does not receive alert doorbells),
and every doorbell for one of them is debounced and rung over to stewards
Expand Down Expand Up @@ -86,7 +86,7 @@ once, harmlessly.
How it wakes: the plugin keeps a durable watch per thread and target in
its SQLite (what it last saw, and cursors on `updatedAt` and the newest
comment), and subscribes to
[bb-gate-hooks](../../bb-gate/docs/hooks.md), the one public endpoint
the hooks service, the one public endpoint
that receives GitHub's webhooks. It proves each watch with the
developer's own token, renews the lease every 30 minutes, and when the
service rings for a target it re-reads it as the developer with one
Expand Down Expand Up @@ -122,7 +122,7 @@ GitHub every ten minutes" at a glance:
last hour saw.
- A line for what stewards asked to have leased beside the watches: its
repositories by name, and its pull requests counted, listed only when
opened. A lease bb-gate-hooks refused in the last hour is called out under
opened. A lease the hooks service refused in the last hour is called out under
it with the reason. The CLI names at most twenty pull requests; `--json`
has them all.
- One row per watch: the pull request or issue (linking to GitHub, with the
Expand All @@ -144,17 +144,14 @@ server does. The view is the same as the linear plugin's, module for
module (`usage.ts`, `format-time.ts`, `components/watches-section.tsx`);
a change to one belongs in the other.

`BB_HOOKS_URL` is the cluster-internal address of bb-gate-hooks
(`http://bb-gate-hooks.bb-gate-production.svc:8081` in bb-gate's backend
template). It is read from the server's environment only; there is no
setting. Without it, `github_watch` returns an error saying watching is
`BB_HOOKS_URL` is the address of the hooks service. It is read from the
server's environment only; there is no setting. Without it, `github_watch` returns an error saying watching is
not available on this server, no background service is started, and
nothing else changes. There is deliberately no polling fallback: reading
the PR again later with `gh` is what the agent would do anyway.

The webhook itself is configured once per GitHub organization, by hand,
on bb-gate's side; `bb-gate/README.md` ("The hooks service") has the
steps and the event list.
in the hooks service; the hooks contract has the steps and the event list.

## Development

Expand All @@ -167,7 +164,7 @@ npm test
`github.ts` is the GraphQL documents and their parsing (including
stewards' snapshot); `watch.ts` the
snapshot, the diff, the wake message and the SQLite store;
`hooks-client.ts` the subscriber side of bb-gate-hooks, the same as the
`hooks-client.ts` the subscriber side of the hooks service, the same as the
linear plugin's with the source and lease kinds changed;
`source-contract.ts` the shared contract with stewards; `gh.ts` reads the token;
`usage.ts` the watches view; `server.ts` wires them to bb, and `app.tsx`
Expand Down
2 changes: 1 addition & 1 deletion plugins/github-watcher/components/watches-section.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ function HooksLine({ view }: { view: UsageView }) {
if (!h.configured) {
return (
<p className="text-muted-foreground">
<Dot tone="off" /> Doorbells unavailable: this server has no bb-gate-hooks service (BB_HOOKS_URL is not set), so threads cannot watch.
<Dot tone="off" /> Doorbells unavailable: this server has no hooks service (BB_HOOKS_URL is not set), so threads cannot watch.
</p>
);
}
Expand Down
2 changes: 1 addition & 1 deletion plugins/github-watcher/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -902,7 +902,7 @@ const deploymentStatusNode = z.object({

/**
* 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
* exactly as the hooks service 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.
Expand Down
12 changes: 6 additions & 6 deletions plugins/github-watcher/hooks-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { createHooksLoop, HooksRequestError, readSse, SseParser, StreamIdleError
const BASE = "http://hooks.test:8081";
const MINUTE = 60_000;

// A bb-gate-hooks whose stream and subscribe endpoint a test drives.
// A the hooks service whose stream and subscribe endpoint a test drives.
function fakeHooks() {
const encoder = new TextEncoder();
type Stream = { send(text: string): void; end(): void; closed: boolean };
Expand Down Expand Up @@ -218,16 +218,16 @@ 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 }));
const workflowRun = { workflow: ".github/workflows/build.yaml", name: "app", conclusion: "failure", url: "https://github.com/acme/web/actions/runs/42", sha: "abc123", run_attempt: 1 };
hooks.last().send(hooks.doorbell("acme/web#42", { kind: "workflow_run", unit: "acme/web", 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", "acme/bb-gate#42", "i-2"]);
expect(s.doorbells).toEqual(["i-1", "acme/widgets#4", "acme/web#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.units).toEqual(["acme/widgets", "acme/widgets", "acme/web", null]);
expect(s.workflowRuns).toEqual([undefined, undefined, workflowRun, undefined]);
expect(s.logs.join("\n")).not.toContain("tok-1");

Expand Down Expand Up @@ -436,7 +436,7 @@ describe("the loop", () => {
await tick(1);
expect(hooks.streams[0]!.closed).toBe(true);
expect(s.loop.connected).toBe(false);
expect(s.logs.some((l) => l.includes("no bytes from bb-gate-hooks for 60 s"))).toBe(true);
expect(s.logs.some((l) => l.includes("no bytes from the hooks service for 60 s"))).toBe(true);
await tick(1000);
expect(hooks.streams).toHaveLength(2);
s.controller.abort();
Expand Down
22 changes: 11 additions & 11 deletions plugins/github-watcher/hooks-client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// The subscriber side of bb-gate-hooks (bb-gate/docs/hooks.md): one SSE
// The subscriber side of the hooks service (hooks.md): one SSE
// stream for doorbells, a lease per watched issue or pull request (and per
// repository stewards asks about) proven with the developer's own token,
// renewed at half-life, and a re-check of every watch whenever coverage
Expand All @@ -24,7 +24,7 @@ export const SUBSCRIBE_BATCH = 100;
* repository and receives every `dependabot_alert` doorbell in it. Doorbells
* are always `issue` or `dependabot_alert`; the unit lease kinds are
* separate because reading a repository does not entitle a token to its
* alerts (bb-gate/docs/hooks.md).
* alerts (hooks.md).
*/
export type LeaseKind = "issue" | "repo" | "dependabot_repo" | "deployment_repo";
export type Lease = { kind: LeaseKind; id: string };
Expand Down Expand Up @@ -75,7 +75,7 @@ export class SseParser {
/** The events of a stream body, until it ends or the signal aborts. */
export class StreamIdleError extends Error {
constructor(idleMs: number) {
super(`no bytes from bb-gate-hooks for ${Math.round(idleMs / 1000)} s`);
super(`no bytes from the hooks service for ${Math.round(idleMs / 1000)} s`);
this.name = "StreamIdleError";
}
}
Expand Down Expand Up @@ -169,7 +169,7 @@ export async function subscribe(fetchImpl: FetchLike, baseUrl: string, connectio
body: JSON.stringify({ connection, source: SOURCE, token, watches }),
signal,
});
if (!response.ok) throw new HooksRequestError(`bb-gate-hooks answered HTTP ${response.status} to subscribe`, response.status, await response.text().catch(() => ""));
if (!response.ok) throw new HooksRequestError(`the hooks service answered HTTP ${response.status} to subscribe`, response.status, await response.text().catch(() => ""));
const parsed = subscribeResponseSchema.parse(await response.json());
merged.leases.push(...parsed.leases);
merged.rejected.push(...parsed.rejected);
Expand Down Expand Up @@ -352,7 +352,7 @@ export function createHooksLoop(deps: HooksLoopDeps): HooksLoop {
// service's side. Refresh regardless of what the expiry says and try
// once more; nothing was admitted or dropped.
if (!(error instanceof HooksRequestError && error.status === 401)) throw error;
deps.log.warn("bb-gate-hooks says GitHub refused the token; refreshing and retrying");
deps.log.warn("the hooks service says GitHub refused the token; refreshing and retrying");
result = await subscribe(deps.fetch, deps.baseUrl, current, await deps.refreshToken(), ids, signal);
}
if (connection === current) leasedUntil = Math.max(leasedUntil, started + leaseMs);
Expand All @@ -363,7 +363,7 @@ export function createHooksLoop(deps: HooksLoopDeps): HooksLoop {
if (error instanceof HooksRequestError && error.status === 404) {
if (error.unknownConnection) {
if (connection === current) {
deps.log.warn("bb-gate-hooks forgot our connection; reconnecting");
deps.log.warn("the hooks service forgot our connection; reconnecting");
stream?.abort();
}
return false;
Expand Down Expand Up @@ -403,13 +403,13 @@ export function createHooksLoop(deps: HooksLoopDeps): HooksLoop {
if (event.event === "hello") {
const hello = helloSchema.safeParse(JSON.parse(event.data));
if (!hello.success) {
deps.log.warn("bb-gate-hooks sent a hello this plugin does not understand; reconnecting");
deps.log.warn("the hooks service sent a hello this plugin does not understand; reconnecting");
return;
}
connection = hello.data.connection;
setState("connected");
leaseMs = hello.data.leaseSeconds === undefined ? timing.defaultLeaseMs : hello.data.leaseSeconds * 1000;
deps.log.info(`GitHub watches: connected to bb-gate-hooks as ${connection}`);
deps.log.info(`GitHub watches: connected to the hooks service as ${connection}`);
// Not awaited: doorbells behind the hello must not wait for GitHub.
void renew("hello", signal);
if (renewTimer !== null) clearInterval(renewTimer);
Expand Down Expand Up @@ -485,12 +485,12 @@ export function createHooksLoop(deps: HooksLoopDeps): HooksLoop {
stream = controller;
try {
const response = await deps.fetch(new URL("/v1/events", deps.baseUrl), { headers: { accept: "text/event-stream" }, signal: controller.signal });
if (!response.ok || response.body === null) throw new HooksRequestError(`bb-gate-hooks answered HTTP ${response.status} to the event stream`, response.status);
if (!response.ok || response.body === null) throw new HooksRequestError(`the hooks service answered HTTP ${response.status} to the event stream`, response.status);
backoff = timing.backoffMinMs;
await consume(response.body, controller.signal);
if (!signal.aborted) deps.log.warn("bb-gate-hooks event stream ended; reconnecting");
if (!signal.aborted) deps.log.warn("the hooks service event stream ended; reconnecting");
} catch (error) {
if (!signal.aborted && !controller.signal.aborted) deps.log.warn(`bb-gate-hooks event stream: ${errorMessage(error)}`);
if (!signal.aborted && !controller.signal.aborted) deps.log.warn(`the hooks service event stream: ${errorMessage(error)}`);
} finally {
signal.removeEventListener("abort", onAbort);
controller.abort();
Expand Down
Loading
Loading