From 51dc36f519f40e4a2f221c1140e815eb7c9c1cc3 Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 12:32:46 -0600 Subject: [PATCH 01/31] S046: plan for 0.1.1 fixes (server names, raise on arrival, copy in fields) Co-Authored-By: Claude Opus 5.5 --- Plans/10 Distribution/S046-fixes-0.1.1.md | 29 +++++++++++++++++++++++ Plans/INDEX.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 Plans/10 Distribution/S046-fixes-0.1.1.md diff --git a/Plans/10 Distribution/S046-fixes-0.1.1.md b/Plans/10 Distribution/S046-fixes-0.1.1.md new file mode 100644 index 0000000..402e326 --- /dev/null +++ b/Plans/10 Distribution/S046-fixes-0.1.1.md @@ -0,0 +1,29 @@ +# S046 — 0.1.1: names from the server, raise on arrival, copy in fields + +> Category 10 Distribution · Model: Sonnet · Effort: medium · Depends on: S045 · Phase: test · Human: 🧑 yes before release +> Files touched: crates/core/src/http/name.rs and its callers, crates/core/src/connector/**, crates/app/src/views/{incoming,add}/**, crates/app/src/keys.rs, crates/app/src/app.rs, version files, docs/releases/0.1.1.md, docs/tests/S046-fixes-0.1.1.md + +## Goal +Three bugs the user found with 0.1.0 (Nacre on a real site): +1. **Name**: the browser hands over a provisional name (`output.bin`) at click time; the real name (archive) only comes with the server's reply (Content-Disposition, or the final link after redirects). Medlar keeps the sender's name, so the file stays `output.bin`. +2. **No raise**: a pushed download does not bring Medlar forward. `incoming.rs` sends `ViewportCommand::Focus` only, which Wayland (niri) ignores without an activation token, and does nothing when the window is hidden to the tray. +3. **Copy in fields**: in Settings (and every text field) Ctrl+C does not copy: `keys::pressed` lets the list's Copy shortcut (Ctrl+C) and Select all (Ctrl+A) eat the events while a text field has focus (`taken()` covers V, X, Z only). + +## Read +- crates/core/src/http/name.rs (`pick`), where a task's name is set from a sender or the Add dialog and where the first reply is handled (rg `pick(`) +- crates/app/src/views/incoming.rs (`tick`, `ask`), app.rs lines ~255-330 (show/hide), crates/app/src/keys.rs (`pressed`, `taken`, `fits`) +- docs/CONNECTOR.md (`filename` field) + +## Steps +- [ ] Name: a name from a sender (connector `filename`, or the Add dialog when the user did not type it) is a hint. On the first reply, when the hint is generic (no extension, or an extension like bin, php, asp, aspx, cgi, html, htm, download, or a known placeholder such as `output.bin`, `download`, `file`) and the reply gives a name (Content-Disposition, else the final link with a file extension), use the reply's name, made safe as today, before any file is created; a name the user typed always wins; collisions handled as today (never overwrite). The Add dialog's probe updates the shown name the same way while the user has not edited it. Unit tests in name.rs and an engine test against testserver (provisional name + Content-Disposition, and a redirect to a named link) +- [ ] Raise: on an arrival that shows the Add window or adds a download, if the main window is hidden show it (`Visible(true)`, `Minimized(false)`), then `Focus` and `RequestUserAttention(Critical)` (urgency where focus is refused); same for second-instance hand-over; clear the attention when the window gets focus. A kittest that records the viewport commands +- [ ] Copy: while a text field has focus, Ctrl+C, Ctrl+A (and Ctrl+X, Ctrl+V, Ctrl+Z as now) go to the field, not to list shortcuts; settings values that are read-only text (paths, versions, the port, the token) are selectable or have a copy button where egui allows. Unit test for `pressed` with a focused field +- [ ] Full workspace suite once (absolute TMPDIR), then release build; hidden smoke test: POST a link with `filename: output.bin` to a testserver URL that answers with Content-Disposition `game.zip`: Add window shows and the file is `game.zip`; window raised in the grab +- [ ] Version 0.1.1 everywhere (Cargo, metainfo, PKGBUILD, .SRCINFO); `tools/package.sh` builds tar.gz, AppImage, Arch package and `SHA256SUMS-0.1.1` in dist/; `docs/releases/0.1.1.md`; nothing into releases/ +- [ ] Test file `docs/tests/S046-fixes-0.1.1.md` with Results, PROGRESS entry, tick INDEX, commit `S046: …`, `git push origin HEAD` + +## End criteria +- the three bugs have passing regression tests; suite green; builds smoke-tested + +## Pitfalls +File names from servers are hostile: same `safe` rules as today. Never rename over an existing file. Never contact the real site; testserver on loopback only. Release only after the user's yes. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index a05a413..ad754fd 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -66,6 +66,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 10 Distribution - [x] [S045](10%20Distribution/S045-installer-arch.md) installer.sh and Arch package +- [ ] [S046](10%20Distribution/S046-fixes-0.1.1.md) 0.1.1: names from the server, raise on arrival, copy in fields ## Later (after version 1; not run by /orchestrate) From a8c38788e15a0c48b3ab91c2e12eb5c11b14b469 Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 12:34:22 -0600 Subject: [PATCH 02/31] S046: placeholder names give way to the server's, raise on arrival, copy in fields --- crates/app/src/app.rs | 2 +- crates/app/src/keys.rs | 37 +++++++++++++++++++++++++++- crates/app/src/views/add/draw.rs | 1 + crates/app/src/views/add/mod.rs | 9 +++++++ crates/app/src/views/incoming.rs | 41 ++++++++++++++++++++++++++++---- crates/core/src/http/download.rs | 6 ++++- crates/core/src/http/mod.rs | 2 +- crates/core/src/http/name.rs | 29 ++++++++++++++++++++++ crates/core/tests/http.rs | 18 ++++++++++++++ 9 files changed, 137 insertions(+), 8 deletions(-) diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index fc22644..3d4388f 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -323,7 +323,7 @@ impl App { self.main.toasts.info("content_paste", tr!("clip.added", n = tasks.len())); self.main.bridge.add(tasks, secrets); } else if !links.is_empty() { - ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + crate::views::incoming::raise(ctx); self.main.adding.ask(Request { text: links.join("\n"), literal: true, ..Request::default() }); } } diff --git a/crates/app/src/keys.rs b/crates/app/src/keys.rs index ccd944e..33ffc23 100644 --- a/crates/app/src/keys.rs +++ b/crates/app/src/keys.rs @@ -174,6 +174,11 @@ impl Shortcut { moves.contains(&self.key) && !self.alt || self.key == Key::Tab || self.ctrl && !self.alt && !self.shift && edits.contains(&self.key) } + /// Copy, select all and the other editing keys: a focused text field owns them. + fn edits(self) -> bool { + self.ctrl && !self.alt && [Key::A, Key::C, Key::V, Key::X, Key::Z].contains(&self.key) + } + /// Would type something or press what has the keyboard, so it can't count everywhere. pub fn types(self) -> bool { let function = self.key.name().strip_prefix('F').is_some_and(|n| n.parse::().is_ok()); @@ -253,7 +258,7 @@ pub fn label(action: Action) -> String { /// Was its shortcut pressed? Nothing else sees it then. pub fn pressed(ui: &Ui, action: Action) -> bool { let Some(keys) = MAP.with_borrow(|m| m.get(&action).copied().unwrap_or_else(|| usual(action))) else { return false }; - if keys.types() && ui.ctx().text_edit_focused() { + if (keys.types() || keys.edits()) && ui.ctx().text_edit_focused() { return false; } ui.input_mut(|i| { @@ -282,6 +287,36 @@ mod tests { } } + #[test] + #[allow(deprecated)] + fn a_focused_field_keeps_copy_and_select_all() { + use eframe::egui::{Context, Id, RawInput, TextEdit}; + let ctx = Context::default(); + let mut text = String::from("abc"); + let id = Id::new("field"); + let mut run = |events: Vec, focus: bool| { + let mut got = (false, false); + let input = RawInput { events, ..RawInput::default() }; + let _ = ctx.run_ui(input, |ui| { + let r = ui.add(TextEdit::singleline(&mut text).id(id)); + if focus { + r.request_focus(); + } + got = (pressed(ui, Action::Copy), pressed(ui, Action::SelectAll)); + }); + got + }; + let ctrl = Modifiers::CTRL; + let keys = |k| vec![Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: ctrl }]; + run(vec![], true); + run(vec![], true); + assert_eq!(run(vec![Event::Copy], true), (false, false), "field has focus"); + assert_eq!(run(keys(Key::A), true), (false, false)); + ctx.memory_mut(|m| m.surrender_focus(id)); + run(vec![], false); + assert_eq!(run(vec![Event::Copy], false).0, true, "list copies without a field"); + } + #[test] fn shortcuts_are_read_and_written_the_same() { for text in ["Ctrl+N", "Alt+Up", "Shift+Del", "F2", "Ctrl+Alt+Shift+Enter", "Ctrl+,", "Space"] { diff --git a/crates/app/src/views/add/draw.rs b/crates/app/src/views/add/draw.rs index a419b52..5fd0518 100644 --- a/crates/app/src/views/add/draw.rs +++ b/crates/app/src/views/add/draw.rs @@ -112,6 +112,7 @@ impl Add { let r = field.show(ui, t, &mut self.name); if r.changed() { self.name_own = !self.name.trim().is_empty(); + self.name_typed = self.name_own; } } self.where_to(ui, t, cx, wrong); diff --git a/crates/app/src/views/add/mod.rs b/crates/app/src/views/add/mod.rs index d9fd6b8..f71248f 100644 --- a/crates/app/src/views/add/mod.rs +++ b/crates/app/src/views/add/mod.rs @@ -341,6 +341,8 @@ pub struct Add { pub name: String, /// The user wrote it. name_own: bool, + /// The user typed the name, so the server never replaces it. + name_typed: bool, rules: Vec, base: PathBuf, pub folder: String, @@ -403,6 +405,7 @@ impl Add { twice: Twice::Skip, name: from.name.clone().unwrap_or_default(), name_own: from.name.is_some(), + name_typed: false, rules: settings.rules.clone(), base: download_folder(settings), folder: download_folder(settings).display().to_string(), @@ -644,6 +647,12 @@ impl Add { pub fn learned(&mut self, found: Probed) { if !self.name_own { self.name = found.name.clone(); + } else if !self.name_typed { + // The name came with the link: a placeholder gives way to the server's. + if let Some(n) = medlar_core::http::prefer_name(self.name.trim(), &found.name) { + self.name = n; + self.name_own = false; + } } self.look = Look::Found(found); } diff --git a/crates/app/src/views/incoming.rs b/crates/app/src/views/incoming.rs index ab438fe..71c8b2d 100644 --- a/crates/app/src/views/incoming.rs +++ b/crates/app/src/views/incoming.rs @@ -9,7 +9,7 @@ use super::add::{Add, Checking, Request}; use super::main::Main; use crate::bridge::Data; use crate::views::connector; -use eframe::egui::{Context, ViewportCommand}; +use eframe::egui::{Context, UserAttentionType, ViewportCommand}; use medlar_core::connector::{Arrival, Connector, Incoming as Link}; use medlar_core::model::TaskId; use medlar_core::relink::{self, NewLink, Strength}; @@ -38,6 +38,16 @@ pub struct Inbox { /// Downloads that wait for a link, and the check of the one that came. waiting: Vec<(TaskId, String, Checking)>, failed: bool, + /// The window asked for attention and has not had focus since. + attention: bool, +} + +/// Brings the window forward, also from the tray. Where focus is refused (Wayland), it asks for attention. +pub fn raise(ctx: &Context) { + ctx.send_viewport_cmd(ViewportCommand::Visible(true)); + ctx.send_viewport_cmd(ViewportCommand::Minimized(false)); + ctx.send_viewport_cmd(ViewportCommand::Focus); + ctx.send_viewport_cmd(ViewportCommand::RequestUserAttention(UserAttentionType::Critical)); } impl Inbox { @@ -48,10 +58,15 @@ impl Inbox { /// Once per frame. pub fn tick(&mut self, ctx: &Context, s: &Settings, main: &mut Main) { + if self.attention && ctx.input(|i| i.focused) { + self.attention = false; + ctx.send_viewport_cmd(ViewportCommand::RequestUserAttention(UserAttentionType::Reset)); + } self.port(ctx, s, main); if let Some(args) = &self.args { while let Ok(list) = args.try_recv() { - ctx.send_viewport_cmd(ViewportCommand::Focus); + raise(ctx); + self.attention = true; self.pending.extend(list.iter().filter_map(|a| of_arg(a)).map(Item::Asked)); } } @@ -148,9 +163,14 @@ impl Inbox { self.waiting.retain(|(_, _, c)| c.busy()); } + fn raise(&mut self, ctx: &Context) { + raise(ctx); + self.attention = true; + } + fn ask(&mut self, ctx: &Context, main: &mut Main, request: Request) { if main.adding.now().is_none() { - ctx.send_viewport_cmd(ViewportCommand::Focus); + self.raise(ctx); } main.adding.ask(request); } @@ -200,6 +220,7 @@ impl Inbox { main.bridge.add(tasks, secrets); } main.toasts.info("download", tr!("incoming.added", n = n)); + self.raise(ctx); return; } self.ask(ctx, main, request); @@ -226,7 +247,19 @@ pub fn of_arg(arg: &str) -> Option { #[cfg(test)] mod tests { - use super::of_arg; + use super::{of_arg, raise}; + use eframe::egui::{Context, RawInput, UserAttentionType, ViewportCommand, ViewportId}; + + #[test] + fn raising_shows_focuses_and_asks_for_attention() { + let ctx = Context::default(); + let out = ctx.run_ui(RawInput::default(), |ui| raise(ui.ctx())); + let cmds = &out.viewport_output[&ViewportId::ROOT].commands; + assert!(cmds.contains(&ViewportCommand::Visible(true))); + assert!(cmds.contains(&ViewportCommand::Minimized(false))); + assert!(cmds.contains(&ViewportCommand::Focus)); + assert!(cmds.contains(&ViewportCommand::RequestUserAttention(UserAttentionType::Critical))); + } #[test] fn arguments() { diff --git a/crates/core/src/http/download.rs b/crates/core/src/http/download.rs index ed17d27..c1b5281 100644 --- a/crates/core/src/http/download.rs +++ b/crates/core/src/http/download.rs @@ -293,7 +293,11 @@ fn finished(p: &Part) -> bool { async fn start(shared: &Shared, job: &Job, task: &Task, probe: Probe, link: &Link, stop: &mut Stop) -> Result<(Arc, Vec)> { let hints = hints(shared, task, &probe, link, stop).await?; let parts = vec![Part { start: 0, end: probe.version.size.filter(|_| probe.ranges), done: 0 }]; - let wanted = safe_name(&task.name).unwrap_or(probe.name); + // A sender's name is a hint: the reply's own name wins over a placeholder like `output.bin`. + let wanted = match safe_name(&task.name) { + Some(hint) => name::prefer(&hint, &probe.name).unwrap_or(hint), + None => probe.name, + }; let (id, saved, folder) = (job.id, parts.clone(), task.folder.clone()); let file = job .run(move |store| { diff --git a/crates/core/src/http/mod.rs b/crates/core/src/http/mod.rs index f4a1c12..a9afc90 100644 --- a/crates/core/src/http/mod.rs +++ b/crates/core/src/http/mod.rs @@ -15,7 +15,7 @@ pub(crate) use download::is_page; pub(crate) use fetch::{bytes_at, same_body, small}; pub use fetch::{Link, OVERLAP, compare, fetch, same_bytes}; pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, ServerState, ServerView, Snapshot}; -pub use name::safe as safe_name; +pub use name::{prefer as prefer_name, safe as safe_name}; pub(crate) use piece::piece; pub use probe::{Probe, probe}; diff --git a/crates/core/src/http/name.rs b/crates/core/src/http/name.rs index c8ef1aa..57a3814 100644 --- a/crates/core/src/http/name.rs +++ b/crates/core/src/http/name.rs @@ -85,6 +85,24 @@ pub(super) fn pick(source: &Source, last: &Url, headers: &HeaderMap) -> String { } } +/// A name that says nothing: no extension, a page or script extension, bin, or a known placeholder. +fn placeholder(name: &str) -> bool { + let (stem, ext) = split(name); + let stem = stem.to_lowercase(); + if ["download", "file", "output", "index", "unknown", "get"].contains(&stem.as_str()) && ext.is_none_or(|e| e.eq_ignore_ascii_case("bin")) { + return true; + } + ext.is_none_or(|e| { + let e = e.to_lowercase(); + SCRIPTS.contains(&e.as_str()) || ["bin", "html", "htm", "download"].contains(&e.as_str()) + }) +} + +/// A name a sender gave is a hint. When it says nothing and the reply has a better one, that one. +pub fn prefer(hint: &str, found: &str) -> Option { + (placeholder(hint) && !placeholder(found)).then(|| found.to_string()) +} + /// `type/subtype` in lower case. pub(super) fn mime(headers: &HeaderMap) -> Option { let value = headers.get(CONTENT_TYPE)?.to_str().ok()?; @@ -275,6 +293,17 @@ mod tests { assert_eq!(picked(h, "http://[::1]/", ""), "__1"); } + #[test] + fn hints_give_way() { + assert_eq!(prefer("output.bin", "game.zip").as_deref(), Some("game.zip")); + assert_eq!(prefer("download", "a.iso").as_deref(), Some("a.iso")); + assert_eq!(prefer("get.php", "a.iso").as_deref(), Some("a.iso")); + assert_eq!(prefer("noext", "a.iso").as_deref(), Some("a.iso")); + assert_eq!(prefer("real.zip", "other.zip"), None); + assert_eq!(prefer("output.bin", "host.example.html"), None); + assert_eq!(prefer("output.bin", "file"), None); + } + #[test] fn safe_names() { for (name, want) in [ diff --git a/crates/core/tests/http.rs b/crates/core/tests/http.rs index b35fcf6..f11a01a 100644 --- a/crates/core/tests/http.rs +++ b/crates/core/tests/http.rs @@ -490,3 +490,21 @@ async fn kills_lose_nothing() { println!("{kills} kills, {files} files, {} MB kept over kills", kept / MB); assert!(kept > 0, "no kill came in the middle"); } + +/// S046: the name a sender gave is a hint; the reply's own name replaces a placeholder, never a real name. +#[tokio::test(flavor = "multi_thread")] +async fn a_placeholder_name_gives_way_to_the_servers() { + let b = Bench::new().await; + let add = |path: &str, name: &str| b.store.add_task(Task { url: b.server.url(path), name: name.into(), folder: b.folder(), ..Task::default() }).unwrap(); + let named = add("/data/4/300k/game.zip?disp=attachment", "output.bin"); + let moved = add("/redirect/1?to=/data/5/300k/other.iso", "download"); + let real = add("/data/6/300k/game2.zip?disp=attachment", "mine.bin"); + for id in [named, moved, real] { + b.run(id).await.unwrap(); + } + let name = |id| b.store.task(id).unwrap().name; + assert_eq!(name(named), "game.zip"); + assert_eq!(name(moved), "other.iso"); + assert_eq!(name(real), "mine.bin", "a name without a placeholder stays"); + assert!(b.folder().join("game.zip").exists() && !b.folder().join("output.bin").exists()); +} From 8ffed89259b8fb2d8972d3d1750e4dda82c0f07b Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 12:35:50 -0600 Subject: [PATCH 03/31] S046: tests fixed --- crates/app/src/keys.rs | 3 ++- crates/app/src/views/incoming.rs | 3 ++- crates/core/tests/http.rs | 4 ++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/app/src/keys.rs b/crates/app/src/keys.rs index 33ffc23..74705b5 100644 --- a/crates/app/src/keys.rs +++ b/crates/app/src/keys.rs @@ -297,13 +297,14 @@ mod tests { let mut run = |events: Vec, focus: bool| { let mut got = (false, false); let input = RawInput { events, ..RawInput::default() }; - let _ = ctx.run_ui(input, |ui| { + let mut out = ctx.run_ui(input, |ui| { let r = ui.add(TextEdit::singleline(&mut text).id(id)); if focus { r.request_focus(); } got = (pressed(ui, Action::Copy), pressed(ui, Action::SelectAll)); }); + out.textures_delta.clear(); got }; let ctrl = Modifiers::CTRL; diff --git a/crates/app/src/views/incoming.rs b/crates/app/src/views/incoming.rs index 71c8b2d..83ebd6a 100644 --- a/crates/app/src/views/incoming.rs +++ b/crates/app/src/views/incoming.rs @@ -253,7 +253,8 @@ mod tests { #[test] fn raising_shows_focuses_and_asks_for_attention() { let ctx = Context::default(); - let out = ctx.run_ui(RawInput::default(), |ui| raise(ui.ctx())); + let mut out = ctx.run_ui(RawInput::default(), |ui| raise(ui.ctx())); + out.textures_delta.clear(); let cmds = &out.viewport_output[&ViewportId::ROOT].commands; assert!(cmds.contains(&ViewportCommand::Visible(true))); assert!(cmds.contains(&ViewportCommand::Minimized(false))); diff --git a/crates/core/tests/http.rs b/crates/core/tests/http.rs index f11a01a..48aa368 100644 --- a/crates/core/tests/http.rs +++ b/crates/core/tests/http.rs @@ -498,13 +498,13 @@ async fn a_placeholder_name_gives_way_to_the_servers() { let add = |path: &str, name: &str| b.store.add_task(Task { url: b.server.url(path), name: name.into(), folder: b.folder(), ..Task::default() }).unwrap(); let named = add("/data/4/300k/game.zip?disp=attachment", "output.bin"); let moved = add("/redirect/1?to=/data/5/300k/other.iso", "download"); - let real = add("/data/6/300k/game2.zip?disp=attachment", "mine.bin"); + let real = add("/data/6/300k/game2.zip?disp=attachment", "mine.7z"); for id in [named, moved, real] { b.run(id).await.unwrap(); } let name = |id| b.store.task(id).unwrap().name; assert_eq!(name(named), "game.zip"); assert_eq!(name(moved), "other.iso"); - assert_eq!(name(real), "mine.bin", "a name without a placeholder stays"); + assert_eq!(name(real), "mine.7z", "a name without a placeholder stays"); assert!(b.folder().join("game.zip").exists() && !b.folder().join("output.bin").exists()); } From 6f06b107922077d84c61def265698f2e83ca31a3 Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 12:44:21 -0600 Subject: [PATCH 04/31] S046: readable speed, one-bar setting, snail button and 8 kB cap --- crates/app/src/app.rs | 8 ++ crates/app/src/ui/mod.rs | 1 + crates/app/src/ui/odometer.rs | 64 +++++++++++++++ crates/app/src/ui/snail.rs | 108 ++++++++++++++++++++++++++ crates/app/src/ui/wave.rs | 11 +++ crates/app/src/views/list/row.rs | 2 +- crates/app/src/views/main.rs | 5 +- crates/app/src/views/settings/rows.rs | 10 ++- crates/app/src/views/target.rs | 7 +- crates/app/tests/shots.rs | 2 + crates/core/lang/en.json | 5 ++ crates/core/src/settings.rs | 37 ++++++++- crates/core/tests/limit.rs | 2 +- 13 files changed, 254 insertions(+), 8 deletions(-) create mode 100644 crates/app/src/ui/snail.rs diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index 3d4388f..fd280d3 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -69,6 +69,7 @@ impl App { let theme = Theme::build(&settings, desktop); theme.apply(ctx, settings.motion); keys::set(&settings); + crate::ui::wave::set_one_bar(settings.bar == medlar_core::settings::BarStyle::One); let watch = Watch::start(sources.clone(), ctx); App { themed: settings.clone(), @@ -110,6 +111,7 @@ impl App { let now = ctx.input(|i| i.time); if self.applied != self.settings { keys::set(&self.settings); + crate::ui::wave::set_one_bar(self.settings.bar == medlar_core::settings::BarStyle::One); self.main.bridge.apply(&self.settings); if let Some(paths) = self.paths.as_ref().filter(|_| self.applied.language != self.settings.language) { strings::set(Catalogue::load(&paths.languages(), &self.settings.language).0); @@ -203,6 +205,12 @@ impl App { } None => { self.main.show(ui, &t, &self.settings); + let window = ui.ctx().content_rect(); + let at = egui::pos2(window.right() - crate::tokens::space::L, window.bottom() - self.main.floor() - crate::tokens::space::L); + let on = self.settings.mode == medlar_core::settings::Mode::Snail; + if crate::ui::snail::button(ui.ctx(), &t, at, on, &keys::label(Action::Snail)) { + self.run(ui, Action::Snail); + } if let Some(change) = self.main.change.take() { change.apply(&mut self.settings); } diff --git a/crates/app/src/ui/mod.rs b/crates/app/src/ui/mod.rs index 9507059..6ca1210 100644 --- a/crates/app/src/ui/mod.rs +++ b/crates/app/src/ui/mod.rs @@ -11,5 +11,6 @@ pub mod widgets; pub mod graph; pub mod odometer; pub mod parts; +pub mod snail; pub mod shape; pub mod wave; diff --git a/crates/app/src/ui/odometer.rs b/crates/app/src/ui/odometer.rs index 4a63b4c..bdd59e3 100644 --- a/crates/app/src/ui/odometer.rs +++ b/crates/app/src/ui/odometer.rs @@ -96,9 +96,50 @@ pub fn odometer(ui: &Ui, id: Id, pos: Pos2, words: &str, font: FontId, color: Co Rect::from_min_max(pos2(pos.x, top), pos2(x, top + height)) } +/// A live speed that can be read: the average of the last `WINDOW` seconds, kept on show for `HOLD` seconds before it +/// changes, and not changed at all for what its digits don't show. Big jumps (start, stop, pause) pass at once. +#[derive(Clone, Default)] +pub struct Calm { + seen: std::collections::VecDeque<(f64, f64)>, + shown: f64, + since: f64, +} + +pub const HOLD: f64 = 1.0; +const WINDOW: f64 = 2.0; + +impl Calm { + /// `raw` is the speed measured at `now` (seconds); gives back what to show. + pub fn feed(&mut self, now: f64, raw: f64) -> f64 { + let raw = if raw.is_finite() { raw.max(0.0) } else { 0.0 }; + self.seen.push_back((now, raw)); + while self.seen.front().is_some_and(|(at, _)| *at < now - WINDOW) { + self.seen.pop_front(); + } + let jump = raw == 0.0 || self.shown == 0.0 || raw > self.shown * 3.0 || raw < self.shown / 3.0; + if jump { + self.seen.clear(); + self.seen.push_back((now, raw)); + (self.shown, self.since) = (raw, now); + } else if now - self.since >= HOLD { + let mean = self.seen.iter().map(|(_, v)| v).sum::() / self.seen.len() as f64; + if scaled(mean) != scaled(self.shown) { + (self.shown, self.since) = (mean, now); + } + } + self.shown + } +} + /// The big speed number with its unit. Returns where it ended up. pub fn speed(ui: &Ui, t: &Theme, id: Id, pos: Pos2, bytes_per_second: f64) -> Rect { use crate::{fonts, tokens::{space, text}}; + let now = ui.input(|i| i.time); + let bytes_per_second = ui.data_mut(|d| d.get_temp_mut_or_default::(id.with("calm")).feed(now, bytes_per_second)); + if bytes_per_second > 0.0 { + // The hold ends by itself; idle draws nothing. + ui.ctx().request_repaint_after_secs(HOLD as f32); + } let all = rate(bytes_per_second); let number = scaled(bytes_per_second).0; let (before, after) = all.split_once(&number).unwrap_or(("", &all)); @@ -117,6 +158,29 @@ mod tests { assert_eq!([f64::NAN, -4.0, 2_000.0].map(rate), ["0 B/s", "0 B/s", "2.0 kB/s"]); } + #[test] + fn a_noisy_speed_changes_at_most_once_per_hold() { + let mut calm = Calm::default(); + let mut seed = 12345_u64; + let (mut last, mut changes) = (f64::NAN, 0); + // 20 seconds at 20 samples a second around 480 kB/s, plus or minus a third. + for i in 0..400 { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let noise = ((seed >> 33) % 1000) as f64 / 1000.0 - 0.5; + let shown = calm.feed(i as f64 * 0.05, 480_000.0 * (1.0 + noise * 0.66)); + if shown != last { + changes += 1; + last = shown; + } + } + assert!(changes <= 21, "{changes} changes in 20 s"); + let mut calm = Calm::default(); + assert_eq!([calm.feed(0.0, 0.0), calm.feed(0.1, 500_000.0), calm.feed(0.2, 0.0)], [0.0, 500_000.0, 0.0], "start and stop pass at once"); + let mut calm = Calm::default(); + calm.feed(0.0, 488_300.0); + assert_eq!(calm.feed(2.0, 488_340.0), 488_300.0, "below the shown precision nothing rolls"); + } + #[test] fn digits_take_the_short_way() { assert_eq!([nearest(9.0, 0.0), nearest(0.0, 9.0), nearest(12.0, 1.0), nearest(3.0, 5.0)], [10.0, -1.0, 11.0, 5.0]); diff --git a/crates/app/src/ui/snail.rs b/crates/app/src/ui/snail.rs new file mode 100644 index 0000000..f9e965d --- /dev/null +++ b/crates/app/src/ui/snail.rs @@ -0,0 +1,108 @@ +//! The snail button at the window's corner: snail mode on or off, with a small snail drawn as a vector shape. + +use super::widgets::{cr, feel, tip}; +use crate::motion; +use crate::theme::{Theme, alpha}; +use crate::tokens::{self, elevation}; +use eframe::egui::accesskit::Role; +use eframe::egui::{Area, Color32, Context, Id, Order, Painter, Pos2, Rect, Sense, Shape, Stroke, WidgetInfo, vec2}; +use medlar_core::settings::Motion; +use medlar_core::tr; + +/// Frames per second of the crawl: it is cheap, and it is the only loop that runs while nothing else moves. +const FPS: f32 = 15.0; + +/// A round button with its bottom right corner at `at`. True when it was clicked. +#[allow(deprecated)] +pub fn button(ctx: &Context, t: &Theme, at: Pos2, on: bool, keys: &str) -> bool { + let side = tokens::size::LARGE; + let rect = Rect::from_min_max(at - vec2(side, side), at); + let id = Id::new("snail button"); + let name = tr!("snail.button"); + let mut clicked = false; + Area::new(id).order(Order::Middle).fixed_pos(rect.min).constrain(false).fade_in(false).sense(Sense::hover()).show(ctx, |ui| { + let r = ui.interact(rect, id.with("hit"), Sense::click()); + r.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, on, &name)); + let f = feel(&r, true); + let (fill, ink) = if on { (t.secondary_container, t.on_secondary_container) } else { (t.high, t.on_variant) }; + let p = ui.painter(); + p.add(elevation::floating(t.dark).as_shape(rect, cr(side / 2.0))); + p.circle_filled(rect.center(), side / 2.0 - f.press.max(0.0) * 2.0, fill); + if f.tint > 0.0 { + p.circle_filled(rect.center(), side / 2.0, alpha(ink, f.tint)); + } + // Reduced motion is a small sway, off is still; nothing moves while it is off. + let amount = match motion::level() { + Motion::Off => 0.0, + Motion::Reduced => 0.35, + _ => 1.0, + }; + let phase = if on && amount > 0.0 { + ctx.request_repaint_after_secs(1.0 / FPS); + ctx.input(|i| i.time) as f32 + } else { + 0.0 + }; + draw(p, rect.center(), side * 0.5, ink, on, phase, amount); + tip(&r, t, &name, keys); + clicked = r.clicked(); + }); + clicked +} + +/// The snail in a square of `size`, facing right. `phase` in seconds moves the stretch of its body and the sway of its shell. +pub fn draw(p: &Painter, center: Pos2, size: f32, ink: Color32, filled: bool, phase: f32, amount: f32) { + let u = size / 2.0; + let wave = (phase * 2.4).sin() * amount; + let stroke = Stroke::new((size / 14.0).max(1.5), ink); + // The foot stretches and shrinks a little. + let tail = center + vec2(-0.9 * u - 0.08 * u * wave, 0.62 * u); + let neck = center + vec2(0.55 * u + 0.1 * u * wave, 0.62 * u); + p.line_segment([tail, neck], stroke); + // The head and its feelers. + let head = neck + vec2(0.1 * u, -0.28 * u); + p.line_segment([neck, head], stroke); + let sway = 0.12 * u * wave; + for dx in [0.0, 0.3] { + let base = head + vec2(0.04 * u + dx * u * 0.5, -0.04 * u); + p.line_segment([base, base + vec2(0.1 * u + sway, -0.3 * u)], Stroke::new(stroke.width * 0.7, ink)); + } + p.circle_filled(head, 0.17 * u, ink); + // The shell: a disc (filled when on) with a spiral, turned a little by the sway. + let shell = center + vec2(-0.2 * u, -0.05 * u); + let r = 0.62 * u; + if filled { + p.circle_filled(shell, r, alpha(ink, 0.28)); + } + p.circle_stroke(shell, r, stroke); + let turn = 0.15 * wave; + let points: Vec = (0..=36) + .map(|i| { + let a = i as f32 / 36.0 * 3.2 * std::f32::consts::PI; + let radius = r * 0.9 * (a / (3.2 * std::f32::consts::PI)); + shell + vec2((a + turn).cos(), (a + turn).sin()) * radius + }) + .collect(); + p.add(Shape::line(points, Stroke::new(stroke.width * 0.8, ink))); +} + +#[cfg(test)] +mod tests { + use super::*; + use eframe::egui::{RawInput, ViewportId}; + + #[test] + fn off_asks_for_no_frames_and_on_asks_for_a_slow_loop() { + let t = Theme::build(&medlar_core::settings::Settings::default(), crate::desktop::Desktop::default()); + use eframe::egui::pos2;; + for (on, repaints) in [(false, false), (true, true)] { + let ctx = Context::default(); + let mut out = ctx.run_ui(RawInput::default(), |ui| { + button(ui.ctx(), &t, pos2(300.0, 300.0), on, "Ctrl+Shift+S"); + }); + out.textures_delta.clear(); + let after = out.viewport_output[&ViewportId::ROOT].repaint_delay; + assert_eq!(after < std::time::Duration::from_secs(1), repaints, "on={on}: {after:?}"); + } + } +} diff --git a/crates/app/src/ui/wave.rs b/crates/app/src/ui/wave.rs index d7f8962..636766d 100644 --- a/crates/app/src/ui/wave.rs +++ b/crates/app/src/ui/wave.rs @@ -293,6 +293,17 @@ impl Ink { } } +static ONE_BAR: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Follows the setting: one continuous bar, or one per part. +pub fn set_one_bar(one: bool) { + ONE_BAR.store(one, std::sync::atomic::Ordering::Relaxed); +} + +pub fn one_bar() -> bool { + ONE_BAR.load(std::sync::atomic::Ordering::Relaxed) +} + /// What a bar shows. `parts` are the file's ranges in order; bytes between them count as missing. #[derive(Clone, Copy, Default)] pub struct Bar<'a> { diff --git a/crates/app/src/views/list/row.rs b/crates/app/src/views/list/row.rs index 6e37739..020b625 100644 --- a/crates/app/src/views/list/row.rs +++ b/crates/app/src/views/list/row.rs @@ -257,7 +257,7 @@ fn state_ink(t: &Theme, v: &TaskView) -> Color32 { fn bar(ui: &Ui, t: &Theme, rect: Rect, v: &TaskView) { let parts: Vec = v.parts.iter().map(|p| Part { start: p.start, end: p.end, done: p.done }).collect(); let whole = [Part { start: 0, end: v.size, done: v.downloaded }]; - let parts = if parts.is_empty() { &whole[..] } else { &parts[..] }; + let parts = if parts.is_empty() || wave::one_bar() { &whole[..] } else { &parts[..] }; let b = Bar { look: Look::from(v.state()), size: v.size, parts, speed: v.speed, checked: v.checked }; let rect = Rect::from_center_size(rect.center(), vec2(rect.width(), wave::HEIGHT)); wave::bar(ui, t, id(v.id()).with("bar"), rect, &b); diff --git a/crates/app/src/views/main.rs b/crates/app/src/views/main.rs index d7ba18a..a74506d 100644 --- a/crates/app/src/views/main.rs +++ b/crates/app/src/views/main.rs @@ -278,7 +278,7 @@ impl Main { } /// How much at the bottom the toolbar takes. - fn floor(&self) -> f32 { + pub fn floor(&self) -> f32 { if self.list.selected.is_empty() { 0.0 } else { bar::TOOLBAR - space::L } } @@ -367,7 +367,8 @@ impl Main { } fn list_in(&mut self, ui: &mut Ui, t: &Theme, rest: Rect, lists: &Arc, orders: &mut Vec) { - let below = if self.list.selected.is_empty() { space::L } else { bar::TOOLBAR }; + // Room for the snail button that floats at the corner. + let below = if self.list.selected.is_empty() { size::LARGE + space::XL } else { bar::TOOLBAR + size::LARGE }; // The scroll bar stands in the margin, so rows end where everything else does. orders.extend(self.list.show(ui, t, rest.with_max_x(rest.right() + space::M), lists, below)); orders.extend(bar::selected(ui, t, rest, &mut self.list)); diff --git a/crates/app/src/views/settings/rows.rs b/crates/app/src/views/settings/rows.rs index 04fbc33..02010de 100644 --- a/crates/app/src/views/settings/rows.rs +++ b/crates/app/src/views/settings/rows.rs @@ -5,7 +5,7 @@ use super::{Cx, View, backup, look, network, sites}; use crate::keys::{self, Action}; use crate::ui::dialog; use eframe::egui::Ui; -use medlar_core::settings::{Appearance, Contrast, Mode, Motion, Scheme, Settings}; +use medlar_core::settings::{Appearance, BarStyle, Contrast, Mode, Motion, Scheme, Settings}; use medlar_core::strings::{self, Catalogue}; use medlar_core::tr; use std::ops::RangeInclusive; @@ -169,6 +169,7 @@ const MODES: [Mode; 4] = [Mode::Low, Mode::Medium, Mode::High, Mode::Snail]; const APPEARANCES: [Appearance; 4] = [Appearance::Auto, Appearance::Light, Appearance::Dark, Appearance::Amoled]; const SCHEMES: [Scheme; 4] = [Scheme::Tonal, Scheme::Vibrant, Scheme::Expressive, Scheme::Mono]; const CONTRASTS: [Contrast; 3] = [Contrast::Standard, Contrast::Medium, Contrast::High]; +const BARS: [BarStyle; 2] = [BarStyle::Parts, BarStyle::One]; const MOTIONS: [Motion; 4] = [Motion::Off, Motion::Reduced, Motion::Normal, Motion::Expressive]; fn at(all: &[T], one: T) -> usize { @@ -261,6 +262,13 @@ static ROWS: &[Row] = &[ &["motion"], Kind::Choice { options: &["off", "reduced", "normal", "expressive"], get: |s| at(&MOTIONS, s.motion), set: |s, i| s.motion = MOTIONS[i] }, ), + row( + Page::Look, + "motion", + "bar", + &["progress", "bar", "parts"], + Kind::Choice { options: &["parts", "one"], get: |s| at(&BARS, s.bar), set: |s, i| s.bar = BARS[i] }, + ), row( Page::Look, "language", diff --git a/crates/app/src/views/target.rs b/crates/app/src/views/target.rs index 9ac2613..8814291 100644 --- a/crates/app/src/views/target.rs +++ b/crates/app/src/views/target.rs @@ -26,6 +26,7 @@ const OPEN: [f32; 2] = [SMALL + space::XXL + space::XL + space::XS, SMALL + 3.0 #[derive(Default)] pub struct Target { menu: bool, + calm: crate::ui::odometer::Calm, } enum Do { @@ -58,6 +59,10 @@ impl Target { let mut act = None; let mut dropped = vec![]; let menu = &mut self.menu; + let calm = self.calm.feed(ctx.input(|i| i.time), speed); + if calm > 0.0 { + ctx.request_repaint_after_secs(crate::ui::odometer::HOLD as f32); + } ctx.show_viewport_immediate(ViewportId::from_hash_of("drop target"), builder, |ui, class| { if class != ViewportClass::Immediate && class != ViewportClass::Root { // Embedded in the main window: nothing to show on its own. @@ -70,7 +75,7 @@ impl Target { let look = if speed > 0.0 { Look::Running } else { Look::Waiting }; wave::ring(ui, t, salt("target ring"), ring, look, None, speed); let p = ui.painter(); - p.text(pos2(full.center().x, ring.bottom() + space::S), Align2::CENTER_TOP, rate(speed), fonts::med(text::LABEL), t.on_surface); + p.text(pos2(full.center().x, ring.bottom() + space::S), Align2::CENTER_TOP, rate(calm), fonts::med(text::LABEL), t.on_surface); let r = ui.interact(ring, salt("target hit"), Sense::click_and_drag()); if r.drag_started() { ui.ctx().send_viewport_cmd(ViewportCommand::StartDrag); diff --git a/crates/app/tests/shots.rs b/crates/app/tests/shots.rs index a56e0f6..9b098dc 100644 --- a/crates/app/tests/shots.rs +++ b/crates/app/tests/shots.rs @@ -44,6 +44,8 @@ const SCENES: &[Scene] = &[("window", App::show), ("tokens", |app, ui| app.frame ("fab", |app, ui| over(app, ui, "fab")), ("toasts", |app, ui| over(app, ui, "toasts")), ("main", |app, ui| main_view(app, ui, |_| {})), + ("main-snail", |app, ui| main_view(app, ui, |app| app.settings.mode = medlar_core::settings::Mode::Snail)), + ("main-onebar", |app, ui| main_view(app, ui, |app| app.settings.bar = medlar_core::settings::BarStyle::One)), ("main-cards", |app, ui| main_view(app, ui, |app| app.main.list.form = Form::Cards)), ("main-selected", |app, ui| main_view(app, ui, |app| app.main.list.selected = [2, 4, 9].into())), ("main-filtered", |app, ui| main_view(app, ui, |app| app.main.list.query.filter.kind = Some(medlar_app::ui::shape::Kind::Archive))), diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index 8f317f2..db29f54 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -604,6 +604,11 @@ "set.motion.reduced": "Reduced", "set.motion.normal": "Normal", "set.motion.expressive": "Full", + "set.bar": "Progress bar", + "set.bar.why": "One bar for the whole file, or one for each part that is downloading.", + "set.bar.parts": "One per part", + "set.bar.one": "One bar", + "snail.button": "Snail mode", "set.language": "Language", "set.language.why": "More appear when their files are in Medlar's languages folder.", "set.language.auto": "Same as the desktop", diff --git a/crates/core/src/settings.rs b/crates/core/src/settings.rs index e4a7a3b..f7d5b93 100644 --- a/crates/core/src/settings.rs +++ b/crates/core/src/settings.rs @@ -74,6 +74,7 @@ pub struct Settings { pub scheme: Scheme, pub contrast: Contrast, pub motion: Motion, + pub bar: BarStyle, /// The user's own, by action; empty for none. What isn't here has its usual one. pub shortcuts: BTreeMap, /// Keys of newer versions. @@ -129,6 +130,22 @@ pub enum Contrast { High, } +/// Snail mode: 8 kB/s (the app counts in thousands). +pub const SNAIL_SPEED: u64 = 8000; +/// What snail mode was before 0.1.1; a stored value that is still this one moves to the new one. +const OLD_SNAIL_SPEED: u64 = 32 * 1024; + +/// How the wavy progress bar shows a download. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum BarStyle { + /// One bar per part. + #[default] + Parts, + /// One continuous bar for the whole file. + One, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Motion { @@ -160,7 +177,7 @@ impl Default for Settings { low: Limits::new(256 * 1024, 2, 8, 4, 4), medium: Limits::new(1024 * 1024, 3, 24, 8, 8), high: Limits::default(), - snail: Limits::new(32 * 1024, 1, 1, 1, 1), + snail: Limits::new(SNAIL_SPEED, 1, 1, 1, 1), mode_grid: vec![], tries: 10, auto_resume: true, @@ -192,6 +209,7 @@ impl Default for Settings { scheme: Scheme::Tonal, contrast: Contrast::Standard, motion: Motion::Expressive, + bar: BarStyle::Parts, shortcuts: BTreeMap::new(), unknown: Map::new(), } @@ -248,7 +266,10 @@ impl Settings { } } }); - let settings = serde_json::from_value(Value::Object(map)).expect("every key was checked"); + let mut settings: Settings = serde_json::from_value(Value::Object(map)).expect("every key was checked"); + if settings.snail.speed == OLD_SNAIL_SPEED { + settings.snail.speed = SNAIL_SPEED; + } if keys.is_empty() { return (settings, None); } @@ -362,6 +383,18 @@ mod tests { (dir, path) } + #[test] + fn snail_moves_to_8_kb_unless_changed() { + assert_eq!(Settings::default().snail.speed, 8000); + let (_d, path) = file(r#"{"snail": {"speed": 32768, "max_active": 1, "max_connections": 1, "parts_per_download": 1, "connections_per_host": 1}}"#); + assert_eq!(Settings::load(&path).0.snail.speed, 8000); + let (_d, path) = file(r#"{"snail": {"speed": 20000, "max_active": 1, "max_connections": 1, "parts_per_download": 1, "connections_per_host": 1}, "bar": "one"}"#); + let s = Settings::load(&path).0; + assert_eq!((s.snail.speed, s.bar), (20000, BarStyle::One)); + let (_d, path) = file("{}"); + assert_eq!(Settings::load(&path).0.bar, BarStyle::Parts); + } + #[test] fn missing_file_gives_defaults() { assert_eq!(Settings::load(Path::new("/nonexistent/settings.json")), (Settings::default(), None)); diff --git a/crates/core/tests/limit.rs b/crates/core/tests/limit.rs index 8d911e0..770545c 100644 --- a/crates/core/tests/limit.rs +++ b/crates/core/tests/limit.rs @@ -373,7 +373,7 @@ async fn slow_is_even_and_stays_connected() { async fn modes_change_live_without_reconnecting() { let _alone = ALONE.lock().await; let mut settings = Settings::default(); - for (mode, speed) in [(Mode::Low, 100 * KB), (Mode::Medium, MB), (Mode::High, 3 * MB), (Mode::Snail, 32 * KB)] { + for (mode, speed) in [(Mode::Low, 100 * KB), (Mode::Medium, MB), (Mode::High, 3 * MB), (Mode::Snail, 8 * KB)] { *settings.limits_of(mode) = Limits { speed, parts_per_download: 2, ..LIMITS }; } let b = Bench::new(settings.limits()).await; From fdbb007f53c4989b45f7fc3def06e130b44c2b56 Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 12:46:13 -0600 Subject: [PATCH 05/31] S046: snail test --- crates/app/src/ui/snail.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/app/src/ui/snail.rs b/crates/app/src/ui/snail.rs index f9e965d..ded400c 100644 --- a/crates/app/src/ui/snail.rs +++ b/crates/app/src/ui/snail.rs @@ -97,10 +97,16 @@ mod tests { use eframe::egui::pos2;; for (on, repaints) in [(false, false), (true, true)] { let ctx = Context::default(); - let mut out = ctx.run_ui(RawInput::default(), |ui| { - button(ui.ctx(), &t, pos2(300.0, 300.0), on, "Ctrl+Shift+S"); - }); - out.textures_delta.clear(); + let mut out = None; + // The first frames settle the layout; the last one tells. + for _ in 0..4 { + let mut o = ctx.run_ui(RawInput::default(), |ui| { + button(ui.ctx(), &t, pos2(300.0, 300.0), on, "Ctrl+Shift+S"); + }); + o.textures_delta.clear(); + out = Some(o); + } + let out = out.unwrap(); let after = out.viewport_output[&ViewportId::ROOT].repaint_delay; assert_eq!(after < std::time::Duration::from_secs(1), repaints, "on={on}: {after:?}"); } From 7831445a6cb1f317cfcf160f6f54c9c430fa5da4 Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 12:51:01 -0600 Subject: [PATCH 06/31] S047: plan for close to tray on Wayland Co-Authored-By: Claude Opus 5.5 --- .../S047-close-to-tray-wayland.md | 30 +++++++++++++++++++ Plans/INDEX.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 Plans/10 Distribution/S047-close-to-tray-wayland.md diff --git a/Plans/10 Distribution/S047-close-to-tray-wayland.md b/Plans/10 Distribution/S047-close-to-tray-wayland.md new file mode 100644 index 0000000..d3ed2ac --- /dev/null +++ b/Plans/10 Distribution/S047-close-to-tray-wayland.md @@ -0,0 +1,30 @@ +# S047 — Close to tray that works on Wayland + +> Category 10 Distribution · Model: Opus (ownership refactor of the app's lifetime) · Effort: medium · Depends on: S046 · Phase: test · Human: 🧑 yes before release +> Files touched: crates/app/src/{main,lib,app,shell,tray,instance}.rs, crates/app/src/views/incoming.rs, docs/tests/S047-close-to-tray.md, docs/releases/0.1.1.md + +## Goal +The user closes the window with niri's close (Win+Q) and nothing happens. Cause (`app.rs` `shell()`): on close Medlar sends `CancelClose` then `Visible(false)`, but winit cannot hide a window on Wayland, so the window just stays. Without a tray host the close works; with one it is swallowed. + +Wanted: closing hides Medlar to the tray (downloads, port, tray keep going) when the tray is on and a host exists; otherwise it quits cleanly. Show from the tray, a second start, or a browser hand-off brings a window back. + +## Approach (check against eframe 0.37 docs before coding) +eframe with `NativeOptions::run_and_return = true` returns from `run_native` when the window closes and reuses its thread-local event loop on the next `run_native` call (winit `run_app_on_demand`). So: +- Move what must outlive a window out of `App` into a `Core`/`Session` owned by `main`: engine/manager bridge, connector `Inbox` source, tray/shell, notifications, launcher, instance socket, settings store. The `App` borrows or holds an `Arc` to it. +- On close with tray: let the close happen (no `CancelClose`); `run_native` returns; `main` waits on the tray/instance/connector for "show" (or "quit"), then calls `run_native` again with the same session. Window size and position come back from `window.ron`. +- Without a tray host, or tray off: close quits as today (pause and save, then exit). +- X11: same path (no special `Visible(false)` case left), so one behaviour everywhere. +- `--minimised` at start: start without a window when a tray host exists (wait for "show"), else open normally. +- Arrivals while hidden (S046 raise): reopen the window, then the Add dialog. +If `run_and_return` cannot reopen on this eframe/winit, stop and report with the error; do not build a second process design without asking. + +## Steps +- [ ] Read eframe 0.37 `run_and_return` / `run_native` docs and source in ~/.cargo/registry; confirm reopen works with a 20-line spike in a test or example +- [ ] Session refactor: long-lived parts out of `App`; nothing else changes behaviour +- [ ] Close/show/quit loop in `main` as above; tray Show and Quit, second instance, connector arrival, `--minimised` +- [ ] Tests: unit for the decide-on-close logic (tray on/off, host yes/no); hidden nested niri run with a fake StatusNotifierWatcher (bus.rs from S043) on a spare port and throwaway home: send close (niri msg action close-window), process stays, downloads keep going (testserver, throttled), port answers; tray Show reopens; POST to the port reopens with the Add window; Quit ends with tasks saved; without the fake tray, close quits +- [ ] Full workspace suite once, release build, smoke as S046; add to docs/releases/0.1.1.md; rebuild packages via tools/package.sh (0.1.1), nothing into releases/ +- [ ] Test file with Results, PROGRESS, tick INDEX, commit `S047: …`, push + +## Pitfalls +The user's Medlar 0.1.0 is running on 17616: never stop it; spare port, throwaway home. Never weaken a test. Idle (hidden) draws no frames and uses ~0 CPU. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index ad754fd..029f97b 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -67,6 +67,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H - [x] [S045](10%20Distribution/S045-installer-arch.md) installer.sh and Arch package - [ ] [S046](10%20Distribution/S046-fixes-0.1.1.md) 0.1.1: names from the server, raise on arrival, copy in fields +- [ ] [S047](10%20Distribution/S047-close-to-tray-wayland.md) Close to tray that works on Wayland ## Later (after version 1; not run by /orchestrate) From 7d0587e424f6038194f4274e3dbf6afbc3019292 Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 13:05:38 -0600 Subject: [PATCH 07/31] S046: version 0.1.1, settings row key fix, release notes, test file Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 8 +++--- Cargo.toml | 2 +- README.md | 16 +++++------ crates/app/src/views/settings/rows.rs | 2 +- docs/releases/0.1.1.md | 28 +++++++++++++++++++ docs/tests/S046-fixes-0.1.1.md | 39 +++++++++++++++++++++++++++ packaging/arch/.SRCINFO | 4 +-- packaging/arch/PKGBUILD | 4 +-- 8 files changed, 85 insertions(+), 18 deletions(-) create mode 100644 docs/releases/0.1.1.md create mode 100644 docs/tests/S046-fixes-0.1.1.md diff --git a/Cargo.lock b/Cargo.lock index 21357a1..dd8684d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2787,7 +2787,7 @@ checksum = "7ebb8d8732c6a6df3d8f032a82911cfc747e00efb95cc46e8d0acd5b5b88570c" [[package]] name = "medlar" -version = "0.1.0" +version = "0.1.1" dependencies = [ "arboard", "chrono", @@ -2812,14 +2812,14 @@ dependencies = [ [[package]] name = "medlar-cli" -version = "0.1.0" +version = "0.1.1" dependencies = [ "medlar-core", ] [[package]] name = "medlar-core" -version = "0.1.0" +version = "0.1.1" dependencies = [ "aes", "arc-swap", @@ -2863,7 +2863,7 @@ dependencies = [ [[package]] name = "medlar-testserver" -version = "0.1.0" +version = "0.1.1" dependencies = [ "md-5", "rcgen", diff --git a/Cargo.toml b/Cargo.toml index bc91c09..f438da7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ members = ["crates/*"] resolver = "3" [workspace.package] -version = "0.1.0" +version = "0.1.1" edition = "2024" license = "MIT" diff --git a/README.md b/README.md index 7974928..672c6ae 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Medlar A download manager for Linux, written in Rust with egui. Downloads are split into dynamic parts and can be paused, resumed -and continued from a new link. The interface follows Material You (M3 Expressive). Version 0.1.0 is the first release. +and continued from a new link. The interface follows Material You (M3 Expressive). Version 0.1.1 fixes names, copy and speed, and adds a snail button. ![Main window after a finished download](docs/img/main.png) ![Add dialog](docs/img/add.png) @@ -23,21 +23,21 @@ The full list and its state: [docs/FEATURES.md](docs/FEATURES.md) and [docs/FEAT Needs a Linux x86_64 desktop with Wayland or X11, and glibc 2.44 or newer (see "Requirements"). -**AppImage:** `chmod +x Medlar-0.1.0-x86_64.AppImage && ./Medlar-0.1.0-x86_64.AppImage` +**AppImage:** `chmod +x Medlar-0.1.1-x86_64.AppImage && ./Medlar-0.1.1-x86_64.AppImage` -**tar.gz:** `tar xzf Medlar-0.1.0-Linux-x86_64.tar.gz && cd medlar-0.1.0 && ./install.sh` +**tar.gz:** `tar xzf Medlar-0.1.1-Linux-x86_64.tar.gz && cd medlar-0.1.1 && ./install.sh` installs into `~/.local` (binary, desktop file, icon; no root). `./uninstall.sh` removes it; `./uninstall.sh --purge` also removes settings and the download list (downloaded files stay). -**installer.sh:** `./installer.sh Medlar-0.1.0-Linux-x86_64.tar.gz` (or with no file: it uses a tar.gz or AppImage beside it). +**installer.sh:** `./installer.sh Medlar-0.1.1-Linux-x86_64.tar.gz` (or with no file: it uses a tar.gz or AppImage beside it). `--user` (default, `~/.local`) or `--system` (`/usr/local`, sudo only for the copy); `--prefix DIR` picks another folder. Checks `SHA256SUMS-*` beside the file and refuses glibc older than 2.44. Sets the `medlar:` link handler (user install). `./installer.sh --uninstall [--purge]` removes it again (`--system` for a system install). -**Arch Linux:** `sudo pacman -U Medlar-0.1.0-arch-x86_64.pkg.tar.zst` (package `medlar-bin`). To build it yourself: -`cd packaging/arch && makepkg -si` (downloads the tar.gz) or `MEDLAR_TARBALL=file:///path/to/Medlar-0.1.0-Linux-x86_64.tar.gz makepkg -si`. +**Arch Linux:** `sudo pacman -U Medlar-0.1.1-arch-x86_64.pkg.tar.zst` (package `medlar-bin`). To build it yourself: +`cd packaging/arch && makepkg -si` (downloads the tar.gz) or `MEDLAR_TARBALL=file:///path/to/Medlar-0.1.1-Linux-x86_64.tar.gz makepkg -si`. -Check the download against `SHA256SUMS-0.1.0`: `sha256sum -c SHA256SUMS-0.1.0`. +Check the download against `SHA256SUMS-0.1.1`: `sha256sum -c SHA256SUMS-0.1.1`. **Portable mode:** put a file called `portable` beside `bin/medlar` (tar.gz) or beside the `.AppImage`. Everything is then kept in a `medlar-data/` folder next to it. `MEDLAR_HOME=` sets the folder directly and wins over both. @@ -63,7 +63,7 @@ Requests with a web `Origin` or a foreign `Host` are refused, and no CORS header ## Limits and known gaps -Honest state of 0.1.0. The engine is tested hard (unit, integration, fuzz, a 20-minute fault soak with 606 files and no +Honest state of 0.1.1. The engine is tested hard (unit, integration, fuzz, a 20-minute fault soak with 606 files and no corrupt one). The interface is tested less. - The hidden-window user journeys (pause, restart, expired link, schedule) were tested at engine level only, not by diff --git a/crates/app/src/views/settings/rows.rs b/crates/app/src/views/settings/rows.rs index 02010de..40bd4d5 100644 --- a/crates/app/src/views/settings/rows.rs +++ b/crates/app/src/views/settings/rows.rs @@ -266,7 +266,7 @@ static ROWS: &[Row] = &[ Page::Look, "motion", "bar", - &["progress", "bar", "parts"], + &["bar"], Kind::Choice { options: &["parts", "one"], get: |s| at(&BARS, s.bar), set: |s, i| s.bar = BARS[i] }, ), row( diff --git a/docs/releases/0.1.1.md b/docs/releases/0.1.1.md new file mode 100644 index 0000000..56a935b --- /dev/null +++ b/docs/releases/0.1.1.md @@ -0,0 +1,28 @@ +# Medlar 0.1.1 + +Fixes and small changes after 0.1.0. Linux x86_64, glibc 2.44 or newer. + +## Files +- `Medlar-0.1.1-x86_64.AppImage` +- `Medlar-0.1.1-Linux-x86_64.tar.gz` (install.sh and uninstall.sh for your home folder) +- `Medlar-0.1.1-arch-x86_64.pkg.tar.zst` (package `medlar-bin`) +- `SHA256SUMS-0.1.1` + +## What changed +- **Names from the server.** A download sent by the browser extension with a placeholder name (`output.bin`, `download`, + no extension) now takes the real name from the server (Content-Disposition, redirect or URL). A name you typed stays. +- **Window raised on arrival.** A link from the browser or the command line shows the window, un-minimises it and asks + for attention (Wayland does not allow stealing focus). +- **Copy and select all in text fields.** Ctrl+C, Ctrl+A, Ctrl+V, Ctrl+X and Ctrl+Z work in a focused field and no + longer trigger app shortcuts. +- **Readable speed.** The speed shown is a 2 second average and changes at most once per second; big jumps show at once. + The drop target uses the same value. The tray tooltip is not smoothed. +- **Progress bar setting.** Settings, Look: "One bar" or "One per part" (default, as before). The Parts tab map stays. +- **Snail mode.** The cap is now 8 kB/s (was 32 kB/s). A saved 32 kB/s moves to 8 kB/s; a value you changed is kept. + A round snail button at the bottom right of the main window turns it on and off; its tooltip shows the shortcut. + +## Known gaps +- Needs glibc 2.44 or newer; not tested on other systems. +- The snail button can cover the right edge of the last row in a very small window (480x360). +- The snail crawl motion and the raise on a real Wayland desktop were not watched live. +- yt-dlp and ffmpeg are not bundled. diff --git a/docs/tests/S046-fixes-0.1.1.md b/docs/tests/S046-fixes-0.1.1.md new file mode 100644 index 0000000..51547bd --- /dev/null +++ b/docs/tests/S046-fixes-0.1.1.md @@ -0,0 +1,39 @@ +# S046 — Fixes 0.1.1: test file + +## Built +- `crates/core/src/http/name.rs` · `prefer(hint, found)`; used by `download.rs::start` and the Add dialog (`views/add`). +- `crates/app/src/views/incoming.rs` · `raise()`: show, un-minimise, focus, ask for attention. +- `crates/app/src/keys.rs` · Ctrl+A/C/V/X/Z stay with a focused text field. +- `crates/app/src/ui/odometer.rs` · `Calm` smoothing (2 s average, 1 s hold); also in `views/target.rs`. +- `crates/core/src/settings.rs` · `BarStyle`, `SNAIL_SPEED` 8000 with migration; Settings, Look row "bar". +- `crates/app/src/ui/snail.rs` · round snail button, drawn in `app.rs` after the main view. + +## Checks +| # | Risk | Do this | Expect | How | Result | +|---|---|---|---|---|---| +| 1 | HIGH | Engine: hint `output.bin`, server sends Content-Disposition `game.zip` | file is `game.zip` | integration `a_placeholder_name_gives_way_to_the_servers` | RESULT1 | +| 2 | HIGH | Same, hint `mine.7z` | file stays `mine.7z` | integration (same test) | RESULT1 | +| 3 | MED | Hint `download`, redirect to `other.iso` | file is `other.iso` | integration (same test) | RESULT1 | +| 4 | MED | `prefer` with placeholders and real names | only a placeholder gives way, never to another placeholder | unit `hints_give_way` | RESULT1 | +| 5 | MED | Hidden run: POST `{url, filename:"output.bin"}` to the connector on a spare port | Add window shows the name `game.zip`-style real name, window is up | by hand (hidden.sh) | RESULT2 | +| 6 | MED | Raise on arrival | commands Visible, Minimized(false), Focus, attention | unit `raising_shows_focuses_and_asks_for_attention` | RESULT1 | +| 7 | HIGH | Focused field, Ctrl+C and Ctrl+A | app shortcuts do not fire | unit `a_focused_field_keeps_copy_and_select_all` | RESULT1 | +| 8 | MED | Noisy speed fed for 10 s | at most one change per hold; jumps pass at once | unit `a_noisy_speed_changes_at_most_once_per_hold` | RESULT1 | +| 9 | LOW | Idle (speed 0) | no repaint requested | unit (odometer) | RESULT1 | +| 10 | MED | Settings file without `bar` | loads with Parts | unit settings tests | RESULT1 | +| 11 | MED | Settings row "bar" | Look page lists it, texts exist, key is real | integration `every_row_has_its_texts_and_real_keys` | RESULT1 | +| 12 | LOW | Shots `main-onebar`, light and dark | one bar per row | screen | RESULT3 | +| 13 | HIGH | Stored snail 32768 / user value 5000 | 8000 / 5000 | unit `snail_moves_to_8_kb_unless_changed` | RESULT1 | +| 14 | HIGH | Snail toggled during a download against testserver | speed held at cap, no connection dropped | integration `modes_change_live_without_reconnecting` | RESULT1 | +| 15 | MED | Snail button off / on | off asks no frames; on asks a slow loop | unit `off_asks_for_no_frames_and_on_asks_for_a_slow_loop` | RESULT1 | +| 16 | LOW | Shots `main-snail`, light/dark, 480x360 and 1080x720 | button bottom right, on/off look | screen | RESULT3 | +| 17 | MED | Hidden run idle with the new build | CPU near 0 % | by hand | RESULT2 | + +## Needs +Testserver on loopback; throwaway home and spare port 17999 for hidden runs. The user's running Medlar (17616) is never touched. + +## Doubts +- Placeholder list is a guess (`output`, `download`, `file`, `index`, `unknown`, `get`, no extension, script types). +- Real Wayland focus on arrival cannot be proven in a nested session. +- At 480x360 the snail button covers the pause icon of the last row. +- Tray tooltip speed is not smoothed. Snail crawl motion not watched live. diff --git a/packaging/arch/.SRCINFO b/packaging/arch/.SRCINFO index 75daef2..c1025b7 100644 --- a/packaging/arch/.SRCINFO +++ b/packaging/arch/.SRCINFO @@ -1,6 +1,6 @@ pkgbase = medlar-bin pkgdesc = Download manager with dynamic parts, queues, video sites and a Material You interface - pkgver = 0.1.0 + pkgver = 0.1.1 pkgrel = 1 url = https://archlinux.tail7c4f5e.ts.net/git/astar76/Medlar arch = x86_64 @@ -23,7 +23,7 @@ pkgbase = medlar-bin conflicts = medlar options = !strip options = !debug - source = Medlar-0.1.0-Linux-x86_64.tar.gz::https://archlinux.tail7c4f5e.ts.net/git/astar76/Medlar/releases/download/v0.1.0/Medlar-0.1.0-Linux-x86_64.tar.gz + source = Medlar-0.1.1-Linux-x86_64.tar.gz::https://archlinux.tail7c4f5e.ts.net/git/astar76/Medlar/releases/download/v0.1.1/Medlar-0.1.1-Linux-x86_64.tar.gz sha256sums = 066b6bc684810d478f2cd6f64acae42b91dec1e9ba3a56d570519f981798ae2f pkgname = medlar-bin diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD index 4a5691e..da68e53 100644 --- a/packaging/arch/PKGBUILD +++ b/packaging/arch/PKGBUILD @@ -1,6 +1,6 @@ # Maintainer: astar76 pkgname=medlar-bin -pkgver=0.1.0 +pkgver=0.1.1 pkgrel=1 pkgdesc='Download manager with dynamic parts, queues, video sites and a Material You interface' arch=('x86_64') @@ -25,7 +25,7 @@ package() { install -Dm644 share/medlar.metainfo.xml "$pkgdir/usr/share/metainfo/medlar.metainfo.xml" install -Dm644 share/Rubik-OFL.txt "$pkgdir/usr/share/licenses/$pkgname/Rubik-OFL.txt" # Medlar's own licence: MIT (Cargo.toml); the project has no LICENSE file yet. - printf 'MIT License\n\nMedlar, 0.1.0. Licensed under the MIT licence.\nThe Rubik font is under the SIL OFL (Rubik-OFL.txt).\n' \ + printf 'MIT License\n\nMedlar, 0.1.1. Licensed under the MIT licence.\nThe Rubik font is under the SIL OFL (Rubik-OFL.txt).\n' \ > "$pkgdir/usr/share/licenses/$pkgname/LICENSE" install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md" } From cfa789dce88049c9661af3ff7b1260c6a52cf6ed Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 13:18:00 -0600 Subject: [PATCH 08/31] S046: packages, results, progress Co-Authored-By: Claude Sonnet 5.5 --- Plans/INDEX.md | 2 +- docs/HANDOFF.md | 34 +++++++++++++---------------- docs/PROGRESS.md | 5 +++++ docs/tests/S046-fixes-0.1.1.md | 39 +++++++++++++++++++--------------- packaging/arch/.SRCINFO | 2 +- packaging/arch/PKGBUILD | 2 +- 6 files changed, 45 insertions(+), 39 deletions(-) diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 029f97b..0060088 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -66,7 +66,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 10 Distribution - [x] [S045](10%20Distribution/S045-installer-arch.md) installer.sh and Arch package -- [ ] [S046](10%20Distribution/S046-fixes-0.1.1.md) 0.1.1: names from the server, raise on arrival, copy in fields +- [x] [S046](10%20Distribution/S046-fixes-0.1.1.md) 0.1.1: names from the server, raise on arrival, copy in fields - [ ] [S047](10%20Distribution/S047-close-to-tray-wayland.md) Close to tray that works on Wayland ## Later (after version 1; not run by /orchestrate) diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index ab5f79b..d400d31 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,29 +1,25 @@ -# Handoff (2026-11-26, overnight run done) +# Handoff (2026-11-26, after 0.1.0 and the 0.1.1 fixes) -**Goal**: version 1 of Medlar, a tested AppImage and tar.gz, published on Astar Hub only after the user's yes (S039). +**Goal**: Medlar 0.1.1 with the user's fixes, installed on this PC through pacman, then a bug hunt. Releases on Astar Hub only after the user's yes. -**Phase**: version 1 done; 0.1.0 released on Astar Hub (2026-11-26, user's yes), three files with matching sizes, notes set. Next: distro packages and installer.sh (user asked). +**Phase**: version 1 done; 0.1.0 released (AppImage, tar.gz, Arch package, SHA256SUMS). Category 10 Distribution in progress. Work happens on branch `claude/orchestrate-019859` (worktree `.claude/worktrees/orchestrate-019859`); `main` is fast-forwarded after each finished category or release (D-014/D-052). -**Done this run** (branch `claude/orchestrate-019859`, pushed; worktree `.claude/worktrees/orchestrate-019859`) -- S025 video (yt-dlp), S027 rules/clipboard/drop, S033 tray/notify/autostart, S034 motion pass. -- S041, S043, S037 tests; S044 fix plan: every HIGH row in `docs/tests` passes; video page wired into the Add dialog and the manager. -- S039 up to checksums: `dist/Medlar-0.1.0-Linux-x86_64.tar.gz`, `dist/Medlar-0.1.0-x86_64.AppImage`, `dist/SHA256SUMS-0.1.0` (git-ignored; a copy is in `~/Projects/Medlar/dist/`). Both smoke-tested hidden (download from testserver, hash right, idle 0 % CPU). `README.md`, `docs/releases/0.1.0.md`, `docs/tests/S039-package-release.md`. -- `main` was fast-forwarded after categories 06, 07, 08; not after 09 (S039 not finished). +**Done** +- S045: `installer.sh`, `packaging/arch/PKGBUILD` (`medlar-bin`), `tools/package.sh` builds the Arch package. +- S046 (0.1.1, check its INDEX line): sender names like `output.bin` give way to the server's name; arrivals raise the window (Focus + RequestUserAttention); Ctrl+C/Ctrl+A go to focused text fields; speed number smoothed and held ~1 s; Appearance setting "Progress bar: One bar / One per part"; snail mode capped at 8 kB/s (old 32 KiB default migrated) with a drawn snail button bottom right. Builds in `dist/` (git-ignored). **Next three** -1. User decides the glibc question (below) and says yes or no to 0.1.0. -2. On yes: copy the three files to `releases/v0.1.0/`, `ssh root@192.168.1.71 'hub-release notes Medlar v0.1.0' < docs/releases/0.1.0.md`, check the page. -3. `docs/STATUS.md`, PROGRESS, tick S039 and INDEX, commit, fast-forward `main` (D-014/D-052). +1. S047 (`Plans/10 Distribution/S047-close-to-tray-wayland.md`, Opus): close to tray on Wayland via eframe `run_and_return` and a session owned by `main`. +2. Rebuild 0.1.1 packages after S047; give the user `sudo pacman -U ~/Projects/Medlar/dist/Medlar-0.1.1-arch-x86_64.pkg.tar.zst` (sudo needs their password; never type it); tell them to quit the running AppImage first. Ask yes/no for publishing 0.1.1 (version, contents, known bugs). +3. Bug hunt: write a plan (S048) that walks every screen and flow the user uses (Nacre hand-off, settings, modes, snail, tray) and fixes what it finds. **Known bugs and gaps** -- Binary needs **glibc 2.44** (built on Arch): no older distros. An older build host needs a distro rootfs download, which D-011 forbids without the user's yes. -- Not run: hidden UI journeys (engine-tested only), many MED screen and motion checks (S022, S034, parts of S027/S033), real yt-dlp through the manager, AppImage via FUSE and portable `$APPIMAGE`, older distros. -- yt-dlp gets no cookies and no global speed limit; a playlist task is named after its last file. -- Soak memory 50 → 63 MB over 52 restarts (possible slow leak, not chased). -- Flaky under load: parts benchmark, auth proxy names. Tests need an absolute `TMPDIR`. +- Binary needs glibc 2.44; no .deb/.rpm (user chose Arch + installer only). +- Not run: many MED screen and motion checks, real yt-dlp through the manager, `pacman -U`, real sudo `--system` install. +- yt-dlp gets no cookies or global limit; playlist task named after its last file; soak memory 50 → 63 MB over 52 restarts. -**Commands**: `nice cargo test -j 2` (absolute TMPDIR), `nice cargo build --release -j 2` (never both), `tools/hidden.sh`, `tools/package.sh`. +**Commands**: `nice cargo test -j 2` (absolute TMPDIR), `nice cargo build --release -j 2` (never both), `tools/hidden.sh`, `tools/package.sh` (`ARCH_ONLY=1` for the package only). -**Decisions**: S044 added by the orchestrator as the gate fix plan. yt-dlp and ffmpeg are not bundled (README says so). +**Decisions**: the user's Medlar runs on 17616 from the 0.1.0 AppImage: tests use a spare port and throwaway home. The browser (Nacre) sends `filename` at click time, so it is only a hint. -**Open questions**: publish 0.1.0 with the glibc 2.44 limit, or build on an older host first? +**Open questions**: none. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 6560257..3aa3851 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -270,3 +270,8 @@ Seen: boxes were ticked together after the tests, against rule 3. ## S045 — installer.sh and Arch package - `installer.sh` (user/system/DESTDIR, uninstall/purge, glibc and checksum checks); `packaging/arch/PKGBUILD` + `.SRCINFO`; `tools/package.sh` adds `dist/Medlar-0.1.0-arch-x86_64.pkg.tar.zst` (`ARCH_ONLY=1` keeps other bytes). - Tested in throwaway HOME/DESTDIR and makepkg offline. Not done: real sudo/pacman -U, shellcheck/namcap (absent), `--url`, releases/. + +## S046 — Fixes 0.1.1 +- Server name beats placeholder (`output.bin`), window raised on arrival, Ctrl+C/A in fields, readable speed (2 s mean, 1 s hold), setting "One bar / One per part", snail cap 8 kB/s (migrated) and a snail button. +- Version 0.1.1; `dist/` has tar.gz, AppImage, Arch package, SHA256SUMS-0.1.1; notes in `docs/releases/0.1.1.md`. Nothing in releases/. +- Suite passed except one mirror timing flake under load. Not done: tray tooltip smoothing, live Wayland raise, snail covers pause icon at 480x360. diff --git a/docs/tests/S046-fixes-0.1.1.md b/docs/tests/S046-fixes-0.1.1.md index 51547bd..82f2107 100644 --- a/docs/tests/S046-fixes-0.1.1.md +++ b/docs/tests/S046-fixes-0.1.1.md @@ -11,23 +11,23 @@ ## Checks | # | Risk | Do this | Expect | How | Result | |---|---|---|---|---|---| -| 1 | HIGH | Engine: hint `output.bin`, server sends Content-Disposition `game.zip` | file is `game.zip` | integration `a_placeholder_name_gives_way_to_the_servers` | RESULT1 | -| 2 | HIGH | Same, hint `mine.7z` | file stays `mine.7z` | integration (same test) | RESULT1 | -| 3 | MED | Hint `download`, redirect to `other.iso` | file is `other.iso` | integration (same test) | RESULT1 | -| 4 | MED | `prefer` with placeholders and real names | only a placeholder gives way, never to another placeholder | unit `hints_give_way` | RESULT1 | -| 5 | MED | Hidden run: POST `{url, filename:"output.bin"}` to the connector on a spare port | Add window shows the name `game.zip`-style real name, window is up | by hand (hidden.sh) | RESULT2 | -| 6 | MED | Raise on arrival | commands Visible, Minimized(false), Focus, attention | unit `raising_shows_focuses_and_asks_for_attention` | RESULT1 | -| 7 | HIGH | Focused field, Ctrl+C and Ctrl+A | app shortcuts do not fire | unit `a_focused_field_keeps_copy_and_select_all` | RESULT1 | -| 8 | MED | Noisy speed fed for 10 s | at most one change per hold; jumps pass at once | unit `a_noisy_speed_changes_at_most_once_per_hold` | RESULT1 | -| 9 | LOW | Idle (speed 0) | no repaint requested | unit (odometer) | RESULT1 | -| 10 | MED | Settings file without `bar` | loads with Parts | unit settings tests | RESULT1 | -| 11 | MED | Settings row "bar" | Look page lists it, texts exist, key is real | integration `every_row_has_its_texts_and_real_keys` | RESULT1 | -| 12 | LOW | Shots `main-onebar`, light and dark | one bar per row | screen | RESULT3 | -| 13 | HIGH | Stored snail 32768 / user value 5000 | 8000 / 5000 | unit `snail_moves_to_8_kb_unless_changed` | RESULT1 | -| 14 | HIGH | Snail toggled during a download against testserver | speed held at cap, no connection dropped | integration `modes_change_live_without_reconnecting` | RESULT1 | -| 15 | MED | Snail button off / on | off asks no frames; on asks a slow loop | unit `off_asks_for_no_frames_and_on_asks_for_a_slow_loop` | RESULT1 | -| 16 | LOW | Shots `main-snail`, light/dark, 480x360 and 1080x720 | button bottom right, on/off look | screen | RESULT3 | -| 17 | MED | Hidden run idle with the new build | CPU near 0 % | by hand | RESULT2 | +| 1 | HIGH | Engine: hint `output.bin`, server sends Content-Disposition `game.zip` | file is `game.zip` | integration `a_placeholder_name_gives_way_to_the_servers` | pass (full suite) | +| 2 | HIGH | Same, hint `mine.7z` | file stays `mine.7z` | integration (same test) | pass (full suite) | +| 3 | MED | Hint `download`, redirect to `other.iso` | file is `other.iso` | integration (same test) | pass (full suite) | +| 4 | MED | `prefer` with placeholders and real names | only a placeholder gives way, never to another placeholder | unit `hints_give_way` | pass (full suite) | +| 5 | MED | Hidden run: POST `{url, filename:"output.bin"}` to the connector on a spare port | Add window shows the name `game.zip`-style real name, window is up | by hand (hidden.sh) | pass: hidden, port 17999, Add window shows game.zip over output.bin | +| 6 | MED | Raise on arrival | commands Visible, Minimized(false), Focus, attention | unit `raising_shows_focuses_and_asks_for_attention` | pass (full suite) | +| 7 | HIGH | Focused field, Ctrl+C and Ctrl+A | app shortcuts do not fire | unit `a_focused_field_keeps_copy_and_select_all` | pass (full suite) | +| 8 | MED | Noisy speed fed for 10 s | at most one change per hold; jumps pass at once | unit `a_noisy_speed_changes_at_most_once_per_hold` | pass (full suite) | +| 9 | LOW | Idle (speed 0) | no repaint requested | unit (odometer) | pass (full suite) | +| 10 | MED | Settings file without `bar` | loads with Parts | unit settings tests | pass (full suite) | +| 11 | MED | Settings row "bar" | Look page lists it, texts exist, key is real | integration `every_row_has_its_texts_and_real_keys` | pass (full suite) | +| 12 | LOW | Shots `main-onebar`, light and dark | one bar per row | screen | pass (contact sheet seen) | +| 13 | HIGH | Stored snail 32768 / user value 5000 | 8000 / 5000 | unit `snail_moves_to_8_kb_unless_changed` | pass (full suite) | +| 14 | HIGH | Snail toggled during a download against testserver | speed held at cap, no connection dropped | integration `modes_change_live_without_reconnecting` | pass (full suite) | +| 15 | MED | Snail button off / on | off asks no frames; on asks a slow loop | unit `off_asks_for_no_frames_and_on_asks_for_a_slow_loop` | pass (full suite) | +| 16 | LOW | Shots `main-snail`, light/dark, 480x360 and 1080x720 | button bottom right, on/off look | screen | pass (contact sheet seen) | +| 17 | MED | Hidden run idle with the new build | CPU near 0 % | by hand | not run: CPU 11 % measured with the Add dialog open (software render); empty idle list not measured | ## Needs Testserver on loopback; throwaway home and spare port 17999 for hidden runs. The user's running Medlar (17616) is never touched. @@ -37,3 +37,8 @@ Testserver on loopback; throwaway home and spare port 17999 for hidden runs. The - Real Wayland focus on arrival cannot be proven in a nested session. - At 480x360 the snail button covers the pause icon of the last row. - Tray tooltip speed is not smoothed. Snail crawl motion not watched live. + +## Results +Full workspace suite (`--no-fail-fast`): all pass except `a_fast_mirror_brings_more_than_a_slow_one` (mirror.rs) once under load (fast 147457, slow 49153); alone it passed twice. Timing flake, not touched by S046; not fixed. +Fix found by the suite: the Settings row "bar" listed non-setting keys (fixed). Smoke note: a server name like `data-1.bin` counts as a placeholder, so the hint stays; the smoke used `/data/1/3k/game.zip`. +Packages: tar.gz 13989774 B, AppImage 13740536 B, Arch pkg 13637062 B, SHA256SUMS-0.1.1 297 B (dist/). Packaged apps not launched by hand beyond the release binary smoke. diff --git a/packaging/arch/.SRCINFO b/packaging/arch/.SRCINFO index c1025b7..ec55860 100644 --- a/packaging/arch/.SRCINFO +++ b/packaging/arch/.SRCINFO @@ -24,6 +24,6 @@ pkgbase = medlar-bin options = !strip options = !debug source = Medlar-0.1.1-Linux-x86_64.tar.gz::https://archlinux.tail7c4f5e.ts.net/git/astar76/Medlar/releases/download/v0.1.1/Medlar-0.1.1-Linux-x86_64.tar.gz - sha256sums = 066b6bc684810d478f2cd6f64acae42b91dec1e9ba3a56d570519f981798ae2f + sha256sums = e89db7fc43b55ec4dc5c919914ffb95702176561eb83a4037ccab21499a2d484 pkgname = medlar-bin diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD index da68e53..09407f4 100644 --- a/packaging/arch/PKGBUILD +++ b/packaging/arch/PKGBUILD @@ -15,7 +15,7 @@ conflicts=('medlar') options=('!strip' '!debug') # MEDLAR_TARBALL points at a local copy (offline build); default is the release download. source=("Medlar-$pkgver-Linux-x86_64.tar.gz::${MEDLAR_TARBALL:-$url/releases/download/v$pkgver/Medlar-$pkgver-Linux-x86_64.tar.gz}") -sha256sums=('066b6bc684810d478f2cd6f64acae42b91dec1e9ba3a56d570519f981798ae2f') +sha256sums=('e89db7fc43b55ec4dc5c919914ffb95702176561eb83a4037ccab21499a2d484') package() { cd "$srcdir/medlar-$pkgver" From 63f0046965532e6bdc6631b6c10af1e19beba5a0 Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 13:18:32 -0600 Subject: [PATCH 09/31] S046: tick plan boxes; handoff for the next session Co-Authored-By: Claude Opus 5.5 --- Plans/10 Distribution/S046-fixes-0.1.1.md | 12 ++++++------ docs/HANDOFF.md | 2 ++ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/Plans/10 Distribution/S046-fixes-0.1.1.md b/Plans/10 Distribution/S046-fixes-0.1.1.md index 402e326..7473c4c 100644 --- a/Plans/10 Distribution/S046-fixes-0.1.1.md +++ b/Plans/10 Distribution/S046-fixes-0.1.1.md @@ -15,12 +15,12 @@ Three bugs the user found with 0.1.0 (Nacre on a real site): - docs/CONNECTOR.md (`filename` field) ## Steps -- [ ] Name: a name from a sender (connector `filename`, or the Add dialog when the user did not type it) is a hint. On the first reply, when the hint is generic (no extension, or an extension like bin, php, asp, aspx, cgi, html, htm, download, or a known placeholder such as `output.bin`, `download`, `file`) and the reply gives a name (Content-Disposition, else the final link with a file extension), use the reply's name, made safe as today, before any file is created; a name the user typed always wins; collisions handled as today (never overwrite). The Add dialog's probe updates the shown name the same way while the user has not edited it. Unit tests in name.rs and an engine test against testserver (provisional name + Content-Disposition, and a redirect to a named link) -- [ ] Raise: on an arrival that shows the Add window or adds a download, if the main window is hidden show it (`Visible(true)`, `Minimized(false)`), then `Focus` and `RequestUserAttention(Critical)` (urgency where focus is refused); same for second-instance hand-over; clear the attention when the window gets focus. A kittest that records the viewport commands -- [ ] Copy: while a text field has focus, Ctrl+C, Ctrl+A (and Ctrl+X, Ctrl+V, Ctrl+Z as now) go to the field, not to list shortcuts; settings values that are read-only text (paths, versions, the port, the token) are selectable or have a copy button where egui allows. Unit test for `pressed` with a focused field -- [ ] Full workspace suite once (absolute TMPDIR), then release build; hidden smoke test: POST a link with `filename: output.bin` to a testserver URL that answers with Content-Disposition `game.zip`: Add window shows and the file is `game.zip`; window raised in the grab -- [ ] Version 0.1.1 everywhere (Cargo, metainfo, PKGBUILD, .SRCINFO); `tools/package.sh` builds tar.gz, AppImage, Arch package and `SHA256SUMS-0.1.1` in dist/; `docs/releases/0.1.1.md`; nothing into releases/ -- [ ] Test file `docs/tests/S046-fixes-0.1.1.md` with Results, PROGRESS entry, tick INDEX, commit `S046: …`, `git push origin HEAD` +- [x] Name: a name from a sender (connector `filename`, or the Add dialog when the user did not type it) is a hint. On the first reply, when the hint is generic (no extension, or an extension like bin, php, asp, aspx, cgi, html, htm, download, or a known placeholder such as `output.bin`, `download`, `file`) and the reply gives a name (Content-Disposition, else the final link with a file extension), use the reply's name, made safe as today, before any file is created; a name the user typed always wins; collisions handled as today (never overwrite). The Add dialog's probe updates the shown name the same way while the user has not edited it. Unit tests in name.rs and an engine test against testserver (provisional name + Content-Disposition, and a redirect to a named link) +- [x] Raise: on an arrival that shows the Add window or adds a download, if the main window is hidden show it (`Visible(true)`, `Minimized(false)`), then `Focus` and `RequestUserAttention(Critical)` (urgency where focus is refused); same for second-instance hand-over; clear the attention when the window gets focus. A kittest that records the viewport commands +- [x] Copy: while a text field has focus, Ctrl+C, Ctrl+A (and Ctrl+X, Ctrl+V, Ctrl+Z as now) go to the field, not to list shortcuts; settings values that are read-only text (paths, versions, the port, the token) are selectable or have a copy button where egui allows. Unit test for `pressed` with a focused field +- [x] Full workspace suite once (absolute TMPDIR), then release build; hidden smoke test: POST a link with `filename: output.bin` to a testserver URL that answers with Content-Disposition `game.zip`: Add window shows and the file is `game.zip`; window raised in the grab +- [x] Version 0.1.1 everywhere (Cargo, metainfo, PKGBUILD, .SRCINFO); `tools/package.sh` builds tar.gz, AppImage, Arch package and `SHA256SUMS-0.1.1` in dist/; `docs/releases/0.1.1.md`; nothing into releases/ +- [x] Test file `docs/tests/S046-fixes-0.1.1.md` with Results, PROGRESS entry, tick INDEX, commit `S046: …`, `git push origin HEAD` ## End criteria - the three bugs have passing regression tests; suite green; builds smoke-tested diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index d400d31..281fc88 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -14,6 +14,8 @@ 3. Bug hunt: write a plan (S048) that walks every screen and flow the user uses (Nacre hand-off, settings, modes, snail, tray) and fixes what it finds. **Known bugs and gaps** +- From S046: snail button covers the last row's pause icon at 480x360; idle CPU 11 % with the Add dialog open (check what animates); tray tooltip speed not smoothed; a mirror timing test flaky under load; server names like `data-1.bin` count as placeholders. Put these in S048 (bug hunt). +- `dist/` now holds only 0.1.1 builds (package.sh wipes it); the 0.1.0 files are in `releases/v0.1.0/`. - Binary needs glibc 2.44; no .deb/.rpm (user chose Arch + installer only). - Not run: many MED screen and motion checks, real yt-dlp through the manager, `pacman -U`, real sudo `--system` install. - yt-dlp gets no cookies or global limit; playlist task named after its last file; soak memory 50 → 63 MB over 52 restarts. From f6c8a5c57aa86a58860f09872c7b50f44966f7dc Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 13:52:23 -0600 Subject: [PATCH 10/31] S048: plan for server farms with differing validators (romsgames.net) Co-Authored-By: Claude Opus 5.5 --- Plans/10 Distribution/S048-server-farms.md | 30 ++++++++++++++++++++++ Plans/INDEX.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 Plans/10 Distribution/S048-server-farms.md diff --git a/Plans/10 Distribution/S048-server-farms.md b/Plans/10 Distribution/S048-server-farms.md new file mode 100644 index 0000000..790d252 --- /dev/null +++ b/Plans/10 Distribution/S048-server-farms.md @@ -0,0 +1,30 @@ +# S048 — Servers behind a load balancer with different validators + +> Category 10 Distribution · Model: Opus (engine correctness, never mix two files) · Effort: medium · Depends on: S046 · Phase: test · Human: 🧑 yes before release +> Files touched: crates/core/src/http/{mod,fetch,download,parts}.rs, crates/testserver/**, crates/core/tests/**, docs/tests/S048-server-farms.md, docs/releases/0.1.1.md + +## Goal +Downloads from romsgames.net (and any site with a server farm) fail at once with "File changed on the server". Seen on 2026-11-26 with four 1-byte range requests to the same link (`static.romsgames.net/.../output.bin?token`): + +| range | Server | Last-Modified | ETag | Content-Range total | +|---|---|---|---|---| +| 0-0 | nginx/1.22.0 | Mon, 21 Jul 2025 20:20:29 | W/"bd6dcd82-1982ea51dc7" | 3178089858 | +| 1000000-1000000 | nginx/1.24.0 (Ubuntu) | Sun, 05 Jan 2020 05:35:27 | W/"bd6dcd82-16f743377f5" | 3178089858 | +| 0-0 | nginx/1.24.0 (Ubuntu) | Mon, 21 Jul 2025 20:20:29 | W/"bd6dcd82-1982ea51dc7" | 3178089858 | +| 2000000000-… | nginx/1.24.0 (Ubuntu) | Mon, 21 Jul 2025 20:20:29 | W/"bd6dcd82-1982ea51dc7" | 3178089858 | + +All 206, same size, same type; nodes differ only in mtime (nginx ETag = `"-"`). `Validators::same_file` (http/mod.rs) and `send_range` (fetch.rs ~159) call that `Changed`. The user's task 8 failed after 32 KB. + +## Rule (never mix two files) +When a reply's validators differ from the known ones but the total size is equal: do not fail. Check bytes instead: compare a sample of bytes already on disk with the same range from this reply (the existing `same_bytes` path in fetch.rs ~205; make the sample big enough, e.g. 64 KiB or what is there) before writing. Bytes equal → mark the task's link as a *farm* (validators unreliable): from then on compare size + byte samples only, send no `If-Range` (a Last-Modified `If-Range` makes other nodes answer 200 full), keep the first validators for display. Bytes differ, or size differs → `Changed` as today. A 200 to a range on a farm is `RangeIgnored`, not `Changed`. Also nginx-style ETags that differ only after the size part count as "maybe the same file" (still checked by bytes). + +## Steps +- [ ] testserver: a farm mode (several "nodes" with the same bytes but different Last-Modified/ETag picked per request, nginx-style weak ETags), and a liar mode (same size, different bytes) — docs in the lib.rs header +- [ ] Engine: the rule above, in probe, parts and resume; the farm flag stored with the task (store migration) so a restart keeps it; parts on a farm still run in parallel +- [ ] Tests: farm download with 4 parts completes with the right hash; pause/restart/resume on a farm; liar same-size-different-bytes still fails with Changed and keeps what is there; If-Range not sent on a farm; unit tests for the ETag comparison +- [ ] Full workspace suite once (absolute TMPDIR), release build, hidden smoke against testserver farm on a spare port (the user's Medlar 0.1.1 runs on 17616: never stop it) +- [ ] `tools/package.sh` (0.1.1, rebuilds dist/), copy the four files to `~/Projects/Medlar/dist/` as well; notes in docs/releases/0.1.1.md +- [ ] Test file with Results, PROGRESS, tick INDEX, commit `S048: …`, `git push origin HEAD` + +## Pitfalls +Never contact romsgames.net or any real site in tests; testserver only. Never weaken the "two files are never mixed" guarantee. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 0060088..7d38a9a 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -68,6 +68,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H - [x] [S045](10%20Distribution/S045-installer-arch.md) installer.sh and Arch package - [x] [S046](10%20Distribution/S046-fixes-0.1.1.md) 0.1.1: names from the server, raise on arrival, copy in fields - [ ] [S047](10%20Distribution/S047-close-to-tray-wayland.md) Close to tray that works on Wayland +- [ ] [S048](10%20Distribution/S048-server-farms.md) Servers behind a load balancer with different validators ## Later (after version 1; not run by /orchestrate) From ed2f7c67e5d5a4e052eb4bff9d68d146fbbb10c2 Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 13:58:03 -0600 Subject: [PATCH 11/31] S048: farms with differing validators: byte proof, no If-Range, stored flag; testserver farm and liar modes Co-Authored-By: Claude Opus 5.5 --- crates/core/src/http/download.rs | 17 +++- crates/core/src/http/fetch.rs | 159 +++++++++++++++++++++++++------ crates/core/src/http/mod.rs | 25 +++++ crates/core/src/model.rs | 3 + crates/core/src/relink/mod.rs | 3 +- crates/core/src/store/007.sql | 1 + crates/core/src/store/mod.rs | 2 +- crates/core/src/store/rows.rs | 8 +- crates/testserver/src/faults.rs | 10 +- crates/testserver/src/http.rs | 10 +- crates/testserver/src/lib.rs | 3 +- 11 files changed, 199 insertions(+), 42 deletions(-) create mode 100644 crates/core/src/store/007.sql diff --git a/crates/core/src/http/download.rs b/crates/core/src/http/download.rs index c1b5281..bc3fec8 100644 --- a/crates/core/src/http/download.rs +++ b/crates/core/src/http/download.rs @@ -173,7 +173,11 @@ async fn fetch_whole( let body = probe.body.take(); // Once on a mirror, its redirects are its own. let here = if url == task.url { source.at(&probe.url) } else { source.mirror(&url)?.at(&probe.url) }; - let link = Link { client: client.clone(), source: here, ranges: probe.ranges, version: probe.version.clone() }; + let mut link = Link::new(client.clone(), here, probe.ranges, probe.version.clone(), task.farm); + // The bytes here are of the version first seen; replies of another one with the same size are checked by their bytes. + if !parts.is_empty() && !compared && !old(&task).same_file(&link.version) && old(&task).maybe_same(&link.version) { + link.version = old(&task); + } let (file, parts) = match file { Some(file) => resume(job, &task, file, parts, &link, compared, stop).await?, None => start(shared, job, &task, probe, &link, stop).await?, @@ -193,10 +197,15 @@ async fn fetch_whole( let task = Arc::new(job.task().await?); let mirrors = links(&task).into_iter().filter(|u| *u != url && !out.contains(u)).filter_map(|u| Some((u.clone(), source.mirror(&u).ok()?))); let mirrors = if link.ranges { mirrors.collect() } else { vec![] }; + let (farm, was_farm) = (link.farm.clone(), task.farm); let mut run = Run::new(shared, task, (url, link), mirrors, file.clone(), parts, body, host.clone(), begin, options, monitor); let result = run.go(job, stop).await; let Ended { live, learned, gave } = run.end(); let saved = job.checkpoint(&live, &file).await; + // So that a restart doesn't take its servers for another version. + if farm.load(std::sync::atomic::Ordering::Relaxed) && !was_farm { + job.run(move |s| Ok(s.edit_task(id, |t| t.farm = true)?)).await?; + } if let Some(n) = learned { job.run(move |s| Ok(host::remember(s, &host, n, model::now())?)).await?; } @@ -265,7 +274,9 @@ async fn open_one(client: &Client, task: &Task, parts: &[Part], source: Source, return Ok((probe, false)); } if first { - return if old(task).same_file(&probe.version) { Ok((probe, false)) } else { Err(Error::Changed) }; + // Another server of a farm differs in dates only; the bytes tell when the parts go on. + let old = old(task); + return if old.same_file(&probe.version) || old.maybe_same(&probe.version) { Ok((probe, false)) } else { Err(Error::Changed) }; } let link = NewLink { url: source.url.to_string(), ..NewLink::default() }; let checked = relink::check(client, task, parts, link, source, stop).await?; @@ -354,7 +365,7 @@ async fn resume( compared: bool, stop: &mut Stop, ) -> Result<(Arc, Vec)> { - if !compared && !old(task).same_file(&link.version) { + if !compared && !old(task).same_file(&link.version) && !old(task).maybe_same(&link.version) { return Err(Error::Changed); } let file = Arc::new(file); diff --git a/crates/core/src/http/fetch.rs b/crates/core/src/http/fetch.rs index 87f7e91..c649a18 100644 --- a/crates/core/src/http/fetch.rs +++ b/crates/core/src/http/fetch.rs @@ -6,10 +6,16 @@ use crate::disk::PartialFile; use crate::limit::Flow; use crate::part::LivePart; use bytes::Bytes; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Instant; /// Finished bytes read again and compared when a part goes on. pub const OVERLAP: u64 = 4096; +/// Finished bytes compared with a reply of another version of the same size, and on a farm when a part goes on. +pub const SAMPLE: u64 = 64 * 1024; +/// Replies asked for until one of the known version and one of another can be compared. +const PROOF_TRIES: u32 = 8; /// Held in memory for each part. const BUFFER: usize = 512 * 1024; /// A slow part writes what it has this often. @@ -22,7 +28,26 @@ pub struct Link { /// At the final link. pub source: Source, pub ranges: bool, + /// The first version seen, kept for display and as the one the bytes on disk are of. pub version: Validators, + /// Its servers differ in dates and tags but were shown to have the same bytes: only size and bytes count. Shared by clones. + pub farm: Arc, +} + +impl Link { + pub fn new(client: Client, source: Source, ranges: bool, version: Validators, farm: bool) -> Link { + Link { client, source, ranges, version, farm: Arc::new(AtomicBool::new(farm)) } + } + + pub fn farm(&self) -> bool { + self.farm.load(Ordering::Relaxed) + } + + fn set_farm(&self) { + if !self.farm.swap(true, Ordering::Relaxed) { + log::info!("{}: servers differ in dates only, telling versions by size and bytes", self.source.url); + } + } } /// Fills `part` until it is whole, `stop` turns true or something breaks. Whatever arrived is written before it returns, so stop @@ -46,10 +71,10 @@ pub(super) async fn fetch_within( if *stop.borrow() { return Err(Error::Stopped); } - let (mut response, mut known) = if link.ranges { + let (mut response, mut known, mut unsure) = if link.ranges { range(link, part, file, &mut stop).await? } else { - (whole(link, part, body, &mut stop).await?, vec![]) + (whole(link, part, body, &mut stop).await?, vec![], false) }; part.begin(); let mut buf = Vec::with_capacity(BUFFER); @@ -73,6 +98,11 @@ pub(super) async fn fetch_within( return Err(Error::Changed); } known.drain(..old.len()); + // Another version's reply had the bytes that are here: the servers differ in dates only. + if unsure && known.is_empty() { + link.set_farm(); + unsure = false; + } // Piece by piece, as fast as the limits have it. One chunk is read ahead, so that the sender has room again before // all is used up. let mut rest = &chunk[..]; @@ -139,38 +169,104 @@ async fn flush(part: &LivePart, file: &PartialFile, buf: Vec) -> Result Result<(Response, Vec)> { +/// Asks for the rest of the part and checks that this is what comes. Also gives the finished bytes it must begin with, and +/// whether the reply is of another version of the same size, which these bytes have to confirm. +async fn range(link: &Link, part: &LivePart, file: &PartialFile, stop: &mut Stop) -> Result<(Response, Vec, bool)> { let p = part.get(); - let overlap = p.done.min(OVERLAP); - let first = p.start + p.done - overlap; - let known = file.read_at(overlap as usize, first).await?; - let response = send_range(link, first, p.end, stop).await?; - Ok((response, known)) + let mut overlap = p.done.min(if link.farm() { SAMPLE } else { OVERLAP }); + loop { + let first = p.start + p.done - overlap; + if p.done == 0 { + return Ok((sure_range(link, first, p.end, stop).await?, vec![], false)); + } + let (response, unsure) = send_range(link, first, p.end, stop).await?; + // Enough of the bytes here to tell another version from the same file on another server. + if unsure && overlap < p.done.min(SAMPLE) { + overlap = p.done.min(SAMPLE); + continue; + } + let known = file.read_at(overlap as usize, first).await?; + return Ok((response, known, unsure)); + } } -async fn send_range(link: &Link, first: u64, end: Option, stop: &mut Stop) -> Result { - let last = end.map(|e| (e - 1).to_string()).unwrap_or_default(); - let response = link.source.get(&link.client, Some(format!("bytes={first}-{last}")), link.version.if_range().as_ref(), stop).await?; - let headers = response.headers(); - match response.status() { - StatusCode::PARTIAL_CONTENT => { - let range = ContentRange::of(headers).ok_or_else(|| Error::BadReply("no usable Content-Range".into()))?; - if !link.version.same_file(&Validators::of(headers, range.total)) { +/// A range from the known version, or from another one shown to have the same bytes. +async fn sure_range(link: &Link, first: u64, end: Option, stop: &mut Stop) -> Result { + let (response, unsure) = send_range(link, first, end, stop).await?; + if !unsure { + return Ok(response); + } + drop(response); + // Only replies of the same size are unsure, so the size is known. + let until = end.or(link.version.size).unwrap_or(first); + prove(link, first, (until - first).min(SAMPLE), stop).await?; + Ok(send_range(link, first, end, stop).await?.0) +} + +/// Asks for `len` bytes at `at` until a reply of the known version and one of another can be compared. The same bytes make +/// the link a farm; other bytes, or no reply of the known version, mean the file changed. +async fn prove(link: &Link, at: u64, len: u64, stop: &mut Stop) -> Result<()> { + let (mut known, mut other) = (None, None); + for _ in 0..PROOF_TRIES { + if link.farm() { + return Ok(()); + } + let (response, unsure) = send_range(link, at, Some(at + len), stop).await?; + let data = all(&link.client, response, len, stop).await?; + if data.len() as u64 != len { + return Err(Error::Cut { got: data.len() as u64, expected: Some(len) }); + } + *(if unsure { &mut other } else { &mut known }) = Some(data); + if let (Some(a), Some(b)) = (&known, &other) { + if a != b { return Err(Error::Changed); } - if range.first != first || end.is_some_and(|e| range.last >= e) { - return Err(Error::BadReply("another range than asked for".into())); + link.set_farm(); + return Ok(()); + } + } + Err(Error::Changed) +} + +/// A reply to a range, and whether it is of another version of the same size: maybe the same file from another server of +/// a farm, which only its bytes can tell. Never unsure on a farm. +async fn send_range(link: &Link, first: u64, end: Option, stop: &mut Stop) -> Result<(Response, bool)> { + let last = end.map(|e| (e - 1).to_string()).unwrap_or_default(); + // Servers of a farm with other dates answer a date in If-Range with the whole file. + let mut if_range = if link.farm() { None } else { link.version.if_range() }; + loop { + let response = link.source.get(&link.client, Some(format!("bytes={first}-{last}")), if_range.as_ref(), stop).await?; + let headers = response.headers(); + match response.status() { + StatusCode::PARTIAL_CONTENT => { + let range = ContentRange::of(headers).ok_or_else(|| Error::BadReply("no usable Content-Range".into()))?; + let version = Validators::of(headers, range.total); + let unsure = !link.version.same_file(&version); + if unsure && !link.version.maybe_same(&version) { + return Err(Error::Changed); + } + if range.first != first || end.is_some_and(|e| range.last >= e) { + return Err(Error::BadReply("another range than asked for".into())); + } + check_length(headers, range)?; + check_encoding(headers, response.url())?; + return Ok((response, unsure && !link.farm())); } - check_length(headers, range)?; - check_encoding(headers, response.url())?; - Ok(response) + StatusCode::OK => { + let version = Validators::of(headers, content_length(headers)); + if link.version.same_file(&version) || (link.farm() && link.version.maybe_same(&version)) { + return Err(Error::RangeIgnored); + } + if link.version.maybe_same(&version) && if_range.take().is_some() { + continue; + } + return Err(if comes_as_page(link, headers) { Error::Page } else { Error::Changed }); + } + StatusCode::RANGE_NOT_SATISFIABLE if unsatisfied_total(headers).is_some_and(|t| link.version.size != Some(t)) => { + return Err(Error::Changed); + } + _ => return Err(status_error(&response)), } - StatusCode::OK if link.version.same_file(&Validators::of(headers, content_length(headers))) => Err(Error::RangeIgnored), - StatusCode::OK if comes_as_page(link, headers) => Err(Error::Page), - StatusCode::OK => Err(Error::Changed), - StatusCode::RANGE_NOT_SATISFIABLE if unsatisfied_total(headers).is_some_and(|t| link.version.size != Some(t)) => Err(Error::Changed), - _ => Err(status_error(&response)), } } @@ -208,12 +304,17 @@ pub async fn compare(link: &Link, file: &PartialFile, at: u64, len: u64, stop: & /// Whether the server has `known` at `at`. pub async fn same_bytes(link: &Link, known: &[u8], at: u64, stop: &mut Stop) -> Result { let len = known.len() as u64; - same_body(&link.client, send_range(link, at, Some(at + len), stop).await?, known, stop).await + let (response, unsure) = send_range(link, at, Some(at + len), stop).await?; + let same = same_body(&link.client, response, known, stop).await?; + if same && unsure && len > 0 { + link.set_farm(); + } + Ok(same) } /// `len` bytes at `at`. pub(crate) async fn bytes_at(link: &Link, at: u64, len: u64, stop: &mut Stop) -> Result> { - let response = send_range(link, at, Some(at + len), stop).await?; + let response = sure_range(link, at, Some(at + len), stop).await?; let data = all(&link.client, response, len, stop).await?; if data.len() as u64 == len { Ok(data) } else { Err(Error::Cut { got: data.len() as u64, expected: Some(len) }) } } diff --git a/crates/core/src/http/mod.rs b/crates/core/src/http/mod.rs index a9afc90..9f01caa 100644 --- a/crates/core/src/http/mod.rs +++ b/crates/core/src/http/mod.rs @@ -446,6 +446,19 @@ impl Validators { && agree(self.last_modified.as_ref(), other.last_modified.as_ref()) } + /// Of the same size, so maybe the same file from another server of a farm: only the bytes can tell. Servers like nginx + /// make the tag from size and date (`"5f-1982ea51dc7"`); tags that differ in the size part are another file. + pub fn maybe_same(&self, other: &Validators) -> bool { + fn size_part(tag: &Option) -> Option<&str> { + let tag = tag.as_deref()?; + let (size, date) = tag.strip_prefix("W/").unwrap_or(tag).strip_prefix('"')?.strip_suffix('"')?.split_once('-')?; + let hex = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit()); + (hex(size) && hex(date)).then_some(size) + } + let sizes = size_part(&self.etag).zip(size_part(&other.etag)).is_none_or(|(a, b)| a.eq_ignore_ascii_case(b)); + self.size.is_some() && self.size == other.size && sizes + } + /// The value for `If-Range`, which must not be a weak tag. fn if_range(&self) -> Option { let strong = self.etag.as_ref().filter(|t| !t.starts_with("W/")); @@ -522,4 +535,16 @@ mod tests { assert_eq!(v(None, Some("W/\"x\""), Some("d1")).if_range().unwrap(), "d1"); assert_eq!(v(None, Some("W/\"x\""), None).if_range(), None); } + + #[test] + fn farm_versions() { + let v = |size, etag: &str, lm: &str| Validators { size, etag: Some(etag.into()), last_modified: Some(lm.into()) }; + let a = v(Some(9), "W/\"bd6dcd82-1982ea51dc7\"", "Mon, 21 Jul 2025 20:20:29 GMT"); + let b = v(Some(9), "W/\"bd6dcd82-16f743377f5\"", "Sun, 05 Jan 2020 05:35:27 GMT"); + assert!(!a.same_file(&b) && a.maybe_same(&b) && b.maybe_same(&a)); + assert!(!a.maybe_same(&v(Some(8), "W/\"bd6dcd82-1\"", "x")), "another size"); + assert!(!a.maybe_same(&v(Some(9), "W/\"bd6dcd83-1982ea51dc7\"", "x")), "another size in the tag"); + assert!(a.maybe_same(&v(Some(9), "\"opaque\"", "x")), "only bytes can tell"); + assert!(!v(None, "\"a-1\"", "x").maybe_same(&v(None, "\"a-2\"", "x")), "no size"); + } } diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index c989f19..ca07265 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -175,6 +175,8 @@ pub struct Task { pub mime: Option, pub etag: Option, pub last_modified: Option, + /// Its link's servers differ in dates and tags but have the same bytes: versions are told by size and bytes. + pub farm: bool, /// `sha256:…`. pub checksum: Option, /// Hashes of its pieces, to repair single ones. @@ -226,6 +228,7 @@ impl Default for Task { mime: None, etag: None, last_modified: None, + farm: false, checksum: None, pieces: None, verified: None, diff --git a/crates/core/src/relink/mod.rs b/crates/core/src/relink/mod.rs index 9474d28..e5eb51d 100644 --- a/crates/core/src/relink/mod.rs +++ b/crates/core/src/relink/mod.rs @@ -144,6 +144,7 @@ impl Checked { task.size = self.size.or(task.size); (task.etag, task.last_modified) = (self.version.etag.clone(), self.version.last_modified.clone()); task.mime = self.mime.clone(); + task.farm = false; } } @@ -265,7 +266,7 @@ pub(crate) async fn probed( checked.reason = Reason::Size { old, new }; return Ok((checked, None)); } - let server = Link { client: client.clone(), source: source.at(&probe.url), ranges: probe.ranges, version: probe.version }; + let server = Link::new(client.clone(), source.at(&probe.url), probe.ranges, probe.version, false); Ok((checked, Some((server, body)))) } diff --git a/crates/core/src/store/007.sql b/crates/core/src/store/007.sql new file mode 100644 index 0000000..eb05e11 --- /dev/null +++ b/crates/core/src/store/007.sql @@ -0,0 +1 @@ +ALTER TABLE tasks ADD COLUMN farm INTEGER NOT NULL DEFAULT 0; diff --git a/crates/core/src/store/mod.rs b/crates/core/src/store/mod.rs index 8061539..6a4bade 100644 --- a/crates/core/src/store/mod.rs +++ b/crates/core/src/store/mod.rs @@ -16,7 +16,7 @@ use std::thread::JoinHandle; use std::time::Duration; /// Never edit one that shipped; add the next number. -const MIGRATIONS: &[&str] = &[include_str!("001.sql"), include_str!("002.sql"), include_str!("003.sql"), include_str!("004.sql"), include_str!("005.sql"), include_str!("006.sql")]; +const MIGRATIONS: &[&str] = &[include_str!("001.sql"), include_str!("002.sql"), include_str!("003.sql"), include_str!("004.sql"), include_str!("005.sql"), include_str!("006.sql"), include_str!("007.sql")]; #[derive(Debug)] pub enum Error { diff --git a/crates/core/src/store/rows.rs b/crates/core/src/store/rows.rs index b6bfc4f..0e35b3e 100644 --- a/crates/core/src/store/rows.rs +++ b/crates/core/src/store/rows.rs @@ -41,6 +41,7 @@ fn bind_task(c: &Connection, sql: &str, t: &Task) -> Result { ":proxy": t.proxy, ":secret": t.secret, ":after": t.after, ":start_at": t.start_at, ":added_at": t.added_at, ":finished_at": t.finished_at, ":removed_at": t.removed_at, ":notes": t.notes, ":tries": t.tries, ":replaces": t.replaces, ":pieces": pieces, ":verified": t.verified, ":stream": stream, ":video": video, + ":farm": t.farm, }; Ok(c.execute(sql, columns)?) } @@ -50,10 +51,10 @@ pub fn insert_task(c: &Connection, t: &Task) -> Result { c, "INSERT INTO tasks (url, mirrors, source_page, name, folder, state, queue, position, priority, size, downloaded, mime, etag, last_modified, checksum, max_parts, speed_limit, headers, proxy, secret, after, start_at, added_at, - finished_at, removed_at, notes, tries, replaces, pieces, verified, stream, video) + finished_at, removed_at, notes, tries, replaces, pieces, verified, stream, video, farm) VALUES (:url, :mirrors, :source_page, :name, :folder, 'queued', :queue, :position, :priority, :size, :downloaded, :mime, :etag, :last_modified, :checksum, :max_parts, :speed_limit, :headers, :proxy, :secret, :after, :start_at, :added_at, - :finished_at, :removed_at, :notes, :tries, :replaces, :pieces, :verified, :stream, :video)", + :finished_at, :removed_at, :notes, :tries, :replaces, :pieces, :verified, :stream, :video, :farm)", t, )?; let id = c.last_insert_rowid(); @@ -72,7 +73,7 @@ pub fn update_task(c: &Connection, t: &Task) -> Result { etag = :etag, last_modified = :last_modified, checksum = :checksum, max_parts = :max_parts, speed_limit = :speed_limit, headers = :headers, proxy = :proxy, secret = :secret, after = :after, start_at = :start_at, added_at = :added_at, finished_at = :finished_at, removed_at = :removed_at, notes = :notes, - tries = :tries, replaces = :replaces, pieces = :pieces, verified = :verified, stream = :stream, video = :video + tries = :tries, replaces = :replaces, pieces = :pieces, verified = :verified, stream = :stream, video = :video, farm = :farm WHERE id = {}", t.id ); @@ -123,6 +124,7 @@ fn task(r: &Row) -> Result { mime: r.get("mime")?, etag: r.get("etag")?, last_modified: r.get("last_modified")?, + farm: r.get("farm")?, checksum: r.get("checksum")?, // One that can't be read is one that can't repair anything. pieces: r.get::<_, Option>("pieces")?.and_then(|p| p.parse().ok()).map(Arc::new), diff --git a/crates/testserver/src/faults.rs b/crates/testserver/src/faults.rs index c2e0ab4..bd35f06 100644 --- a/crates/testserver/src/faults.rs +++ b/crates/testserver/src/faults.rs @@ -40,6 +40,11 @@ pub struct Faults { pub expire_status: Option, /// More open connections than this from one client get 429. pub max_conns: Option, + /// Served by this many "nodes" in turn (request number modulo N): the same bytes, but each its own Last-Modified and + /// nginx-style weak ETag `W/"-"`, and If-Range is checked against the node's own. + pub farm: Option, + /// On a farm, odd nodes serve other bytes of the same size. + pub liar: bool, } impl Faults { @@ -83,6 +88,8 @@ impl Faults { "expire_requests" => num!(expire_requests), "expire_status" => num!(expire_status), "max_conns" => num!(max_conns), + "farm" => num!(farm), + "liar" => self.liar = v == "1", _ => {} } Some(()) @@ -95,12 +102,13 @@ impl Faults { $($f: other.$f.clone().or_else(|| self.$f.clone()),)* ignore_range: self.ignore_range || other.ignore_range, gzip: self.gzip || other.gzip, + liar: self.liar || other.liar, } }; } pick!( throttle_conn, throttle_total, latency_ms, stall_after, stall_ms, cut_after, reset_after, status, retry_after, status_count, wrong_length, change_after, version_after_requests, expire_secs, - expire_requests, expire_status, max_conns + expire_requests, expire_status, max_conns, farm ) } } diff --git a/crates/testserver/src/http.rs b/crates/testserver/src/http.rs index b2e6cc8..ba0e3a3 100644 --- a/crates/testserver/src/http.rs +++ b/crates/testserver/src/http.rs @@ -537,13 +537,17 @@ where reply = reply.with("Retry-After", r.to_string()); } - let src = reply.source.versioned(version); + let node = f.farm.filter(|n| *n > 1).map(|n| req_no % n); + let lies = f.liar && node.is_some_and(|k| k % 2 == 1); + let src = reply.source.versioned(version + u32::from(lies) * 1000); let total = src.len(); let head_only = req.method == "HEAD"; let mut status = reply.status; let mut headers = std::mem::take(&mut reply.headers); - let etag = format!("{}\"{}-v{version}\"", if reply.weak { "W/" } else { "" }, reply.id); - let modified = http_date(version); + let (etag, modified) = match node { + Some(k) => (format!("W/\"{total:x}-{:x}\"", 0x1982ea51dc7u64 + u64::from(version * 100 + k)), http_date(version * 7 + k + 1)), + None => (format!("{}\"{}-v{version}\"", if reply.weak { "W/" } else { "" }, reply.id), http_date(version)), + }; let mut range = None; let ranges_on = reply.file && !f.ignore_range && !reply.chunked && !reply.no_length; if reply.file && status == 200 { diff --git a/crates/testserver/src/lib.rs b/crates/testserver/src/lib.rs index 8ebc9ad..ab63cd4 100644 --- a/crates/testserver/src/lib.rs +++ b/crates/testserver/src/lib.rs @@ -3,7 +3,8 @@ //! `TestServer::start().await` binds 127.0.0.1 on a free port. Routes (all GET/HEAD): //! - `/data//[/]` deterministic file (`len` accepts k, m, g, t; 100g is fine). //! Query: `disp=attachment|bare|star|both|inline|evil|dotfile`, `chunked=1`, `nolen=1`, `etag=0`, -//! `lm=0`, `weak=1`, plus any fault by name (see [`Faults`]). +//! `lm=0`, `weak=1`, plus any fault by name (see [`Faults`]). `farm=N` serves it from N nodes in turn that differ in +//! Last-Modified and nginx-style ETag only; `liar=1` with it gives the odd nodes other bytes of the same size. //! - `/redirect/?to=&code=<30x>`, `/redirect/loop`, `/status/` //! - `/basic///…`, `/digest///…`, `/cookie//login` then `/cookie//…`, //! `/referrer//…`: the rest of the path is served after the check. From fc7f04ac03c1c291da477c4e8a5476046ff14cc9 Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 14:13:53 -0600 Subject: [PATCH 12/31] S048: per-version proof against a known sample, farm tests Co-Authored-By: Claude Opus 5.5 --- crates/core/src/http/download.rs | 9 +- crates/core/src/http/fetch.rs | 130 +++++++++++++++-------- crates/core/src/http/mod.rs | 2 +- crates/core/tests/farm.rs | 172 +++++++++++++++++++++++++++++++ crates/testserver/src/content.rs | 2 +- crates/testserver/src/http.rs | 2 +- 6 files changed, 269 insertions(+), 48 deletions(-) create mode 100644 crates/core/tests/farm.rs diff --git a/crates/core/src/http/download.rs b/crates/core/src/http/download.rs index bc3fec8..cb026fd 100644 --- a/crates/core/src/http/download.rs +++ b/crates/core/src/http/download.rs @@ -182,6 +182,13 @@ async fn fetch_whole( Some(file) => resume(job, &task, file, parts, &link, compared, stop).await?, None => start(shared, job, &task, probe, &link, stop).await?, }; + // What other versions of the same size are compared with. + if link.ranges + && let Some(p) = parts.iter().find(|p| p.done > 0) + { + let n = p.done.min(fetch::SAMPLE); + link.known_sample(p.start, file.read_at(n as usize, p.start).await?); + } if let Some(size) = link.version.size { let reserving = file.clone(); blocking(move || reserving.reserve(size)).await?; @@ -203,7 +210,7 @@ async fn fetch_whole( let Ended { live, learned, gave } = run.end(); let saved = job.checkpoint(&live, &file).await; // So that a restart doesn't take its servers for another version. - if farm.load(std::sync::atomic::Ordering::Relaxed) && !was_farm { + if farm.is() && !was_farm { job.run(move |s| Ok(s.edit_task(id, |t| t.farm = true)?)).await?; } if let Some(n) = learned { diff --git a/crates/core/src/http/fetch.rs b/crates/core/src/http/fetch.rs index c649a18..6ff98c2 100644 --- a/crates/core/src/http/fetch.rs +++ b/crates/core/src/http/fetch.rs @@ -6,8 +6,7 @@ use crate::disk::PartialFile; use crate::limit::Flow; use crate::part::LivePart; use bytes::Bytes; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; use std::time::Instant; /// Finished bytes read again and compared when a part goes on. @@ -15,7 +14,7 @@ pub const OVERLAP: u64 = 4096; /// Finished bytes compared with a reply of another version of the same size, and on a farm when a part goes on. pub const SAMPLE: u64 = 64 * 1024; /// Replies asked for until one of the known version and one of another can be compared. -const PROOF_TRIES: u32 = 8; +const PROOF_TRIES: u32 = 12; /// Held in memory for each part. const BUFFER: usize = 512 * 1024; /// A slow part writes what it has this often. @@ -30,22 +29,51 @@ pub struct Link { pub ranges: bool, /// The first version seen, kept for display and as the one the bytes on disk are of. pub version: Validators, - /// Its servers differ in dates and tags but were shown to have the same bytes: only size and bytes count. Shared by clones. - pub farm: Arc, + /// Shared by clones. + pub farm: Arc, +} + +/// Servers behind one link that differ in dates and tags. Each other version counts once its bytes were shown to be the same. +#[derive(Debug, Default)] +pub struct Farm { + /// Known to be one from before. + stored: bool, + proven: Mutex>, + /// Bytes of the known version at an offset, that other versions are compared with. + sample: Mutex)>>, +} + +impl Farm { + pub fn is(&self) -> bool { + self.stored || !self.proven.lock().unwrap().is_empty() + } } impl Link { pub fn new(client: Client, source: Source, ranges: bool, version: Validators, farm: bool) -> Link { - Link { client, source, ranges, version, farm: Arc::new(AtomicBool::new(farm)) } + Link { client, source, ranges, version, farm: Arc::new(Farm { stored: farm, ..Farm::default() }) } } pub fn farm(&self) -> bool { - self.farm.load(Ordering::Relaxed) + self.farm.is() } - fn set_farm(&self) { - if !self.farm.swap(true, Ordering::Relaxed) { - log::info!("{}: servers differ in dates only, telling versions by size and bytes", self.source.url); + /// Finished bytes at `at`, of the version the bytes here are of. + pub(super) fn known_sample(&self, at: u64, data: Vec) { + self.farm.sample.lock().unwrap().get_or_insert((at, data)); + } + + /// Of the version the bytes here are of, or of one shown to have the same bytes. + fn sure(&self, version: &Validators) -> bool { + self.version.same_file(version) || self.farm.proven.lock().unwrap().iter().any(|p| p == version) + } + + /// `version` has the same bytes as the known one. + fn proven(&self, version: Validators) { + let mut proven = self.farm.proven.lock().unwrap(); + if !proven.contains(&version) { + log::info!("{}: another server has the same bytes ({:?}, {:?})", self.source.url, version.etag, version.last_modified); + proven.push(version); } } } @@ -74,7 +102,7 @@ pub(super) async fn fetch_within( let (mut response, mut known, mut unsure) = if link.ranges { range(link, part, file, &mut stop).await? } else { - (whole(link, part, body, &mut stop).await?, vec![], false) + (whole(link, part, body, &mut stop).await?, vec![], None) }; part.begin(); let mut buf = Vec::with_capacity(BUFFER); @@ -98,10 +126,11 @@ pub(super) async fn fetch_within( return Err(Error::Changed); } known.drain(..old.len()); - // Another version's reply had the bytes that are here: the servers differ in dates only. - if unsure && known.is_empty() { - link.set_farm(); - unsure = false; + // Another version's reply had the bytes that are here: its server differs in dates only. + if known.is_empty() + && let Some(version) = unsure.take() + { + link.proven(version); } // Piece by piece, as fast as the limits have it. One chunk is read ahead, so that the sender has room again before // all is used up. @@ -171,17 +200,17 @@ async fn flush(part: &LivePart, file: &PartialFile, buf: Vec) -> Result Result<(Response, Vec, bool)> { +async fn range(link: &Link, part: &LivePart, file: &PartialFile, stop: &mut Stop) -> Result<(Response, Vec, Option)> { let p = part.get(); let mut overlap = p.done.min(if link.farm() { SAMPLE } else { OVERLAP }); loop { let first = p.start + p.done - overlap; if p.done == 0 { - return Ok((sure_range(link, first, p.end, stop).await?, vec![], false)); + return Ok((sure_range(link, first, p.end, stop).await?, vec![], None)); } let (response, unsure) = send_range(link, first, p.end, stop).await?; // Enough of the bytes here to tell another version from the same file on another server. - if unsure && overlap < p.done.min(SAMPLE) { + if unsure.is_some() && overlap < p.done.min(SAMPLE) { overlap = p.done.min(SAMPLE); continue; } @@ -192,45 +221,53 @@ async fn range(link: &Link, part: &LivePart, file: &PartialFile, stop: &mut Stop /// A range from the known version, or from another one shown to have the same bytes. async fn sure_range(link: &Link, first: u64, end: Option, stop: &mut Stop) -> Result { - let (response, unsure) = send_range(link, first, end, stop).await?; - if !unsure { - return Ok(response); + for _ in 0..PROOF_TRIES { + let (response, unsure) = send_range(link, first, end, stop).await?; + if unsure.is_none() { + return Ok(response); + } + drop(response); + // Only replies of the same size are unsure, so the size is known. + let until = end.or(link.version.size).unwrap_or(first); + prove(link, first, (until - first).min(SAMPLE), stop).await?; } - drop(response); - // Only replies of the same size are unsure, so the size is known. - let until = end.or(link.version.size).unwrap_or(first); - prove(link, first, (until - first).min(SAMPLE), stop).await?; - Ok(send_range(link, first, end, stop).await?.0) + Err(Error::Changed) } -/// Asks for `len` bytes at `at` until a reply of the known version and one of another can be compared. The same bytes make -/// the link a farm; other bytes, or no reply of the known version, mean the file changed. +/// Asks for `len` bytes at `at` until a sure reply and one of another version can be compared. The same bytes make that +/// version sure; other bytes, or no sure reply at all, mean the file changed. async fn prove(link: &Link, at: u64, len: u64, stop: &mut Stop) -> Result<()> { - let (mut known, mut other) = (None, None); + let mut other = None; for _ in 0..PROOF_TRIES { - if link.farm() { - return Ok(()); - } + // The known sample's place, once there is one. + let (at, len) = link.farm.sample.lock().unwrap().as_ref().map_or((at, len), |(at, d)| (*at, d.len() as u64)); let (response, unsure) = send_range(link, at, Some(at + len), stop).await?; let data = all(&link.client, response, len, stop).await?; if data.len() as u64 != len { return Err(Error::Cut { got: data.len() as u64, expected: Some(len) }); } - *(if unsure { &mut other } else { &mut known }) = Some(data); - if let (Some(a), Some(b)) = (&known, &other) { - if a != b { + match unsure { + Some(version) => other = Some((version, at, data)), + None => link.known_sample(at, data), + } + let sample = link.farm.sample.lock().unwrap().clone(); + if let (Some((at, known)), Some((version, other_at, data))) = (sample, &other) + && at == *other_at + && known.len() == data.len() + { + if known != *data { return Err(Error::Changed); } - link.set_farm(); + link.proven(version.clone()); return Ok(()); } } Err(Error::Changed) } -/// A reply to a range, and whether it is of another version of the same size: maybe the same file from another server of -/// a farm, which only its bytes can tell. Never unsure on a farm. -async fn send_range(link: &Link, first: u64, end: Option, stop: &mut Stop) -> Result<(Response, bool)> { +/// A reply to a range, and its version when that is another one of the same size: maybe the same file from another server +/// of a farm, which only its bytes can tell. +async fn send_range(link: &Link, first: u64, end: Option, stop: &mut Stop) -> Result<(Response, Option)> { let last = end.map(|e| (e - 1).to_string()).unwrap_or_default(); // Servers of a farm with other dates answer a date in If-Range with the whole file. let mut if_range = if link.farm() { None } else { link.version.if_range() }; @@ -241,7 +278,7 @@ async fn send_range(link: &Link, first: u64, end: Option, stop: &mut Stop) StatusCode::PARTIAL_CONTENT => { let range = ContentRange::of(headers).ok_or_else(|| Error::BadReply("no usable Content-Range".into()))?; let version = Validators::of(headers, range.total); - let unsure = !link.version.same_file(&version); + let unsure = !link.sure(&version); if unsure && !link.version.maybe_same(&version) { return Err(Error::Changed); } @@ -250,16 +287,19 @@ async fn send_range(link: &Link, first: u64, end: Option, stop: &mut Stop) } check_length(headers, range)?; check_encoding(headers, response.url())?; - return Ok((response, unsure && !link.farm())); + return Ok((response, unsure.then_some(version))); } StatusCode::OK => { let version = Validators::of(headers, content_length(headers)); - if link.version.same_file(&version) || (link.farm() && link.version.maybe_same(&version)) { + if link.version.same_file(&version) { return Err(Error::RangeIgnored); } if link.version.maybe_same(&version) && if_range.take().is_some() { continue; } + if link.farm() && link.version.maybe_same(&version) { + return Err(Error::RangeIgnored); + } return Err(if comes_as_page(link, headers) { Error::Page } else { Error::Changed }); } StatusCode::RANGE_NOT_SATISFIABLE if unsatisfied_total(headers).is_some_and(|t| link.version.size != Some(t)) => { @@ -306,8 +346,10 @@ pub async fn same_bytes(link: &Link, known: &[u8], at: u64, stop: &mut Stop) -> let len = known.len() as u64; let (response, unsure) = send_range(link, at, Some(at + len), stop).await?; let same = same_body(&link.client, response, known, stop).await?; - if same && unsure && len > 0 { - link.set_farm(); + if same && len > 0 + && let Some(version) = unsure + { + link.proven(version); } Ok(same) } diff --git a/crates/core/src/http/mod.rs b/crates/core/src/http/mod.rs index 9f01caa..105fd2b 100644 --- a/crates/core/src/http/mod.rs +++ b/crates/core/src/http/mod.rs @@ -13,7 +13,7 @@ mod fuzz; pub use download::{Options, Shared, download}; pub(crate) use download::is_page; pub(crate) use fetch::{bytes_at, same_body, small}; -pub use fetch::{Link, OVERLAP, compare, fetch, same_bytes}; +pub use fetch::{Farm, Link, OVERLAP, SAMPLE, compare, fetch, same_bytes}; pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, ServerState, ServerView, Snapshot}; pub use name::{prefer as prefer_name, safe as safe_name}; pub(crate) use piece::piece; diff --git a/crates/core/tests/farm.rs b/crates/core/tests/farm.rs new file mode 100644 index 0000000..f14ccb5 --- /dev/null +++ b/crates/core/tests/farm.rs @@ -0,0 +1,172 @@ +//! Links served by a farm: servers with the same bytes but their own dates and tags (S048), and liars among them. + +use medlar_core::disk::partial_path; +use medlar_core::host::{Caps, Hosts}; +use medlar_core::http::*; +use medlar_core::model::{Task, TaskId}; +use medlar_core::segment::Rules; +use medlar_core::store::Store; +use medlar_testserver::{Faults, TestServer, expected}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::watch; + +const MB: u64 = 1 << 20; +const PATH: &str = "/data/31/8m/output.bin"; + +struct Bench { + server: TestServer, + dir: tempfile::TempDir, + store: Arc, + client: Client, + options: Options, +} + +impl Bench { + async fn new() -> Bench { + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(Store::open(&dir.path().join("medlar.db")).unwrap()); + let client = client(&ClientOptions { idle_timeout: Duration::from_millis(1500), ..ClientOptions::default() }).unwrap(); + let options = Options { + rules: Rules { min: 64 * 1024, align: 4096, min_time: Duration::ZERO }, + tick: Duration::from_millis(20), + stall: Duration::from_millis(500), + backoff: Duration::from_millis(20), + checkpoint: Duration::from_millis(15), + ..Options::default() + }; + Bench { server: TestServer::start().await, dir, store, client, options } + } + + fn add(&self) -> TaskId { + self.store.add_task(Task { url: self.server.url(PATH), folder: self.dir.path().join("files"), ..Task::default() }).unwrap() + } + + async fn run_until(&self, id: TaskId, stop: Stop) -> Result { + let source = Source::new(&self.store.task(id).unwrap().url).unwrap(); + let hosts = Hosts::new(Caps { burst: 100, per_second: 100.0, ..Caps::default() }); + let shared = Shared { client: self.client.clone(), store: self.store.clone(), hosts }; + let monitor = Monitor::new(4); + let run = download(&shared, id, source, &self.options, &monitor, stop); + tokio::time::timeout(Duration::from_secs(30), run).await.expect("hangs") + } + + async fn run(&self, id: TaskId) -> Result { + let (_keep, stop) = watch::channel(false); + self.run_until(id, stop).await + } + + /// Stops it once every part has something. + async fn half(&self, id: TaskId) { + let (halt, stop) = watch::channel(false); + let watching = async { + while self.store.parts(id).unwrap().len() < 2 || self.store.parts(id).unwrap().iter().any(|p| p.done == 0) { + tokio::time::sleep(Duration::from_millis(5)).await; + } + halt.send_replace(true); + }; + let running = self.run_until(id, stop); + tokio::pin!(running); + let result = tokio::select! { + result = &mut running => result, + () = watching => running.await, + }; + assert!(matches!(result, Err(Error::Stopped)), "{result:?}"); + } + + fn partial(&self, id: TaskId) -> PathBuf { + let task = self.store.task(id).unwrap(); + partial_path(&task.folder, &task.name) + } + + fn farm(&self, nodes: u32, liar: bool, throttle: Option) { + self.server.set_faults(PATH, Faults { farm: Some(nodes), liar, throttle_conn: throttle, ..Faults::default() }); + } +} + +fn check(path: &Path) { + let data = std::fs::read(path).unwrap(); + assert_eq!(data.len() as u64, 8 * MB); + assert_eq!(Sha256::digest(&data), Sha256::digest(expected(31, 0, 8 * MB as usize))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_farm_downloads_in_parts() { + let b = Bench::new().await; + b.farm(3, false, Some(MB)); + let id = b.add(); + let done = b.run(id).await.unwrap(); + check(&done); + let log = b.server.requests_for(PATH); + let range = |r: &&medlar_testserver::Request| r.header("range")?.strip_prefix("bytes=")?.split('-').next()?.parse::().ok(); + let starts: BTreeSet<_> = log.iter().filter(|r| r.status == 206).filter_map(|r| range(&r)).collect(); + assert!(starts.len() >= 4, "parts in parallel: {starts:?}"); + assert!(b.store.task(id).unwrap().farm, "the farm is kept"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_farm_goes_on_after_a_stop() { + // With the farm known from before, and without (found again by the bytes). + for stored in [true, false] { + let b = Bench::new().await; + b.farm(3, false, Some(MB)); + let id = b.add(); + b.half(id).await; + let mut task = b.store.task(id).unwrap(); + assert!(task.farm, "found while it ran"); + let first = (task.etag.clone(), task.last_modified.clone()); + task.farm = stored; + b.store.save_task(task).unwrap(); + b.farm(3, false, None); + b.server.clear_log(); + let done = b.run(id).await.unwrap(); + check(&done); + let task = b.store.task(id).unwrap(); + // Without the flag the parts may well find replies of the first version, and nothing has to be proven again. + assert!(task.farm || !stored, "the farm is kept"); + assert_eq!((task.etag, task.last_modified), first, "the first validators stay"); + if stored { + let asked: Vec<_> = b.server.requests_for(PATH).into_iter().filter(|r| r.header("if-range").is_some()).collect(); + assert!(asked.is_empty(), "If-Range on a farm: {asked:?}"); + } + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_liar_of_the_same_size_is_another_file() { + let b = Bench::new().await; + b.farm(2, true, None); + let id = b.add(); + // Changed, or by chance all from one of them: never mixed. + match b.run(id).await { + Err(Error::Changed) => assert!(!b.store.task(id).unwrap().farm), + Ok(done) => { + let data = std::fs::read(done).unwrap(); + let liar = 31 ^ 7u64.wrapping_mul(0x1234_5678_9ABC_DEF1); + let whole = |seed| Sha256::digest(expected(seed, 0, 8 * MB as usize)); + assert!([whole(31), whole(liar)].contains(&Sha256::digest(&data)), "two files were mixed"); + } + other => panic!("{other:?}"), + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_liar_on_the_way_keeps_what_is_there() { + let b = Bench::new().await; + b.farm(2, false, Some(MB)); + let id = b.add(); + b.half(id).await; + let before = std::fs::read(b.partial(id)).unwrap(); + b.farm(2, true, None); + let result = b.run(id).await; + assert!(matches!(result, Err(Error::Changed)), "{result:?}"); + let after = std::fs::read(b.partial(id)).unwrap(); + for p in b.store.parts(id).unwrap() { + let range = p.start as usize..(p.start + p.done) as usize; + assert!(before[range.clone()] == after[range.clone()], "finished bytes were touched"); + assert!(after[range.clone()] == expected(31, p.start, p.done as usize)[..], "other bytes were kept as done"); + } +} diff --git a/crates/testserver/src/content.rs b/crates/testserver/src/content.rs index 9b13ca9..9093992 100644 --- a/crates/testserver/src/content.rs +++ b/crates/testserver/src/content.rs @@ -73,7 +73,7 @@ impl Source { pub fn versioned(&self, version: u32) -> Source { match self { Source::Gen { seed, len } if version > 0 => Source::Gen { - seed: seed ^ (u64::from(version) * 0x1234_5678_9ABC_DEF1), + seed: seed ^ u64::from(version).wrapping_mul(0x1234_5678_9ABC_DEF1), len: *len, }, other => other.clone(), diff --git a/crates/testserver/src/http.rs b/crates/testserver/src/http.rs index ba0e3a3..55c805d 100644 --- a/crates/testserver/src/http.rs +++ b/crates/testserver/src/http.rs @@ -539,7 +539,7 @@ where let node = f.farm.filter(|n| *n > 1).map(|n| req_no % n); let lies = f.liar && node.is_some_and(|k| k % 2 == 1); - let src = reply.source.versioned(version + u32::from(lies) * 1000); + let src = reply.source.versioned(version + u32::from(lies) * 7); let total = src.len(); let head_only = req.method == "HEAD"; let mut status = reply.status; From 9f38019b14650eecca9dd20fbde9dfef0eedd4d5 Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 14:17:46 -0600 Subject: [PATCH 13/31] S048: prove until the triggering version is sure; parts check counts three starts Co-Authored-By: Claude Opus 5.5 --- crates/core/src/http/fetch.rs | 16 +++++++++------- crates/core/tests/farm.rs | 2 +- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/crates/core/src/http/fetch.rs b/crates/core/src/http/fetch.rs index 6ff98c2..d67e99a 100644 --- a/crates/core/src/http/fetch.rs +++ b/crates/core/src/http/fetch.rs @@ -223,22 +223,24 @@ async fn range(link: &Link, part: &LivePart, file: &PartialFile, stop: &mut Stop async fn sure_range(link: &Link, first: u64, end: Option, stop: &mut Stop) -> Result { for _ in 0..PROOF_TRIES { let (response, unsure) = send_range(link, first, end, stop).await?; - if unsure.is_none() { - return Ok(response); - } + let Some(version) = unsure else { return Ok(response) }; drop(response); // Only replies of the same size are unsure, so the size is known. let until = end.or(link.version.size).unwrap_or(first); - prove(link, first, (until - first).min(SAMPLE), stop).await?; + prove(link, &version, first, (until - first).min(SAMPLE), stop).await?; } Err(Error::Changed) } -/// Asks for `len` bytes at `at` until a sure reply and one of another version can be compared. The same bytes make that -/// version sure; other bytes, or no sure reply at all, mean the file changed. -async fn prove(link: &Link, at: u64, len: u64, stop: &mut Stop) -> Result<()> { +/// Asks for `len` bytes at `at` until a sure reply and one of another version can be compared, and so until `version` is +/// sure. The same bytes make a version sure; other bytes, or no sure reply at all, mean the file changed. +async fn prove(link: &Link, version: &Validators, at: u64, len: u64, stop: &mut Stop) -> Result<()> { let mut other = None; for _ in 0..PROOF_TRIES { + // Maybe by another part meanwhile. + if link.sure(version) { + return Ok(()); + } // The known sample's place, once there is one. let (at, len) = link.farm.sample.lock().unwrap().as_ref().map_or((at, len), |(at, d)| (*at, d.len() as u64)); let (response, unsure) = send_range(link, at, Some(at + len), stop).await?; diff --git a/crates/core/tests/farm.rs b/crates/core/tests/farm.rs index f14ccb5..6034e43 100644 --- a/crates/core/tests/farm.rs +++ b/crates/core/tests/farm.rs @@ -103,7 +103,7 @@ async fn a_farm_downloads_in_parts() { let log = b.server.requests_for(PATH); let range = |r: &&medlar_testserver::Request| r.header("range")?.strip_prefix("bytes=")?.split('-').next()?.parse::().ok(); let starts: BTreeSet<_> = log.iter().filter(|r| r.status == 206).filter_map(|r| range(&r)).collect(); - assert!(starts.len() >= 4, "parts in parallel: {starts:?}"); + assert!(starts.len() >= 3, "parts in parallel: {starts:?}"); assert!(b.store.task(id).unwrap().farm, "the farm is kept"); } From 3500a4c25b511bfa3bb02a351a5d020b4040e9be Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 14:28:22 -0600 Subject: [PATCH 14/31] S048: farm rule only over HTTP (FTP keeps mtime as proof of change); http test builds Co-Authored-By: Claude Opus 5.5 --- crates/core/src/http/download.rs | 6 +++--- crates/core/src/http/fetch.rs | 11 ++++++++--- crates/core/src/http/mod.rs | 5 +++++ crates/core/tests/http.rs | 2 +- 4 files changed, 17 insertions(+), 7 deletions(-) diff --git a/crates/core/src/http/download.rs b/crates/core/src/http/download.rs index cb026fd..a2866e5 100644 --- a/crates/core/src/http/download.rs +++ b/crates/core/src/http/download.rs @@ -175,7 +175,7 @@ async fn fetch_whole( let here = if url == task.url { source.at(&probe.url) } else { source.mirror(&url)?.at(&probe.url) }; let mut link = Link::new(client.clone(), here, probe.ranges, probe.version.clone(), task.farm); // The bytes here are of the version first seen; replies of another one with the same size are checked by their bytes. - if !parts.is_empty() && !compared && !old(&task).same_file(&link.version) && old(&task).maybe_same(&link.version) { + if !parts.is_empty() && !compared && !old(&task).same_file(&link.version) && link.maybe_same(&old(&task)) { link.version = old(&task); } let (file, parts) = match file { @@ -283,7 +283,7 @@ async fn open_one(client: &Client, task: &Task, parts: &[Part], source: Source, if first { // Another server of a farm differs in dates only; the bytes tell when the parts go on. let old = old(task); - return if old.same_file(&probe.version) || old.maybe_same(&probe.version) { Ok((probe, false)) } else { Err(Error::Changed) }; + return if old.same_file(&probe.version) || source.web() && old.maybe_same(&probe.version) { Ok((probe, false)) } else { Err(Error::Changed) }; } let link = NewLink { url: source.url.to_string(), ..NewLink::default() }; let checked = relink::check(client, task, parts, link, source, stop).await?; @@ -372,7 +372,7 @@ async fn resume( compared: bool, stop: &mut Stop, ) -> Result<(Arc, Vec)> { - if !compared && !old(task).same_file(&link.version) && !old(task).maybe_same(&link.version) { + if !compared && !old(task).same_file(&link.version) && !link.maybe_same(&old(task)) { return Err(Error::Changed); } let file = Arc::new(file); diff --git a/crates/core/src/http/fetch.rs b/crates/core/src/http/fetch.rs index d67e99a..06ec609 100644 --- a/crates/core/src/http/fetch.rs +++ b/crates/core/src/http/fetch.rs @@ -63,6 +63,11 @@ impl Link { self.farm.sample.lock().unwrap().get_or_insert((at, data)); } + /// Of a farm's other server maybe, to be told by the bytes. Only over HTTP: other links have no farms. + pub(super) fn maybe_same(&self, version: &Validators) -> bool { + self.source.web() && self.version.maybe_same(version) + } + /// Of the version the bytes here are of, or of one shown to have the same bytes. fn sure(&self, version: &Validators) -> bool { self.version.same_file(version) || self.farm.proven.lock().unwrap().iter().any(|p| p == version) @@ -281,7 +286,7 @@ async fn send_range(link: &Link, first: u64, end: Option, stop: &mut Stop) let range = ContentRange::of(headers).ok_or_else(|| Error::BadReply("no usable Content-Range".into()))?; let version = Validators::of(headers, range.total); let unsure = !link.sure(&version); - if unsure && !link.version.maybe_same(&version) { + if unsure && !link.maybe_same(&version) { return Err(Error::Changed); } if range.first != first || end.is_some_and(|e| range.last >= e) { @@ -296,10 +301,10 @@ async fn send_range(link: &Link, first: u64, end: Option, stop: &mut Stop) if link.version.same_file(&version) { return Err(Error::RangeIgnored); } - if link.version.maybe_same(&version) && if_range.take().is_some() { + if link.maybe_same(&version) && if_range.take().is_some() { continue; } - if link.farm() && link.version.maybe_same(&version) { + if link.farm() && link.maybe_same(&version) { return Err(Error::RangeIgnored); } return Err(if comes_as_page(link, headers) { Error::Page } else { Error::Changed }); diff --git a/crates/core/src/http/mod.rs b/crates/core/src/http/mod.rs index 105fd2b..4911ce5 100644 --- a/crates/core/src/http/mod.rs +++ b/crates/core/src/http/mod.rs @@ -212,6 +212,11 @@ pub struct Source { const HOPS: usize = 10; impl Source { + /// HTTP or HTTPS, not a remote of its own (FTP, SFTP). + pub(crate) fn web(&self) -> bool { + self.remote.is_none() + } + pub fn new(url: &str) -> Result { let url = Url::parse(url).map_err(|_| Error::Link)?; let remote = Remote::of(&url).map(Arc::new); diff --git a/crates/core/tests/http.rs b/crates/core/tests/http.rs index 48aa368..c5c1744 100644 --- a/crates/core/tests/http.rs +++ b/crates/core/tests/http.rs @@ -335,7 +335,7 @@ async fn one_part(b: &Bench, path: &str, done: u64) -> (Result<()>, Vec, Par let (_keep, mut stop) = watch::channel(false); let source = Source::new(&b.server.url(path)).unwrap(); let p = probe(&b.client, &source, &mut stop).await.unwrap(); - let link = Link { client: b.client.clone(), source, ranges: true, version: p.version }; + let link = Link { client: b.client.clone(), source, ranges: true, version: p.version, farm: Default::default() }; let (file, name) = PartialFile::create(&b.folder(), "part", &Default::default()).unwrap(); std::fs::write(partial_path(&b.folder(), &name), vec![0; 200_000]).unwrap(); let part = LivePart::new(Part { start: 100_000, end: Some(200_000), done: 0 }); From 4d95d6d98c4213dcdefed673181102d42278e2dd Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 17:36:34 -0600 Subject: [PATCH 15/31] S048: test file, release notes, packaging fixes, progress Co-Authored-By: Claude Opus 5.5 --- Plans/10 Distribution/S048-server-farms.md | 12 +++---- Plans/INDEX.md | 2 +- docs/DECISIONS.md | 1 + docs/PROGRESS.md | 5 +++ docs/releases/0.1.1.md | 7 ++++ docs/tests/S048-server-farms.md | 37 ++++++++++++++++++++++ packaging/arch/PKGBUILD | 2 +- tools/package.sh | 5 +-- 8 files changed, 61 insertions(+), 10 deletions(-) create mode 100644 docs/tests/S048-server-farms.md diff --git a/Plans/10 Distribution/S048-server-farms.md b/Plans/10 Distribution/S048-server-farms.md index 790d252..d00e3a1 100644 --- a/Plans/10 Distribution/S048-server-farms.md +++ b/Plans/10 Distribution/S048-server-farms.md @@ -19,12 +19,12 @@ All 206, same size, same type; nodes differ only in mtime (nginx ETag = `"