Merge remote-tracking branch 'origin/main' into feat/launcher-overhaul

# Conflicts:
#	docs/launcher.md
This commit is contained in:
OreoFR
2026-12-02 23:11:00 +01:00
10 changed files with 312 additions and 95 deletions

View File

@ -10,7 +10,7 @@
//! load in [`tick`]. Otherwise [`start`] runs the thread once; the renderer
//! calls [`tick`] at every present.
//!
//! - [`sandbox`]: the Lua state and what a mod can reach in it.
//! - [`sandbox`]: a mod's Lua state and what the mod can reach in it.
//! - [`api`]: the `leonida` table.
//! - [`runtime`]: the mods, and the passes that call their handlers.
//! - [`memory`], [`keys`], [`input`], [`settings`], [`manifest`]: what the API stands on.
@ -93,13 +93,7 @@ pub fn start() {
/// A fresh runtime with the mods of the mods folder loaded.
fn fresh(platform: &Rc<dyn platform::Platform>) -> Option<runtime::Runtime> {
let mut rt = match runtime::Runtime::new(platform.clone(), runtime::Config::default()) {
Ok(rt) => rt,
Err(e) => {
tracing::warn!(error = %e, "the Lua state could not be made; no Lua mods");
return None;
}
};
let mut rt = runtime::Runtime::new(platform.clone(), runtime::Config::default());
match manifest::mods_dir() {
Some(dir) => {
let report = rt.load_dir(&dir);

View File

@ -79,11 +79,14 @@ pub fn inside(root: &Path, name: &str) -> Result<PathBuf, String> {
let path = root.join(rel);
// A link or junction inside the folder must not lead out of it.
let canon_root = std::fs::canonicalize(root).map_err(|e| format!("the mod's folder: {e}"))?;
// The deepest entry that is there, a link counted even when its target is missing:
// canonicalising a link to nothing fails, and that is a refusal.
let mut probe = path.as_path();
while !probe.exists() {
while std::fs::symlink_metadata(probe).is_err() {
probe = probe.parent().ok_or("no such folder")?;
}
let canon = std::fs::canonicalize(probe).map_err(|e| e.to_string())?;
let canon = std::fs::canonicalize(probe)
.map_err(|e| format!("`{name}` cannot be resolved inside the mod's folder ({e})"))?;
if !canon.starts_with(&canon_root) {
return Err(format!("`{name}` leads out of the mod's folder"));
}

View File

@ -1,4 +1,4 @@
//! The mods' runtime: the Lua state, the mods loaded into it, and the
//! The mods' runtime: the mods, each in a Lua state of its own, and the
//! passes that call their handlers. It runs on one thread and knows the host
//! only through [`Platform`], so the tests drive it without a title.
@ -130,7 +130,8 @@ pub struct Config {
}
pub struct Runtime {
lua: Lua,
/// Each loaded mod's state, kept for its handlers and callbacks.
states: Vec<Lua>,
guard: Guard,
shared: Rc<RefCell<Shared>>,
config: Config,
@ -153,8 +154,8 @@ pub enum Status {
}
impl Runtime {
pub fn new(platform: Rc<dyn Platform>, config: Config) -> mlua::Result<Runtime> {
let (lua, guard) = sandbox::new_lua()?;
pub fn new(platform: Rc<dyn Platform>, config: Config) -> Runtime {
let guard = Guard::default();
let shared = Rc::new(RefCell::new(Shared {
platform: platform.clone(),
mods: Vec::new(),
@ -169,8 +170,8 @@ impl Runtime {
started: Instant::now(),
guard: guard.clone(),
}));
Ok(Runtime {
lua,
Runtime {
states: Vec::new(),
guard,
shared,
config,
@ -180,7 +181,7 @@ impl Runtime {
keys_down: [false; 256],
menu_was_open: false,
drew: false,
})
}
}
/// The mods and how each stands.
@ -263,10 +264,11 @@ impl Runtime {
));
}
let code = std::fs::read(&path).map_err(|e| format!("cannot read {script}: {e}"))?;
let env = api::build_env(&self.lua, &self.guard, &self.shared, idx, folder)
let lua =
sandbox::new_lua(&self.guard).map_err(|e| format!("cannot set the mod up: {e}"))?;
let env = api::build_env(&lua, &self.guard, &self.shared, idx, folder)
.map_err(|e| format!("cannot set the mod up: {e}"))?;
let function = self
.lua
let function = lua
.load(code)
.set_name(format!(
"={}/{}",
@ -280,7 +282,11 @@ impl Runtime {
.into_function()
.map_err(|e| e.to_string())?;
self.guard.start(self.config.budget.load);
function.call::<()>(()).map_err(|e| e.to_string())
function.call::<()>(()).map_err(|e| e.to_string())?;
// Kept only for a mod that loaded: a failed one's state (and its
// memory) goes now, and the handles it left behind go with `disable`.
self.states.push(lua);
Ok(())
}
/// Calls `function` for mod `idx` with `args`, within the call budget; an

View File

@ -1,7 +1,7 @@
//! The Lua state and what a mod can reach in it.
//! A mod's Lua state and what the mod can reach in it.
//!
//! One state holds all the mods; each gets an environment of its own made
//! from a short list of what is safe: the base functions, the `coroutine`,
//! Each mod has a Lua state of its own, with an environment made from a
//! short list of what is safe: the base functions, the `coroutine`,
//! `table`, `string`, `utf8` and `math` libraries, and `os.time`, `os.clock`,
//! `os.date` and `os.difftime`. There is no `io`, no `package`, no `debug`,
//! no `dofile` or `loadfile`, no `os.execute`, `os.remove`, `os.rename`,
@ -12,8 +12,9 @@
//!
//! Each mod's library tables are copies, so one mod changing `string.rep`
//! changes nothing for another. A time budget and a memory limit stop a mod
//! that loops or allocates without end; `pcall` and the like cannot swallow
//! the budget's error.
//! that loops or allocates without end. The limit is the mod's own, so a mod
//! that holds memory does not starve the others; `pcall` and the like cannot
//! swallow the budget's error.
use std::cell::Cell;
use std::rc::Rc;
@ -24,7 +25,7 @@ use mlua::{
Function, HookTriggers, Lua, LuaOptions, MultiValue, Result, StdLib, Table, Value, VmState,
};
/// The Lua state's memory limit.
/// The memory limit of one mod's Lua state.
pub const MEMORY_LIMIT: usize = 128 << 20;
/// How often (in VM instructions) the budget is looked at.
@ -46,14 +47,23 @@ impl Default for Budget {
}
}
/// The state's guard: the moment the running call must end by, and whether it
/// went past it.
/// The states' guard (one call runs at a time): the moment the running call
/// must end by, and whether it went past it.
#[derive(Clone)]
pub struct Guard {
deadline: Rc<Cell<Instant>>,
tripped: Rc<Cell<bool>>,
}
impl Default for Guard {
fn default() -> Guard {
Guard {
deadline: Rc::new(Cell::new(Instant::now() + Duration::from_secs(3600))),
tripped: Rc::new(Cell::new(false)),
}
}
}
impl Guard {
/// Starts a call that may run for `limit`.
pub fn start(&self, limit: Duration) {
@ -71,8 +81,8 @@ impl Guard {
}
}
/// A fresh state with its guard.
pub fn new_lua() -> Result<(Lua, Guard)> {
/// A fresh state for one mod, watched by `guard`.
pub fn new_lua(guard: &Guard) -> Result<Lua> {
let lua = Lua::new_with(
StdLib::COROUTINE
| StdLib::TABLE
@ -84,10 +94,6 @@ pub fn new_lua() -> Result<(Lua, Guard)> {
)?;
lua.set_memory_limit(MEMORY_LIMIT)?;
hide_string_dump(&lua)?;
let guard = Guard {
deadline: Rc::new(Cell::new(Instant::now() + Duration::from_secs(3600))),
tripped: Rc::new(Cell::new(false)),
};
let watch = guard.clone();
lua.set_global_hook(
HookTriggers::new().every_nth_instruction(HOOK_EVERY),
@ -101,7 +107,7 @@ pub fn new_lua() -> Result<(Lua, Guard)> {
Ok(VmState::Continue)
},
)?;
Ok((lua, guard))
Ok(lua)
}
/// The string metatable points at the real `string` table, so a mod would find

View File

@ -166,7 +166,7 @@ fn rig_with(mods: &[(&str, &str)], config: Config) -> (tempfile::TempDir, Rc<Fak
let all: Vec<(&str, &str, &str)> = mods.iter().map(|(n, c)| (*n, JSON, *c)).collect();
let dir = folder(&all);
let fake = Fake::new();
let mut rt = Runtime::new(fake.clone(), config).unwrap();
let mut rt = Runtime::new(fake.clone(), config);
rt.load_dir(dir.path());
(dir, fake, rt)
}
@ -261,6 +261,20 @@ fn a_mod_cannot_change_what_another_mod_sees() {
assert_eq!(fake.of("b"), ["function 1 nil nil function"]);
}
#[test]
fn a_mod_that_holds_memory_does_not_starve_another() {
// A holds nearly the whole limit; B's ordinary allocation still succeeds,
// and B's count is its own memory, not A's.
let a = "Held = {} for i = 1, 120 do Held[i] = string.rep('a', 1 << 20) end";
let b = r#"
local ok, s = pcall(string.rep, "b", 40 << 20)
leonida.log(ok, ok and #s, collectgarbage("count") < 64 * 1024)
"#;
let (_d, fake, rt) = rig(&[("a", a), ("b", b)]);
assert_eq!(fake.of("b"), ["true 41943040 true"]);
assert_eq!(status(&rt, "a"), Status::Running);
}
#[test]
fn frame_key_and_menu_events_reach_the_handlers_in_order() {
let a = r#"
@ -326,7 +340,7 @@ fn input_is_read_by_name() {
lx: -1.0,
..Pad::default()
});
let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
let mut rt = Runtime::new(fake.clone(), Config::default());
rt.load_dir(dir.path());
let log = fake.of("a");
assert_eq!(log[0], "keys true false false");
@ -921,7 +935,7 @@ fn require_loads_the_mods_own_modules_once() {
std::fs::write(at.join("pkg/sub.lua"), "return 'sub:' .. (...)").unwrap();
std::fs::write(at.join("loop.lua"), "require('loop')").unwrap();
let fake = Fake::new();
let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
let mut rt = Runtime::new(fake.clone(), Config::default());
rt.load_dir(dir.path());
let log = fake.of("a");
assert_eq!(log[0], "m 43 true sub:pkg.sub", "{log:?}");
@ -956,7 +970,7 @@ fn a_link_out_of_the_mods_folder_is_not_a_module_and_not_a_script() {
return;
}
let fake = Fake::new();
let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
let mut rt = Runtime::new(fake.clone(), Config::default());
rt.load_dir(dir.path());
let log = fake.of("a");
assert!(
@ -976,7 +990,7 @@ fn a_link_out_of_the_mods_folder_is_not_a_module_and_not_a_script() {
return;
}
let fake = Fake::new();
let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
let mut rt = Runtime::new(fake.clone(), Config::default());
rt.load_dir(dir.path());
let log = fake.of("b");
assert!(
@ -1014,7 +1028,7 @@ fn a_directory_link_out_of_the_mods_folder_is_not_a_module_and_not_a_script() {
return;
}
let fake = Fake::new();
let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
let mut rt = Runtime::new(fake.clone(), Config::default());
rt.load_dir(dir.path());
let log = fake.of("a");
assert!(
@ -1034,7 +1048,7 @@ fn a_directory_link_out_of_the_mods_folder_is_not_a_module_and_not_a_script() {
return;
}
let fake = Fake::new();
let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
let mut rt = Runtime::new(fake.clone(), Config::default());
rt.load_dir(dir.path());
let log = fake.of("b");
assert!(
@ -1047,6 +1061,53 @@ fn a_directory_link_out_of_the_mods_folder_is_not_a_module_and_not_a_script() {
);
}
#[test]
fn a_link_to_nothing_is_not_written_through() {
// A link inside the mod's folder whose target is missing: the old check walked past it to the
// folder that holds it, and `write_file` then made the target, out of the mod's folder. The
// file link is the case that escaped; it needs rights on Windows, so it runs only where links
// can be made. The junction (to a missing folder, no rights needed) never escaped (the write
// failed later, in `create_dir_all`): it pins that `inside()` itself refuses it.
let dir = folder(&[(
"a",
JSON,
r#"
leonida.log("file", leonida.write_file("out.txt", "x"))
leonida.log("dir", leonida.write_file("lib/x.txt", "x"))
"#,
)]);
let at = dir.path().join("a");
let outside = dir.path().join("outside.txt");
let made_file = link(&outside, &at.join("out.txt"));
let gone = dir.path().join("gone");
let made_dir = dir_link(&gone, &at.join("lib"));
if !made_file && !made_dir {
// No rights to make a link here: nothing to check.
return;
}
let fake = Fake::new();
let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
rt.load_dir(dir.path());
let log = fake.of("a");
for (i, (made, key, name)) in [
(made_file, "file", "out.txt"),
(made_dir, "dir", "lib/x.txt"),
]
.into_iter()
.enumerate()
{
if made {
assert!(
log[i].starts_with(&format!(
"{key} false `{name}` cannot be resolved inside the mod's folder"
)),
"{log:?}"
);
}
}
assert!(!outside.exists() && !gone.exists());
}
/// A link from `link` to `target`, when this machine allows one.
fn link(target: &std::path::Path, link: &std::path::Path) -> bool {
#[cfg(unix)]
@ -1118,7 +1179,7 @@ fn only_enabled_lua_mods_are_loaded() {
std::fs::create_dir_all(dir.path().join("nojson")).unwrap();
std::fs::write(dir.path().join("nojson/main.lua"), "").unwrap();
let fake = Fake::new();
let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
let mut rt = Runtime::new(fake.clone(), Config::default());
let report = rt.load_dir(dir.path());
let get = |n: &str| {
report
@ -1176,7 +1237,7 @@ fn the_example_mod_ships_disabled_and_runs_when_enabled() {
std::fs::write(at.join("mod.json"), manifest.replace("false", "true")).unwrap();
std::fs::copy(source.join("main.lua"), at.join("main.lua")).unwrap();
let fake = Fake::new();
let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
let mut rt = Runtime::new(fake.clone(), Config::default());
let report = rt.load_dir(dir.path());
assert_eq!(report, [("Example Lua mod".to_owned(), Status::Running)]);
// Its page: a toggle, a number and two actions.
@ -1272,7 +1333,7 @@ fn gate_driver_logs(scenario: &str) -> Vec<String> {
.unwrap();
std::fs::write(at.join("main.lua"), format!("{GATE_HARNESS}\n{scenario}\n")).unwrap();
let fake = Fake::new();
let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
let mut rt = Runtime::new(fake.clone(), Config::default());
let report = rt.load_dir(dir.path());
assert_eq!(
report,
@ -1421,7 +1482,7 @@ fn the_gate_driver_ships_disabled_and_loads_when_enabled() {
)
.unwrap();
let fake = Fake::new();
let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
let mut rt = Runtime::new(fake.clone(), Config::default());
assert_eq!(
rt.load_dir(dir.path()),
[("Gate driver".to_owned(), Status::Running)]

View File

@ -442,10 +442,23 @@ mod tests {
use super::*;
/// The test binary itself is a real MSVC-linked PE32+ image.
#[cfg(windows)]
fn own_image() -> Vec<u8> {
std::fs::read(std::env::current_exe().unwrap()).unwrap()
}
/// Minimal valid PE32+ image with no data directories and `entry_rva = 0x1000`.
fn synthetic_pe_image() -> Vec<u8> {
let mut data = synthetic_image(&[]);
let opt = 0x58;
// AddressOfEntryPoint inside the single section at RVA 0x1000.
data[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
// Clear the export directory so the empty section does not need valid exports.
data[opt + 112..opt + 120].fill(0);
data
}
#[cfg(windows)]
#[test]
fn parses_own_test_binary() {
let info = ImageInfo::parse(&own_image()).unwrap();
@ -467,15 +480,15 @@ mod tests {
#[test]
fn rva_to_file_offset_maps_entry_point() {
let data = own_image();
let data = synthetic_pe_image();
let info = ImageInfo::parse(&data).unwrap();
let off = info.rva_to_file_offset(info.entry_rva).unwrap() as usize;
assert!(off < data.len());
assert_eq!(off, 0x200);
}
#[test]
fn rva_to_file_offset_rejects_offsets_past_4_gib() {
let mut info = ImageInfo::parse(&own_image()).unwrap();
let mut info = ImageInfo::parse(&synthetic_pe_image()).unwrap();
let rva = info.sections[0].rva + 0x20;
assert!(info.rva_to_file_offset(rva).is_some());
// Used to overflow (a panic in debug builds, a wrong offset in
@ -488,20 +501,26 @@ mod tests {
fn rejects_garbage_without_panicking() {
assert!(ImageInfo::parse(b"").is_err());
assert!(ImageInfo::parse(b"MZ not really").is_err());
let mut truncated = own_image();
let mut truncated = synthetic_pe_image();
truncated.truncate(0x200);
assert!(ImageInfo::parse(&truncated).is_err());
}
#[test]
fn rejects_iat_outside_image() {
let mut data = own_image();
let dd = layout::data_directory_offset(&data, dir::IMPORT).unwrap();
let import_rva = layout::read_u32(&data, dd).unwrap();
let desc = ImageInfo::parse(&data)
.unwrap()
.rva_to_file_offset(import_rva)
.unwrap() as usize;
let mut data = synthetic_pe_image();
let opt = 0x58;
// Point Import directory (index 1) to RVA 0x1000, size 40 bytes (two descriptors).
data[opt + 120..opt + 124].copy_from_slice(&0x1000u32.to_le_bytes());
data[opt + 124..opt + 128].copy_from_slice(&40u32.to_le_bytes());
// Descriptor 0 at file offset 0x200: Name at RVA 0x1028, FirstThunk at RVA 0x1034.
let desc = 0x200;
data[desc + 12..desc + 16].copy_from_slice(&0x1028u32.to_le_bytes());
data[desc + 16..desc + 20].copy_from_slice(&0x1034u32.to_le_bytes());
data[0x228..0x231].copy_from_slice(b"test.dll\0");
let info = ImageInfo::parse(&data).unwrap();
assert_eq!(info.imports[0].dll, "test.dll");
// First descriptor's FirstThunk, at the 4 GiB limit: used to overflow.
data[desc + 16..desc + 20].copy_from_slice(&0xFFFF_FFF8u32.to_le_bytes());
assert!(matches!(

View File

@ -98,9 +98,12 @@ needs its line in every file, which `tests/test_leonida_launcher.py` checks (sam
is running.
- **Updates**: at every start the launcher runs `git fetch` in
its own folder and, when the clone is behind the branch it follows, lists the new commits in the Play page's
Updates card (`git log --first-parent HEAD..@{u}`) with an **Update Mandy** button. Update runs `git pull --ff-only` (it stops, changing nothing, if local
changes or another branch are in the way), then rebuilds the runtime when `d3d12/` changed. A copy downloaded as
a zip has no `.git`: the launcher says so, and updating means a `git clone` of the repository instead.
Updates card (`git log --first-parent HEAD..@{u}`) with an **Update Mandy** button. Update runs `git pull --ff-only`
(it stops, changing nothing, if local changes or another branch are in the way), then, on Windows, rebuilds the
runtime when `d3d12/` changed; on Linux it only says that `d3d12/` changed, and the rebuild is yours to run
([linux.md](linux.md#the-runtime-under-wine-or-proton)). A copy downloaded as a zip has no `.git`, and updating
means a `git clone` of the repository instead. A zip copy, a missing git, a failed check (with git's reason) or a
branch that follows no upstream is shown in the Updates card and the rail instead of an update.
- **Tools**: update Leonida (as above), fetch NVIDIA's DLSS files (`d3d12\Get-NVIDIA-DLSS.cmd`, after a confirmation: about 70 MB from NVIDIA's
GitHub), rebuild the runtime (`d3d12\scripts\build-nvidia.ps1`), open the logs folder
(`%LOCALAPPDATA%\Leonida\logs`) and the screenshots folder. The two scripts are Windows only.

View File

@ -29,7 +29,7 @@ the running title**. What that leaves open is listed at the end.
which (`Lua mods` line, target `lua`).
3. Set `"enabled": true` in `mods\example_lua\mod.json` (it ships disabled), start the title, and look at the lower
left corner: a frame-rate line. F4 opens the trainer menu; the last item, Mods, has the example's page.
After editing a script, F4, Mods, Reload Lua mods loads them all again (a fresh Lua state).
After editing a script, F4, Mods, Reload Lua mods loads them all again (each in a fresh Lua state).
`LEONIDA_LUA=0` turns it off completely: no thread, nothing per frame but one atomic load at present, no Mods page.
@ -164,8 +164,9 @@ require("helper") -- helper.lua (or helper/init.lua; dots are folders) o
```
Files: only the mod's own folder, plain relative paths (no `..`, drive letters, streams or reserved device names; a
link that leads out is refused), reads up to 4 MiB, writes up to 1 MiB, never `mod.json` or a program (`.exe`, `.dll`,
`.bat`, ...). There is no `io`. The rule holds for `require` and for the script the manifest names, too.
link that leads out of it, or to nothing, is refused), reads up to 4 MiB, writes up to 1 MiB, never `mod.json` or a
program (`.exe`, `.dll`, `.bat`, ...). There is no `io`. The rule holds for `require` and for the script the manifest
names, too.
## The sandbox
@ -183,7 +184,9 @@ runtime offers none and the standard libraries that could reach one are not load
Limits: a call into a mod (loading it, a handler, a menu callback) may run for 200 ms (the load 2 s) of Lua; a loop
that does not end stops with an error, also inside `pcall`, `xpcall` and `coroutine.resume`, which hand that error
back instead of swallowing it. The whole Lua state may use 128 MiB. A coroutine can still yield through `pcall`.
back instead of swallowing it. Each mod has a Lua state of its own and may use 128 MiB: a mod that holds memory leaves
the others theirs (all the mods together may use 128 MiB times their number), and `collectgarbage("count")` counts
its own. A coroutine can still yield through `pcall`.
An error anywhere (the script's own, a handler, a menu callback, a bad argument, an exceeded limit) is logged with
the mod's name and **disables that mod only**: its handlers, its menu pages and the keys it holds go, the other mods

View File

@ -4,13 +4,18 @@
A fake GitHub API stands in for the network, so this checks the calls the tool makes: which pull requests get the
label, that one whose merge GitHub has not computed yet is asked again and otherwise left alone, that the label is
created only when it is first needed, that `--dry-run` writes nothing, and that the workflow runs the tool without
checking out pull request code. Standard library only; no network, no game files.
created only when it is first needed, that `--dry-run` writes nothing, that a run over every open pull request stays
under the hourly request limit of the workflow's token, and that the workflow runs the tool without checking out
pull request code. Standard library only; no network, no game files.
"""
import contextlib
import functools
import io
import os
import re
import sys
import unittest
from unittest import mock
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tools"))
@ -22,22 +27,40 @@ REPO = "owner/name"
class FakeApi:
"""Pull requests as {number: [mergeable answers in order, the last one repeating]} plus their labels."""
def __init__(self, prs, labeled=(), label_exists=False, closed=()):
def __init__(self, prs, labeled=(), label_exists=False, closed=(), limit=None):
self.answers = {n: list(a) for n, a in prs.items()}
self.labels = {n: ({pcl.LABEL} if n in labeled else set()) for n in prs}
self.closed = set(closed)
self.label_exists = label_exists
self.limit = limit # requests this token may make, as GitHub counts them per hour
self.calls = []
def mergeable(self, n):
answers = self.answers[n]
return answers.pop(0) if len(answers) > 1 else answers[0]
def __call__(self, method, path, body=None):
self.calls.append((method, path, body))
if self.limit is not None and len(self.calls) > self.limit:
raise pcl.ApiError(403, "API rate limit exceeded for installation")
if method == "POST" and path == "/graphql":
self.assert_query(body)
numbers = sorted(n for n in self.answers if n not in self.closed)
start = int(body["variables"]["after"] or 0)
names = {True: "MERGEABLE", False: "CONFLICTING", None: "UNKNOWN"}
nodes = [{"number": n, "mergeable": names[self.mergeable(n)],
"labels": {"nodes": [{"name": name} for name in sorted(self.labels[n])]}}
for n in numbers[start:start + 100]]
more = start + 100 < len(numbers)
return {"data": {"repository": {"pullRequests": {
"pageInfo": {"hasNextPage": more, "endCursor": str(start + 100) if more else None}, "nodes": nodes}}}}
m = re.fullmatch(rf"/repos/{REPO}/pulls/(\d+)", path)
if method == "GET" and m:
n = int(m.group(1))
answers = self.answers[n]
mergeable = answers.pop(0) if len(answers) > 1 else answers[0]
return {"number": n, "state": "closed" if n in self.closed else "open", "mergeable": mergeable,
return {"number": n, "state": "closed" if n in self.closed else "open", "mergeable": self.mergeable(n),
"labels": [{"name": name} for name in sorted(self.labels[n])]}
# How the tool listed them before the GraphQL listing: kept so that these tests, run against that version,
# end in its HTTP 403 rather than in "unexpected call".
if method == "GET" and path.startswith(f"/repos/{REPO}/pulls?"):
page = int(re.search(r"[?&]page=(\d+)", path).group(1))
numbers = sorted(self.answers)
@ -60,8 +83,15 @@ class FakeApi:
return None
raise AssertionError(f"unexpected call {method} {path}")
def assert_query(self, body):
owner, name = REPO.split("/")
assert (body["variables"]["owner"], body["variables"]["name"]) == (owner, name), body["variables"]
for part in ("states: OPEN", "first: 100", "after: $after", "hasNextPage", "endCursor", "number", "mergeable",
"labels(first: 100)"):
assert part in body["query"], part
def writes(self):
return [c for c in self.calls if c[0] != "GET"]
return [c for c in self.calls if c[0] != "GET" and c[1] != "/graphql"]
def run(api, numbers, **kw):
@ -127,9 +157,60 @@ class RunTest(unittest.TestCase):
self.assertEqual((done["add"], done["remove"]), ([1], [2]))
self.assertEqual(api.writes(), [])
def test_open_pull_numbers_follows_pages(self):
api = FakeApi({n: [True] for n in range(1, 251)})
self.assertEqual(pcl.open_pull_numbers(api, REPO), list(range(1, 251)))
def test_open_pulls_follows_pages(self):
api = FakeApi({n: [n % 3 != 0 if n % 5 else None] for n in range(1, 251)}, labeled={4, 250}, closed={8})
pulls = pcl.open_pulls(api, REPO)
self.assertEqual(sorted(pulls), [n for n in range(1, 251) if n != 8])
self.assertEqual((pulls[1], pulls[3], pulls[4], pulls[5], pulls[250]),
((True, False), (False, False), (True, True), (None, False), (None, True)))
self.assertEqual(len(api.calls), 3)
def test_a_graphql_error_is_not_read_as_no_pull_requests(self):
def api(method, path, body=None):
return {"data": {"repository": None}, "errors": [{"type": "NOT_FOUND", "message": "no such repository"}]}
with self.assertRaisesRegex(pcl.ApiError, "no such repository"):
pcl.open_pulls(api, REPO)
class AllOpenTest(unittest.TestCase):
"""A run over every open pull request, as the workflow starts it."""
def main(self, api, *args):
out = io.StringIO()
self.waits = []
no_wait = functools.partial(pcl.run, sleep=self.waits.append)
with mock.patch.object(pcl, "github_api", lambda token: api), mock.patch.object(pcl, "run", no_wait), \
mock.patch.dict(os.environ, {"GITHUB_TOKEN": "t"}), contextlib.redirect_stdout(out):
status = pcl.main(["--repo", REPO, *args])
return status, out.getvalue()
def test_1500_open_pull_requests_stay_under_the_token_limit(self):
# The workflow's GITHUB_TOKEN gets 1,000 requests an hour for the repository, shared by every run. One GET
# per pull request and attempt spends them: with 1,500 open a single run ended in HTTP 403 before the last.
prs = {n: [True] for n in range(1, 1501)}
prs.update({7: [False], 1200: [False], 1400: [None, False], 1499: [True], 1500: [None]})
api = FakeApi(prs, labeled={1499, 1500}, limit=1000)
status, text = self.main(api)
self.assertEqual(status, 0)
self.assertEqual(sorted(n for n, names in api.labels.items() if names), [7, 1200, 1400, 1500])
self.assertIn("1500 checked: 3 labeled, 1 unlabeled, 1 not computed yet", text)
self.assertLessEqual(len(api.calls), 4 * 15 + 5) # 15 pages an attempt, then the label and four changes
self.assertEqual(self.waits, [pcl.LIST_WAIT] * 3) # a listing is cheap: GitHub gets longer between attempts
def test_a_pull_request_closed_between_two_listings_is_skipped(self):
api = FakeApi({1: [None, False], 2: [None, False]})
pulls = pcl.open_pulls(api, REPO)
api.closed.add(2)
done = run(api, sorted(pulls), pulls=pulls)
self.assertEqual(done, {"add": [1], "remove": [], "unknown": []})
self.assertEqual(api.labels, {1: {pcl.LABEL}, 2: set()})
def test_one_named_pull_request_is_one_request(self):
api = FakeApi({n: [True] for n in range(1, 301)}, labeled={5})
status, text = self.main(api, "--pr", "5")
self.assertEqual(status, 0)
self.assertEqual([c[:2] for c in api.calls], [("GET", f"/repos/{REPO}/pulls/5"),
("DELETE", f"/repos/{REPO}/issues/5/labels/needs%20rebase")])
class WorkflowTest(unittest.TestCase):

View File

@ -8,8 +8,13 @@ per-pull-request trigger: one run per push to every pull request flooded the rep
the ones that cannot be merged as they stand and tells their authors to rebase.
GitHub computes `mergeable` in the background and answers `null` until it has, so a pull request whose answer is
still unknown is asked again a few times and otherwise left as it is for the next run. Only the GitHub REST API is
read and written: no pull request code is checked out or run. The token comes from `GITHUB_TOKEN` (or `GH_TOKEN`); `--dry-run` prints the changes and writes nothing.
still unknown is asked again a few times and otherwise left as it is for the next run. A run over every open pull
request reads them 100 per request through the GraphQL API: the workflow's token gets 1,000 requests an hour for the
whole repository, and one request per open pull request on every attempt of every run spent them with several hundred
open, so runs failed with HTTP 403 and the other workflows had none left. A listing is cheap, so its attempts are
LIST_WAIT seconds apart: three waits give GitHub about the minutes a pass of one request per pull request used to,
to compute the merges a push to `main` reset. `--pr` still asks for each one by number.
Only the GitHub API is read and written: no pull request code is checked out or run. The token comes from `GITHUB_TOKEN` (or `GH_TOKEN`); `--dry-run` prints the changes and writes nothing.
Standard library only; no game files.
"""
import argparse
@ -25,6 +30,17 @@ LABEL = "needs rebase"
LABEL_COLOR = "d93f0b"
LABEL_DESCRIPTION = "Conflicts with the base branch: rebase it on main"
API = "https://api.github.com"
# Every open pull request, 100 per request: its number, GitHub's merge answer and its labels.
PULLS_QUERY = """query($owner: String!, $name: String!, $after: String) {
repository(owner: $owner, name: $name) {
pullRequests(states: OPEN, first: 100, after: $after) {
pageInfo { hasNextPage endCursor }
nodes { number mergeable labels(first: 100) { nodes { name } } }
}
}
}"""
MERGEABLE = {"MERGEABLE": True, "CONFLICTING": False} # "UNKNOWN": not computed yet
LIST_WAIT = 60.0 # seconds between the attempts of a run over every open pull request
class ApiError(Exception):
@ -34,7 +50,8 @@ class ApiError(Exception):
def github_api(token):
"""A function (method, path, body=None) -> parsed JSON (or None) that calls the GitHub REST API with `token`."""
"""A function (method, path, body=None) -> parsed JSON (or None) that calls the GitHub API with `token`: REST,
and GraphQL at `/graphql`."""
def call(method, path, body=None):
data = None if body is None else json.dumps(body).encode("utf-8")
req = urllib.request.Request(API + path, data=data, method=method, headers={
@ -61,14 +78,23 @@ def decide(mergeable, labeled):
return None
def open_pull_numbers(api, repo):
numbers, page = [], 1
def open_pulls(api, repo):
"""{number: (mergeable, labeled)} for every open pull request, read 100 per request. `mergeable` is True, False
or None (not computed yet)."""
owner, _, name = repo.partition("/")
pulls, after = {}, None
while True:
batch = api("GET", f"/repos/{repo}/pulls?state=open&per_page=100&page={page}")
numbers += [p["number"] for p in batch]
if len(batch) < 100:
return numbers
page += 1
answer = api("POST", "/graphql", {"query": PULLS_QUERY,
"variables": {"owner": owner, "name": name, "after": after}})
if answer.get("errors") or not (answer.get("data") or {}).get("repository"):
raise ApiError(200, json.dumps(answer.get("errors"))[:300]) # GraphQL reports its errors in the body
page = answer["data"]["repository"]["pullRequests"]
for node in page["nodes"]:
labeled = any(label.get("name") == LABEL for label in node["labels"]["nodes"])
pulls[node["number"]] = (MERGEABLE.get(node["mergeable"]), labeled)
if not page["pageInfo"]["hasNextPage"]:
return pulls
after = page["pageInfo"]["endCursor"]
def ensure_label(api, repo):
@ -91,8 +117,14 @@ def apply(api, repo, number, action):
raise
def run(api, repo, numbers, dry_run=False, attempts=4, wait=10.0, sleep=time.sleep, out=print):
"""Label or unlabel each pull request of `numbers`. Returns {'add': [...], 'remove': [...], 'unknown': [...]}."""
def run(api, repo, numbers, dry_run=False, attempts=4, wait=None, sleep=time.sleep, out=print, pulls=None):
"""Label or unlabel each pull request of `numbers`. Returns {'add': [...], 'remove': [...], 'unknown': [...]}.
`pulls` is what open_pulls() answered when `numbers` are all the open pull requests: each attempt then reads
them again in pages instead of one request per pull request, LIST_WAIT seconds after the last one (10 seconds
between attempts that ask by number, unless `wait` says otherwise)."""
if wait is None:
wait = 10.0 if pulls is None else LIST_WAIT
done = {"add": [], "remove": [], "unknown": []}
pending = list(numbers)
label_ready = dry_run
@ -100,15 +132,23 @@ def run(api, repo, numbers, dry_run=False, attempts=4, wait=10.0, sleep=time.sle
if attempt:
sleep(wait) # asking for a pull request starts GitHub's merge computation; give it time
unknown = []
if pulls is not None and attempt:
pulls = open_pulls(api, repo)
for number in pending:
pr = api("GET", f"/repos/{repo}/pulls/{number}")
if pr.get("state") != "open":
continue
labeled = any(label.get("name") == LABEL for label in pr.get("labels", []))
if pr.get("mergeable") is None:
if pulls is None:
pr = api("GET", f"/repos/{repo}/pulls/{number}")
if pr.get("state") != "open":
continue
mergeable = pr.get("mergeable")
labeled = any(label.get("name") == LABEL for label in pr.get("labels", []))
elif number in pulls:
mergeable, labeled = pulls[number]
else:
continue # closed or merged since it was listed
if mergeable is None:
unknown.append(number)
continue
action = decide(pr["mergeable"], labeled)
action = decide(mergeable, labeled)
if action is None:
continue
out(f"#{number}: {action} '{LABEL}'" + (" (dry run)" if dry_run else ""))
@ -137,8 +177,9 @@ def main(argv=None):
if not args.repo or not token:
ap.error("needs --repo (or GITHUB_REPOSITORY) and GITHUB_TOKEN (or GH_TOKEN)")
api = github_api(token)
numbers = args.pr or open_pull_numbers(api, args.repo)
done = run(api, args.repo, numbers, dry_run=args.dry_run)
pulls = None if args.pr else open_pulls(api, args.repo)
numbers = args.pr or sorted(pulls)
done = run(api, args.repo, numbers, dry_run=args.dry_run, pulls=pulls)
print(f"{len(numbers)} checked: {len(done['add'])} labeled, {len(done['remove'])} unlabeled, "
f"{len(done['unknown'])} not computed yet")
return 0