Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 43 additions & 22 deletions workers/nos-runner-watchdog/src/github.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { POOLS } from "./pools.js";

const API = "https://api.github.com";
const ORG = "nightowlstudiollc";
const VAR = "NOS_RUNNER";
const LABEL = "mimolette";

/** Non-2xx from GitHub. `what` names the call; it never holds a token. */
export class GitHubError extends Error {
Expand Down Expand Up @@ -83,30 +82,31 @@ export async function appToken(env, fetchFn, now = Date.now()) {
return out.token;
}

/** Online runners that carry the mimolette label, as [{name, busy}]. */
export async function getRunners(token, fetchFn) {
/** Online runners that carry the pool's label, as [{name, busy}]. */
export async function getRunners(token, fetchFn, pool = POOLS.nos) {
const out = await call(
token,
"GET",
`/orgs/${ORG}/actions/runners?per_page=100`,
`/orgs/${pool.org}/actions/runners?per_page=100`,
"runners",
fetchFn,
);
return (out.runners ?? [])
.filter(
(r) =>
r.status === "online" && (r.labels ?? []).some((l) => l.name === LABEL),
r.status === "online" &&
(r.labels ?? []).some((l) => l.name === pool.label),
)
.map((r) => ({ name: r.name, busy: Boolean(r.busy) }));
}

/** NOS_RUNNER value, or null when the variable does not exist. */
export async function getVar(token, fetchFn) {
/** The pool's variable value, or null when the variable does not exist. */
export async function getVar(token, fetchFn, pool = POOLS.nos) {
try {
const out = await call(
token,
"GET",
`/orgs/${ORG}/actions/variables/${VAR}`,
`/orgs/${pool.org}/actions/variables/${pool.variable}`,
"var get",
fetchFn,
);
Expand All @@ -117,14 +117,14 @@ export async function getVar(token, fetchFn) {
}
}

/** Updates NOS_RUNNER; creates it when the update returns 404. */
export async function setVar(token, value, fetchFn) {
const body = { name: VAR, value, visibility: "private" };
/** Updates the pool's variable; creates it when the update returns 404. */
export async function setVar(token, value, fetchFn, pool = POOLS.nos) {
const body = { name: pool.variable, value, visibility: pool.visibility };
try {
await call(
token,
"PATCH",
`/orgs/${ORG}/actions/variables/${VAR}`,
`/orgs/${pool.org}/actions/variables/${pool.variable}`,
"var update",
fetchFn,
body,
Expand All @@ -134,7 +134,7 @@ export async function setVar(token, value, fetchFn) {
await call(
token,
"POST",
`/orgs/${ORG}/actions/variables`,
`/orgs/${pool.org}/actions/variables`,
"var create",
fetchFn,
body,
Expand Down Expand Up @@ -177,10 +177,14 @@ export async function getJobs(token, repo, runId, fetchFn) {
return out.jobs ?? [];
}

/** Jobs on a mimolette runner that are still waiting or running. */
export function mimoletteJobs(jobs, statuses = ["queued", "in_progress"]) {
/** Jobs for the pool's runner label that are still waiting or running. */
export function mimoletteJobs(
jobs,
statuses = ["queued", "in_progress"],
pool = POOLS.nos,
) {
return jobs.filter(
(j) => statuses.includes(j.status) && (j.labels ?? []).includes(LABEL),
(j) => statuses.includes(j.status) && (j.labels ?? []).includes(pool.label),
);
}

Expand All @@ -190,7 +194,13 @@ const SCAN_STATUSES = ["queued", "in_progress"];
export const MAX_JOB_PROBES = 3;

/** One repo: its waiting runs, then jobs run by run until a queued mimolette job. Null when canFetch(n) refuses. */
export async function scanRepo(token, repo, fetchFn, canFetch = () => true) {
export async function scanRepo(
token,
repo,
fetchFn,
canFetch = () => true,
pool = POOLS.nos,
) {
// Ask for the worst case (lists + job probes) up front, so a started repo is never dropped half-read.
if (!canFetch(SCAN_STATUSES.length + MAX_JOB_PROBES)) return null;
const runs = [];
Expand All @@ -206,7 +216,7 @@ export async function scanRepo(token, repo, fetchFn, canFetch = () => true) {
for (const run of ordered.slice(0, MAX_JOB_PROBES)) {
const list = await getJobs(token, repo, run.id, fetchFn);
jobs.set(run.id, list);
const queued = mimoletteJobs(list, ["queued"]);
const queued = mimoletteJobs(list, ["queued"], pool);
if (queued.length === 0) continue;
oldestAt = Math.min(...queued.map((j) => Date.parse(j.created_at)));
break;
Expand All @@ -215,13 +225,24 @@ export async function scanRepo(token, repo, fetchFn, canFetch = () => true) {
}

/** Scans repos in rotation from cursor until canFetch(n) refuses. oldestAt is epoch ms or null. */
export async function scanQueue(token, fetchFn, { cursor = 0, canFetch } = {}) {
export async function scanQueue(
token,
fetchFn,
{ cursor = 0, canFetch } = {},
pool = POOLS.nos,
) {
const all = await listRepos(token, fetchFn);
const n = all.length;
const start = n > 0 ? ((cursor % n) + n) % n : 0;
const repos = [];
for (let i = 0; i < n; i += 1) {
const r = await scanRepo(token, all[(start + i) % n], fetchFn, canFetch);
const r = await scanRepo(
token,
all[(start + i) % n],
fetchFn,
canFetch,
pool,
);
if (!r) break;
repos.push(r);
}
Expand Down
76 changes: 45 additions & 31 deletions workers/nos-runner-watchdog/src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { decide } from "./decide.js";
import * as gh from "./github.js";
import { APPS, POOLS, poolForCron, appEnv } from "./pools.js";

// Free plan allows 50 subrequests a run; KV calls are counted too, for headroom.
export const CAP = 40;
Expand All @@ -11,22 +12,12 @@ const RESERVE_FINAL = 1;
const OPTIONAL_SHARE = 10;
// A pending run is dropped after this many failed status or rerun calls.
const MAX_ATTEMPTS = 6;
const FALLBACK = "ubuntu-latest";
const TOKEN_TTL = 3000;
// Skipped ticks in a row (about 30 minutes) before the one "watchdog skipping" alert.
const SKIP_ALERT = 3;
// Sends per alert. A tick sends at most two alerts, so retries fit in the CAP headroom.
const NTFY_TRIES = 3;

const MESSAGES = {
down: () =>
"NOS runner down: NOS_RUNNER set to ubuntu-latest; stuck runs cancelled for re-run.",
recovered: () => "NOS runner recovered: NOS_RUNNER set to mimolette.",
online: () => "NOS runner online: NOS_RUNNER was unset, now mimolette.",
held: (v) =>
`NOS runner held: NOS_RUNNER=${v}; the watchdog leaves it alone.`,
};

// Logs name the failed call and status only, never a URL, token or topic.
const describe = (e) =>
e instanceof gh.GitHubError ? e.message : (e?.name ?? "Error");
Expand All @@ -45,25 +36,40 @@ function makeBudget(cap) {
};
}

/** One watchdog tick. deps: {fetch, now}. Every fetch and KV call is counted against CAP. */
export async function runTick(env, { fetch: rawFetch, now }) {
/** One tick for one pool. deps: {fetch, now, pool}. Every fetch and KV call is counted against CAP. */
export async function runTick(env, { fetch: rawFetch, now, pool = POOLS.nos }) {
// An optional pool without its App secrets touches nothing: no fetch, no KV, not even the skips counter.
const app = appEnv(env, pool);
if (!app && pool.optional) {
log(`pool ${pool.id} not configured: App secrets missing`);
return;
}
// Other pools mint from their own App's raw values, so a missing secret fails the mint and goes through skipTick.
const a = APPS[pool.app];
const creds = app ?? {
APP_ID: env[a.idKey],
INSTALLATION_ID: env[a.installKey],
APP_KEY_PKCS8: env[a.keyKey],
};
const budget = makeBudget(CAP);
const fetchFn = (url, init) => {
budget.take();
return rawFetch(url, init);
};
// Every key carries the pool prefix; NOS has none, so its keys are unchanged.
const key = (k) => `${pool.prefix}${k}`;
const kv = {
get(k) {
budget.take();
return env.STATE.get(k);
return env.STATE.get(key(k));
},
put(k, v, opts) {
budget.take();
return env.STATE.put(k, v, opts);
return env.STATE.put(key(k), v, opts);
},
delete(k) {
budget.take();
return env.STATE.delete(k);
return env.STATE.delete(key(k));
},
};

Expand Down Expand Up @@ -110,15 +116,15 @@ export async function runTick(env, { fetch: rawFetch, now }) {
const count = (skips?.count ?? 0) + 1;
let notified = skips?.notified === true;
if (count >= SKIP_ALERT && !notified) {
notified = await notify(`watchdog skipping: ${reasonClass(e)}`);
notified = await notify(pool.messages.skip(reasonClass(e)));
}
await kv.put("skips", JSON.stringify({ count, notified }));
};

let token = null;
let cached = false;
const mint = async () => {
token = await gh.appToken(env, fetchFn, now);
token = await gh.appToken(creds, fetchFn, now);
cached = false;
await kv.put("token", token, { expirationTtl: TOKEN_TTL });
};
Expand All @@ -138,7 +144,7 @@ export async function runTick(env, { fetch: rawFetch, now }) {
// Required phase: any failure skips the tick; state, pendingReruns and GitHub stay untouched (the token cache may change).
const sweepLikely =
pending.length > 0 ||
prev.lastVar === FALLBACK ||
prev.lastVar === pool.fallback ||
prev.lastVar === null ||
(prev.misses ?? 0) >= 1;
const scanReserve =
Expand All @@ -150,12 +156,12 @@ export async function runTick(env, { fetch: rawFetch, now }) {
token = await kv.get("token");
cached = Boolean(token);
if (!token) await mint();
const runners = await withToken((t) => gh.getRunners(t, fetchFn));
const varValue = await withToken((t) => gh.getVar(t, fetchFn));
const runners = await withToken((t) => gh.getRunners(t, fetchFn, pool));
const varValue = await withToken((t) => gh.getVar(t, fetchFn, pool));
const canFetch = (n) => budget.canAfford(n + scanReserve);
const cursor = prev.cursor ?? 0;
scan = await withToken((t) =>
gh.scanQueue(t, fetchFn, { cursor, canFetch }),
gh.scanQueue(t, fetchFn, { cursor, canFetch }, pool),
);
repoOldest = mergeOldest(scan, prev.repoOldest ?? {});
const times = Object.values(repoOldest);
Expand All @@ -170,18 +176,21 @@ export async function runTick(env, { fetch: rawFetch, now }) {
return;
}

const decision = decide(prev, observed);
const decision = decide(prev, observed, {
selfHosted: pool.label,
fallback: pool.fallback,
});
if (decision.setVar) {
try {
await withToken((t) => gh.setVar(t, decision.setVar, fetchFn));
await withToken((t) => gh.setVar(t, decision.setVar, fetchFn, pool));
} catch (e) {
// State is not saved, so the next tick sees the same variable and decides again.
await skipTick("tick skipped: var write failed", e);
return;
}
}
// After a down switch, in_progress mimolette jobs stay in the sweep until the rotation covered every repo.
const fallback = decision.next.lastVar === FALLBACK;
const fallback = decision.next.lastVar === pool.fallback;
const prevLeft = fallback ? (prev.downSweepLeft ?? 0) : 0;
const downSweep = decision.rerunStuck || prevLeft > 0;
const downSweepLeft = Math.max(
Expand All @@ -199,16 +208,14 @@ export async function runTick(env, { fetch: rawFetch, now }) {
}),
);
if (decision.notify) {
await notify(MESSAGES[decision.notify](decision.next.lastVar));
await notify(pool.messages[decision.notify](decision.next.lastVar));
}
if (skips) {
if (skips.notified) await notify("watchdog ok: ticks are running again.");
if (skips.notified) await notify(pool.messages.ok);
await kv.delete("skips");
}
if (drill !== null) {
const ok = await notify(
"NOS runner drill: watchdog alert path. No action needed.",
);
const ok = await notify(pool.messages.drill);
await kv.put(
"drill-result",
JSON.stringify({
Expand Down Expand Up @@ -266,7 +273,7 @@ export async function runTick(env, { fetch: rawFetch, now }) {

// Plan cancels within the budget: each planned run keeps one call for its cancel.
const planned = [];
if (decision.rerunStuck || decision.next.lastVar === FALLBACK) {
if (decision.rerunStuck || decision.next.lastVar === pool.fallback) {
const statuses = downSweep ? ["queued", "in_progress"] : ["queued"];
const candidates = [];
for (const r of scan.repos) {
Expand All @@ -288,7 +295,7 @@ export async function runTick(env, { fetch: rawFetch, now }) {
if (!r.ok) continue;
jobs = r.value;
}
if (gh.mimoletteJobs(jobs, statuses).length === 0) continue;
if (gh.mimoletteJobs(jobs, statuses, pool).length === 0) continue;
if (!budget.canAfford(RESERVE_FINAL + planned.length + 1)) break;
planned.push({
repo: c.repo,
Expand Down Expand Up @@ -360,10 +367,17 @@ function mergeOldest(scan, carried) {
}

export default {
// Each cron trigger is one pool, so each pool gets its own invocation and subrequest budget.
async scheduled(event, env) {
const pool = poolForCron(event?.cron);
if (!pool) {
log(`unknown cron: ${event.cron}`);
return;
}
await runTick(env, {
fetch: (url, init) => fetch(url, init),
now: event?.scheduledTime ?? Date.now(),
pool,
});
},
};
6 changes: 4 additions & 2 deletions workers/nos-runner-watchdog/src/pools.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Runner pools the watchdog manages. NOS is the live pool; swmMacos is added dormant (no cron yet in wrangler.toml).
// Runner pools the watchdog manages. Each pool has its own cron in wrangler.toml; scheduled() picks the pool by cron.

export const APPS = {
nos: {
Expand All @@ -13,7 +13,7 @@ export const APPS = {
},
};

// NOS texts are copies of index.js MESSAGES; pool_nos_messages_unchanged pins them. Task 2 switches index.js to these.
// NOS texts are the live alert texts, byte for byte; pool_nos_messages_unchanged and the index tests pin them.
const NOS_MESSAGES = {
down: () =>
"NOS runner down: NOS_RUNNER set to ubuntu-latest; stuck runs cancelled for re-run.",
Expand Down Expand Up @@ -65,6 +65,8 @@ export const POOLS = {
prefix: "swm-macos:",
cron: "5,15,25,35,45,55 * * * *",
rerunLost: true,
// Optional: with any App secret missing the tick goes quiet. NOS is not optional, so a lost secret stays loud.
optional: true,
messages: MACOS_MESSAGES,
},
};
Expand Down
Loading
Loading