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
12 changes: 10 additions & 2 deletions .github/workflows/autobump.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
.cache/
rubies/
.claude/settings.local.json
.wrangler/
43 changes: 43 additions & 0 deletions watcher/README.md
Original file line number Diff line number Diff line change
@@ -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
```
92 changes: 92 additions & 0 deletions watcher/src/index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// 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.body ? { "content-type": "application/json" } : {}),
...init.headers,
},
});
if (!res.ok) {
throw new Error(`GitHub ${init.method ?? "GET"} ${path}: ${res.status} ${await res.text()}`);
}
return res;
}
Comment thread
jdx marked this conversation as resolved.
Resolved

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);

// 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=20`,
).then((r) => r.json());
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 };
}

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))),
);
},
};
98 changes: 98 additions & 0 deletions watcher/src/versions.mjs
Original file line number Diff line number Diff line change
@@ -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;
}
Loading
Loading