pr-shepherd 1.5.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +1 -0
- package/bin/api.d.mts +1 -1
- package/bin/commands/iterate/index.mjs +4 -0
- package/bin/commands/poll-events.d.mts +44 -0
- package/bin/commands/poll-events.mjs +123 -0
- package/bin/commands/poll-options.d.mts +9 -0
- package/bin/commands/poll-options.mjs +1 -0
- package/bin/commands/poll-progress.d.mts +2 -0
- package/bin/commands/poll-progress.mjs +6 -4
- package/bin/commands/poll-quota.d.mts +2 -0
- package/bin/commands/poll-quota.mjs +4 -0
- package/bin/commands/poll-summary.d.mts +1 -0
- package/bin/commands/poll-summary.mjs +30 -18
- package/bin/commands/poll-tick.d.mts +17 -0
- package/bin/commands/poll-tick.mjs +24 -0
- package/bin/commands/poll.d.mts +3 -9
- package/bin/commands/poll.mjs +64 -60
- package/bin/commands/stall-deadline.d.mts +20 -0
- package/bin/commands/stall-deadline.mjs +42 -0
- package/bin/commands/tick.mjs +1 -16
- package/bin/config/schema.d.mts +14 -0
- package/bin/config/schema.mjs +6 -0
- package/bin/events/config.d.mts +7 -0
- package/bin/events/config.mjs +66 -0
- package/bin/events/envelope.d.mts +4 -0
- package/bin/events/envelope.mjs +27 -0
- package/bin/events/filters.d.mts +8 -0
- package/bin/events/filters.mjs +27 -0
- package/bin/events/health.d.mts +14 -0
- package/bin/events/health.mjs +27 -0
- package/bin/events/matcher.d.mts +2 -0
- package/bin/events/matcher.mjs +32 -0
- package/bin/events/relay.d.mts +11 -0
- package/bin/events/relay.mjs +86 -0
- package/bin/events/serve.d.mts +10 -0
- package/bin/events/serve.mjs +137 -0
- package/bin/events/sse.d.mts +10 -0
- package/bin/events/sse.mjs +50 -0
- package/bin/events/types.d.mts +69 -0
- package/bin/events/types.mjs +1 -0
- package/bin/events/waiter.d.mts +47 -0
- package/bin/events/waiter.mjs +80 -0
- package/bin/github/batch-first-page.d.mts +17 -0
- package/bin/github/batch-first-page.mjs +48 -0
- package/bin/github/batch-page.d.mts +2 -0
- package/bin/github/batch-page.mjs +2 -2
- package/bin/github/batch-stack-evidence.d.mts +3 -1
- package/bin/github/batch-stack-evidence.mjs +4 -2
- package/bin/github/batch-viewer.d.mts +24 -0
- package/bin/github/batch-viewer.mjs +66 -0
- package/bin/github/batch.d.mts +1 -1
- package/bin/github/batch.mjs +30 -35
- package/bin/github/check-annotations-batch.mjs +1 -7
- package/bin/github/gql/batch-pr-viewer.gql +46 -0
- package/bin/github/gql-strip-viewer.d.mts +7 -0
- package/bin/github/gql-strip-viewer.mjs +14 -0
- package/bin/github/queries.d.mts +8 -0
- package/bin/github/queries.mjs +9 -0
- package/bin/github/thread-comments.d.mts +1 -1
- package/bin/github/thread-comments.mjs +7 -7
- package/bin/types/iterate.d.mts +9 -0
- package/bin/util/chunks.d.mts +2 -0
- package/bin/util/chunks.mjs +8 -0
- package/package.json +1 -1
- package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
- package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
- package/plugins/pr-shepherd/.codex.mcp.json +1 -1
- package/plugins/pr-shepherd/.mcp.json +1 -1
- package/plugins/pr-shepherd/package-lock.json +4 -4
- package/plugins/pr-shepherd/package.json +1 -1
- package/pr-shepherd.schema.json +21 -0
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { loadConfig } from "../config/load.mjs";
|
|
2
|
+
import { readStallState } from "../state/iterate-stall.mjs";
|
|
3
|
+
import { readStackStallDeadline } from "./stack-stall.mjs";
|
|
4
|
+
export function earliestDeadline(...deadlines) {
|
|
5
|
+
const known = deadlines.filter((d) => d !== undefined);
|
|
6
|
+
return known.length > 0 ? Math.min(...known) : undefined;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The `deadlineAt` (epoch ms) for an aggregate tick's event wait: a stack stall timer or a
|
|
10
|
+
* ready-delay countdown. No event announces either, so the wait must not outlast them.
|
|
11
|
+
*/
|
|
12
|
+
export async function aggregateDeadline(result, stallTimeoutSeconds) {
|
|
13
|
+
const stall = await readStackStallDeadline(result, stallTimeoutSeconds ?? loadConfig().iterate["stall-timeout-minutes"] * 60);
|
|
14
|
+
const ready = result.prs
|
|
15
|
+
.filter((item) => (item.remainingSeconds ?? 0) > 0)
|
|
16
|
+
.map((item) => [Date.now() / 1000 + item.remainingSeconds, "ready-delay"]);
|
|
17
|
+
return firstDeadline([stall, "stall-timeout"], ...ready);
|
|
18
|
+
}
|
|
19
|
+
/** The `deadlineAt` for a single-PR wait: the stall timeout or the CI-start timeout. */
|
|
20
|
+
export async function onePrDeadline(result, opts, sink) {
|
|
21
|
+
return firstDeadline([await readStallDeadline(result, opts.stallTimeoutSeconds), "stall-timeout"], [result.action === "wait" ? sink.ciStartDeadlineSeconds : undefined, "CI-start"]);
|
|
22
|
+
}
|
|
23
|
+
function firstDeadline(...candidates) {
|
|
24
|
+
let first;
|
|
25
|
+
for (const [seconds, reason] of candidates) {
|
|
26
|
+
if (seconds !== undefined && (first === undefined || seconds * 1000 < first.deadlineAt)) {
|
|
27
|
+
first = { deadlineAt: seconds * 1000, deadlineReason: reason };
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return first;
|
|
31
|
+
}
|
|
32
|
+
/** When an unchanged state would trip the stall timeout, or undefined when no timer is running. */
|
|
33
|
+
export async function readStallDeadline(result, stallTimeoutSeconds) {
|
|
34
|
+
if (result.action !== "wait")
|
|
35
|
+
return undefined;
|
|
36
|
+
const timeout = stallTimeoutSeconds ?? loadConfig().iterate["stall-timeout-minutes"] * 60;
|
|
37
|
+
const [owner, repo] = result.repo.split("/");
|
|
38
|
+
if (timeout <= 0 || !owner || !repo)
|
|
39
|
+
return undefined;
|
|
40
|
+
const read = await readStallState({ owner, repo, pr: result.pr });
|
|
41
|
+
return read.ok && read.state ? read.state.firstSeenAt + timeout : undefined;
|
|
42
|
+
}
|
package/bin/commands/tick.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { loadConfig } from "../config/load.mjs";
|
|
2
|
-
import { readStallState } from "../state/iterate-stall.mjs";
|
|
3
2
|
import { tickAggregateStep } from "./tick-instructions.mjs";
|
|
4
3
|
import { earliestNextCheck, MERGE_QUEUE_RECHECK_SECONDS, nextCheckCandidates, SAFETY_NET_SECONDS, } from "./next-check.mjs";
|
|
5
4
|
import { isHandedOffSelection, onlyDraftVerificationSelection, } from "./poll-summary-explicit-instructions.mjs";
|
|
6
5
|
import { runIterate } from "./iterate/index.mjs";
|
|
6
|
+
import { earliestDeadline, readStallDeadline } from "./stall-deadline.mjs";
|
|
7
7
|
import { runsSingleTick } from "./single-tick.mjs";
|
|
8
8
|
import { readStackStallDeadline } from "./stack-stall.mjs";
|
|
9
9
|
import { runPoll } from "./poll.mjs";
|
|
@@ -51,21 +51,6 @@ export function runPollCommand(opts) {
|
|
|
51
51
|
export function runAggregatePollCommand(opts) {
|
|
52
52
|
return runsSingleTick() ? runPollSummaryTick(opts) : runAggregatePoll(opts);
|
|
53
53
|
}
|
|
54
|
-
function earliestDeadline(...deadlines) {
|
|
55
|
-
const known = deadlines.filter((d) => d !== undefined);
|
|
56
|
-
return known.length > 0 ? Math.min(...known) : undefined;
|
|
57
|
-
}
|
|
58
|
-
/** When an unchanged state would trip the stall timeout, or undefined when no timer is running. */
|
|
59
|
-
async function readStallDeadline(result, stallTimeoutSeconds) {
|
|
60
|
-
if (result.action !== "wait")
|
|
61
|
-
return undefined;
|
|
62
|
-
const timeout = stallTimeoutSeconds ?? loadConfig().iterate["stall-timeout-minutes"] * 60;
|
|
63
|
-
const [owner, repo] = result.repo.split("/");
|
|
64
|
-
if (timeout <= 0 || !owner || !repo)
|
|
65
|
-
return undefined;
|
|
66
|
-
const read = await readStallState({ owner, repo, pr: result.pr });
|
|
67
|
-
return read.ok && read.state ? read.state.firstSeenAt + timeout : undefined;
|
|
68
|
-
}
|
|
69
54
|
async function withAggregateNextCheck(result, opts) {
|
|
70
55
|
const stallDeadlineSeconds = await readStackStallDeadline(result, opts.stallTimeoutSeconds ?? loadConfig().iterate["stall-timeout-minutes"] * 60);
|
|
71
56
|
const nextCheck = aggregateNextCheck(result, stallDeadlineSeconds);
|
package/bin/config/schema.d.mts
CHANGED
|
@@ -53,6 +53,13 @@ export declare const configSchema: z.ZodObject<{
|
|
|
53
53
|
"interval-factor": z.ZodOptional<z.ZodNumber>;
|
|
54
54
|
}, z.core.$strict>>>;
|
|
55
55
|
}, z.core.$strict>>;
|
|
56
|
+
events: z.ZodPrefault<z.ZodObject<{
|
|
57
|
+
source: z.ZodDefault<z.ZodEnum<{
|
|
58
|
+
"hook-harness": "hook-harness";
|
|
59
|
+
none: "none";
|
|
60
|
+
}>>;
|
|
61
|
+
"fallback-interval-seconds": z.ZodDefault<z.ZodNumber>;
|
|
62
|
+
}, z.core.$strict>>;
|
|
56
63
|
apply: z.ZodPrefault<z.ZodObject<{
|
|
57
64
|
"sha-poll-interval-seconds": z.ZodDefault<z.ZodNumber>;
|
|
58
65
|
"sha-poll-max-attempts": z.ZodDefault<z.ZodNumber>;
|
|
@@ -131,6 +138,13 @@ export declare const configFileSchema: z.ZodObject<{
|
|
|
131
138
|
"interval-factor": z.ZodOptional<z.ZodNumber>;
|
|
132
139
|
}, z.core.$strict>>>;
|
|
133
140
|
}, z.core.$strict>>;
|
|
141
|
+
events: z.ZodPrefault<z.ZodObject<{
|
|
142
|
+
source: z.ZodDefault<z.ZodEnum<{
|
|
143
|
+
"hook-harness": "hook-harness";
|
|
144
|
+
none: "none";
|
|
145
|
+
}>>;
|
|
146
|
+
"fallback-interval-seconds": z.ZodDefault<z.ZodNumber>;
|
|
147
|
+
}, z.core.$strict>>;
|
|
134
148
|
apply: z.ZodPrefault<z.ZodObject<{
|
|
135
149
|
"sha-poll-interval-seconds": z.ZodDefault<z.ZodNumber>;
|
|
136
150
|
"sha-poll-max-attempts": z.ZodDefault<z.ZodNumber>;
|
package/bin/config/schema.mjs
CHANGED
|
@@ -134,6 +134,12 @@ export const configSchema = z.strictObject({
|
|
|
134
134
|
"quota-warnings": quotaWarnings.default(() => structuredClone(DEFAULT_QUOTA_WARNINGS)),
|
|
135
135
|
})
|
|
136
136
|
.prefault({}),
|
|
137
|
+
events: z
|
|
138
|
+
.strictObject({
|
|
139
|
+
source: z.enum(["none", "hook-harness"]).default("none"),
|
|
140
|
+
"fallback-interval-seconds": positive().max(86_400).default(300),
|
|
141
|
+
})
|
|
142
|
+
.prefault({}),
|
|
137
143
|
apply: z
|
|
138
144
|
.strictObject({
|
|
139
145
|
"sha-poll-interval-seconds": positive().default(2),
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { EventsSourceConfig } from "./types.mts";
|
|
2
|
+
/**
|
|
3
|
+
* Resolve the hook-harness source with its own precedence: `HOOK_HARNESS_SOURCE` (a local
|
|
4
|
+
* `serve`) wins, then `HOOK_HARNESS_URL` + `HOOK_HARNESS_TOKEN`, then `client.json`. Throws a
|
|
5
|
+
* config error when none resolves. The token is returned to callers but never logged here.
|
|
6
|
+
*/
|
|
7
|
+
export declare function resolveEventsSource(env?: NodeJS.ProcessEnv): EventsSourceConfig;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { EXIT, ShepherdError } from "../exit-codes.mjs";
|
|
5
|
+
const SETUP_HINT = "run `npx -y hook-harness@0.3.3 token create --repos 'owner/*' --label pr-shepherd --login`, " +
|
|
6
|
+
"or set HOOK_HARNESS_URL and HOOK_HARNESS_TOKEN, or set HOOK_HARNESS_SOURCE to a " +
|
|
7
|
+
"`hook-harness serve` URL";
|
|
8
|
+
/** Where hook-harness keeps `client.json`: the same resolution its own CLI uses. */
|
|
9
|
+
function hookHarnessConfigDir(env) {
|
|
10
|
+
if (env["HOOK_HARNESS_CONFIG_DIR"])
|
|
11
|
+
return env["HOOK_HARNESS_CONFIG_DIR"];
|
|
12
|
+
return join(env["XDG_CONFIG_HOME"] || join(homedir(), ".config"), "hook-harness");
|
|
13
|
+
}
|
|
14
|
+
function readSaved(env) {
|
|
15
|
+
try {
|
|
16
|
+
const saved = JSON.parse(readFileSync(join(hookHarnessConfigDir(env), "client.json"), "utf8"));
|
|
17
|
+
if (saved === null || typeof saved !== "object")
|
|
18
|
+
return {};
|
|
19
|
+
const { url, token } = saved;
|
|
20
|
+
return {
|
|
21
|
+
...(typeof url === "string" && { url }),
|
|
22
|
+
...(typeof token === "string" && { token }),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return {};
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
30
|
+
/** An http(s) URL; one that carries a bearer token must be https unless it is loopback. */
|
|
31
|
+
function checkedUrl(url, origin, token) {
|
|
32
|
+
let protocol;
|
|
33
|
+
let hostname = "";
|
|
34
|
+
try {
|
|
35
|
+
({ protocol, hostname } = new URL(url));
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
protocol = undefined;
|
|
39
|
+
}
|
|
40
|
+
if (protocol !== "http:" && protocol !== "https:") {
|
|
41
|
+
throw new ShepherdError(`events.source is hook-harness but ${origin} is not an http(s) URL.`, EXIT.CONFIG);
|
|
42
|
+
}
|
|
43
|
+
if (token && protocol === "http:" && !LOOPBACK_HOSTS.has(hostname)) {
|
|
44
|
+
throw new ShepherdError(`events.source is hook-harness but ${origin} would send a token over plain http to a non-loopback host; use https.`, EXIT.CONFIG);
|
|
45
|
+
}
|
|
46
|
+
return url;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Resolve the hook-harness source with its own precedence: `HOOK_HARNESS_SOURCE` (a local
|
|
50
|
+
* `serve`) wins, then `HOOK_HARNESS_URL` + `HOOK_HARNESS_TOKEN`, then `client.json`. Throws a
|
|
51
|
+
* config error when none resolves. The token is returned to callers but never logged here.
|
|
52
|
+
*/
|
|
53
|
+
export function resolveEventsSource(env = process.env) {
|
|
54
|
+
const source = env["HOOK_HARNESS_SOURCE"];
|
|
55
|
+
if (source) {
|
|
56
|
+
const token = env["HOOK_HARNESS_SOURCE_TOKEN"] ?? "";
|
|
57
|
+
return { kind: "serve", url: checkedUrl(source, "HOOK_HARNESS_SOURCE", token), token };
|
|
58
|
+
}
|
|
59
|
+
const saved = readSaved(env);
|
|
60
|
+
const url = env["HOOK_HARNESS_URL"] || saved.url;
|
|
61
|
+
const token = env["HOOK_HARNESS_TOKEN"] || saved.token;
|
|
62
|
+
if (!url || !token) {
|
|
63
|
+
throw new ShepherdError(`events.source is hook-harness but no hook-harness login was found: ${SETUP_HINT}.`, EXIT.CONFIG);
|
|
64
|
+
}
|
|
65
|
+
return { kind: "relay", url: checkedUrl(url, "the hook-harness relay URL", token), token };
|
|
66
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { EventEnvelope } from "./types.mts";
|
|
2
|
+
/** Keep only the fields pr-shepherd reads; additive envelope fields are ignored. */
|
|
3
|
+
export declare function parseEnvelope(raw: unknown): EventEnvelope | null;
|
|
4
|
+
export declare function parseEnvelopes(raw: unknown): EventEnvelope[];
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const text = (value) => (typeof value === "string" ? value : null);
|
|
2
|
+
/** Keep only the fields pr-shepherd reads; additive envelope fields are ignored. */
|
|
3
|
+
export function parseEnvelope(raw) {
|
|
4
|
+
if (raw === null || typeof raw !== "object")
|
|
5
|
+
return null;
|
|
6
|
+
const value = raw;
|
|
7
|
+
if (typeof value["id"] !== "string" || typeof value["event"] !== "string")
|
|
8
|
+
return null;
|
|
9
|
+
const prs = Array.isArray(value["prs"])
|
|
10
|
+
? value["prs"].filter((pr) => typeof pr === "number")
|
|
11
|
+
: [];
|
|
12
|
+
return {
|
|
13
|
+
id: value["id"],
|
|
14
|
+
event: value["event"],
|
|
15
|
+
action: text(value["action"]),
|
|
16
|
+
repo: text(value["repo"]),
|
|
17
|
+
prs,
|
|
18
|
+
headSha: text(value["headSha"]),
|
|
19
|
+
headRef: text(value["headRef"]),
|
|
20
|
+
baseRef: text(value["baseRef"]),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export function parseEnvelopes(raw) {
|
|
24
|
+
if (!Array.isArray(raw))
|
|
25
|
+
return [];
|
|
26
|
+
return raw.flatMap((item) => parseEnvelope(item) ?? []);
|
|
27
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { EventFilter, WatchTarget } from "./types.mts";
|
|
2
|
+
/**
|
|
3
|
+
* A superset hint for the relay: events for these PR numbers, head SHAs, head branches, or pushes
|
|
4
|
+
* to their base branches. Local matching stays authoritative; older relays ignore the parameter.
|
|
5
|
+
*/
|
|
6
|
+
export declare function filtersFor(targets: readonly WatchTarget[]): EventFilter[];
|
|
7
|
+
/** The `filters` query value, or undefined when over the relay's limits (match locally). */
|
|
8
|
+
export declare function filtersParam(filters: readonly EventFilter[]): string | undefined;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const MAX_FILTERS = 50;
|
|
2
|
+
const MAX_FILTER_BYTES = 4096;
|
|
3
|
+
/**
|
|
4
|
+
* A superset hint for the relay: events for these PR numbers, head SHAs, head branches, or pushes
|
|
5
|
+
* to their base branches. Local matching stays authoritative; older relays ignore the parameter.
|
|
6
|
+
*/
|
|
7
|
+
export function filtersFor(targets) {
|
|
8
|
+
const unique = (values) => [
|
|
9
|
+
...new Set(values.filter((value) => Boolean(value))),
|
|
10
|
+
];
|
|
11
|
+
const sha = unique(targets.map((target) => target.headSha));
|
|
12
|
+
const ref = unique(targets.map((target) => target.headRef));
|
|
13
|
+
const base = unique(targets.map((target) => target.baseRef));
|
|
14
|
+
return [
|
|
15
|
+
{ pr: targets.map((target) => target.pr) },
|
|
16
|
+
...(sha.length > 0 ? [{ sha }] : []),
|
|
17
|
+
...(ref.length > 0 ? [{ ref }] : []),
|
|
18
|
+
...(base.length > 0 ? [{ event: ["push"], branch: base }] : []),
|
|
19
|
+
];
|
|
20
|
+
}
|
|
21
|
+
/** The `filters` query value, or undefined when over the relay's limits (match locally). */
|
|
22
|
+
export function filtersParam(filters) {
|
|
23
|
+
if (filters.length === 0 || filters.length > MAX_FILTERS)
|
|
24
|
+
return undefined;
|
|
25
|
+
const json = JSON.stringify(filters);
|
|
26
|
+
return json.length > MAX_FILTER_BYTES ? undefined : json;
|
|
27
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { WatchTarget } from "./types.mts";
|
|
2
|
+
export declare const ownerOf: (repo: string) => string;
|
|
3
|
+
/**
|
|
4
|
+
* Per-run source health. An owner the token cannot read stays uncovered for the run; transient
|
|
5
|
+
* trouble (5xx, network, gap) is tracked as a flag so each state change is noted exactly once.
|
|
6
|
+
*/
|
|
7
|
+
export interface EventHealth {
|
|
8
|
+
/** True when no watched owner is uncovered, so an event wait is worth attempting. */
|
|
9
|
+
covers(targets: readonly WatchTarget[]): boolean;
|
|
10
|
+
markUncovered(owner: string, reason: string): void;
|
|
11
|
+
markUnhealthy(reason: string): void;
|
|
12
|
+
markHealthy(): void;
|
|
13
|
+
}
|
|
14
|
+
export declare function createHealth(note: (message: string) => void): EventHealth;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export const ownerOf = (repo) => repo.split("/")[0].toLowerCase();
|
|
2
|
+
export function createHealth(note) {
|
|
3
|
+
const uncovered = new Set();
|
|
4
|
+
let unhealthy = false;
|
|
5
|
+
return {
|
|
6
|
+
covers: (targets) => targets.length > 0 && targets.every((target) => !uncovered.has(ownerOf(target.repo))),
|
|
7
|
+
markUncovered(owner, reason) {
|
|
8
|
+
const key = owner.toLowerCase();
|
|
9
|
+
if (uncovered.has(key))
|
|
10
|
+
return;
|
|
11
|
+
uncovered.add(key);
|
|
12
|
+
note(`events: ${owner} is not covered by this token (${reason}); polling it normally`);
|
|
13
|
+
},
|
|
14
|
+
markUnhealthy(reason) {
|
|
15
|
+
if (unhealthy)
|
|
16
|
+
return;
|
|
17
|
+
unhealthy = true;
|
|
18
|
+
note(`events: source unhealthy (${reason}); polling normally until it recovers`);
|
|
19
|
+
},
|
|
20
|
+
markHealthy() {
|
|
21
|
+
if (!unhealthy)
|
|
22
|
+
return;
|
|
23
|
+
unhealthy = false;
|
|
24
|
+
note("events: source recovered");
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const QUEUE_REF = /^gh-readonly-queue\/(.+)\/pr-(\d+)-/;
|
|
2
|
+
function branch(ref) {
|
|
3
|
+
return ref === null ? null : ref.replace(/^refs\/heads\//, "");
|
|
4
|
+
}
|
|
5
|
+
function queuedPr(ref) {
|
|
6
|
+
const match = ref === null ? null : QUEUE_REF.exec(ref);
|
|
7
|
+
return match ? { base: match[1], pr: Number(match[2]) } : null;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* True when `event` may change what an iterate tick sees for `target`. Deliberately generous:
|
|
11
|
+
* a spurious wake costs one tick, a missed one costs up to the fallback interval.
|
|
12
|
+
*/
|
|
13
|
+
function matchesTarget(event, target) {
|
|
14
|
+
if (event.repo?.toLowerCase() !== target.repo.toLowerCase())
|
|
15
|
+
return false;
|
|
16
|
+
if (event.prs.includes(target.pr))
|
|
17
|
+
return true;
|
|
18
|
+
if (target.headSha !== undefined && event.headSha?.toLowerCase() === target.headSha.toLowerCase())
|
|
19
|
+
return true;
|
|
20
|
+
const eventHead = branch(event.headRef);
|
|
21
|
+
if (target.headRef !== undefined && eventHead === target.headRef)
|
|
22
|
+
return true;
|
|
23
|
+
const queued = queuedPr(eventHead);
|
|
24
|
+
if (queued?.pr === target.pr && (target.baseRef === undefined || queued.base === target.baseRef))
|
|
25
|
+
return true;
|
|
26
|
+
// Only a push moves the base. Other PRs' events also carry this base as `baseRef`; matching
|
|
27
|
+
// them would wake every PR in a busy repository on every sibling's activity.
|
|
28
|
+
return target.baseRef !== undefined && event.event === "push" && eventHead === target.baseRef;
|
|
29
|
+
}
|
|
30
|
+
export function matchesAny(event, targets) {
|
|
31
|
+
return targets.some((target) => matchesTarget(event, target));
|
|
32
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { EventDeps, EventTransport } from "./types.mts";
|
|
2
|
+
/** Per-request bound the default fetch applies (proxy-aware `githubFetch`). */
|
|
3
|
+
export declare const RELAY_REQUEST_TIMEOUT_MS = 10000;
|
|
4
|
+
/**
|
|
5
|
+
* Polls the relay's `GET /events`, one request per owner (DynamoDB partitions by owner). Cursors
|
|
6
|
+
* are opaque and echoed back exactly; the only one constructed is the bare epoch-ms start.
|
|
7
|
+
*/
|
|
8
|
+
export declare function createRelayTransport(config: {
|
|
9
|
+
url: string;
|
|
10
|
+
token: string;
|
|
11
|
+
}, startMs: number, deps: Pick<EventDeps, "fetch">): EventTransport;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { filtersParam } from "./filters.mjs";
|
|
2
|
+
import { parseEnvelopes } from "./envelope.mjs";
|
|
3
|
+
const RELAY_POLL_MS = 15_000;
|
|
4
|
+
/** Per-request bound the default fetch applies (proxy-aware `githubFetch`). */
|
|
5
|
+
export const RELAY_REQUEST_TIMEOUT_MS = 10_000;
|
|
6
|
+
const PAGE_LIMIT = 100;
|
|
7
|
+
/** `more: true` repolls at once; this bounds a runaway relay. */
|
|
8
|
+
const MAX_PAGES = 20;
|
|
9
|
+
/**
|
|
10
|
+
* Polls the relay's `GET /events`, one request per owner (DynamoDB partitions by owner). Cursors
|
|
11
|
+
* are opaque and echoed back exactly; the only one constructed is the bare epoch-ms start.
|
|
12
|
+
*/
|
|
13
|
+
export function createRelayTransport(config, startMs, deps) {
|
|
14
|
+
const base = config.url.endsWith("/") ? config.url : `${config.url}/`;
|
|
15
|
+
const cursors = new Map();
|
|
16
|
+
let filtersRejected = false;
|
|
17
|
+
let notice;
|
|
18
|
+
async function pollOwner(scope) {
|
|
19
|
+
const events = [];
|
|
20
|
+
let failure;
|
|
21
|
+
try {
|
|
22
|
+
for (let page = 0; page < MAX_PAGES; page += 1) {
|
|
23
|
+
const params = new URLSearchParams({ owner: scope.owner });
|
|
24
|
+
if (scope.repos.length > 0)
|
|
25
|
+
params.set("repos", scope.repos.join(","));
|
|
26
|
+
params.set("after", cursors.get(scope.owner) ?? String(startMs));
|
|
27
|
+
params.set("limit", String(PAGE_LIMIT));
|
|
28
|
+
params.set("payload", "0");
|
|
29
|
+
const filters = filtersRejected ? undefined : filtersParam(scope.filters);
|
|
30
|
+
if (filters)
|
|
31
|
+
params.set("filters", filters);
|
|
32
|
+
const response = await deps.fetch(new URL(`events?${params}`, base), {
|
|
33
|
+
headers: { authorization: `Bearer ${config.token}` },
|
|
34
|
+
});
|
|
35
|
+
if (response.status === 401 || response.status === 403) {
|
|
36
|
+
return { kind: "uncovered", reason: `relay answered HTTP ${response.status}` };
|
|
37
|
+
}
|
|
38
|
+
if (response.status === 400 && filters) {
|
|
39
|
+
filtersRejected = true;
|
|
40
|
+
notice = "events: relay rejected `filters` (HTTP 400); matching locally without them";
|
|
41
|
+
page -= 1;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (!response.ok) {
|
|
45
|
+
failure = `relay answered HTTP ${response.status}`;
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
const body = (await response.json());
|
|
49
|
+
if (body === null || typeof body.cursor !== "string" || !Array.isArray(body.events)) {
|
|
50
|
+
failure = "relay returned a malformed page";
|
|
51
|
+
break;
|
|
52
|
+
}
|
|
53
|
+
cursors.set(scope.owner, body.cursor);
|
|
54
|
+
events.push(...parseEnvelopes(body.events));
|
|
55
|
+
if (body.gap === true)
|
|
56
|
+
failure = "relay reported a gap (cursor older than retention)";
|
|
57
|
+
if (body.more !== true)
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
failure = `relay request failed (${error instanceof Error ? error.name : "error"})`;
|
|
63
|
+
}
|
|
64
|
+
return { kind: "ok", events, ...(failure && { failure }) };
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
intervalMs: RELAY_POLL_MS,
|
|
68
|
+
async poll(scopes) {
|
|
69
|
+
const outcomes = await Promise.all(scopes.map(pollOwner));
|
|
70
|
+
const result = { events: [], ...(notice && { notice }) };
|
|
71
|
+
notice = undefined;
|
|
72
|
+
outcomes.forEach((outcome, index) => {
|
|
73
|
+
if (outcome.kind === "ok") {
|
|
74
|
+
result.events.push(...outcome.events);
|
|
75
|
+
if (outcome.failure)
|
|
76
|
+
result.unhealthy = outcome.failure;
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
(result.uncovered ??= []).push({ owner: scopes[index].owner, reason: outcome.reason });
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
return result;
|
|
83
|
+
},
|
|
84
|
+
close() { },
|
|
85
|
+
};
|
|
86
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { EventDeps, EventTransport } from "./types.mts";
|
|
2
|
+
/**
|
|
3
|
+
* Streams a local `hook-harness serve` over SSE. The stream feeds an in-memory buffer; `poll`
|
|
4
|
+
* drains it, waiting up to `waitMs` for the first event. A dropped stream is reconnected on the
|
|
5
|
+
* next poll from the last `id` seen, so a wait that finds it dead degrades rather than hangs.
|
|
6
|
+
*/
|
|
7
|
+
export declare function createServeTransport(config: {
|
|
8
|
+
url: string;
|
|
9
|
+
token: string;
|
|
10
|
+
}, startMs: number, deps: Pick<EventDeps, "fetch">): EventTransport;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { parseEnvelope } from "./envelope.mjs";
|
|
2
|
+
import { createSseParser } from "./sse.mjs";
|
|
3
|
+
const CONNECT_TIMEOUT_MS = 10_000;
|
|
4
|
+
/** hook-harness's own resume cursor: base64url JSON around the relay sort key. */
|
|
5
|
+
function resumeCursor(startMs) {
|
|
6
|
+
return Buffer.from(JSON.stringify({ v: 1, sk: String(startMs), seen: [] })).toString("base64url");
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Streams a local `hook-harness serve` over SSE. The stream feeds an in-memory buffer; `poll`
|
|
10
|
+
* drains it, waiting up to `waitMs` for the first event. A dropped stream is reconnected on the
|
|
11
|
+
* next poll from the last `id` seen, so a wait that finds it dead degrades rather than hangs.
|
|
12
|
+
*/
|
|
13
|
+
export function createServeTransport(config, startMs, deps) {
|
|
14
|
+
const url = new URL("events", config.url.endsWith("/") ? config.url : `${config.url}/`);
|
|
15
|
+
let lastId = resumeCursor(startMs);
|
|
16
|
+
let controller;
|
|
17
|
+
let streamError;
|
|
18
|
+
let gap = false;
|
|
19
|
+
let buffer = [];
|
|
20
|
+
let wake;
|
|
21
|
+
const notify = () => {
|
|
22
|
+
wake?.();
|
|
23
|
+
wake = undefined;
|
|
24
|
+
};
|
|
25
|
+
async function read(body, mine) {
|
|
26
|
+
const parse = createSseParser();
|
|
27
|
+
const decoder = new TextDecoder();
|
|
28
|
+
try {
|
|
29
|
+
for await (const chunk of body) {
|
|
30
|
+
if (controller !== mine)
|
|
31
|
+
return;
|
|
32
|
+
for (const message of parse(decoder.decode(chunk, { stream: true }))) {
|
|
33
|
+
if (message.id)
|
|
34
|
+
lastId = message.id;
|
|
35
|
+
if (message.event === "gap")
|
|
36
|
+
gap = true;
|
|
37
|
+
const envelope = message.event === "envelope" ? parseEnvelope(safeJson(message.data)) : null;
|
|
38
|
+
if (envelope)
|
|
39
|
+
buffer.push(envelope);
|
|
40
|
+
}
|
|
41
|
+
notify();
|
|
42
|
+
}
|
|
43
|
+
if (controller === mine)
|
|
44
|
+
streamError = "serve closed the stream";
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (controller === mine) {
|
|
48
|
+
streamError = `serve stream failed (${error instanceof Error ? error.name : "error"})`;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
notify();
|
|
52
|
+
}
|
|
53
|
+
/** Open the stream; returns a failure reason, or undefined once connected. */
|
|
54
|
+
async function connect() {
|
|
55
|
+
const next = new AbortController();
|
|
56
|
+
const timer = setTimeout(() => next.abort(), CONNECT_TIMEOUT_MS);
|
|
57
|
+
try {
|
|
58
|
+
const response = await deps.fetch(url, {
|
|
59
|
+
headers: {
|
|
60
|
+
accept: "text/event-stream",
|
|
61
|
+
"last-event-id": lastId,
|
|
62
|
+
...(config.token && { authorization: `Bearer ${config.token}` }),
|
|
63
|
+
},
|
|
64
|
+
signal: next.signal,
|
|
65
|
+
});
|
|
66
|
+
if (response.status === 401 || response.status === 403) {
|
|
67
|
+
return { reason: `serve answered HTTP ${response.status}`, denied: true };
|
|
68
|
+
}
|
|
69
|
+
if (!response.ok || !response.body) {
|
|
70
|
+
return { reason: `serve answered HTTP ${response.status}`, denied: false };
|
|
71
|
+
}
|
|
72
|
+
controller = next;
|
|
73
|
+
streamError = undefined;
|
|
74
|
+
void read(response.body, next);
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
next.abort();
|
|
79
|
+
return {
|
|
80
|
+
reason: `serve connection failed (${error instanceof Error ? error.name : "error"})`,
|
|
81
|
+
denied: false,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
clearTimeout(timer);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
intervalMs: 0,
|
|
90
|
+
async poll(scopes, waitMs) {
|
|
91
|
+
if (controller === undefined || streamError !== undefined) {
|
|
92
|
+
controller?.abort();
|
|
93
|
+
controller = undefined;
|
|
94
|
+
const failure = await connect();
|
|
95
|
+
if (failure?.denied) {
|
|
96
|
+
return {
|
|
97
|
+
events: [],
|
|
98
|
+
uncovered: scopes.map(({ owner }) => ({ owner, reason: failure.reason })),
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
if (failure)
|
|
102
|
+
return { events: [], unhealthy: failure.reason };
|
|
103
|
+
}
|
|
104
|
+
if (buffer.length === 0 && streamError === undefined) {
|
|
105
|
+
await new Promise((resolve) => {
|
|
106
|
+
const timer = setTimeout(() => done(), waitMs);
|
|
107
|
+
const done = () => {
|
|
108
|
+
clearTimeout(timer);
|
|
109
|
+
resolve();
|
|
110
|
+
};
|
|
111
|
+
wake = done;
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
const events = buffer;
|
|
115
|
+
buffer = [];
|
|
116
|
+
const result = { events };
|
|
117
|
+
if (gap)
|
|
118
|
+
result.unhealthy = "serve reported a gap";
|
|
119
|
+
else if (streamError)
|
|
120
|
+
result.unhealthy = streamError;
|
|
121
|
+
gap = false;
|
|
122
|
+
return result;
|
|
123
|
+
},
|
|
124
|
+
close() {
|
|
125
|
+
controller?.abort();
|
|
126
|
+
controller = undefined;
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
function safeJson(text) {
|
|
131
|
+
try {
|
|
132
|
+
return JSON.parse(text);
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export interface SseMessage {
|
|
2
|
+
id?: string;
|
|
3
|
+
event: string;
|
|
4
|
+
data: string;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Incremental Server-Sent Events parser. Feed it decoded chunks; it returns each completed
|
|
8
|
+
* message. Comment lines (`: ping` keepalives) and unknown fields are dropped.
|
|
9
|
+
*/
|
|
10
|
+
export declare function createSseParser(): (chunk: string) => SseMessage[];
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** Longest line or frame accepted; a larger one throws so the wait degrades to plain polling. */
|
|
2
|
+
const MAX_SSE_BYTES = 1024 * 1024;
|
|
3
|
+
/**
|
|
4
|
+
* Incremental Server-Sent Events parser. Feed it decoded chunks; it returns each completed
|
|
5
|
+
* message. Comment lines (`: ping` keepalives) and unknown fields are dropped.
|
|
6
|
+
*/
|
|
7
|
+
export function createSseParser() {
|
|
8
|
+
let buffer = "";
|
|
9
|
+
let id;
|
|
10
|
+
let event = "message";
|
|
11
|
+
let data = [];
|
|
12
|
+
let dataLength = 0;
|
|
13
|
+
return (chunk) => {
|
|
14
|
+
buffer += chunk;
|
|
15
|
+
// A trailing "\r" may be the first half of "\r\n"; keep it until the next chunk decides.
|
|
16
|
+
const heldCr = buffer.endsWith("\r");
|
|
17
|
+
const lines = (heldCr ? buffer.slice(0, -1) : buffer).split(/\r\n|\n|\r/);
|
|
18
|
+
const tail = lines.pop();
|
|
19
|
+
buffer = heldCr ? `${tail}\r` : tail;
|
|
20
|
+
if (buffer.length > MAX_SSE_BYTES)
|
|
21
|
+
throw new Error("SSE line exceeds 1 MiB");
|
|
22
|
+
const messages = [];
|
|
23
|
+
for (const line of lines) {
|
|
24
|
+
if (line === "") {
|
|
25
|
+
if (data.length > 0)
|
|
26
|
+
messages.push({ ...(id !== undefined && { id }), event, data: data.join("\n") });
|
|
27
|
+
event = "message";
|
|
28
|
+
data = [];
|
|
29
|
+
dataLength = 0;
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
if (line.startsWith(":"))
|
|
33
|
+
continue;
|
|
34
|
+
const colon = line.indexOf(":");
|
|
35
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
36
|
+
const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
37
|
+
if (field === "id")
|
|
38
|
+
id = value;
|
|
39
|
+
else if (field === "event")
|
|
40
|
+
event = value;
|
|
41
|
+
else if (field === "data") {
|
|
42
|
+
dataLength += value.length + 1;
|
|
43
|
+
if (dataLength > MAX_SSE_BYTES)
|
|
44
|
+
throw new Error("SSE frame exceeds 1 MiB");
|
|
45
|
+
data.push(value);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return messages;
|
|
49
|
+
};
|
|
50
|
+
}
|