From 9d92a52f8948da0c408f3ce47cb890773f6349b8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 20:31:45 +0000 Subject: [PATCH 1/3] ci: dispatch autobump within a minute of a Ruby release GitHub fires the hourly autobump cron only every 8 to 10 hours, so new Rubies waited that long to build. Add a Cloudflare Worker that checks ruby/ruby's releases every minute and dispatches autobump (rubies only) when a release has no recipe yet, with a cooldown so it never stacks runs. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/autobump.yml | 12 +++- .github/workflows/tests.yml | 2 + .gitignore | 1 + watcher/README.md | 43 ++++++++++++ watcher/src/index.mjs | 88 +++++++++++++++++++++++ watcher/src/versions.mjs | 98 ++++++++++++++++++++++++++ watcher/test/watcher.test.mjs | 124 +++++++++++++++++++++++++++++++++ watcher/wrangler.jsonc | 11 +++ 8 files changed, 377 insertions(+), 2 deletions(-) create mode 100644 watcher/README.md create mode 100644 watcher/src/index.mjs create mode 100644 watcher/src/versions.mjs create mode 100644 watcher/test/watcher.test.mjs create mode 100644 watcher/wrangler.jsonc diff --git a/.github/workflows/autobump.yml b/.github/workflows/autobump.yml index 7d5f2fa..2fa374a 100644 --- a/.github/workflows/autobump.yml +++ b/.github/workflows/autobump.yml @@ -7,8 +7,15 @@ on: paths: - .github/workflows/autobump.yml workflow_dispatch: + inputs: + rubies_only: + description: Only look for new Ruby releases, not bundled gem updates + type: boolean + default: false schedule: # Hourly: look for new Ruby releases (the check job needs no checkout). + # GitHub drops most of these runs, so watcher/ dispatches this workflow + # within a minute of a release; this cron is the fallback. - cron: "17 * * * *" # Weekly: also look for new bundled gem versions. - cron: "47 4 * * 1" @@ -203,8 +210,9 @@ jobs: fi bundled-gems: - # Not on the hourly schedule: gem releases are slow, and the script queries rubygems. - if: github.event.schedule != '17 * * * *' + # Not on the hourly schedule or the release watcher's dispatches (watcher/): + # gem releases are slow, and the script queries rubygems. + if: github.event.schedule != '17 * * * *' && !inputs.rubies_only runs-on: ubuntu-latest timeout-minutes: 15 steps: diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index a2ba8a1..67c1d71 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -25,6 +25,8 @@ jobs: run: bin/validate-recipes - name: Test the autobump check run: test/autobump_check_test.sh + - name: Test the release watcher + run: node --test watcher/test/*.test.mjs - name: Check Ruby syntax run: | ruby -c libexec/package.rb diff --git a/.gitignore b/.gitignore index 7f57487..f091f96 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ .cache/ rubies/ .claude/settings.local.json +.wrangler/ diff --git a/watcher/README.md b/watcher/README.md new file mode 100644 index 0000000..73547ad --- /dev/null +++ b/watcher/README.md @@ -0,0 +1,43 @@ +# Ruby release watcher + +A Cloudflare Worker that checks for new Ruby releases every minute and +dispatches the [autobump workflow](../.github/workflows/autobump.yml) as soon +as one appears, so a new Ruby is built and published within minutes instead +of whenever GitHub gets around to the hourly cron (which in practice fires +every several hours). + +Each minute it reads `ruby/ruby`'s GitHub releases and this repo's +`recipes/rubies.yml`, and picks the versions autobump would add with the same +rules autobump uses. When something is missing, and no autobump run is in +progress or started within the cooldown, it dispatches autobump with +`rubies_only: true`. Autobump writes the recipe and pushes it, which starts +`release-new.yml` and the build, as before. + +The cooldown is 3 minutes for a release published in the last 2 hours (its +tarball can reach cache.ruby-lang.org a little after the GitHub release), 30 +minutes up to a day, and after that the watcher leaves it to the hourly cron +and its failure email. + +That is two GitHub API calls a minute when nothing is new, well under the +authenticated rate limit. + +## Deploy + +Create a fine-grained token for `jdx/ruby` only, with **Actions: read and +write** (to list and dispatch autobump runs) and **Contents: read**. Then: + +```sh +cd watcher +npx wrangler deploy +npx wrangler secret put GITHUB_TOKEN +``` + +Logs: `npx wrangler tail`, or the Worker's Observability tab. Each run logs +one line: `none`, `dispatched`, `running`, `cooldown` or `stale`, with the +missing versions. + +## Test + +```sh +node --test watcher/test/*.test.mjs +``` diff --git a/watcher/src/index.mjs b/watcher/src/index.mjs new file mode 100644 index 0000000..d3f3079 --- /dev/null +++ b/watcher/src/index.mjs @@ -0,0 +1,88 @@ +// Cloudflare Worker that watches for new Ruby releases every minute and +// dispatches jdx/ruby's autobump workflow as soon as one appears. +// +// GitHub's own scheduled runs are too unreliable for this: the hourly autobump +// cron fires only every few hours. Autobump stays the one place that writes +// recipes; this worker only decides when to start it. + +import { missingVersions, recipeVersions } from "./versions.mjs"; + +const UPSTREAM = "ruby/ruby"; +const WORKFLOW = "autobump.yml"; + +// How long to wait after the last autobump run before dispatching again, by +// how long ago the missing release was published. A fresh release is retried +// often, since its tarball can reach cache.ruby-lang.org a little after the +// GitHub release; an older one backs off so a release autobump can't add +// doesn't start a run every few minutes forever. Past a day, the hourly cron +// and its failure email take over. +export function cooldownMinutes(ageMinutes) { + if (ageMinutes < 120) return 3; + if (ageMinutes < 24 * 60) return 30; + return null; +} + +async function github(env, path, init = {}) { + const res = await fetch(`https://api.github.com${path}`, { + ...init, + headers: { + accept: "application/vnd.github+json", + authorization: `Bearer ${env.GITHUB_TOKEN}`, + "user-agent": "jdx-ruby-release-watcher", + "x-github-api-version": "2022-11-28", + ...init.headers, + }, + }); + if (!res.ok) { + throw new Error(`GitHub ${init.method ?? "GET"} ${path}: ${res.status} ${await res.text()}`); + } + return res; +} + +export async function check(env, now = Date.now()) { + const repo = env.REPO; + const [releases, recipes] = await Promise.all([ + github(env, `/repos/${UPSTREAM}/releases?per_page=100`).then((r) => r.json()), + github(env, `/repos/${repo}/contents/recipes/rubies.yml?ref=main`, { + headers: { accept: "application/vnd.github.raw+json" }, + }).then((r) => r.text()), + ]); + + const tags = releases.filter((r) => !r.draft).map((r) => r.tag_name); + const missing = missingVersions(tags, recipeVersions(recipes)); + if (missing.length === 0) return { action: "none" }; + + const published = new Map(releases.map((r) => [r.tag_name, Date.parse(r.published_at)])); + const cooldowns = missing + .map((m) => cooldownMinutes((now - published.get(m.tag)) / 60000)) + .filter((c) => c !== null); + const versions = missing.map((m) => m.version); + if (cooldowns.length === 0) return { action: "stale", versions }; + const cooldown = Math.min(...cooldowns); + + const { workflow_runs: runs } = await github( + env, + `/repos/${repo}/actions/workflows/${WORKFLOW}/runs?per_page=1`, + ).then((r) => r.json()); + const last = runs[0]; + if (last && last.status !== "completed") { + return { action: "running", versions, run: last.html_url }; + } + if (last && now - Date.parse(last.created_at) < cooldown * 60000) { + return { action: "cooldown", versions, run: last.html_url }; + } + + await github(env, `/repos/${repo}/actions/workflows/${WORKFLOW}/dispatches`, { + method: "POST", + body: JSON.stringify({ ref: "main", inputs: { rubies_only: "true" } }), + }); + return { action: "dispatched", versions }; +} + +export default { + async scheduled(_controller, env, ctx) { + ctx.waitUntil( + check(env).then((result) => console.log(JSON.stringify(result))), + ); + }, +}; diff --git a/watcher/src/versions.mjs b/watcher/src/versions.mjs new file mode 100644 index 0000000..e4ea2ab --- /dev/null +++ b/watcher/src/versions.mjs @@ -0,0 +1,98 @@ +// Decides which upstream Ruby releases the autobump workflow would add. +// +// Mirrors the version selection in .github/workflows/autobump.yml so the +// watcher only dispatches autobump when that run would actually add a recipe: +// the newest stable release of every series from 3.2 on, and prereleases of +// series that have no stable release yet. + +const PRERELEASE = /(preview|rc)/i; + +function supportedSeries(minor) { + const [major, min] = minor.split(".").map(Number); + return major > 3 || (major === 3 && min >= 2); +} + +function compareVersions(a, b) { + const pa = a.split(".").map(Number); + const pb = b.split(".").map(Number); + for (let i = 0; i < Math.max(pa.length, pb.length); i++) { + const d = (pa[i] ?? 0) - (pb[i] ?? 0); + if (d !== 0) return d; + } + return 0; +} + +// v3_4_13 -> 3.4.13, v4.0.10 -> 4.0.10 +function stableVersion(tag) { + return tag.replace(/^v/, "").replace(/_/g, "."); +} + +// v3_4_0_preview1 -> 3.4.0-preview1, v4.1.0-preview1 -> 4.1.0-preview1 +function prereleaseVersion(tag) { + if (tag.includes(".")) return tag.replace(/^v/, ""); + return stableVersion(tag) + .replace(/\.(preview)/i, "-$1") + .replace(/\.(rc)/i, "-$1"); +} + +function escape(s) { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +// Returns [{ version, tag }] for every release autobump would add a recipe for. +export function missingVersions(tags, recipeVersions) { + const recipes = new Set(recipeVersions); + const missing = []; + + const stable = []; + for (const tag of tags) { + if (PRERELEASE.test(tag)) continue; + const version = stableVersion(tag); + if (/^\d+\.\d+\.\d+$/.test(version)) stable.push({ version, tag }); + } + + const latestBySeries = new Map(); + for (const entry of stable) { + const minor = entry.version.split(".").slice(0, 2).join("."); + if (!supportedSeries(minor)) continue; + const current = latestBySeries.get(minor); + if (!current || compareVersions(entry.version, current.version) > 0) { + latestBySeries.set(minor, entry); + } + } + for (const entry of latestBySeries.values()) { + if (!recipes.has(entry.version)) missing.push(entry); + } + + for (const tag of tags) { + if (!PRERELEASE.test(tag)) continue; + const version = prereleaseVersion(tag); + const minor = version.match(/^\d+\.\d+/)?.[0]; + if (!minor || !supportedSeries(minor)) continue; + const stableTag = new RegExp( + `^v(${escape(minor.replace(".", "_"))}_\\d+|${escape(minor)}\\.\\d+)$`, + ); + if (tags.some((t) => stableTag.test(t))) continue; + if (!recipes.has(version)) missing.push({ version, tag }); + } + + return missing; +} + +// Reads the version keys under `rubies:` in recipes/rubies.yml. The file is +// machine-written by bin/update-ruby-recipe, so a line scan is enough and +// keeps the worker free of a YAML dependency. +export function recipeVersions(yaml) { + const versions = []; + let inRubies = false; + for (const line of yaml.split("\n")) { + if (/^\S/.test(line)) { + inRubies = /^rubies:\s*$/.test(line); + continue; + } + if (!inRubies) continue; + const m = line.match(/^ {2}(['"]?)([^\s'":#][^'":]*)\1:\s*$/); + if (m) versions.push(m[2]); + } + return versions; +} diff --git a/watcher/test/watcher.test.mjs b/watcher/test/watcher.test.mjs new file mode 100644 index 0000000..6d04edc --- /dev/null +++ b/watcher/test/watcher.test.mjs @@ -0,0 +1,124 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; + +import { check, cooldownMinutes } from "../src/index.mjs"; +import { missingVersions, recipeVersions } from "../src/versions.mjs"; + +const old = ["v1_9_3_551", "v2_7_8", "v3_1_6", "v3_2_0_rc1", "v3_3_0_preview1"]; +const both = ["v3_2_11", "v3_3_13", "v3_4_12", "v4.0.9"]; +const current = ["3.2.11", "3.3.13", "3.4.12", "4.0.9"]; +const missing = (tags, recipes) => missingVersions(tags, recipes).map((m) => m.version); + +// Same cases as test/autobump_check_test.sh, so the watcher and autobump agree. +test("recipes are current", () => { + assert.deepEqual(missing([...old, ...both], current), []); +}); +test("new stable, underscore tag", () => { + assert.deepEqual(missing([...old, ...both, "v3_4_13"], current), ["3.4.13"]); +}); +test("new stable, dotted tag", () => { + assert.deepEqual(missing([...old, ...both, "v4.0.10"], current), ["4.0.10"]); +}); +test("older patch missing, newest present", () => { + assert.deepEqual(missing(["v3_4_11", "v3_4_12"], ["3.4.12"]), []); +}); +test("series older than 3.2 are ignored", () => { + assert.deepEqual(missing([...old, "v3_1_7", ...both], current), []); +}); +test("new prerelease, underscore tag", () => { + assert.deepEqual(missing([...both, "v4_2_0_preview1"], current), ["4.2.0-preview1"]); +}); +test("new prerelease, dotted tag", () => { + assert.deepEqual(missing([...both, "v4.2.0-preview1"], current), ["4.2.0-preview1"]); +}); +test("new rc, underscore tag", () => { + assert.deepEqual(missing([...both, "v4_2_0_rc1"], current), ["4.2.0-rc1"]); +}); +test("recorded prerelease", () => { + assert.deepEqual( + missing([...both, "v4_2_0_preview1", "v4.3.0-preview2"], [...current, "4.2.0-preview1", "4.3.0-preview2"]), + [], + ); +}); +test("prerelease in a series that has a stable release", () => { + assert.deepEqual(missing([...both, "v3_4_0_rc1", "v3_4_0_preview1", "v4.0.0-preview3"], current), []); +}); +test("patch versions compare numerically", () => { + assert.deepEqual(missing(["v4.0.9", "v4.0.10"], ["4.0.9"]), ["4.0.10"]); +}); + +test("reads every version from the real recipes file", () => { + const yaml = readFileSync(new URL("../../recipes/rubies.yml", import.meta.url), "utf8"); + const versions = recipeVersions(yaml); + assert.ok(versions.includes("3.2.1")); + assert.ok(versions.includes("4.1.0-preview1")); + assert.equal(versions.length, (yaml.match(/^ {4}sha256:/gm) ?? []).length); +}); +test("reads quoted keys and ignores other sections", () => { + const yaml = "schema: 1\nrubies:\n '3.4.1':\n series: x\n \"4.0.0\":\n series: y\nother:\n 9.9.9:\n"; + assert.deepEqual(recipeVersions(yaml), ["3.4.1", "4.0.0"]); +}); + +test("cooldown backs off as a release ages", () => { + assert.equal(cooldownMinutes(5), 3); + assert.equal(cooldownMinutes(300), 30); + assert.equal(cooldownMinutes(2000), null); +}); + +// check() against a stubbed GitHub API. +const NOW = Date.parse("2026-12-25T03:30:00Z"); +const recipesYaml = `rubies:\n${current.map((v) => ` ${v}:\n series: x\n`).join("")}`; + +function stubGitHub({ releases, runs }) { + const calls = []; + globalThis.fetch = async (url, init = {}) => { + const path = new URL(url).pathname; + calls.push(`${init.method ?? "GET"} ${path}`); + if (path === "/repos/ruby/ruby/releases") return Response.json(releases); + if (path === "/repos/jdx/ruby/contents/recipes/rubies.yml") return new Response(recipesYaml); + if (path.endsWith("/runs")) return Response.json({ workflow_runs: runs }); + if (path.endsWith("/dispatches")) { + assert.deepEqual(JSON.parse(init.body), { ref: "main", inputs: { rubies_only: "true" } }); + return new Response(null, { status: 204 }); + } + throw new Error(`unexpected ${path}`); + }; + return calls; +} +const env = { REPO: "jdx/ruby", GITHUB_TOKEN: "t" }; +const release = (tag, minutesAgo) => ({ + tag_name: tag, + draft: false, + published_at: new Date(NOW - minutesAgo * 60000).toISOString(), +}); +const run = (status, minutesAgo) => ({ + status, + created_at: new Date(NOW - minutesAgo * 60000).toISOString(), + html_url: "https://github.com/jdx/ruby/actions/runs/1", +}); +const upToDate = both.map((t) => release(t, 60 * 24 * 30)); + +test("does nothing when the recipes are current", async () => { + const calls = stubGitHub({ releases: upToDate, runs: [] }); + assert.equal((await check(env, NOW)).action, "none"); + assert.ok(!calls.some((c) => c.includes("/runs") || c.includes("dispatches"))); +}); +test("dispatches autobump for a fresh release", async () => { + const calls = stubGitHub({ releases: [release("v4.1.0", 1), ...upToDate], runs: [run("completed", 50)] }); + assert.deepEqual(await check(env, NOW), { action: "dispatched", versions: ["4.1.0"] }); + assert.ok(calls.includes("POST /repos/jdx/ruby/actions/workflows/autobump.yml/dispatches")); +}); +test("waits while autobump is already running", async () => { + stubGitHub({ releases: [release("v4.1.0", 1), ...upToDate], runs: [run("in_progress", 1)] }); + assert.equal((await check(env, NOW)).action, "running"); +}); +test("waits out the cooldown after a recent run", async () => { + stubGitHub({ releases: [release("v4.1.0", 10), ...upToDate], runs: [run("completed", 2)] }); + assert.equal((await check(env, NOW)).action, "cooldown"); +}); +test("leaves releases older than a day to the hourly cron", async () => { + const calls = stubGitHub({ releases: [release("v4.1.0", 60 * 25), ...upToDate], runs: [] }); + assert.equal((await check(env, NOW)).action, "stale"); + assert.ok(!calls.some((c) => c.includes("dispatches"))); +}); diff --git a/watcher/wrangler.jsonc b/watcher/wrangler.jsonc new file mode 100644 index 0000000..3d2cdb1 --- /dev/null +++ b/watcher/wrangler.jsonc @@ -0,0 +1,11 @@ +{ + "$schema": "https://unpkg.com/wrangler/config-schema.json", + "name": "ruby-release-watcher", + "main": "src/index.mjs", + "compatibility_date": "2026-11-01", + // Scheduled only: no public URL that could spend the token's rate limit. + "workers_dev": false, + "triggers": { "crons": ["* * * * *"] }, + "vars": { "REPO": "jdx/ruby" }, + "observability": { "enabled": true } +} From f412d0503f6916958a5176f288973e3faa9879ae Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 20:38:12 +0000 Subject: [PATCH 2/3] fix(watcher): skip dispatch while any recent autobump run is active The newest run can be a queued run that concurrency cancelled while an older run is still working, so look at the last 20 runs, not just one. Co-Authored-By: Claude Opus 5.5 --- watcher/src/index.mjs | 11 +++++++---- watcher/test/watcher.test.mjs | 7 +++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/watcher/src/index.mjs b/watcher/src/index.mjs index d3f3079..1af29e8 100644 --- a/watcher/src/index.mjs +++ b/watcher/src/index.mjs @@ -60,14 +60,17 @@ export async function check(env, now = Date.now()) { if (cooldowns.length === 0) return { action: "stale", versions }; const cooldown = Math.min(...cooldowns); + // Newest first. Look past the newest run: a queued run that concurrency + // cancelled can sit on top while an older one is still working. const { workflow_runs: runs } = await github( env, - `/repos/${repo}/actions/workflows/${WORKFLOW}/runs?per_page=1`, + `/repos/${repo}/actions/workflows/${WORKFLOW}/runs?per_page=20`, ).then((r) => r.json()); - const last = runs[0]; - if (last && last.status !== "completed") { - return { action: "running", versions, run: last.html_url }; + const active = runs.find((r) => r.status !== "completed"); + if (active) { + return { action: "running", versions, run: active.html_url }; } + const last = runs[0]; if (last && now - Date.parse(last.created_at) < cooldown * 60000) { return { action: "cooldown", versions, run: last.html_url }; } diff --git a/watcher/test/watcher.test.mjs b/watcher/test/watcher.test.mjs index 6d04edc..5498ec3 100644 --- a/watcher/test/watcher.test.mjs +++ b/watcher/test/watcher.test.mjs @@ -113,6 +113,13 @@ test("waits while autobump is already running", async () => { stubGitHub({ releases: [release("v4.1.0", 1), ...upToDate], runs: [run("in_progress", 1)] }); assert.equal((await check(env, NOW)).action, "running"); }); +test("sees an older run still working under a cancelled one", async () => { + stubGitHub({ + releases: [release("v4.1.0", 1), ...upToDate], + runs: [run("completed", 1), run("in_progress", 4)], + }); + assert.equal((await check(env, NOW)).action, "running"); +}); test("waits out the cooldown after a recent run", async () => { stubGitHub({ releases: [release("v4.1.0", 10), ...upToDate], runs: [run("completed", 2)] }); assert.equal((await check(env, NOW)).action, "cooldown"); From 57b102933a1a0ca37068af8e5c94245e6521ebda Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 20:47:27 +0000 Subject: [PATCH 3/3] fix(watcher): send the dispatch body as JSON Co-Authored-By: Claude Opus 5.5 --- watcher/src/index.mjs | 1 + watcher/test/watcher.test.mjs | 1 + 2 files changed, 2 insertions(+) diff --git a/watcher/src/index.mjs b/watcher/src/index.mjs index 1af29e8..a3926fd 100644 --- a/watcher/src/index.mjs +++ b/watcher/src/index.mjs @@ -30,6 +30,7 @@ async function github(env, path, init = {}) { authorization: `Bearer ${env.GITHUB_TOKEN}`, "user-agent": "jdx-ruby-release-watcher", "x-github-api-version": "2022-11-28", + ...(init.body ? { "content-type": "application/json" } : {}), ...init.headers, }, }); diff --git a/watcher/test/watcher.test.mjs b/watcher/test/watcher.test.mjs index 5498ec3..a1f7252 100644 --- a/watcher/test/watcher.test.mjs +++ b/watcher/test/watcher.test.mjs @@ -79,6 +79,7 @@ function stubGitHub({ releases, runs }) { if (path === "/repos/jdx/ruby/contents/recipes/rubies.yml") return new Response(recipesYaml); if (path.endsWith("/runs")) return Response.json({ workflow_runs: runs }); if (path.endsWith("/dispatches")) { + assert.equal(init.headers["content-type"], "application/json"); assert.deepEqual(JSON.parse(init.body), { ref: "main", inputs: { rubies_only: "true" } }); return new Response(null, { status: 204 }); }