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
21 changes: 20 additions & 1 deletion infra/fleet/terraform/redelivery.tf
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ data "archive_file" "redelivery" {
output_path = "${path.module}/.build/redelivery.zip"
}

# Per-job redelivery counts (the function owns the value).
resource "aws_ssm_parameter" "redelivery_state" {
name = "/${local.ssm_root}/redelivery/state"
description = "Webhook redelivery sweeper state: last redelivery per job id"
type = "String"
value = "{}"

lifecycle {
ignore_changes = [value]
}
}

resource "aws_cloudwatch_log_group" "redelivery" {
name = "/aws/lambda/${local.redelivery_name}"
retention_in_days = 7
Expand Down Expand Up @@ -41,6 +53,11 @@ data "aws_iam_policy_document" "redelivery" {
actions = ["ssm:GetParameter"]
resources = [local.ssm_arn_for["id"], local.ssm_arn_for["key_base64"]]
}
statement {
sid = "State"
actions = ["ssm:GetParameter", "ssm:PutParameter"]
resources = [aws_ssm_parameter.redelivery_state.arn]
}
statement {
sid = "DecryptSecureString"
actions = ["kms:Decrypt"]
Expand Down Expand Up @@ -80,8 +97,10 @@ resource "aws_lambda_function" "redelivery" {
APP_ID_PARAM = "${local.github_app_ssm_prefix}/id"
APP_KEY_PARAM = "${local.github_app_ssm_prefix}/key_base64"
ALLOWED_REPOSITORIES = join(",", local.allowed_repositories)
STATE_PARAM = aws_ssm_parameter.redelivery_state.name
WINDOW_MINUTES = "60"
MAX_ATTEMPTS = "5"
MAX_ATTEMPTS = "3"
BACKOFF_MINUTES = "4"
SPACING_MS = "300"
}
}
Expand Down
93 changes: 72 additions & 21 deletions infra/fleet/terraform/redelivery/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,26 @@
// no runner, forever. Every minute this function signs in as the App, finds
// failed `workflow_job: queued` deliveries for allow-listed repositories, and
// asks GitHub to redeliver them, spaced out so the redeliveries do not throttle
// in turn. A delivery (by guid) is retried at most MAX_ATTEMPTS times in total.
// in turn. A job is redelivered only while it is still queued, at most once per
// BACKOFF_MINUTES and MAX_ATTEMPTS times in total; those counts live in an SSM
// parameter (STATE_PARAM) keyed by job id. Without them one stranded job could
// be redelivered every minute while its runner boots, launching a runner each
// time.
//
// Environment: APP_ID_PARAM, APP_KEY_PARAM (SSM names), ALLOWED_REPOSITORIES
// (comma-separated owner/repo), WINDOW_MINUTES, MAX_ATTEMPTS, SPACING_MS.
// (comma-separated owner/repo), STATE_PARAM, WINDOW_MINUTES, MAX_ATTEMPTS,
// BACKOFF_MINUTES, SPACING_MS.

import { createSign } from "node:crypto";
import { GetParameterCommand, SSMClient } from "@aws-sdk/client-ssm";
import { GetParameterCommand, PutParameterCommand, SSMClient } from "@aws-sdk/client-ssm";

const ssm = new SSMClient({});
const API = "https://api.github.com";
const WINDOW_MS = Number(process.env.WINDOW_MINUTES ?? 60) * 60_000;
const MAX_ATTEMPTS = Number(process.env.MAX_ATTEMPTS ?? 5);
const SPACING_MS = Number(process.env.SPACING_MS ?? 300);
const BACKOFF_MS = Number(process.env.BACKOFF_MINUTES ?? 4) * 60_000;
const STATE_ENTRIES = 120; // keeps the state parameter under the 4 KB standard tier
const SETTLE_MS = 20_000; // leave a delivery that is seconds old to its first attempt
const ALLOWED = new Set(
(process.env.ALLOWED_REPOSITORIES ?? "").split(",").map((r) => r.trim().toLowerCase()).filter(Boolean),
Expand Down Expand Up @@ -56,12 +63,12 @@ async function json(res) {
return JSON.parse((await res.text()).replace(/"id":\s*(\d{16,})/g, '"id":"$1"'));
}

async function gh(jwt, path, init = {}) {
async function gh(auth, path, init = {}) {
const res = await fetch(path.startsWith("http") ? path : `${API}${path}`, {
...init,
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${jwt}`,
Authorization: auth.startsWith("ghs_") ? `token ${auth}` : `Bearer ${auth}`,
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "nimbus-runners-webhook-redelivery",
},
Expand Down Expand Up @@ -90,44 +97,88 @@ async function recentDeliveries(jwt) {
return all.filter((d) => Date.parse(d.delivered_at) >= cutoff);
}

// { [jobId]: { at: epoch ms of the last redelivery, n: redeliveries so far } }
async function loadState() {
try {
return JSON.parse(await param(process.env.STATE_PARAM));
} catch {
return {};
}
}

async function saveState(state) {
const keep = Object.entries(state)
.filter(([, v]) => Date.now() - v.at < WINDOW_MS)
.sort((a, b) => b[1].at - a[1].at)
.slice(0, STATE_ENTRIES);
await ssm.send(new PutParameterCommand({
Name: process.env.STATE_PARAM, Type: "String", Overwrite: true, Value: JSON.stringify(Object.fromEntries(keep)) || "{}",
}));
}

async function installationToken(jwt, installationId, cache) {
if (!cache.has(installationId)) {
const res = await gh(jwt, `/app/installations/${installationId}/access_tokens`, { method: "POST" });
cache.set(installationId, (await json(res)).token);
}
return cache.get(installationId);
}

export async function handler() {
const jwt = appJwt(await credentials());
const deliveries = await recentDeliveries(jwt);
const state = await loadState();
const tokens = new Map();

const byGuid = new Map();
for (const d of deliveries) {
if (d.event !== "workflow_job" || d.action !== "queued") continue;
byGuid.set(d.guid, [...(byGuid.get(d.guid) ?? []), d]);
}

let redelivered = 0;
let skipped = 0;
let failed = 0;
const counts = { redelivered: 0, backoff: 0, notQueued: 0, notAllowed: 0, exhausted: 0, failed: 0 };
let changed = false;
for (const attempts of byGuid.values()) {
if (attempts.some(ok)) continue;
const latest = attempts.reduce((a, b) => (Date.parse(a.delivered_at) > Date.parse(b.delivered_at) ? a : b));
if (attempts.length >= MAX_ATTEMPTS || Date.now() - Date.parse(latest.delivered_at) < SETTLE_MS) {
skipped++;
continue;
}
if (Date.now() - Date.parse(latest.delivered_at) < SETTLE_MS) continue;
try {
const detail = await json(await gh(jwt, `/app/hook/deliveries/${latest.id}`));
const repo = detail.request?.payload?.repository?.full_name?.toLowerCase();
if (!repo || !ALLOWED.has(repo)) {
skipped++;
const payload = (await json(await gh(jwt, `/app/hook/deliveries/${latest.id}`))).request?.payload ?? {};
const repo = payload.repository?.full_name?.toLowerCase();
const jobId = String(payload.workflow_job?.id ?? "");
if (!repo || !ALLOWED.has(repo) || !jobId) {
counts.notAllowed++;
continue;
}
const seen = state[jobId];
if (seen && seen.n >= MAX_ATTEMPTS) {
counts.exhausted++;
continue;
}
if (seen && Date.now() - seen.at < BACKOFF_MS) {
counts.backoff++;
continue;
}
const token = await installationToken(jwt, payload.installation.id, tokens);
const job = await json(await gh(token, `/repos/${repo}/actions/jobs/${jobId}`));
if (job.status !== "queued") {
counts.notQueued++;
continue;
}
await gh(jwt, `/app/hook/deliveries/${latest.id}/attempts`, { method: "POST" });
redelivered++;
console.log(JSON.stringify({ msg: "redelivered", guid: latest.guid, repo, status: latest.status_code, attempt: attempts.length + 1 }));
state[jobId] = { at: Date.now(), n: (seen?.n ?? 0) + 1 };
changed = true;
counts.redelivered++;
console.log(JSON.stringify({ msg: "redelivered", repo, jobId, guid: latest.guid, status: latest.status_code, n: state[jobId].n }));
await sleep(SPACING_MS);
} catch (err) {
failed++;
counts.failed++;
console.log(JSON.stringify({ msg: "redelivery failed", guid: latest.guid, error: String(err).slice(0, 300) }));
}
await sleep(SPACING_MS);
}
if (changed) await saveState(state);

const summary = { scanned: deliveries.length, queuedGuids: byGuid.size, redelivered, skipped, failed };
const summary = { scanned: deliveries.length, queuedGuids: byGuid.size, ...counts };
console.log(JSON.stringify({ msg: "summary", ...summary }));
return summary;
}
Loading