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/daemon.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { rmSync } from "node:fs";
|
|
2
|
+
import { connect, createServer } from "node:net";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { configPath, loadConfig } from "./config.js";
|
|
5
|
+
import { handleConnection } from "./daemon/handlers.js";
|
|
6
|
+
import { createRuntime } from "./daemon/runtime.js";
|
|
7
|
+
import { watchConfig } from "./daemon/watch.js";
|
|
8
|
+
export function socketPathFor(config) {
|
|
9
|
+
return join(process.env.XDG_RUNTIME_DIR ?? config.stateDir, "pollhook.sock");
|
|
10
|
+
}
|
|
11
|
+
export async function startDaemon(config, options = {}) {
|
|
12
|
+
const socketPath = options.socketPath ?? socketPathFor(config);
|
|
13
|
+
if (await socketAlive(socketPath)) {
|
|
14
|
+
throw new Error(`another pollhook is listening on ${socketPath}`);
|
|
15
|
+
}
|
|
16
|
+
const runtime = createRuntime(config, options, socketPath);
|
|
17
|
+
const sockets = new Set();
|
|
18
|
+
const server = createServer((socket) => {
|
|
19
|
+
sockets.add(socket);
|
|
20
|
+
socket.on("close", () => sockets.delete(socket));
|
|
21
|
+
handleConnection(socket, runtime.context);
|
|
22
|
+
});
|
|
23
|
+
await listen(server, socketPath);
|
|
24
|
+
let resolveClosed = () => { };
|
|
25
|
+
const closed = new Promise((resolve) => {
|
|
26
|
+
resolveClosed = resolve;
|
|
27
|
+
});
|
|
28
|
+
const path = configPath(options.configPath);
|
|
29
|
+
const reload = () => {
|
|
30
|
+
try {
|
|
31
|
+
runtime.reload(loadConfig(path));
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
runtime.configError(error);
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
const watch = options.watch === false ? null : watchConfig(path, reload, runtime.configError);
|
|
38
|
+
process.on("SIGHUP", reload);
|
|
39
|
+
process.once("SIGINT", () => void close());
|
|
40
|
+
process.once("SIGTERM", () => void close());
|
|
41
|
+
const stop = createClose(server, runtime, sockets, socketPath, resolveClosed);
|
|
42
|
+
const close = async () => {
|
|
43
|
+
watch?.stop();
|
|
44
|
+
process.off("SIGHUP", reload);
|
|
45
|
+
await stop();
|
|
46
|
+
};
|
|
47
|
+
return { socketPath, closed, close };
|
|
48
|
+
}
|
|
49
|
+
async function listen(server, path) {
|
|
50
|
+
rmSync(path, { force: true });
|
|
51
|
+
await new Promise((resolve, reject) => {
|
|
52
|
+
server.once("error", reject);
|
|
53
|
+
server.listen(path, () => {
|
|
54
|
+
server.off("error", reject);
|
|
55
|
+
resolve();
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
function createClose(server, runtime, sockets, socketPath, resolveClosed) {
|
|
60
|
+
let closing = false;
|
|
61
|
+
return async () => {
|
|
62
|
+
if (closing)
|
|
63
|
+
return;
|
|
64
|
+
closing = true;
|
|
65
|
+
runtime.stop();
|
|
66
|
+
for (const socket of sockets)
|
|
67
|
+
socket.destroy();
|
|
68
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
69
|
+
runtime.db.close();
|
|
70
|
+
rmSync(socketPath, { force: true });
|
|
71
|
+
resolveClosed();
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function socketAlive(path) {
|
|
75
|
+
return new Promise((resolve) => {
|
|
76
|
+
const socket = connect(path);
|
|
77
|
+
socket.once("connect", () => {
|
|
78
|
+
socket.destroy();
|
|
79
|
+
resolve(true);
|
|
80
|
+
});
|
|
81
|
+
socket.once("error", () => resolve(false));
|
|
82
|
+
});
|
|
83
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export class CursorRepository {
|
|
2
|
+
db;
|
|
3
|
+
constructor(db) {
|
|
4
|
+
this.db = db;
|
|
5
|
+
}
|
|
6
|
+
get(kind) {
|
|
7
|
+
const row = this.db.prepare("select etag, value from cursors where kind = ?").get(kind);
|
|
8
|
+
return row ?? null;
|
|
9
|
+
}
|
|
10
|
+
set(kind, etag, value) {
|
|
11
|
+
this.db
|
|
12
|
+
.prepare(`insert into cursors (kind, etag, value) values (?, ?, ?)
|
|
13
|
+
on conflict (kind) do update set etag = excluded.etag, value = excluded.value`)
|
|
14
|
+
.run(kind, etag, value);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { nowIso, sha256 } from "../util.js";
|
|
3
|
+
function toDelivery(row) {
|
|
4
|
+
return {
|
|
5
|
+
id: row.id,
|
|
6
|
+
repo: row.repo,
|
|
7
|
+
event: row.event,
|
|
8
|
+
action: row.action,
|
|
9
|
+
key: row.key,
|
|
10
|
+
payload: JSON.parse(row.payload),
|
|
11
|
+
createdAt: row.created_at,
|
|
12
|
+
deliveredAt: row.delivered_at,
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export class DeliveryRepository {
|
|
16
|
+
db;
|
|
17
|
+
constructor(db) {
|
|
18
|
+
this.db = db;
|
|
19
|
+
}
|
|
20
|
+
record(repo, event, action, key, state, payload) {
|
|
21
|
+
const fingerprint = sha256(`${repo}|${event}|${key}|${state}|${action ?? ""}`);
|
|
22
|
+
const id = randomUUID();
|
|
23
|
+
const createdAt = nowIso();
|
|
24
|
+
const info = this.db
|
|
25
|
+
.prepare(`insert or ignore into deliveries (id, repo, event, action, key, fingerprint, payload, created_at, delivered_at)
|
|
26
|
+
values (?, ?, ?, ?, ?, ?, ?, ?, null)`)
|
|
27
|
+
.run(id, repo, event, action, key, fingerprint, JSON.stringify(payload), createdAt);
|
|
28
|
+
if (info.changes === 0)
|
|
29
|
+
return null;
|
|
30
|
+
return { id, repo, event, action, key, payload, createdAt, deliveredAt: null };
|
|
31
|
+
}
|
|
32
|
+
markDelivered(id) {
|
|
33
|
+
this.db.prepare("update deliveries set delivered_at = ? where id = ?").run(nowIso(), id);
|
|
34
|
+
}
|
|
35
|
+
list(limit, repo) {
|
|
36
|
+
const rows = (repo
|
|
37
|
+
? this.db
|
|
38
|
+
.prepare("select id, repo, event, action, key, payload, created_at, delivered_at from deliveries where repo = ? order by rowid desc limit ?")
|
|
39
|
+
.all(repo, limit)
|
|
40
|
+
: this.db
|
|
41
|
+
.prepare("select id, repo, event, action, key, payload, created_at, delivered_at from deliveries order by rowid desc limit ?")
|
|
42
|
+
.all(limit));
|
|
43
|
+
return rows.map(toDelivery);
|
|
44
|
+
}
|
|
45
|
+
latest(repo, event) {
|
|
46
|
+
const row = this.db
|
|
47
|
+
.prepare("select id, repo, event, action, key, payload, created_at, delivered_at from deliveries where repo = ? and event = ? order by rowid desc limit 1")
|
|
48
|
+
.get(repo, event);
|
|
49
|
+
return row ? toDelivery(row) : null;
|
|
50
|
+
}
|
|
51
|
+
count() {
|
|
52
|
+
const row = this.db.prepare("select count(*) as count from deliveries").get();
|
|
53
|
+
return row.count;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { nowIso } from "../util.js";
|
|
2
|
+
const KEEP_PER_WORKFLOW = 20;
|
|
3
|
+
const MIN_SAMPLES = 3;
|
|
4
|
+
export class DurationRepository {
|
|
5
|
+
db;
|
|
6
|
+
constructor(db) {
|
|
7
|
+
this.db = db;
|
|
8
|
+
}
|
|
9
|
+
record(repo, runId, workflowId, durationMs) {
|
|
10
|
+
if (!Number.isFinite(durationMs) || durationMs <= 0)
|
|
11
|
+
return;
|
|
12
|
+
this.db
|
|
13
|
+
.prepare(`insert or ignore into run_durations (repo, run_id, workflow_id, duration_ms, recorded_at)
|
|
14
|
+
values (?, ?, ?, ?, ?)`)
|
|
15
|
+
.run(repo, runId, workflowId, Math.round(durationMs), nowIso());
|
|
16
|
+
this.db
|
|
17
|
+
.prepare(`delete from run_durations where repo = ? and workflow_id = ? and rowid not in
|
|
18
|
+
(select rowid from run_durations where repo = ? and workflow_id = ?
|
|
19
|
+
order by rowid desc limit ?)`)
|
|
20
|
+
.run(repo, workflowId, repo, workflowId, KEEP_PER_WORKFLOW);
|
|
21
|
+
}
|
|
22
|
+
typical(repo, workflowId) {
|
|
23
|
+
const rows = this.db
|
|
24
|
+
.prepare(`select duration_ms from run_durations where repo = ? and workflow_id = ?
|
|
25
|
+
order by rowid desc limit ?`)
|
|
26
|
+
.all(repo, workflowId, KEEP_PER_WORKFLOW);
|
|
27
|
+
if (rows.length < MIN_SAMPLES)
|
|
28
|
+
return null;
|
|
29
|
+
const values = rows.map((row) => row.duration_ms).sort((a, b) => a - b);
|
|
30
|
+
const middle = Math.floor(values.length / 2);
|
|
31
|
+
const median = values.length % 2 === 1
|
|
32
|
+
? values[middle]
|
|
33
|
+
: Math.round((values[middle - 1] + values[middle]) / 2);
|
|
34
|
+
return { typicalMs: median, samples: rows.length };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export const SCHEMA = `
|
|
2
|
+
create table if not exists snapshots (
|
|
3
|
+
repo text not null,
|
|
4
|
+
event text not null,
|
|
5
|
+
key text not null,
|
|
6
|
+
state text not null,
|
|
7
|
+
data text not null,
|
|
8
|
+
updated_at text not null,
|
|
9
|
+
primary key (repo, event, key)
|
|
10
|
+
);
|
|
11
|
+
create table if not exists cursors (
|
|
12
|
+
kind text primary key,
|
|
13
|
+
etag text,
|
|
14
|
+
value text
|
|
15
|
+
);
|
|
16
|
+
create table if not exists deliveries (
|
|
17
|
+
id text primary key,
|
|
18
|
+
repo text not null,
|
|
19
|
+
event text not null,
|
|
20
|
+
action text,
|
|
21
|
+
key text not null,
|
|
22
|
+
fingerprint text not null,
|
|
23
|
+
payload text not null,
|
|
24
|
+
created_at text not null,
|
|
25
|
+
delivered_at text,
|
|
26
|
+
unique (repo, event, fingerprint)
|
|
27
|
+
);
|
|
28
|
+
drop table if exists workflow_durations;
|
|
29
|
+
create table if not exists run_durations (
|
|
30
|
+
repo text not null,
|
|
31
|
+
run_id text not null,
|
|
32
|
+
workflow_id text not null,
|
|
33
|
+
duration_ms integer not null,
|
|
34
|
+
recorded_at text not null,
|
|
35
|
+
unique (repo, run_id)
|
|
36
|
+
);
|
|
37
|
+
create index if not exists run_durations_lookup on run_durations (repo, workflow_id);
|
|
38
|
+
create index if not exists deliveries_repo_event on deliveries (repo, event);
|
|
39
|
+
`;
|
|
40
|
+
export const KEEP_PER_GROUP = 500;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { nowIso } from "../util.js";
|
|
2
|
+
export class SnapshotRepository {
|
|
3
|
+
db;
|
|
4
|
+
constructor(db) {
|
|
5
|
+
this.db = db;
|
|
6
|
+
}
|
|
7
|
+
get(repo, event, key) {
|
|
8
|
+
const row = this.db
|
|
9
|
+
.prepare("select state, data, updated_at from snapshots where repo = ? and event = ? and key = ?")
|
|
10
|
+
.get(repo, event, key);
|
|
11
|
+
if (!row)
|
|
12
|
+
return null;
|
|
13
|
+
return { state: row.state, data: JSON.parse(row.data), updatedAt: row.updated_at };
|
|
14
|
+
}
|
|
15
|
+
put(repo, event, key, state, data) {
|
|
16
|
+
this.db
|
|
17
|
+
.prepare(`insert into snapshots (repo, event, key, state, data, updated_at)
|
|
18
|
+
values (?, ?, ?, ?, ?, ?)
|
|
19
|
+
on conflict (repo, event, key) do update
|
|
20
|
+
set state = excluded.state, data = excluded.data, updated_at = excluded.updated_at`)
|
|
21
|
+
.run(repo, event, key, state, JSON.stringify(data), nowIso());
|
|
22
|
+
}
|
|
23
|
+
list(repo, event) {
|
|
24
|
+
const rows = this.db
|
|
25
|
+
.prepare("select repo, event, key, state, data, updated_at from snapshots where repo = ? and event = ? order by updated_at desc, rowid desc")
|
|
26
|
+
.all(repo, event);
|
|
27
|
+
return rows.map((row) => ({
|
|
28
|
+
repo: row.repo,
|
|
29
|
+
event: row.event,
|
|
30
|
+
key: row.key,
|
|
31
|
+
state: row.state,
|
|
32
|
+
data: JSON.parse(row.data),
|
|
33
|
+
updatedAt: row.updated_at,
|
|
34
|
+
}));
|
|
35
|
+
}
|
|
36
|
+
}
|
package/dist/db/store.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
import { CursorRepository } from "./cursors.js";
|
|
5
|
+
import { DeliveryRepository } from "./deliveries.js";
|
|
6
|
+
import { DurationRepository } from "./durations.js";
|
|
7
|
+
import { KEEP_PER_GROUP, SCHEMA } from "./schema.js";
|
|
8
|
+
import { SnapshotRepository } from "./snapshots.js";
|
|
9
|
+
export class StateStore {
|
|
10
|
+
db;
|
|
11
|
+
snapshots;
|
|
12
|
+
deliveries;
|
|
13
|
+
durations;
|
|
14
|
+
cursors;
|
|
15
|
+
constructor(path) {
|
|
16
|
+
if (path !== ":memory:")
|
|
17
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
18
|
+
this.db = new DatabaseSync(path);
|
|
19
|
+
this.db.exec("pragma journal_mode = wal");
|
|
20
|
+
this.db.exec(SCHEMA);
|
|
21
|
+
this.snapshots = new SnapshotRepository(this.db);
|
|
22
|
+
this.deliveries = new DeliveryRepository(this.db);
|
|
23
|
+
this.cursors = new CursorRepository(this.db);
|
|
24
|
+
this.durations = new DurationRepository(this.db);
|
|
25
|
+
}
|
|
26
|
+
getSnapshot(repo, event, key) {
|
|
27
|
+
return this.snapshots.get(repo, event, key);
|
|
28
|
+
}
|
|
29
|
+
putSnapshot(repo, event, key, state, data) {
|
|
30
|
+
this.snapshots.put(repo, event, key, state, data);
|
|
31
|
+
}
|
|
32
|
+
listSnapshots(repo, event) {
|
|
33
|
+
return this.snapshots.list(repo, event);
|
|
34
|
+
}
|
|
35
|
+
getCursor(kind) {
|
|
36
|
+
return this.cursors.get(kind);
|
|
37
|
+
}
|
|
38
|
+
setCursor(kind, etag, value) {
|
|
39
|
+
this.cursors.set(kind, etag, value);
|
|
40
|
+
}
|
|
41
|
+
recordDelivery(repo, event, action, key, state, payload) {
|
|
42
|
+
return this.deliveries.record(repo, event, action, key, state, payload);
|
|
43
|
+
}
|
|
44
|
+
markDelivered(id) {
|
|
45
|
+
this.deliveries.markDelivered(id);
|
|
46
|
+
}
|
|
47
|
+
listDeliveries(limit, repo) {
|
|
48
|
+
return this.deliveries.list(limit, repo);
|
|
49
|
+
}
|
|
50
|
+
latestDelivery(repo, event) {
|
|
51
|
+
return this.deliveries.latest(repo, event);
|
|
52
|
+
}
|
|
53
|
+
countDeliveries() {
|
|
54
|
+
return this.deliveries.count();
|
|
55
|
+
}
|
|
56
|
+
prune(maxAgeMs) {
|
|
57
|
+
const cutoff = new Date(Date.now() - maxAgeMs).toISOString();
|
|
58
|
+
this.db.prepare("delete from snapshots where updated_at < ?").run(cutoff);
|
|
59
|
+
this.db.prepare("delete from deliveries where created_at < ?").run(cutoff);
|
|
60
|
+
const groups = this.db.prepare("select distinct repo, event from snapshots").all();
|
|
61
|
+
for (const group of groups) {
|
|
62
|
+
this.db
|
|
63
|
+
.prepare(`delete from snapshots where repo = ? and event = ? and rowid not in
|
|
64
|
+
(select rowid from snapshots where repo = ? and event = ? order by updated_at desc limit ?)`)
|
|
65
|
+
.run(group.repo, group.event, group.repo, group.event, KEEP_PER_GROUP);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
close() {
|
|
69
|
+
this.db.close();
|
|
70
|
+
}
|
|
71
|
+
}
|
package/dist/db.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { StateStore } from "./db/store.js";
|
package/dist/delivery.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { createHmac } from "node:crypto";
|
|
2
|
+
import { sleep } from "./util.js";
|
|
3
|
+
export function signatureHeaders(body, secret) {
|
|
4
|
+
if (!secret)
|
|
5
|
+
return {};
|
|
6
|
+
return {
|
|
7
|
+
"x-hub-signature-256": `sha256=${createHmac("sha256", secret).update(body).digest("hex")}`,
|
|
8
|
+
"x-hub-signature": `sha1=${createHmac("sha1", secret).update(body).digest("hex")}`,
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
export function deliveryHeaders(delivery, secret) {
|
|
12
|
+
const body = JSON.stringify(delivery.payload);
|
|
13
|
+
return {
|
|
14
|
+
"content-type": "application/json",
|
|
15
|
+
"user-agent": "pollhook/0.1.0",
|
|
16
|
+
"x-github-event": delivery.event,
|
|
17
|
+
"x-github-delivery": delivery.id,
|
|
18
|
+
"x-github-hook-id": "pollhook",
|
|
19
|
+
"x-github-hook-installation-target-type": "repository",
|
|
20
|
+
"x-github-hook-installation-target-id": String(delivery.payload.repository?.id ?? ""),
|
|
21
|
+
...signatureHeaders(body, secret),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
const MAX_ATTEMPTS = 5;
|
|
25
|
+
const BASE_DELAY_MS = 500;
|
|
26
|
+
class Rejected extends Error {
|
|
27
|
+
}
|
|
28
|
+
export async function postDelivery(delivery, target) {
|
|
29
|
+
const body = JSON.stringify(delivery.payload);
|
|
30
|
+
let lastError = new Error("delivery was never attempted");
|
|
31
|
+
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {
|
|
32
|
+
try {
|
|
33
|
+
const response = await fetch(target.url, {
|
|
34
|
+
method: "POST",
|
|
35
|
+
headers: deliveryHeaders(delivery, target.secret),
|
|
36
|
+
body,
|
|
37
|
+
signal: AbortSignal.timeout(5000),
|
|
38
|
+
});
|
|
39
|
+
if (response.ok)
|
|
40
|
+
return;
|
|
41
|
+
if (!isRetryable(response.status))
|
|
42
|
+
throw new Rejected(`delivery rejected with ${response.status}`);
|
|
43
|
+
lastError = new Error(`delivery failed with ${response.status}`);
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (error instanceof Rejected)
|
|
47
|
+
throw new Error(error.message);
|
|
48
|
+
lastError = error;
|
|
49
|
+
}
|
|
50
|
+
if (attempt < MAX_ATTEMPTS)
|
|
51
|
+
await sleep(BASE_DELAY_MS * 2 ** (attempt - 1));
|
|
52
|
+
}
|
|
53
|
+
throw lastError;
|
|
54
|
+
}
|
|
55
|
+
function isRetryable(status) {
|
|
56
|
+
return status >= 500 || status === 408 || status === 429;
|
|
57
|
+
}
|
package/dist/github.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { sleep } from "./util.js";
|
|
3
|
+
const DEFAULT_BASE = "https://api.github.com";
|
|
4
|
+
const API_VERSION = "2022-11-28";
|
|
5
|
+
const MIN_REMAINING = 100;
|
|
6
|
+
function isRateLimited(response) {
|
|
7
|
+
if (response.status !== 403 && response.status !== 429)
|
|
8
|
+
return false;
|
|
9
|
+
return (response.headers.get("retry-after") !== null ||
|
|
10
|
+
response.headers.get("x-ratelimit-remaining") === "0");
|
|
11
|
+
}
|
|
12
|
+
export class GitHubError extends Error {
|
|
13
|
+
status;
|
|
14
|
+
constructor(status, path, body) {
|
|
15
|
+
super(`${status} ${path}: ${body.slice(0, 200)}`);
|
|
16
|
+
this.status = status;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export function resolveToken(env = process.env, ghToken = readGhToken) {
|
|
20
|
+
if (env.POLLHOOK_TOKEN)
|
|
21
|
+
return env.POLLHOOK_TOKEN;
|
|
22
|
+
const fromGh = ghToken();
|
|
23
|
+
if (fromGh)
|
|
24
|
+
return fromGh;
|
|
25
|
+
const fromEnv = env.GH_TOKEN || env.GITHUB_TOKEN;
|
|
26
|
+
if (fromEnv)
|
|
27
|
+
return fromEnv;
|
|
28
|
+
throw new Error("no GitHub token: set POLLHOOK_TOKEN, run `gh auth login`, or set GH_TOKEN");
|
|
29
|
+
}
|
|
30
|
+
function readGhToken() {
|
|
31
|
+
try {
|
|
32
|
+
return execFileSync("gh", ["auth", "token"], { encoding: "utf8" }).trim();
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return "";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export class GitHub {
|
|
39
|
+
etags = new Map();
|
|
40
|
+
memoValues = new Map();
|
|
41
|
+
token;
|
|
42
|
+
db;
|
|
43
|
+
baseUrl;
|
|
44
|
+
quota = { limit: 0, remaining: 5000, resetAt: null };
|
|
45
|
+
stats = { requests: 0, notModified: 0 };
|
|
46
|
+
constructor(token, db, baseUrl = DEFAULT_BASE) {
|
|
47
|
+
this.token = token;
|
|
48
|
+
this.db = db;
|
|
49
|
+
this.baseUrl = baseUrl;
|
|
50
|
+
}
|
|
51
|
+
async get(path, opts = {}) {
|
|
52
|
+
const etagKey = opts.etagKey;
|
|
53
|
+
const etag = etagKey
|
|
54
|
+
? (this.etags.get(etagKey) ?? this.db.getCursor(etagKey)?.etag ?? undefined)
|
|
55
|
+
: undefined;
|
|
56
|
+
for (let attempt = 0;; attempt++) {
|
|
57
|
+
await this.gate();
|
|
58
|
+
const headers = {
|
|
59
|
+
accept: "application/vnd.github+json",
|
|
60
|
+
authorization: `Bearer ${this.token}`,
|
|
61
|
+
"user-agent": "pollhook/0.1.0",
|
|
62
|
+
"x-github-api-version": API_VERSION,
|
|
63
|
+
};
|
|
64
|
+
if (etag)
|
|
65
|
+
headers["if-none-match"] = etag;
|
|
66
|
+
const response = await fetch(this.baseUrl + path, {
|
|
67
|
+
headers,
|
|
68
|
+
signal: AbortSignal.timeout(20_000),
|
|
69
|
+
});
|
|
70
|
+
this.readQuota(response);
|
|
71
|
+
this.stats.requests += 1;
|
|
72
|
+
if (response.status === 304) {
|
|
73
|
+
this.stats.notModified += 1;
|
|
74
|
+
return { notModified: true, data: undefined };
|
|
75
|
+
}
|
|
76
|
+
if (isRateLimited(response) && attempt < 1) {
|
|
77
|
+
await this.backOff(response);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (response.status >= 500 && attempt < 2) {
|
|
81
|
+
await sleep(500 * 2 ** attempt);
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (!response.ok)
|
|
85
|
+
throw new GitHubError(response.status, path, await response.text());
|
|
86
|
+
const nextEtag = response.headers.get("etag");
|
|
87
|
+
if (nextEtag && etagKey) {
|
|
88
|
+
this.etags.set(etagKey, nextEtag);
|
|
89
|
+
this.db.setCursor(etagKey, nextEtag, null);
|
|
90
|
+
}
|
|
91
|
+
return { notModified: false, data: (await response.json()) };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async probe(path) {
|
|
95
|
+
await this.gate();
|
|
96
|
+
const response = await fetch(this.baseUrl + path, {
|
|
97
|
+
headers: {
|
|
98
|
+
accept: "application/vnd.github+json",
|
|
99
|
+
authorization: `Bearer ${this.token}`,
|
|
100
|
+
"user-agent": "pollhook/0.1.0",
|
|
101
|
+
"x-github-api-version": API_VERSION,
|
|
102
|
+
},
|
|
103
|
+
signal: AbortSignal.timeout(20_000),
|
|
104
|
+
});
|
|
105
|
+
this.readQuota(response);
|
|
106
|
+
this.stats.requests += 1;
|
|
107
|
+
if (response.status === 404)
|
|
108
|
+
return false;
|
|
109
|
+
if (!response.ok)
|
|
110
|
+
throw new GitHubError(response.status, path, await response.text());
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
async repoInfo(repo) {
|
|
114
|
+
return this.memoized(`/repos/${repo}`, 10 * 60_000, async () => {
|
|
115
|
+
const result = await this.get(`/repos/${repo}`);
|
|
116
|
+
if (!result.data)
|
|
117
|
+
throw new Error(`empty repository response for ${repo}`);
|
|
118
|
+
return result.data;
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
async sender() {
|
|
122
|
+
return this.memoized("/user", 60 * 60_000, async () => {
|
|
123
|
+
const result = await this.get("/user");
|
|
124
|
+
return result.data ?? { login: "ghost" };
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
async memoized(key, ttlMs, load) {
|
|
128
|
+
const hit = this.memoValues.get(key);
|
|
129
|
+
if (hit && hit.at + ttlMs > Date.now())
|
|
130
|
+
return hit.value;
|
|
131
|
+
const value = await load();
|
|
132
|
+
this.memoValues.set(key, { at: Date.now(), value });
|
|
133
|
+
return value;
|
|
134
|
+
}
|
|
135
|
+
pressure() {
|
|
136
|
+
if (this.quota.limit <= 0)
|
|
137
|
+
return 1;
|
|
138
|
+
const share = this.quota.remaining / this.quota.limit;
|
|
139
|
+
if (share <= 0.05)
|
|
140
|
+
return 10;
|
|
141
|
+
if (share <= 0.15)
|
|
142
|
+
return 3;
|
|
143
|
+
return 1;
|
|
144
|
+
}
|
|
145
|
+
async backOff(response) {
|
|
146
|
+
const retryAfter = Number(response.headers.get("retry-after") ?? 0);
|
|
147
|
+
if (retryAfter > 0) {
|
|
148
|
+
await sleep(Math.min(retryAfter, 300) * 1000);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
await this.waitForReset();
|
|
152
|
+
}
|
|
153
|
+
readQuota(response) {
|
|
154
|
+
const limit = Number(response.headers.get("x-ratelimit-limit") ?? 0);
|
|
155
|
+
const remaining = Number(response.headers.get("x-ratelimit-remaining") ?? this.quota.remaining);
|
|
156
|
+
const reset = response.headers.get("x-ratelimit-reset");
|
|
157
|
+
this.quota = {
|
|
158
|
+
limit: limit || this.quota.limit,
|
|
159
|
+
remaining,
|
|
160
|
+
resetAt: reset ? new Date(Number(reset) * 1000).toISOString() : this.quota.resetAt,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
async gate() {
|
|
164
|
+
if (this.quota.remaining >= MIN_REMAINING || !this.quota.resetAt)
|
|
165
|
+
return;
|
|
166
|
+
await this.waitForReset();
|
|
167
|
+
}
|
|
168
|
+
async waitForReset() {
|
|
169
|
+
if (!this.quota.resetAt)
|
|
170
|
+
return;
|
|
171
|
+
const waitMs = Math.min(Date.parse(this.quota.resetAt) - Date.now(), 15 * 60_000);
|
|
172
|
+
if (waitMs > 0)
|
|
173
|
+
await sleep(waitMs + 1000);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { unique } from "../util.js";
|
|
2
|
+
const HEAD_TTL_MS = 30_000;
|
|
3
|
+
export class HeadCache {
|
|
4
|
+
entries = new Map();
|
|
5
|
+
async head(gh, repo) {
|
|
6
|
+
const cached = this.entries.get(repo);
|
|
7
|
+
if (cached && cached.at + HEAD_TTL_MS > Date.now())
|
|
8
|
+
return cached.sha;
|
|
9
|
+
try {
|
|
10
|
+
const info = await gh.repoInfo(repo);
|
|
11
|
+
const result = await gh.get(`/repos/${repo}/git/ref/heads/${encodeURIComponent(info.default_branch)}`);
|
|
12
|
+
const sha = result.data?.object?.sha;
|
|
13
|
+
if (!sha)
|
|
14
|
+
return null;
|
|
15
|
+
this.entries.set(repo, { at: Date.now(), sha });
|
|
16
|
+
return sha;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export async function refsFor(db, cache, gh, repo, events, limit) {
|
|
24
|
+
const wantsRefs = events.some((event) => event === "check_run" || event === "check_suite" || event === "status");
|
|
25
|
+
if (!wantsRefs)
|
|
26
|
+
return [];
|
|
27
|
+
const refs = db
|
|
28
|
+
.listSnapshots(repo, "pull_request")
|
|
29
|
+
.filter((row) => row.data?.state === "open" && typeof row.data?.head?.sha === "string")
|
|
30
|
+
.slice(0, limit)
|
|
31
|
+
.map((row) => row.data.head.sha);
|
|
32
|
+
const head = await cache.head(gh, repo);
|
|
33
|
+
if (head)
|
|
34
|
+
refs.push(head);
|
|
35
|
+
return unique(refs);
|
|
36
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const SLOW_INTERVAL_MS = 30_000;
|
|
2
|
+
const EARLY_SHARE = 0.5;
|
|
3
|
+
export function resolveInterval(config, target, adapter) {
|
|
4
|
+
return target.intervals?.[adapter.name] ?? config.intervals?.[adapter.name] ?? target.intervalMs;
|
|
5
|
+
}
|
|
6
|
+
export function resolveStrategy(config, target, adapter) {
|
|
7
|
+
return target.strategies?.[adapter.name] ?? config.strategies?.[adapter.name] ?? "fixed";
|
|
8
|
+
}
|
|
9
|
+
export function delayFor(adapter, intervalMs, db, repo, strategy = "fixed", pressure = 1) {
|
|
10
|
+
const base = Math.max(adapter.intervalFloorMs, intervalMs) * Math.max(1, pressure);
|
|
11
|
+
if (strategy !== "while-active")
|
|
12
|
+
return base;
|
|
13
|
+
return runsAreEarly(db, repo) ? Math.max(base, SLOW_INTERVAL_MS) : base;
|
|
14
|
+
}
|
|
15
|
+
function runsAreEarly(db, repo) {
|
|
16
|
+
const active = db
|
|
17
|
+
.listSnapshots(repo, "workflow_run")
|
|
18
|
+
.filter((row) => row.data?.status !== "completed");
|
|
19
|
+
if (active.length === 0)
|
|
20
|
+
return false;
|
|
21
|
+
return active.every((row) => {
|
|
22
|
+
const started = Date.parse(row.data?.run_started_at ?? "");
|
|
23
|
+
const typical = db.durations.typical(repo, String(row.data?.workflow_id ?? ""));
|
|
24
|
+
if (!Number.isFinite(started) || !typical)
|
|
25
|
+
return false;
|
|
26
|
+
return Date.now() - started < typical.typicalMs * EARLY_SHARE;
|
|
27
|
+
});
|
|
28
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { adaptersFor } from "../registry.js";
|
|
2
|
+
import { isStatus } from "../util.js";
|
|
3
|
+
export const DEGRADED_MS = 60 * 60 * 1000;
|
|
4
|
+
export function statusFor(kind, name, events) {
|
|
5
|
+
return {
|
|
6
|
+
repo: name,
|
|
7
|
+
kind,
|
|
8
|
+
events: [...events],
|
|
9
|
+
lastPollAt: null,
|
|
10
|
+
lastEventAt: null,
|
|
11
|
+
lastError: null,
|
|
12
|
+
nextPollAt: null,
|
|
13
|
+
degraded: [],
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export function statusList(statuses, nextDue, degraded) {
|
|
17
|
+
return [...statuses.values()].map((status) => ({
|
|
18
|
+
...status,
|
|
19
|
+
nextPollAt: nextPollFor(nextDue, status),
|
|
20
|
+
degraded: [...(degraded.get(status.repo) ?? new Map())].map(([event, reason]) => ({ event, reason })),
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
function nextPollFor(nextDue, status) {
|
|
24
|
+
const due = adaptersFor(status.events, status.kind)
|
|
25
|
+
.map((adapter) => nextDue.get(`${status.kind}:${status.repo}:${adapter.name}`))
|
|
26
|
+
.filter((value) => typeof value === "number");
|
|
27
|
+
if (due.length === 0)
|
|
28
|
+
return null;
|
|
29
|
+
return new Date(Math.min(...due)).toISOString();
|
|
30
|
+
}
|
|
31
|
+
export function isPermanent(error) {
|
|
32
|
+
return isStatus(error, 403) || isStatus(error, 404);
|
|
33
|
+
}
|