pollhook 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +251 -2
- package/dist/adapters/branch-protection.js +42 -0
- package/dist/adapters/check-run.js +23 -0
- package/dist/adapters/check-suite.js +23 -0
- package/dist/adapters/code-scanning-alert.js +34 -0
- package/dist/adapters/commit-comment.js +20 -0
- package/dist/adapters/common.js +36 -0
- package/dist/adapters/dependabot-alert.js +26 -0
- package/dist/adapters/deploy-key.js +34 -0
- package/dist/adapters/deployment-protection-rule.js +60 -0
- package/dist/adapters/deployment-review.js +48 -0
- package/dist/adapters/deployment-status.js +30 -0
- package/dist/adapters/deployment.js +20 -0
- package/dist/adapters/dispatch.js +53 -0
- package/dist/adapters/fork.js +20 -0
- package/dist/adapters/issue-comment.js +25 -0
- package/dist/adapters/issues.js +45 -0
- package/dist/adapters/label.js +33 -0
- package/dist/adapters/member.js +38 -0
- package/dist/adapters/membership.js +57 -0
- package/dist/adapters/milestone.js +48 -0
- package/dist/adapters/page-build.js +29 -0
- package/dist/adapters/pull-request-review-comment.js +30 -0
- package/dist/adapters/pull-request-review.js +35 -0
- package/dist/adapters/pull-request.js +50 -0
- package/dist/adapters/push.js +78 -0
- package/dist/adapters/refs.js +94 -0
- package/dist/adapters/release.js +33 -0
- package/dist/adapters/repository-advisory.js +27 -0
- package/dist/adapters/repository-ruleset.js +33 -0
- package/dist/adapters/repository.js +71 -0
- package/dist/adapters/secret-scanning-alert.js +33 -0
- package/dist/adapters/security-and-analysis.js +24 -0
- package/dist/adapters/status.js +33 -0
- package/dist/adapters/team.js +34 -0
- package/dist/adapters/vulnerability-alert.js +17 -0
- package/dist/adapters/workflow-job.js +33 -0
- package/dist/adapters/workflow-run.js +34 -0
- package/dist/cli/args.js +54 -0
- package/dist/cli/commands.js +146 -0
- package/dist/cli/docs.js +55 -0
- package/dist/cli/format.js +23 -0
- package/dist/cli/rpc.js +57 -0
- package/dist/cli/spec.js +86 -0
- package/dist/cli/usage.js +7 -0
- package/dist/cli.js +33 -0
- package/dist/config/tuning.js +47 -0
- package/dist/config.js +125 -0
- package/dist/daemon/context.js +1 -0
- package/dist/daemon/handlers.js +102 -0
- package/dist/daemon/runtime.js +71 -0
- package/dist/daemon/waiter.js +48 -0
- package/dist/daemon/watch.js +27 -0
- package/dist/daemon.js +83 -0
- package/dist/db/cursors.js +16 -0
- package/dist/db/deliveries.js +55 -0
- package/dist/db/durations.js +36 -0
- package/dist/db/schema.js +40 -0
- package/dist/db/snapshots.js +36 -0
- package/dist/db/store.js +71 -0
- package/dist/db.js +1 -0
- package/dist/delivery.js +57 -0
- package/dist/github.js +175 -0
- package/dist/poller/refs.js +36 -0
- package/dist/poller/schedule.js +28 -0
- package/dist/poller/status.js +33 -0
- package/dist/poller.js +160 -0
- package/dist/registry.js +86 -0
- package/dist/types.js +1 -0
- package/dist/util.js +45 -0
- package/dist/waits.js +114 -0
- package/package.json +39 -4
package/dist/cli/rpc.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { connect } from "node:net";
|
|
2
|
+
import { socketPathFor } from "../daemon.js";
|
|
3
|
+
export async function rpc(config, message) {
|
|
4
|
+
const socket = await connectSocket(socketPathFor(config));
|
|
5
|
+
try {
|
|
6
|
+
return await new Promise((resolve, reject) => {
|
|
7
|
+
let buffer = "";
|
|
8
|
+
socket.setEncoding("utf8");
|
|
9
|
+
socket.on("data", (chunk) => {
|
|
10
|
+
buffer += chunk;
|
|
11
|
+
const index = buffer.indexOf("\n");
|
|
12
|
+
if (index < 0)
|
|
13
|
+
return;
|
|
14
|
+
try {
|
|
15
|
+
resolve(JSON.parse(buffer.slice(0, index)));
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
reject(error);
|
|
19
|
+
}
|
|
20
|
+
socket.end();
|
|
21
|
+
});
|
|
22
|
+
socket.on("error", reject);
|
|
23
|
+
socket.write(`${JSON.stringify(message)}\n`);
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
socket.destroy();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export async function stream(config, message, format = (body) => JSON.stringify(body)) {
|
|
31
|
+
const socket = await connectSocket(socketPathFor(config));
|
|
32
|
+
socket.setEncoding("utf8");
|
|
33
|
+
let buffer = "";
|
|
34
|
+
socket.on("data", (chunk) => {
|
|
35
|
+
buffer += chunk;
|
|
36
|
+
let index = buffer.indexOf("\n");
|
|
37
|
+
while (index >= 0) {
|
|
38
|
+
const line = buffer.slice(0, index);
|
|
39
|
+
buffer = buffer.slice(index + 1);
|
|
40
|
+
if (line) {
|
|
41
|
+
const response = JSON.parse(line);
|
|
42
|
+
if (!response.body?.subscribed)
|
|
43
|
+
process.stdout.write(`${format(response.body)}\n`);
|
|
44
|
+
}
|
|
45
|
+
index = buffer.indexOf("\n");
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
socket.write(`${JSON.stringify(message)}\n`);
|
|
49
|
+
await new Promise((resolve) => socket.on("close", () => resolve()));
|
|
50
|
+
}
|
|
51
|
+
function connectSocket(path) {
|
|
52
|
+
return new Promise((resolve, reject) => {
|
|
53
|
+
const socket = connect(path);
|
|
54
|
+
socket.once("connect", () => resolve(socket));
|
|
55
|
+
socket.once("error", (error) => reject(new Error(`cannot reach pollhook at ${path}: ${error.message}`)));
|
|
56
|
+
});
|
|
57
|
+
}
|
package/dist/cli/spec.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
export const EXIT_CODES = [
|
|
2
|
+
{ flag: "0", description: "success" },
|
|
3
|
+
{ flag: "1", description: "the waited-on run, check set or pull request failed" },
|
|
4
|
+
{ flag: "8", description: "timeout" },
|
|
5
|
+
{ flag: "2", description: "bad input or daemon unreachable" },
|
|
6
|
+
];
|
|
7
|
+
const REPO = { flag: "--repo OWNER/NAME", description: "targets one repository" };
|
|
8
|
+
const TIMEOUT = { flag: "--timeout 30m", description: "how long to wait" };
|
|
9
|
+
export const COMMANDS = [
|
|
10
|
+
{
|
|
11
|
+
name: "daemon",
|
|
12
|
+
args: "[--config PATH]",
|
|
13
|
+
summary: "Polls GitHub and serves consumers over a unix socket.",
|
|
14
|
+
flags: [
|
|
15
|
+
{ flag: "--config PATH", description: "config file, default ~/.config/pollhook/config.json" },
|
|
16
|
+
],
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
name: "status",
|
|
20
|
+
args: "[--json]",
|
|
21
|
+
summary: "Shows last and next poll per target, quota, degraded adapters and waiters.",
|
|
22
|
+
flags: [{ flag: "--json", description: "prints the raw status body" }],
|
|
23
|
+
},
|
|
24
|
+
{ name: "events", args: "", summary: "Lists every implemented event with its polling floor." },
|
|
25
|
+
{
|
|
26
|
+
name: "deliveries",
|
|
27
|
+
args: "[--limit N] [--repo OWNER/NAME]",
|
|
28
|
+
summary: "Prints recent deliveries from the state store.",
|
|
29
|
+
flags: [{ flag: "--limit N", description: "how many to print, default 20" }, REPO],
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
name: "emit",
|
|
33
|
+
args: "[--brief]",
|
|
34
|
+
summary: "Streams deliveries as JSON lines until stopped.",
|
|
35
|
+
flags: [{ flag: "--brief", description: "one human line per delivery instead of the payload" }],
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
name: "run",
|
|
39
|
+
args: "<run-id> [--repo OWNER/NAME] [--timeout 30m]",
|
|
40
|
+
summary: "Waits for a workflow run and exits with its conclusion.",
|
|
41
|
+
flags: [REPO, TIMEOUT],
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
name: "checks",
|
|
45
|
+
args: "<pr> [--repo OWNER/NAME] [--timeout 30m]",
|
|
46
|
+
summary: "Waits for every check on a pull request's head commit.",
|
|
47
|
+
flags: [REPO, TIMEOUT],
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
name: "pr",
|
|
51
|
+
args: "<pr> --until merged|closed|reviewed|conflict [--repo OWNER/NAME] [--timeout 30m]",
|
|
52
|
+
summary: "Waits for a pull request to reach a state.",
|
|
53
|
+
flags: [
|
|
54
|
+
{ flag: "--until STATE", description: "merged, closed, reviewed or conflict" },
|
|
55
|
+
REPO,
|
|
56
|
+
TIMEOUT,
|
|
57
|
+
],
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
name: "pages",
|
|
61
|
+
args: "<sha> [--repo OWNER/NAME] [--timeout 30m]",
|
|
62
|
+
summary: "Waits for the Pages build of a commit.",
|
|
63
|
+
flags: [REPO, TIMEOUT],
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
name: "wait",
|
|
67
|
+
args: "--event EVENT [--match key=value]... [--repo OWNER/NAME] [--timeout 30m]",
|
|
68
|
+
summary: "Waits for any delivery matching an event and optional field matches.",
|
|
69
|
+
flags: [
|
|
70
|
+
{ flag: "--event EVENT", description: "event name, see `pollhook events`" },
|
|
71
|
+
{ flag: "--match key=value", description: "repeatable top-level field match" },
|
|
72
|
+
REPO,
|
|
73
|
+
TIMEOUT,
|
|
74
|
+
],
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
name: "poke",
|
|
78
|
+
args: "[--repo OWNER/NAME]",
|
|
79
|
+
summary: "Polls now instead of waiting out the interval.",
|
|
80
|
+
flags: [REPO],
|
|
81
|
+
},
|
|
82
|
+
{ name: "cleanup", args: "", summary: "Reports that pollhook creates no webhooks." },
|
|
83
|
+
];
|
|
84
|
+
export function invocation(command) {
|
|
85
|
+
return ["pollhook", command.name, command.args].filter(Boolean).join(" ");
|
|
86
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { COMMANDS, EXIT_CODES, invocation } from "./spec.js";
|
|
2
|
+
export const USAGE = `pollhook: GitHub webhook deliveries without webhooks
|
|
3
|
+
|
|
4
|
+
${COMMANDS.map((command) => ` ${invocation(command)}`).join("\n")}
|
|
5
|
+
|
|
6
|
+
Exit codes: ${EXIT_CODES.map((code) => `${code.flag} ${code.description}`).join(", ")}.
|
|
7
|
+
`;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { loadConfig } from "./config.js";
|
|
3
|
+
import { startDaemon } from "./daemon.js";
|
|
4
|
+
import { valueFlag } from "./cli/args.js";
|
|
5
|
+
import { dispatchCommand } from "./cli/commands.js";
|
|
6
|
+
import { brief } from "./cli/format.js";
|
|
7
|
+
import { stream } from "./cli/rpc.js";
|
|
8
|
+
import { USAGE } from "./cli/usage.js";
|
|
9
|
+
import { errorMessage } from "./util.js";
|
|
10
|
+
async function main(argv) {
|
|
11
|
+
const [command, ...args] = argv;
|
|
12
|
+
if (!command || command === "--help" || command === "-h") {
|
|
13
|
+
process.stdout.write(USAGE);
|
|
14
|
+
return 0;
|
|
15
|
+
}
|
|
16
|
+
const config = loadConfig(valueFlag(args, "--config"));
|
|
17
|
+
if (command === "daemon") {
|
|
18
|
+
const daemon = await startDaemon(config);
|
|
19
|
+
await daemon.closed;
|
|
20
|
+
return 0;
|
|
21
|
+
}
|
|
22
|
+
if (command === "emit") {
|
|
23
|
+
await stream(config, { op: "emit" }, args.includes("--brief") ? brief : undefined);
|
|
24
|
+
return 0;
|
|
25
|
+
}
|
|
26
|
+
return dispatchCommand(config, command, args);
|
|
27
|
+
}
|
|
28
|
+
main(process.argv.slice(2)).then((code) => {
|
|
29
|
+
process.exitCode = code;
|
|
30
|
+
}, (error) => {
|
|
31
|
+
process.stderr.write(`pollhook: ${errorMessage(error)}\n`);
|
|
32
|
+
process.exitCode = 2;
|
|
33
|
+
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
const STRATEGIES = new Set(["fixed", "while-active"]);
|
|
2
|
+
export function parseTuning(value, path, label, allowed) {
|
|
3
|
+
const intervals = parseIntervals(value.intervals, path, label, allowed);
|
|
4
|
+
const strategies = parseStrategies(value.strategies, path, label, allowed);
|
|
5
|
+
return { ...(intervals ? { intervals } : {}), ...(strategies ? { strategies } : {}) };
|
|
6
|
+
}
|
|
7
|
+
function isRecord(value) {
|
|
8
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9
|
+
}
|
|
10
|
+
function parseIntervals(value, path, label, allowed) {
|
|
11
|
+
if (value === undefined)
|
|
12
|
+
return undefined;
|
|
13
|
+
if (!isRecord(value))
|
|
14
|
+
throw new Error(`config ${path}: ${label}.intervals must be an object`);
|
|
15
|
+
const intervals = {};
|
|
16
|
+
for (const [event, seconds] of Object.entries(value)) {
|
|
17
|
+
if (!allowed.includes(event)) {
|
|
18
|
+
throw new Error(`config ${path}: ${label}.intervals.${event} is not a subscribed event`);
|
|
19
|
+
}
|
|
20
|
+
if (typeof seconds !== "number" || !Number.isFinite(seconds)) {
|
|
21
|
+
throw new Error(`config ${path}: ${label}.intervals.${event} must be a number of seconds`);
|
|
22
|
+
}
|
|
23
|
+
const parsed = seconds;
|
|
24
|
+
if (parsed < 5) {
|
|
25
|
+
throw new Error(`config ${path}: ${label}.intervals.${event} must be at least 5 seconds`);
|
|
26
|
+
}
|
|
27
|
+
intervals[event] = parsed * 1000;
|
|
28
|
+
}
|
|
29
|
+
return Object.keys(intervals).length > 0 ? intervals : undefined;
|
|
30
|
+
}
|
|
31
|
+
function parseStrategies(value, path, label, allowed) {
|
|
32
|
+
if (value === undefined)
|
|
33
|
+
return undefined;
|
|
34
|
+
if (!isRecord(value))
|
|
35
|
+
throw new Error(`config ${path}: ${label}.strategies must be an object`);
|
|
36
|
+
const strategies = {};
|
|
37
|
+
for (const [event, strategy] of Object.entries(value)) {
|
|
38
|
+
if (!allowed.includes(event)) {
|
|
39
|
+
throw new Error(`config ${path}: ${label}.strategies.${event} is not a subscribed event`);
|
|
40
|
+
}
|
|
41
|
+
if (typeof strategy !== "string" || !STRATEGIES.has(strategy)) {
|
|
42
|
+
throw new Error(`config ${path}: ${label}.strategies.${event} must be fixed or while-active`);
|
|
43
|
+
}
|
|
44
|
+
strategies[event] = strategy;
|
|
45
|
+
}
|
|
46
|
+
return Object.keys(strategies).length > 0 ? strategies : undefined;
|
|
47
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { implementedEvents } from "./registry.js";
|
|
3
|
+
import { parseTuning } from "./config/tuning.js";
|
|
4
|
+
import { errorMessage, expandHome } from "./util.js";
|
|
5
|
+
const DEFAULT_CONFIG = "~/.config/pollhook/config.json";
|
|
6
|
+
const DEFAULT_STATE = "~/.local/state/pollhook";
|
|
7
|
+
const LOOPBACK = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
|
|
8
|
+
const REPO_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
9
|
+
const ORG_PATTERN = /^[A-Za-z0-9_.-]+$/;
|
|
10
|
+
export function configPath(override) {
|
|
11
|
+
return expandHome(override ?? process.env.POLLHOOK_CONFIG ?? DEFAULT_CONFIG);
|
|
12
|
+
}
|
|
13
|
+
export function loadConfig(override) {
|
|
14
|
+
const path = configPath(override);
|
|
15
|
+
let raw;
|
|
16
|
+
try {
|
|
17
|
+
raw = JSON.parse(readFileSync(path, "utf8"));
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
throw new Error(`cannot read config ${path}: ${errorMessage(error)}`);
|
|
21
|
+
}
|
|
22
|
+
if (!isRecord(raw))
|
|
23
|
+
throw new Error(`config ${path} must be a JSON object`);
|
|
24
|
+
const reposRaw = raw.repos ?? [];
|
|
25
|
+
const orgsRaw = raw.orgs ?? [];
|
|
26
|
+
if (!Array.isArray(reposRaw))
|
|
27
|
+
throw new Error(`config ${path}: repos must be an array`);
|
|
28
|
+
if (!Array.isArray(orgsRaw))
|
|
29
|
+
throw new Error(`config ${path}: orgs must be an array`);
|
|
30
|
+
const repos = reposRaw.map((entry, index) => parseRepo(entry, index, path));
|
|
31
|
+
const orgs = orgsRaw.map((entry, index) => parseOrg(entry, index, path));
|
|
32
|
+
if (repos.length === 0 && orgs.length === 0) {
|
|
33
|
+
throw new Error(`config ${path}: at least one of repos or orgs is required`);
|
|
34
|
+
}
|
|
35
|
+
const stateDir = expandHome(typeof raw.stateDir === "string" ? raw.stateDir : DEFAULT_STATE);
|
|
36
|
+
const deliver = raw.deliver === undefined ? undefined : parseDeliver(raw.deliver, path);
|
|
37
|
+
const tuning = parseTuning(raw, path, "config", implementedEvents("repo"));
|
|
38
|
+
return { repos, orgs, stateDir, ...tuning, ...(deliver ? { deliver } : {}) };
|
|
39
|
+
}
|
|
40
|
+
function parseRepo(value, index, path) {
|
|
41
|
+
if (!isRecord(value))
|
|
42
|
+
throw new Error(`config ${path}: repos[${index}] must be an object`);
|
|
43
|
+
const repo = value.repo;
|
|
44
|
+
if (typeof repo !== "string" || !REPO_PATTERN.test(repo)) {
|
|
45
|
+
throw new Error(`config ${path}: repos[${index}].repo must look like owner/name`);
|
|
46
|
+
}
|
|
47
|
+
const intervalSeconds = intervalFor(value.intervalSeconds, 60, path, `repos[${index}]`);
|
|
48
|
+
const events = parseEvents(value.events, index, path, "repos", "repo");
|
|
49
|
+
return {
|
|
50
|
+
repo,
|
|
51
|
+
events,
|
|
52
|
+
intervalMs: intervalSeconds * 1000,
|
|
53
|
+
checkRefLimit: positiveNumber(value.checkRefLimit, 5),
|
|
54
|
+
...parseTuning(value, path, `repos[${index}]`, events),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function parseOrg(value, index, path) {
|
|
58
|
+
if (!isRecord(value))
|
|
59
|
+
throw new Error(`config ${path}: orgs[${index}] must be an object`);
|
|
60
|
+
const org = value.org;
|
|
61
|
+
if (typeof org !== "string" || !ORG_PATTERN.test(org)) {
|
|
62
|
+
throw new Error(`config ${path}: orgs[${index}].org must be an organization name`);
|
|
63
|
+
}
|
|
64
|
+
const intervalSeconds = intervalFor(value.intervalSeconds, 300, path, `orgs[${index}]`);
|
|
65
|
+
const events = parseEvents(value.events, index, path, "orgs", "org");
|
|
66
|
+
return {
|
|
67
|
+
org,
|
|
68
|
+
events,
|
|
69
|
+
intervalMs: intervalSeconds * 1000,
|
|
70
|
+
...parseTuning(value, path, `orgs[${index}]`, events),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function parseEvents(value, index, path, group, scope) {
|
|
74
|
+
const allowed = implementedEvents(scope);
|
|
75
|
+
if (value === undefined)
|
|
76
|
+
return [...allowed];
|
|
77
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
78
|
+
throw new Error(`config ${path}: ${group}[${index}].events must be a non-empty array`);
|
|
79
|
+
}
|
|
80
|
+
for (const event of value) {
|
|
81
|
+
if (!allowed.includes(event)) {
|
|
82
|
+
throw new Error(`config ${path}: event "${event}" is not available for ${scope} targets; supported: ${allowed.join(", ") || "none"}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return value;
|
|
86
|
+
}
|
|
87
|
+
function intervalFor(value, fallback, path, label) {
|
|
88
|
+
const seconds = positiveNumber(value, fallback);
|
|
89
|
+
if (seconds < 5)
|
|
90
|
+
throw new Error(`config ${path}: ${label}.intervalSeconds must be at least 5`);
|
|
91
|
+
return seconds;
|
|
92
|
+
}
|
|
93
|
+
function parseDeliver(value, path) {
|
|
94
|
+
if (!isRecord(value) || typeof value.url !== "string") {
|
|
95
|
+
throw new Error(`config ${path}: deliver.url is required`);
|
|
96
|
+
}
|
|
97
|
+
let url;
|
|
98
|
+
try {
|
|
99
|
+
url = new URL(value.url);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
throw new Error(`config ${path}: deliver.url is not a valid URL`);
|
|
103
|
+
}
|
|
104
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
105
|
+
throw new Error(`config ${path}: deliver.url must be http or https`);
|
|
106
|
+
}
|
|
107
|
+
if (!LOOPBACK.has(url.hostname)) {
|
|
108
|
+
throw new Error(`config ${path}: deliver.url must be loopback, got ${url.hostname}`);
|
|
109
|
+
}
|
|
110
|
+
if (value.secret !== undefined && typeof value.secret !== "string") {
|
|
111
|
+
throw new Error(`config ${path}: deliver.secret must be a string`);
|
|
112
|
+
}
|
|
113
|
+
return value.secret === undefined ? { url: value.url } : { url: value.url, secret: value.secret };
|
|
114
|
+
}
|
|
115
|
+
function positiveNumber(value, fallback) {
|
|
116
|
+
if (value === undefined)
|
|
117
|
+
return fallback;
|
|
118
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
119
|
+
throw new Error(`expected a positive number, got ${JSON.stringify(value)}`);
|
|
120
|
+
}
|
|
121
|
+
return value;
|
|
122
|
+
}
|
|
123
|
+
function isRecord(value) {
|
|
124
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
125
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { ADAPTERS, IMPLEMENTED_EVENTS } from "../registry.js";
|
|
2
|
+
import { Waiter } from "./waiter.js";
|
|
3
|
+
const DEFAULT_WAIT_MS = 30 * 60 * 1000;
|
|
4
|
+
export function handleConnection(socket, ctx) {
|
|
5
|
+
const cleanup = [];
|
|
6
|
+
let buffer = "";
|
|
7
|
+
socket.setEncoding("utf8");
|
|
8
|
+
socket.on("data", (chunk) => {
|
|
9
|
+
buffer = drain(socket, buffer + chunk, ctx, cleanup);
|
|
10
|
+
});
|
|
11
|
+
socket.on("close", () => {
|
|
12
|
+
for (const fn of cleanup)
|
|
13
|
+
fn();
|
|
14
|
+
});
|
|
15
|
+
socket.on("error", () => { });
|
|
16
|
+
}
|
|
17
|
+
function drain(socket, buffer, ctx, cleanup) {
|
|
18
|
+
let index = buffer.indexOf("\n");
|
|
19
|
+
while (index >= 0) {
|
|
20
|
+
const line = buffer.slice(0, index).trim();
|
|
21
|
+
buffer = buffer.slice(index + 1);
|
|
22
|
+
if (line)
|
|
23
|
+
handleLine(socket, line, ctx, cleanup);
|
|
24
|
+
index = buffer.indexOf("\n");
|
|
25
|
+
}
|
|
26
|
+
return buffer;
|
|
27
|
+
}
|
|
28
|
+
function handleLine(socket, line, ctx, cleanup) {
|
|
29
|
+
let message;
|
|
30
|
+
try {
|
|
31
|
+
message = JSON.parse(line);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
writeLine(socket, { ok: false, error: "invalid json" });
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
handleRequest(socket, message, ctx, cleanup);
|
|
38
|
+
}
|
|
39
|
+
function handleRequest(socket, message, ctx, cleanup) {
|
|
40
|
+
switch (message.op) {
|
|
41
|
+
case "status":
|
|
42
|
+
writeLine(socket, { ok: true, body: ctx.status() });
|
|
43
|
+
return;
|
|
44
|
+
case "events":
|
|
45
|
+
writeLine(socket, { ok: true, body: eventList() });
|
|
46
|
+
return;
|
|
47
|
+
case "deliveries":
|
|
48
|
+
writeLine(socket, {
|
|
49
|
+
ok: true,
|
|
50
|
+
body: ctx.db.listDeliveries(Number(message.limit ?? 20), message.repo),
|
|
51
|
+
});
|
|
52
|
+
return;
|
|
53
|
+
case "poke":
|
|
54
|
+
if (ctx.poke(message.repo))
|
|
55
|
+
writeLine(socket, { ok: true, body: { poked: true } });
|
|
56
|
+
else
|
|
57
|
+
writeLine(socket, { ok: false, error: `unknown repository ${String(message.repo)}` });
|
|
58
|
+
return;
|
|
59
|
+
case "emit":
|
|
60
|
+
subscribe(socket, ctx, cleanup);
|
|
61
|
+
return;
|
|
62
|
+
case "wait":
|
|
63
|
+
onWait(socket, message, ctx, cleanup);
|
|
64
|
+
return;
|
|
65
|
+
default:
|
|
66
|
+
writeLine(socket, { ok: false, error: `unknown op ${String(message.op)}` });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function eventList() {
|
|
70
|
+
return IMPLEMENTED_EVENTS.map((event) => ({
|
|
71
|
+
event,
|
|
72
|
+
intervalFloorSeconds: ADAPTERS[event].intervalFloorMs / 1000,
|
|
73
|
+
}));
|
|
74
|
+
}
|
|
75
|
+
function subscribe(socket, ctx, cleanup) {
|
|
76
|
+
const listener = (delivery) => writeLine(socket, { ok: true, body: delivery });
|
|
77
|
+
ctx.listeners.add(listener);
|
|
78
|
+
cleanup.push(() => ctx.listeners.delete(listener));
|
|
79
|
+
writeLine(socket, { ok: true, body: { subscribed: true, pid: process.pid } });
|
|
80
|
+
}
|
|
81
|
+
function onWait(socket, message, ctx, cleanup) {
|
|
82
|
+
const request = message.request;
|
|
83
|
+
if (!request || typeof request.kind !== "string") {
|
|
84
|
+
writeLine(socket, { ok: false, error: "wait request missing" });
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
seedChecksHead(ctx, request);
|
|
88
|
+
ctx.waiters.count += 1;
|
|
89
|
+
const waiter = new Waiter(socket, request, ctx, Number(message.timeoutMs ?? DEFAULT_WAIT_MS));
|
|
90
|
+
cleanup.push(() => waiter.cancel());
|
|
91
|
+
waiter.start();
|
|
92
|
+
}
|
|
93
|
+
function seedChecksHead(ctx, request) {
|
|
94
|
+
if (request.kind !== "checks" || request.initialHead)
|
|
95
|
+
return;
|
|
96
|
+
request.initialHead = ctx.db.getSnapshot(request.repo, "pull_request", String(request.pr))?.data?.head?.sha;
|
|
97
|
+
}
|
|
98
|
+
function writeLine(socket, message) {
|
|
99
|
+
if (socket.destroyed)
|
|
100
|
+
return;
|
|
101
|
+
socket.write(`${JSON.stringify(message)}\n`);
|
|
102
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { StateStore } from "../db.js";
|
|
3
|
+
import { postDelivery } from "../delivery.js";
|
|
4
|
+
import { GitHub, resolveToken } from "../github.js";
|
|
5
|
+
import { Poller } from "../poller.js";
|
|
6
|
+
import { errorMessage, nowIso } from "../util.js";
|
|
7
|
+
const PRUNE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
8
|
+
export function createRuntime(initial, options, socketPath) {
|
|
9
|
+
const db = new StateStore(join(initial.stateDir, "state.db"));
|
|
10
|
+
db.prune(PRUNE_MS);
|
|
11
|
+
const gh = options.gh ?? new GitHub(resolveToken(), db);
|
|
12
|
+
const listeners = new Set();
|
|
13
|
+
const waiters = { count: 0 };
|
|
14
|
+
const ref = { config: initial, reloadedAt: null, error: null };
|
|
15
|
+
const emit = createEmit(() => ref.config, db, listeners, ref);
|
|
16
|
+
ref.poller = new Poller(initial, db, gh, emit);
|
|
17
|
+
ref.poller.start();
|
|
18
|
+
const status = () => ({
|
|
19
|
+
pid: process.pid,
|
|
20
|
+
socket: socketPath,
|
|
21
|
+
quota: gh instanceof GitHub ? gh.quota : null,
|
|
22
|
+
http: gh instanceof GitHub ? gh.stats : null,
|
|
23
|
+
repos: ref.poller?.listStatuses() ?? [],
|
|
24
|
+
waiters: waiters.count,
|
|
25
|
+
deliveries: db.countDeliveries(),
|
|
26
|
+
configReloadedAt: ref.reloadedAt,
|
|
27
|
+
configError: ref.error,
|
|
28
|
+
});
|
|
29
|
+
const poke = (repo) => ref.poller?.poke(repo) ?? false;
|
|
30
|
+
const config = () => ref.config;
|
|
31
|
+
const stop = () => ref.poller?.stop();
|
|
32
|
+
const reload = (next) => {
|
|
33
|
+
ref.poller?.stop();
|
|
34
|
+
ref.config = next;
|
|
35
|
+
ref.poller = new Poller(next, db, gh, emit);
|
|
36
|
+
ref.poller.start();
|
|
37
|
+
ref.reloadedAt = nowIso();
|
|
38
|
+
ref.error = null;
|
|
39
|
+
};
|
|
40
|
+
const configError = (error) => {
|
|
41
|
+
ref.error = errorMessage(error);
|
|
42
|
+
};
|
|
43
|
+
return {
|
|
44
|
+
db,
|
|
45
|
+
config,
|
|
46
|
+
reload,
|
|
47
|
+
configError,
|
|
48
|
+
stop,
|
|
49
|
+
context: { db, listeners, status, poke, waiters },
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function createEmit(currentConfig, db, listeners, ref) {
|
|
53
|
+
return (repo, event, action, key, payload, state) => {
|
|
54
|
+
const delivery = db.recordDelivery(repo, event, action, key, state, payload);
|
|
55
|
+
if (!delivery)
|
|
56
|
+
return;
|
|
57
|
+
ref.poller?.markEvent(repo);
|
|
58
|
+
for (const listener of listeners) {
|
|
59
|
+
try {
|
|
60
|
+
listener(delivery);
|
|
61
|
+
}
|
|
62
|
+
catch { }
|
|
63
|
+
}
|
|
64
|
+
const deliver = currentConfig().deliver;
|
|
65
|
+
if (!deliver)
|
|
66
|
+
return;
|
|
67
|
+
void postDelivery(delivery, deliver)
|
|
68
|
+
.then(() => db.markDelivered(delivery.id))
|
|
69
|
+
.catch((error) => console.error(`[pollhook] delivery ${delivery.id} failed: ${errorMessage(error)}`));
|
|
70
|
+
};
|
|
71
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { resolveWait } from "../waits.js";
|
|
2
|
+
const POLL_MS = 250;
|
|
3
|
+
export class Waiter {
|
|
4
|
+
socket;
|
|
5
|
+
request;
|
|
6
|
+
ctx;
|
|
7
|
+
timeoutMs;
|
|
8
|
+
settled = false;
|
|
9
|
+
interval;
|
|
10
|
+
timer;
|
|
11
|
+
constructor(socket, request, ctx, timeoutMs) {
|
|
12
|
+
this.socket = socket;
|
|
13
|
+
this.request = request;
|
|
14
|
+
this.ctx = ctx;
|
|
15
|
+
this.timeoutMs = timeoutMs;
|
|
16
|
+
}
|
|
17
|
+
start() {
|
|
18
|
+
this.ctx.listeners.add(this.wake);
|
|
19
|
+
this.interval = setInterval(this.wake, POLL_MS);
|
|
20
|
+
this.timer = setTimeout(() => this.finish({ exitCode: 8, body: { reason: "timeout" } }), this.timeoutMs);
|
|
21
|
+
this.wake();
|
|
22
|
+
}
|
|
23
|
+
wake = () => {
|
|
24
|
+
const outcome = resolveWait(this.ctx.db, this.request);
|
|
25
|
+
if (outcome)
|
|
26
|
+
this.finish(outcome);
|
|
27
|
+
};
|
|
28
|
+
finish(outcome) {
|
|
29
|
+
if (!this.release())
|
|
30
|
+
return;
|
|
31
|
+
this.socket.write(`${JSON.stringify({ ok: true, ...outcome })}\n`);
|
|
32
|
+
}
|
|
33
|
+
cancel() {
|
|
34
|
+
this.release();
|
|
35
|
+
}
|
|
36
|
+
release() {
|
|
37
|
+
if (this.settled)
|
|
38
|
+
return false;
|
|
39
|
+
this.settled = true;
|
|
40
|
+
if (this.interval)
|
|
41
|
+
clearInterval(this.interval);
|
|
42
|
+
if (this.timer)
|
|
43
|
+
clearTimeout(this.timer);
|
|
44
|
+
this.ctx.listeners.delete(this.wake);
|
|
45
|
+
this.ctx.waiters.count -= 1;
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { watchFile, unwatchFile } from "node:fs";
|
|
2
|
+
const DEBOUNCE_MS = 200;
|
|
3
|
+
export function watchConfig(path, onChange, onError) {
|
|
4
|
+
let timer = null;
|
|
5
|
+
watchFile(path, { interval: 1000 }, (current, previous) => {
|
|
6
|
+
if (current.mtimeMs === previous.mtimeMs)
|
|
7
|
+
return;
|
|
8
|
+
if (timer)
|
|
9
|
+
clearTimeout(timer);
|
|
10
|
+
timer = setTimeout(() => {
|
|
11
|
+
timer = null;
|
|
12
|
+
try {
|
|
13
|
+
onChange();
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
onError(error);
|
|
17
|
+
}
|
|
18
|
+
}, DEBOUNCE_MS);
|
|
19
|
+
});
|
|
20
|
+
return {
|
|
21
|
+
stop() {
|
|
22
|
+
if (timer)
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
unwatchFile(path);
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|