From 2174cc97e4bd0df39beaaa726ce6cffaf2edbc81 Mon Sep 17 00:00:00 2001 From: Peterino Date: Thu, 26 Nov 2026 21:07:28 -0700 Subject: [PATCH] Show transfer speed in the desktop client The service now measures the bytes a sync, submit or clone moves and adds them to its activity events as a transfer: direction, bytes done and total, the rate over the last 3 s, and the elapsed time. On finish, the rate is the transfer's average. Running events are sent at most every 250 ms, or when the file count changes, rather than on every liblore progress event. The workspace bar shows the running transfer's direction, speed, bytes and time left under it, and keeps the last transfer's size, time and average speed until the next one. Sizes in the file list and the bar share one formatter, in units of 1024, with GB and TB. The desktop e2e checks that a submit reports bytes pushed and a sync bytes fetched. --- .ai/designs/desktop-client.md | 7 +- desktop/gui/src/explorer.cpp | 22 ++-- desktop/gui/src/main.cpp | 38 ++++++- desktop/gui/src/model.cpp | 67 +++++++++++++ desktop/gui/src/model.hpp | 22 ++++ desktop/protocol/src/lib.rs | 27 +++++ desktop/service/src/server.rs | 183 ++++++++++++++++++++++++++++++++-- scripts/desktop-e2e.py | 12 ++- 8 files changed, 348 insertions(+), 30 deletions(-) diff --git a/.ai/designs/desktop-client.md b/.ai/designs/desktop-client.md index 6e2850d..bbca304 100644 --- a/.ai/designs/desktop-client.md +++ b/.ai/designs/desktop-client.md @@ -114,7 +114,7 @@ autosync is holding back. An account is `{auth_url, user_id, name, expires_ms}`. | Event | Data | | --- | --- | -| `activity` | `{workspace, kind (sync, submit, clone), phase, progress, message}` | +| `activity` | `{workspace, kind (sync, submit, clone), phase, progress, message, transfer}`. `transfer` is `{direction (up, down), bytes_done, bytes_total, rate, elapsed_ms}` once liblore has counted bytes: `rate` is bytes per second over the last 3 s while running, and the average on `finished`. Running events come at most every 250 ms, or when the file count changes | | `workspaces` | The `status` workspaces list, after any change | | `login` | `{remote, phase (waiting, done, failed), url, code, message}` | | `locks` | `{workspace}`: someone locked or unlocked something; read `locks` and `files` again | @@ -232,7 +232,10 @@ or submit finishing. - **Workspace bar:** branch, revision, AHEAD, BEHIND or OFFLINE, LOCK ON EDIT, SIGN IN when signed out, progress, AUTO and SYNC. AUTO shows the autosync mode (OFF, 5M, ON CHANGE) and opens a popup with the mode, the interval in minutes, and LOCK BINARY FILES ON FIRST EDIT. - Autosync's warning shows under the bar. + Autosync's warning shows under the bar. While a sync, submit or clone moves bytes, a line + under the bar shows the direction, speed, bytes done of the total and the time left; once + it ends, the bar keeps the last transfer's size, time and average speed. A sync counts the + bytes of the files it writes, so files liblore restores from its local cache count too. - **Notices** from the service show as dismissable lines under the header, and the newest one and any autosync warnings go in the tray tooltip. UHDK has no OS notifications. - **FILES:** breadcrumbs with UP and REFRESH, LOCK and UNLOCK for the chosen files (ctrl- or diff --git a/desktop/gui/src/explorer.cpp b/desktop/gui/src/explorer.cpp index dc678fe..33409f6 100644 --- a/desktop/gui/src/explorer.cpp +++ b/desktop/gui/src/explorer.cpp @@ -53,17 +53,6 @@ void Note(const char *text, ImU32 colour = theme::kMuted) { theme::TextAt({p.x + 8, p.y + 2}, colour, text, p.x + ImGui::GetItemRectSize().x); } -std::string Size(uint64_t bytes) { - char out[32]; - if (bytes < 1024) - std::snprintf(out, sizeof out, "%llu B", (unsigned long long)bytes); - else if (bytes < 1024 * 1024) - std::snprintf(out, sizeof out, "%.1f KB", bytes / 1024.0); - else - std::snprintf(out, sizeof out, "%.1f MB", bytes / (1024.0 * 1024.0)); - return out; -} - ImU32 FileTint(const std::string &name) { auto ends = [&name](const char *suffix) { size_t n = std::char_traits::length(suffix); @@ -319,6 +308,11 @@ void Explorer::DrawBar(const model::Workspace &ws, const model::Repo &repo, Expl theme::Progress(ws.activity.progress < 0 ? 0 : ws.activity.progress, bar); float mw = ImGui::CalcTextSize(ws.activity.message.c_str()).x; theme::TextAt({std::max(x, button_x - 24 - bar - mw), y}, theme::kMuted, ws.activity.message.c_str(), button_x - 24 - bar); + } else if (ws.activity.last.Any()) { + // The last transfer, until the next starts. + std::string last = model::DescribeFinished(ws.activity.last); + float lw = ImGui::CalcTextSize(last.c_str()).x; + theme::TextAt({std::max(x, button_x - 12 - lw), y}, theme::kMuted, last.c_str(), button_x - 12); } ImGui::SetCursorScreenPos({button_x, p.y}); if (sign_in) { @@ -337,6 +331,8 @@ void Explorer::DrawBar(const model::Workspace &ws, const model::Repo &repo, Expl if (theme::Button("SYNC", connected && !busy && ws.signed_in, !sign_in)) host.Sync(); ImGui::SetCursorScreenPos({p.x, p.y + ImGui::GetFrameHeight() + 2 + 6}); + if (busy && ws.activity.transfer.Any()) + theme::TextColoured(theme::kSpark, model::DescribeRunning(ws.activity.transfer).c_str()); if (!ws.error.empty()) { ImGui::PushStyleColor(ImGuiCol_Text, theme::kRed); ImGui::TextWrapped("%s", ws.error.c_str()); @@ -611,7 +607,7 @@ void Explorer::DrawFileList(model::Repo &repo, ExplorerHost &host) { theme::TextAt({p.x + 30, y}, e.change == model::Action::Delete ? theme::kMuted : theme::kPaper, e.name.c_str(), p.x + size_right - 80); if (!e.dir && e.change != model::Action::Delete) { - std::string size = Size(e.size); + std::string size = model::Bytes(e.size); theme::TextAt({p.x + size_right - ImGui::CalcTextSize(size.c_str()).x, y}, theme::kMuted, size.c_str()); } float tx = p.x + state_x; @@ -654,7 +650,7 @@ void Explorer::DrawFileDetails(const model::Workspace &ws, model::Repo &repo, Ex if (listed != repo.dirs.end()) facts = std::to_string(listed->second.size()) + " items"; } else { - facts = e->change == model::Action::Delete ? "deleted here" : Size(e->size); + facts = e->change == model::Action::Delete ? "deleted here" : model::Bytes(e->size); ImU32 colour = 0; if (StateLabel(e->change, colour) && e->change != model::Action::Delete) facts += e->change == model::Action::Add ? " new here" : " changed here"; diff --git a/desktop/gui/src/main.cpp b/desktop/gui/src/main.cpp index c741602..2e420ed 100644 --- a/desktop/gui/src/main.cpp +++ b/desktop/gui/src/main.cpp @@ -204,6 +204,37 @@ bool NormalizeServerWorks() { return ok; } +// The transfer text on the workspace bar. +bool TransferTextWorks() { + model::Transfer up; + up.up = true; + up.bytes_done = uint64_t(5) << 29; // 2.5 GB + up.bytes_total = uint64_t(6) << 30; + up.rate = 40 << 20; + up.elapsed_ms = 140'400; + model::Transfer down; + down.bytes_done = 812'000; + down.elapsed_ms = 1'560; + down.rate = 812'000 / 1.56; + model::Transfer starting = down; + starting.rate = -1; + std::pair cases[] = { + {model::DescribeRunning(up), "UP 40.0 MB/s 2.5 GB of 6.0 GB 1m 30s left"}, + {model::DescribeFinished(up), "pushed 2.5 GB in 2m 20s, 40.0 MB/s"}, + {model::DescribeRunning(starting), "DOWN ... 793.0 KB"}, + {model::DescribeFinished(down), "fetched 793.0 KB in 1.6s, 508.3 KB/s"}, + {model::Bytes(17), "17 B"}, + {model::Duration(7500), "2h 05m"}, + }; + bool ok = true; + for (const auto &[got, want] : cases) + if (got != want) { + std::fprintf(stderr, "forge-desktop: --test: transfer text \"%s\", not \"%s\"\n", got.c_str(), want.c_str()); + ok = false; + } + return ok; +} + // A sign-in in progress or just finished. struct LoginState { std::string remote, url, code, phase, message; @@ -903,7 +934,12 @@ void App::HandleMessage(const json::Value &message) { w.activity.phase = params["phase"].str(); w.activity.message = params["message"].str(); w.activity.progress = float(params["progress"].num(-1)); + w.activity.transfer = model::ParseTransfer(params["transfer"]); bool done = w.activity.phase == "finished"; + if (done && w.activity.transfer.Any()) { + w.activity.last = w.activity.transfer; + w.activity.last_kind = w.activity.kind; + } if (w.activity.phase == "failed") error_ = w.name + ": " + w.activity.message; if (done && w.activity.kind == "submit" && w.id == selected_workspace_) { @@ -1586,7 +1622,7 @@ int main(int argc, char **argv) { } } if (test) { - if (!NormalizeServerWorks()) + if (!NormalizeServerWorks() || !TransferTextWorks()) return 1; // Never touch the user's own service: the spawned one inherits this directory. std::string dir, error; diff --git a/desktop/gui/src/model.cpp b/desktop/gui/src/model.cpp index 1d59810..1bbbc3b 100644 --- a/desktop/gui/src/model.cpp +++ b/desktop/gui/src/model.cpp @@ -2,6 +2,7 @@ #include "theme.hpp" +#include #include namespace model { @@ -198,6 +199,72 @@ std::vector ParseLocks(const json::Value &list) { return out; } +Transfer ParseTransfer(const json::Value &value) { + Transfer t; + if (!value.is_object()) + return t; + t.up = value["direction"].str() == "up"; + t.bytes_done = uint64_t(value["bytes_done"].num()); + t.bytes_total = uint64_t(value["bytes_total"].num()); + t.rate = value["rate"].num(-1); + t.elapsed_ms = uint64_t(value["elapsed_ms"].num()); + return t; +} + +std::string Bytes(uint64_t bytes) { + static const char *const units[] = {"B", "KB", "MB", "GB", "TB"}; + double value = double(bytes); + int unit = 0; + while (value >= 1024 && unit < 4) { + value /= 1024; + ++unit; + } + char out[32]; + if (unit == 0) + std::snprintf(out, sizeof out, "%llu B", (unsigned long long)bytes); + else + std::snprintf(out, sizeof out, "%.1f %s", value, units[unit]); + return out; +} + +std::string Duration(uint64_t seconds) { + char out[32]; + if (seconds < 60) + std::snprintf(out, sizeof out, "%llus", (unsigned long long)seconds); + else if (seconds < 3600) + std::snprintf(out, sizeof out, "%llum %02llus", (unsigned long long)(seconds / 60), (unsigned long long)(seconds % 60)); + else + std::snprintf(out, sizeof out, "%lluh %02llum", (unsigned long long)(seconds / 3600), + (unsigned long long)(seconds / 60 % 60)); + return out; +} + +std::string DescribeRunning(const Transfer &t) { + std::string out = t.up ? "UP " : "DOWN "; + out += t.rate >= 0 ? Bytes(uint64_t(t.rate)) + "/s" : "..."; + out += " " + Bytes(t.bytes_done); + if (t.bytes_total) { + out += " of " + Bytes(t.bytes_total); + if (t.rate > 0 && t.bytes_total > t.bytes_done) + out += " " + Duration(uint64_t(double(t.bytes_total - t.bytes_done) / t.rate + 0.5)) + " left"; + } + return out; +} + +std::string DescribeFinished(const Transfer &t) { + std::string out = (t.up ? "pushed " : "fetched ") + Bytes(t.bytes_done) + " in "; + if (t.elapsed_ms < 10'000) { + char seconds[16]; + std::snprintf(seconds, sizeof seconds, "%.1fs", t.elapsed_ms / 1000.0); + out += seconds; + } else { + out += Duration((t.elapsed_ms + 500) / 1000); + } + if (t.rate >= 0) + out += ", " + Bytes(uint64_t(t.rate)) + "/s"; + return out; +} + std::string Short(const std::string &signature) { return signature.substr(0, 7); } diff --git a/desktop/gui/src/model.hpp b/desktop/gui/src/model.hpp index eb6d127..8baea07 100644 --- a/desktop/gui/src/model.hpp +++ b/desktop/gui/src/model.hpp @@ -15,10 +15,23 @@ namespace model { enum class Action { None, Add, Modify, Delete, Move, Copy }; Action ParseAction(const std::string &text); +// Bytes moving to or from the server during a sync, submit or clone. +struct Transfer { + bool up = false; // to the server (a push); else from it + uint64_t bytes_done = 0, bytes_total = 0; // total 0: not yet known + double rate = -1; // bytes per second; -1 until measured + uint64_t elapsed_ms = 0; + bool Any() const { return bytes_done || bytes_total; } +}; +Transfer ParseTransfer(const json::Value &value); // none (Any() false) when absent + struct Activity { std::string kind, phase; // phase: started, running, finished, failed; empty when none std::string message; float progress = -1; + Transfer transfer; // the running one's + Transfer last; // the last finished one, with its average rate + std::string last_kind; // what it was: sync, submit or clone }; struct Workspace { @@ -114,6 +127,15 @@ std::vector ParseLocks(const json::Value &list); // "a3f9c21": the first seven hex digits of a signature. std::string Short(const std::string &signature); +// "5.5 GB", "793.0 KB", "17 B": units of 1024, as the file list shows sizes. +std::string Bytes(uint64_t bytes); +// "45s", "3m 20s", "2h 05m". +std::string Duration(uint64_t seconds); +// "UP 40.0 MB/s 2.5 GB of 6.0 GB 1m 30s left" while running. +std::string DescribeRunning(const Transfer &t); +// "pushed 2.5 GB in 2m 20s, 40.0 MB/s" for one that finished; tenths of a second under 10 s. +std::string DescribeFinished(const Transfer &t); + // "2026-11-25 14:03" in local time; empty for 0. std::string Date(uint64_t timestamp_ms); diff --git a/desktop/protocol/src/lib.rs b/desktop/protocol/src/lib.rs index 88fed00..f6c8044 100644 --- a/desktop/protocol/src/lib.rs +++ b/desktop/protocol/src/lib.rs @@ -543,6 +543,33 @@ pub struct Activity { #[serde(skip_serializing_if = "Option::is_none")] pub progress: Option, pub message: String, + /// Bytes moving to or from the server, once liblore has counted any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub transfer: Option, +} + +/// A sync's, submit's or clone's bytes so far. On `finished`, the whole transfer: `rate` is then +/// its average. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Transfer { + pub direction: Direction, + pub bytes_done: u64, + /// 0 while liblore is still finding the work to do. + pub bytes_total: u64, + /// Bytes per second over the last few seconds; absent until there is enough to measure. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rate: Option, + pub elapsed_ms: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Direction { + /// To the server: a submit's push. + Up, + /// From the server: a sync or a clone. A sync counts the bytes of the files it writes, some + /// of which may come from the local cache rather than the network. + Down, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] diff --git a/desktop/service/src/server.rs b/desktop/service/src/server.rs index dd0bb70..3fe4914 100644 --- a/desktop/service/src/server.rs +++ b/desktop/service/src/server.rs @@ -16,6 +16,7 @@ use std::time::Instant; use forge_protocol::Account; use forge_protocol::Activity; use forge_protocol::Change; +use forge_protocol::Direction; use forge_protocol::ChangesResult; use forge_protocol::FileHistoryResult; use forge_protocol::FilesResult; @@ -35,6 +36,7 @@ use forge_protocol::Notification; use forge_protocol::PROTOCOL_VERSION; use forge_protocol::PathParams; use forge_protocol::Phase; +use forge_protocol::Transfer; use forge_protocol::RemoteParams; use forge_protocol::RepositoriesResult; use forge_protocol::Repository; @@ -259,9 +261,21 @@ impl Service { } fn activity(&self, workspace: &str, kind: &str, phase: Phase, progress: Option, message: impl Into) { + self.transfer_activity(workspace, kind, phase, progress, message, None); + } + + fn transfer_activity( + &self, + workspace: &str, + kind: &str, + phase: Phase, + progress: Option, + message: impl Into, + transfer: Option, + ) { self.notify( events::ACTIVITY, - Activity { workspace: workspace.into(), kind: kind.into(), phase, progress, message: message.into() }, + Activity { workspace: workspace.into(), kind: kind.into(), phase, progress, message: message.into(), transfer }, ); } @@ -665,14 +679,31 @@ impl Service { let service = Arc::clone(&self); let progress_id = id.clone(); let path = workspace.path.clone(); + let meter = Arc::new(Mutex::new(Meter::new(Direction::Down))); + let counted = Arc::clone(&meter); let result = self .blocking(move |lore| { let globals = lore::globals(&path); let mut outcome = None; + let mut files_shown = (0, 0); let synced = lore.revision_sync(&globals, |event| match event { Event::SyncProgress { files_done, files_total, bytes_done, bytes_total } => { - let fraction = fraction(bytes_done, bytes_total).or_else(|| fraction(files_done, files_total)); - service.activity(&progress_id, "sync", Phase::Running, fraction, format!("{files_done}/{files_total} files")); + let mut meter = counted.lock().unwrap(); + // Throttled, but a new file count always shows. + if meter.update(bytes_done, bytes_total) || files_shown != (files_done, files_total) { + files_shown = (files_done, files_total); + let fraction = fraction(bytes_done, bytes_total).or_else(|| fraction(files_done, files_total)); + let transfer = meter.running(); + drop(meter); + service.transfer_activity( + &progress_id, + "sync", + Phase::Running, + fraction, + format!("{files_done}/{files_total} files"), + transfer, + ); + } } Event::SyncRevision { number, merge, conflict, .. } => outcome = Some((number, merge, conflict)), _ => {} @@ -707,7 +738,8 @@ impl Service { self.release(&id, None); self.clear_warning(&id); self.refresh(&id).await; - self.activity(&id, "sync", Phase::Finished, Some(1.0), message); + let transfer = meter.lock().unwrap().finished(); + self.transfer_activity(&id, "sync", Phase::Finished, Some(1.0), message, transfer); } Err((_, message)) => { self.release(&id, Some(message.clone())); @@ -726,6 +758,8 @@ impl Service { let service = Arc::clone(&self); let progress_id = id.clone(); let path = workspace.path.clone(); + let meter = Arc::new(Mutex::new(Meter::new(Direction::Up))); + let counted = Arc::clone(&meter); let result = self .blocking(move |lore| { let globals = lore::globals(&path); @@ -754,10 +788,16 @@ impl Service { .map_err(|error| lore_failure("commit", error))?; } service.activity(&progress_id, "submit", Phase::Running, Some(0.4), "pushing"); + counted.lock().unwrap().restart(); lore.branch_push(&globals, |event| { if let Event::PushProgress { bytes_done, bytes_total } = event { - let fraction = fraction(bytes_done, bytes_total).map(|f| 0.4 + 0.6 * f); - service.activity(&progress_id, "submit", Phase::Running, fraction, "pushing"); + let mut meter = counted.lock().unwrap(); + if meter.update(bytes_done, bytes_total) { + let fraction = fraction(bytes_done, bytes_total).map(|f| 0.4 + 0.6 * f); + let transfer = meter.running(); + drop(meter); + service.transfer_activity(&progress_id, "submit", Phase::Running, fraction, "pushing", transfer); + } } }) .map_err(|error| lore_failure("push", error))?; @@ -782,7 +822,8 @@ impl Service { } } self.refresh(&id).await; - self.activity(&id, "submit", Phase::Finished, Some(1.0), message); + let transfer = meter.lock().unwrap().finished(); + self.transfer_activity(&id, "submit", Phase::Finished, Some(1.0), message, transfer); } Err((_, message)) => { self.release(&id, Some(message.clone())); @@ -994,13 +1035,29 @@ impl Service { let service = Arc::clone(&self); let progress_id = id.clone(); let path = workspace.path.clone(); + let meter = Arc::new(Mutex::new(Meter::new(Direction::Down))); + let counted = Arc::clone(&meter); let result = self .blocking(move |lore| { let globals = lore::globals(&path); + let mut files_shown = (0, 0); let cloned = lore.repository_clone(&globals, &url, |event| { if let Event::CloneProgress { files_done, files_total, bytes_done, bytes_total } = event { - let fraction = fraction(bytes_done, bytes_total).or_else(|| fraction(files_done, files_total)); - service.activity(&progress_id, "clone", Phase::Running, fraction, format!("{files_done}/{files_total} files")); + let mut meter = counted.lock().unwrap(); + if meter.update(bytes_done, bytes_total) || files_shown != (files_done, files_total) { + files_shown = (files_done, files_total); + let fraction = fraction(bytes_done, bytes_total).or_else(|| fraction(files_done, files_total)); + let transfer = meter.running(); + drop(meter); + service.transfer_activity( + &progress_id, + "clone", + Phase::Running, + fraction, + format!("{files_done}/{files_total} files"), + transfer, + ); + } } }); let _ = lore.repository_flush(&globals); @@ -1012,7 +1069,8 @@ impl Service { self.release(&id, None); self.refresh(&id).await; self.watch(&id); - self.activity(&id, "clone", Phase::Finished, Some(1.0), "cloned"); + let transfer = meter.lock().unwrap().finished(); + self.transfer_activity(&id, "clone", Phase::Finished, Some(1.0), "cloned", transfer); } Err((_, message)) => { // Forget the workspace; the folder and whatever arrived stay for the user. @@ -1143,6 +1201,87 @@ fn fraction(done: u64, total: u64) -> Option { (total > 0).then(|| (done as f32 / total as f32).clamp(0.0, 1.0)) } +/// Measures a transfer from liblore's running byte counts: its speed over the last few seconds, +/// and when to tell the frontends, so tens of thousands of progress events become a few a second. +struct Meter { + direction: Direction, + started: Instant, + /// Recent (time, bytes done), oldest first, spanning about [`Meter::WINDOW`]. + samples: std::collections::VecDeque<(Instant, u64)>, + done: u64, + total: u64, + sent: Option, +} + +impl Meter { + const WINDOW: std::time::Duration = std::time::Duration::from_secs(3); + const EVERY: std::time::Duration = std::time::Duration::from_millis(250); + /// Shorter than this, a rate is mostly noise. + const SHORTEST: std::time::Duration = std::time::Duration::from_millis(500); + + fn new(direction: Direction) -> Self { + Self { direction, started: Instant::now(), samples: Default::default(), done: 0, total: 0, sent: None } + } + + /// Starts timing again, for a transfer that follows other work (a push after staging). + fn restart(&mut self) { + *self = Self::new(self.direction); + } + + /// Records a count; true when it is time to tell the frontends. + fn update(&mut self, done: u64, total: u64) -> bool { + self.update_at(Instant::now(), done, total) + } + + fn update_at(&mut self, now: Instant, done: u64, total: u64) -> bool { + self.done = done; + self.total = total; + self.samples.push_back((now, done)); + // Keep one sample older than the window, so the rate always spans the whole of it. + while self.samples.len() > 2 && now.duration_since(self.samples[1].0) >= Self::WINDOW { + self.samples.pop_front(); + } + let due = self.sent.is_none_or(|sent| now.duration_since(sent) >= Self::EVERY); + if due { + self.sent = Some(now); + } + due + } + + fn rate(&self) -> Option { + let (&(first, from), &(last, to)) = (self.samples.front()?, self.samples.back()?); + let span = last.duration_since(first); + (span >= Self::SHORTEST).then(|| to.saturating_sub(from) as f64 / span.as_secs_f64()) + } + + fn running(&self) -> Option { + self.transfer(self.rate(), Instant::now()) + } + + /// The whole transfer, with its average rate; none when no bytes moved. + fn finished(&self) -> Option { + self.finished_at(Instant::now()) + } + + fn finished_at(&self, now: Instant) -> Option { + if self.done == 0 { + return None; + } + let elapsed = now.duration_since(self.started).as_secs_f64(); + self.transfer((elapsed > 0.0).then(|| self.done as f64 / elapsed), now) + } + + fn transfer(&self, rate: Option, now: Instant) -> Option { + (self.done > 0 || self.total > 0).then(|| Transfer { + direction: self.direction, + bytes_done: self.done, + bytes_total: self.total, + rate, + elapsed_ms: now.duration_since(self.started).as_millis() as u64, + }) + } +} + fn canonical(path: &str) -> Result { std::fs::canonicalize(path) .map(|path| path.to_string_lossy().into_owned()) @@ -1182,6 +1321,30 @@ mod tests { use super::*; + #[test] + fn meter_measures_the_last_few_seconds_and_throttles() { + let mut meter = Meter::new(Direction::Up); + let start = meter.started; + let at = |ms| start + Duration::from_millis(ms); + assert!(meter.update_at(at(0), 0, 1000)); + assert!(!meter.update_at(at(100), 10, 1000), "within 250 ms of the last report"); + assert_eq!(meter.rate(), None, "too short to measure"); + // 10 bytes a second for 4 s, then 100 a second: the window sees only the fast part. + for s in 1..=4 { + meter.update_at(at(s * 1000), s * 10, 1000); + } + for s in 1..=4 { + meter.update_at(at(4000 + s * 1000), 40 + s * 100, 1000); + } + let rate = meter.rate().unwrap(); + assert!((rate - 100.0).abs() < 1e-9, "{rate}"); + assert!(meter.update_at(at(8300), 440, 1000), "a report is due again"); + let done = meter.finished_at(at(10_000)).unwrap(); + assert_eq!((done.direction, done.bytes_done, done.bytes_total, done.elapsed_ms), (Direction::Up, 440, 1000, 10_000)); + assert!((done.rate.unwrap() - 44.0).abs() < 1e-9, "the average over the whole transfer"); + assert_eq!(Meter::new(Direction::Down).finished(), None, "nothing moved"); + } + struct Client { lines: Lines>>, write: tokio::io::WriteHalf, diff --git a/scripts/desktop-e2e.py b/scripts/desktop-e2e.py index 7749aac..58346f9 100644 --- a/scripts/desktop-e2e.py +++ b/scripts/desktop-e2e.py @@ -232,14 +232,16 @@ def main(): if changes != {("a.txt", "modify"), ("e.txt", "add"), ("kept.txt", "add")}: fail(f"changes are {changes}") service.call("submit", {"workspace": ws, "message": "From the desktop", "paths": ["a.txt", "e.txt"]}) - service.finished(ws, "submit") + pushed = service.finished(ws, "submit").get("transfer") + if not pushed or pushed["direction"] != "up" or pushed["bytes_done"] <= 0: + fail(f"the submit's transfer is {pushed}") left = [c["path"] for c in service.call("changes", {"workspace": ws})["changes"]] if left != ["kept.txt"]: fail(f"after submit the changes are {left}") newest = service.call("history", {"workspace": ws})["revisions"][0] if newest["message"] != "From the desktop" or newest["author"] != "alice": fail(f"the newest revision is {newest}") - step(f"submitted r{newest['number']}, kept.txt left out") + step(f"submitted r{newest['number']}, kept.txt left out; pushed {pushed['bytes_done']} bytes") # The CLI's working copy, added and synced: it gets the desktop's revision. cli = os.path.join(work, "alice-work") @@ -247,7 +249,9 @@ def main(): f.write("local\n") cli_ws = service.call("workspace_add", {"path": cli})["id"] service.call("sync_now", {"workspace": cli_ws}) - service.finished(cli_ws, "sync") + fetched = service.finished(cli_ws, "sync").get("transfer") + if not fetched or fetched["direction"] != "down" or fetched["bytes_done"] <= 0: + fail(f"the sync's transfer is {fetched}") with open(os.path.join(cli, "a.txt")) as f: if f.read().strip() != "five": fail("sync did not bring a.txt from the desktop's submit") @@ -260,7 +264,7 @@ def main(): ws_state = {w["id"]: w for w in status["workspaces"]} if ws_state[cli_ws]["revision"] != newest["number"]: fail(f"the synced workspace is at r{ws_state[cli_ws]['revision']}, not r{newest['number']}") - step(f"working copy synced to r{newest['number']}, local.txt kept") + step(f"working copy synced to r{newest['number']}, local.txt kept; fetched {fetched['bytes_done']} bytes") service.call("workspace_remove", {"workspace": cli_ws})