misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
The free-space check runs on a busy computer too; the host limit test tells a reconnect from a connection too many (#224) (#232)
Ahmed Nefzaoui026c6a2ab9a3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ca2f374e..e30d734f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -372,6 +372,12 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Changed+- **Developers: the host connection limit test tells a reconnect from a connection too many**+ ([#224](https://github.com/anefzaoui/misterdownloadmanager/issues/224)). A server sees that a+ client dropped an answer only when it next writes to it, so on a busy computer a connection+ that reconnects can be refused once while the server still counts its old answer. The lab+ server now logs, with each refusal, how far the answers holding the client's slots had been+ sent; the test fails only for a refusal none of them explains.- **The help shows what it describes** ([#228](https://github.com/anefzaoui/misterdownloadmanager/issues/228)):every guide and the main help pages now have pictures of the windows they explain, cropped towhat matters, numbered where a step points at one control, and step strips for the usual flows@@ -504,6 +510,15 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Fixed+- **A download too big for the drive is refused on a busy computer too**+ ([#224](https://github.com/anefzaoui/misterdownloadmanager/issues/224)): before a download+ starts, MDM checks the drive has room for it. It gave up checking after 5 seconds (a network+ drive that no longer answers can hang), counted from when it asked; on a very busy computer+ the check could wait longer than that just to start, and a download too big for its drive+ started anyway. The 5 seconds now count from when the check runs, and it asks only the+ folder's own drive instead of listing every drive, which takes well under a millisecond. A+ shared network folder (`\\server\share`) is checked too, which it wasn't before, and a+ folder that doesn't exist yet is checked on the drive it will be made on.- **The crash report window in other languages**([#204](https://github.com/anefzaoui/misterdownloadmanager/issues/204)): in any language butEnglish, the report in its box ran together on a few long lines, as its line breaks were takendiff --git a/Cargo.lock b/Cargo.lockindex 895eb679..91092812 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4552,6 +4552,8 @@ version = "0.3.0"dependencies = ["base64 0.23.1","bytes",+ "core-foundation 0.10.1",+ "core-foundation-sys","craft-atomic","crc32fast","futures",@@ -4567,6 +4569,7 @@ dependencies = ["proptest","reqwest 0.13.5","rquickjs",+ "rustix 1.1.6","rustls","rustls-platform-verifier","serde",diff --git a/ROADMAP.md b/ROADMAP.mdindex eba92af7..a9b1edb5 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -13,6 +13,10 @@ Everything below ships together, in one release, as version 0.3.0.### Done+- ✅ A download too big for its drive is refused on a very busy computer too: the free-space+ check's 5 seconds count from when it runs, not from when it was asked, and it asks only the+ folder's own drive (shared network folders too) instead of listing every drive; and the host+ connection limit test tells a reconnect from a connection too many ([#224](https://github.com/anefzaoui/misterdownloadmanager/issues/224))- ✅ The crash report window in every language: the report keeps its lines (German and Arabicran them together) and reads left to right in Arabic and Persian; **End and restart MDM** fitsits text ([#204](https://github.com/anefzaoui/misterdownloadmanager/issues/204))diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.tomlindex 31cb472e..b894137c 100644--- a/crates/engine/Cargo.toml+++ b/crates/engine/Cargo.toml@@ -21,7 +21,6 @@ tokio.workspace = truetokio-util.workspace = trueurl.workspace = truehttpdate.workspace = true-sysinfo.workspace = truesha2.workspace = truemd-5.workspace = truesha1.workspace = true@@ -46,10 +45,22 @@ rustls-platform-verifier.workspace = truetokio-rustls.workspace = true[target.'cfg(windows)'.dependencies]-# Sparse part files only (src/sparse.rs, D-008 amendment).+# Sparse part files (src/sparse.rs, D-008 amendment) and the free-space probe (src/disk.rs).windows-sys.workspace = true+[target.'cfg(unix)'.dependencies]+# The free-space probe (src/disk.rs): statvfs and statfs, safely (already in the tree).+rustix = { version = "1.1.6", features = ["fs"] }++[target.'cfg(target_vendor = "apple")'.dependencies]+# The free-space probe (src/disk.rs) asks for the space Finder shows, purgeable space included+# (already in the tree through security-framework).+core-foundation = "0.10.1"+core-foundation-sys = "0.8.7"+[dev-dependencies]+# The free-space probe's test compares it with the volume list it replaced (#224).+sysinfo.workspace = truemdm-labserver.workspace = trueproptest.workspace = trueserde_json.workspace = truediff --git a/crates/engine/src/disk.rs b/crates/engine/src/disk.rsindex 9521dca4..b465b65c 100644--- a/crates/engine/src/disk.rs+++ b/crates/engine/src/disk.rs@@ -1,51 +1,302 @@//! Disk preflight: will a download fit where it is going? (notes/PLAN.md "Disk preflight";//! lessons from AB Download Manager, Motrix, JDownloader, aria2.)-use std::path::Path;--use sysinfo::Disks;+use std::path::{Path, PathBuf};+use std::sync::{Arc, OnceLock};+use std::time::{Duration, Instant};/// Room kept free beyond the file itself (the OS, our list file, other programs).pub const MARGIN: u64 = 128 << 20;-/// The longest the volume probe may take before the check is skipped.-pub const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);+/// The longest the volume probe may run before the check is skipped (a stale network drive+/// can hang it), counted from when it starts running: see [`probe`].+pub const PROBE_TIMEOUT: Duration = Duration::from_secs(5);/// FAT32's largest file: 4 GiB − 1.pub const FAT32_MAX: u64 = (4 << 30) - 1;/// Free space and file system of the volume holding `path`.#[derive(Clone, Debug, PartialEq, Eq)]pub struct Volume {+ /// The bytes a new file may take, as each system counts them for the user: on Windows the+ /// space this user may use, disk quotas included (GetDiskFreeSpaceExW); on Linux and other+ /// Unix systems the blocks left to programs that aren't root (statvfs's `f_bavail`); on+ /// macOS the volume's capacity "for important usage", which includes the purgeable space+ /// (caches, local snapshots) the system frees as soon as a program writes. Finder shows the+ /// same number; statvfs leaves the purgeable space out, and would refuse a download that+ /// fits.pub free: u64,+ /// As the system names it (`NTFS`, `FAT32`, `exFAT`; `ext4`, `vfat`; `apfs`, `msdos`), or+ /// empty when it can't tell: the space is still checked.pub file_system: String,}-/// The volume with the longest mount point that contains `path` (None when unknown, e.g. a-/// network path sysinfo doesn't list: the check is then skipped).+/// The volume `path` is on, or will be once created: a missing folder is looked up through the+/// nearest folder above it that exists. Only that volume is asked (a network drive too). None+/// when no folder of the path exists (a removed drive) or the system can't tell: the check is+/// then skipped.pub fn volume_of(path: &Path) -> Option<Volume> {- let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_owned());- let disks = Disks::new_with_refreshed_list().ok()?;- disks- .iter()- .filter(|d| starts_with_ignoring_verbatim(&path, d.mount_point()))- .max_by_key(|d| d.mount_point().as_os_str().len())- .map(|d| Volume {- free: d.available_space(),- file_system: d.file_system().to_string_lossy().into_owned(),+ let path = if path.as_os_str().is_empty() {+ Path::new(".")+ } else {+ path+ };+ let path = std::path::absolute(path).ok()?;+ let dir = path.ancestors().find(|p| p.is_dir())?;+ imp::volume_of(dir)+}++/// [`volume_of`] off the async threads, skipped (None) if it runs for [`PROBE_TIMEOUT`].+///+/// The time counts from when the probe starts, not from when it is asked for: on a starved CPU+/// the blocking thread itself can take seconds to start (#224: 1 in 90 starved runs refused+/// nothing, the check skipped though the probe takes under a millisecond). Waiting for a+/// thread is not a hung drive.+pub async fn probe(path: PathBuf) -> Option<Volume> {+ bounded(move || volume_of(&path), PROBE_TIMEOUT)+ .await+ .flatten()+}++/// `f` on a blocking thread, given up (None) once it has run for `limit`.+async fn bounded<T: Send + 'static>(+ f: impl FnOnce() -> T + Send + 'static,+ limit: Duration,+) -> Option<T> {+ let started = Arc::new(OnceLock::new());+ let mut task = tokio::task::spawn_blocking({+ let started = started.clone();+ move || {+ let _ = started.set(Instant::now());+ f()+ }+ });+ loop {+ let left = started+ .get()+ .map_or(limit, |t: &Instant| limit.saturating_sub(t.elapsed()));+ match tokio::time::timeout(left, &mut task).await {+ Ok(done) => return done.ok(),+ Err(_) if started.get().is_some_and(|t| t.elapsed() >= limit) => return None,+ // Not started yet, or only just: wait on.+ Err(_) => {}+ }+ }+}++#[cfg(windows)]+#[allow(unsafe_code)] // Two calls; the engine's other unsafe code is in `crate::sparse`.+mod imp {+ use std::os::windows::ffi::OsStrExt;+ use std::os::windows::fs::OpenOptionsExt;+ use std::os::windows::io::AsRawHandle;+ use std::path::Path;++ use windows_sys::Win32::Storage::FileSystem::{+ FILE_FLAG_BACKUP_SEMANTICS, GetDiskFreeSpaceExW, GetVolumeInformationByHandleW,+ };++ pub fn volume_of(dir: &Path) -> Option<super::Volume> {+ // A folder of the volume; a share's root (`\\server\share\`) needs its backslash.+ let mut wide: Vec<u16> = dir.as_os_str().encode_wide().collect();+ if !matches!(wide.last(), Some(&c) if c == u16::from(b'\\') || c == u16::from(b'/')) {+ wide.push(u16::from(b'\\'));+ }+ wide.push(0);+ let mut free = 0u64;+ // SAFETY: `wide` is a NUL-terminated UTF-16 path that outlives the call; `free` is a+ // valid u64 (the space this user may use, quotas included); the two other outputs are+ // optional and left null.+ let ok = unsafe {+ GetDiskFreeSpaceExW(+ wide.as_ptr(),+ &mut free,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ )+ };+ if ok == 0 {+ return None;+ }+ Some(super::Volume {+ free,+ file_system: file_system(dir).unwrap_or_default(),})+ }++ /// The file system of the volume the folder really is on (through junctions and mounted+ /// folders), from a handle to the folder that asks for no access.+ fn file_system(dir: &Path) -> Option<String> {+ let dir = std::fs::OpenOptions::new()+ .access_mode(0)+ .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)+ .open(dir)+ .ok()?;+ // MAX_PATH + 1, the size the documentation asks for.+ let mut name = [0u16; 261];+ // SAFETY: `dir` owns the handle and outlives the call; `name` is a writable buffer of+ // the length passed; every other output is optional and left null (with size 0).+ let ok = unsafe {+ GetVolumeInformationByHandleW(+ dir.as_raw_handle(),+ std::ptr::null_mut(),+ 0,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ name.as_mut_ptr(),+ name.len() as u32,+ )+ };+ if ok == 0 {+ return None;+ }+ let len = name.iter().position(|&c| c == 0).unwrap_or(name.len());+ Some(String::from_utf16_lossy(&name[..len]))+ }}-/// `canonicalize` on Windows yields `\\?\C:\…`; mount points are `C:\`.-fn starts_with_ignoring_verbatim(path: &Path, mount: &Path) -> bool {- let p = path.to_string_lossy();- let p = p.strip_prefix(r"\\?\").unwrap_or(&p);- let m = mount.to_string_lossy();- p.to_ascii_lowercase().starts_with(&m.to_ascii_lowercase())+#[cfg(unix)]+mod imp {+ use std::path::Path;++ pub fn volume_of(dir: &Path) -> Option<super::Volume> {+ let st = rustix::fs::statvfs(dir).ok()?;+ let block = if st.f_frsize > 0 {+ st.f_frsize+ } else {+ st.f_bsize+ };+ // The blocks a program may use (without the reserve kept for root).+ let free = st.f_bavail.saturating_mul(block);+ #[cfg(target_vendor = "apple")]+ let free = apple::important_capacity(dir).unwrap_or(free);+ Some(super::Volume {+ free,+ file_system: file_system(dir),+ })+ }++ /// The capacity Apple's systems give "for important usage" (a download the user asked for+ /// is one): the free space plus the purgeable space the system frees on demand, as Finder+ /// shows it. Asked of the folder's volume only. `target_vendor` rather than `target_os =+ /// "macos"`, as for the file system's name below: the key is on iOS (11+) too. It needs macOS+ /// 10.13; the macOS build asks for 11.0 (build-macos.sh).+ #[cfg(target_vendor = "apple")]+ #[allow(unsafe_code)] // One call and its key; the engine's other unsafe code is in `crate::sparse`.+ mod apple {+ use std::path::Path;++ use core_foundation::base::{CFType, TCFType};+ use core_foundation::number::CFNumber;+ use core_foundation::url::CFURL;+ use core_foundation_sys::base::{Boolean, CFTypeRef};+ use core_foundation_sys::error::CFErrorRef;+ use core_foundation_sys::string::CFStringRef;+ use core_foundation_sys::url::CFURLRef;++ // Both are commented out in core-foundation-sys 0.8.+ #[link(name = "CoreFoundation", kind = "framework")]+ unsafe extern "C" {+ static kCFURLVolumeAvailableCapacityForImportantUsageKey: CFStringRef;+ fn CFURLCopyResourcePropertyForKey(+ url: CFURLRef,+ key: CFStringRef,+ value: *mut CFTypeRef,+ error: *mut CFErrorRef,+ ) -> Boolean;+ }++ /// None when the system can't tell (the key unknown to the volume, a failed call): the+ /// statvfs count is used then.+ pub fn important_capacity(dir: &Path) -> Option<u64> {+ let url = CFURL::from_path(dir, true)?;+ let mut value: CFTypeRef = std::ptr::null();+ // SAFETY: `url` is a live CFURL that outlives the call; the key is a constant+ // CFString CoreFoundation exports (macOS 10.13+, iOS 11+); `value` is a writable+ // pointer the call fills with a +1 reference or leaves null; the error output is+ // optional and left null.+ let ok = unsafe {+ CFURLCopyResourcePropertyForKey(+ url.as_concrete_TypeRef(),+ kCFURLVolumeAvailableCapacityForImportantUsageKey,+ &mut value,+ std::ptr::null_mut(),+ )+ };+ if ok == 0 || value.is_null() {+ return None;+ }+ // SAFETY: a non-null `value` from a Copy function is ours to release: the CFType+ // takes that reference and releases it when dropped.+ let value = unsafe { CFType::wrap_under_create_rule(value) };+ // A CFNumber (a 64-bit integer); anything else, or a negative count, is no answer.+ let bytes = value.downcast::<CFNumber>()?.to_i64()?;+ u64::try_from(bytes).ok()+ }+ }++ /// Linux tells a file system by a number; the FAT check needs `vfat`'s, the others are+ /// named for messages.+ #[cfg(any(target_os = "linux", target_os = "android"))]+ fn file_system(dir: &Path) -> String {+ let Ok(st) = rustix::fs::statfs(dir) else {+ return String::new();+ };+ let name = match i128::from(st.f_type) {+ 0x4d44 => "vfat",+ 0x2011_bab0 => "exfat",+ 0xef53 => "ext4",+ 0x9123_683e => "btrfs",+ 0x5846_5342 => "xfs",+ 0x2fc1_2fc1 => "zfs",+ 0xf2f5_2010 => "f2fs",+ 0x0102_1994 => "tmpfs",+ 0x794c_7630 => "overlay",+ 0x6969 => "nfs",+ 0xff53_4d42 => "cifs",+ 0xfe53_4d42 => "smb2",+ 0x5346_544e => "ntfs",+ 0x7366_746e => "ntfs3",+ 0x6573_5546 => "fuse",+ _ => "",+ };+ name.to_owned()+ }++ /// macOS names it (`apfs`, `hfs`, `msdos`, `exfat`, `smbfs`).+ #[cfg(target_vendor = "apple")]+ fn file_system(dir: &Path) -> String {+ let Ok(st) = rustix::fs::statfs(dir) else {+ return String::new();+ };+ let bytes: Vec<u8> = st+ .f_fstypename+ .iter()+ .take_while(|&&c| c != 0)+ .map(|&c| c as u8)+ .collect();+ String::from_utf8_lossy(&bytes).into_owned()+ }++ /// Other Unix systems: the space only.+ #[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]+ fn file_system(_: &Path) -> String {+ String::new()+ }+}++/// Neither Windows nor Unix: no probe, the check is skipped.+#[cfg(not(any(windows, unix)))]+mod imp {+ pub fn volume_of(_: &std::path::Path) -> Option<super::Volume> {+ None+ }}/// Why a file of `size` bytes can't go on `volume`, if it can't.pub fn check(volume: &Volume, size: u64) -> Result<(), Refusal> {let fs = volume.file_system.to_ascii_uppercase();- if size > FAT32_MAX && (fs == "FAT32" || fs == "VFAT" || fs == "FAT") {+ // Windows names it FAT32 (or FAT), Linux vfat, macOS msdos.+ if size > FAT32_MAX && matches!(fs.as_str(), "FAT32" | "FAT" | "VFAT" | "MSDOS") {return Err(Refusal::TooBigForFileSystem {size,file_system: volume.file_system.clone(),@@ -111,12 +362,20 @@ mod tests {#[test]fn fat32_refuses_4_gib_files() {- assert!(check(&vol(64 << 30, "FAT32"), FAT32_MAX).is_ok());- assert!(matches!(- check(&vol(64 << 30, "FAT32"), 4 << 30),- Err(Refusal::TooBigForFileSystem { .. })- ));+ for fs in ["FAT32", "vfat", "msdos"] {+ assert!(check(&vol(64 << 30, fs), FAT32_MAX).is_ok());+ assert!(+ matches!(+ check(&vol(64 << 30, fs), 4 << 30),+ Err(Refusal::TooBigForFileSystem { .. })+ ),+ "{fs}"+ );+ }assert!(check(&vol(64 << 30, "exFAT"), 8 << 30).is_ok());+ // Unknown: the space is still checked.+ assert!(check(&vol(64 << 30, ""), 8 << 30).is_ok());+ assert!(check(&vol(1 << 30, ""), 8 << 30).is_err());}#[test]@@ -127,9 +386,137 @@ mod tests {assert_eq!(human(150 << 20), "150 MB");}+ /// The volume as `sysinfo` lists it (the probe before #224, which listed every volume).+ fn listed(path: &Path) -> Option<(u64, String)> {+ let path = std::fs::canonicalize(path).ok()?;+ let p = path.to_string_lossy().to_ascii_lowercase();+ let p = p.strip_prefix(r"\\?\").unwrap_or(&p).to_owned();+ let disks = sysinfo::Disks::new_with_refreshed_list().ok()?;+ disks+ .iter()+ .filter(|d| p.starts_with(&d.mount_point().to_string_lossy().to_ascii_lowercase()))+ .max_by_key(|d| d.mount_point().as_os_str().len())+ .map(|d| {+ (+ d.available_space(),+ d.file_system().to_string_lossy().into_owned(),+ )+ })+ }+#[test]fn finds_the_volume_of_a_real_path() {- let v = volume_of(&std::env::temp_dir()).expect("temp dir is on a listed volume");- assert!(v.free > 0 && !v.file_system.is_empty(), "{v:?}");+ let dir = tempfile::tempdir().unwrap();+ let v = volume_of(dir.path()).expect("the temp folder's volume");+ assert!(v.free > 0, "{v:?}");+ // The volume sysinfo lists, give or take what other programs wrote meanwhile. On macOS+ // sysinfo counts the important-usage capacity too (purgeable space included), so the+ // two agree there as well: statvfs alone fell short of it by more than 1 GiB on CI.+ if let Some((free, fs)) = listed(dir.path()) {+ assert!(+ v.file_system.eq_ignore_ascii_case(&fs),+ "{v:?} against {fs}"+ );+ assert!(v.free.abs_diff(free) < 1 << 30, "{v:?} against {free}");+ }+ }++ #[test]+ fn a_missing_folder_is_on_the_volume_of_the_folder_above() {+ let dir = tempfile::tempdir().unwrap();+ let missing = dir.path().join("not").join("yet");+ let v = volume_of(&missing).expect("found through its parent");+ let above = volume_of(dir.path()).unwrap();+ assert_eq!(v.file_system, above.file_system);+ assert!(v.free.abs_diff(above.free) < 1 << 30);+ // A file's path is looked up through its folder.+ let file = dir.path().join("f.bin");+ std::fs::write(&file, b"x").unwrap();+ assert_eq!(volume_of(&file).unwrap().file_system, above.file_system);+ // A relative path, and the empty one, are in the current folder.+ assert!(volume_of(Path::new("")).is_some());+ assert!(volume_of(Path::new("some/missing/folder")).is_some());+ }++ /// A runtime with one blocking thread, so a test can keep it busy.+ fn one_blocking_thread() -> tokio::runtime::Runtime {+ tokio::runtime::Builder::new_current_thread()+ .max_blocking_threads(1)+ .enable_time()+ .build()+ .unwrap()+ }++ #[test]+ fn a_probe_that_hangs_is_given_up() {+ // Given up before it ends: waited for, it would answer `Some(())`.+ let v = one_blocking_thread().block_on(bounded(+ || std::thread::sleep(Duration::from_secs(1)),+ Duration::from_millis(200),+ ));+ assert_eq!(v, None);+ }++ #[test]+ fn a_probe_that_starts_late_still_answers() {+ // #224: on a starved CPU the probe's thread started after the time the probe is given.+ // Here the only blocking thread is busy for 3 times that first.+ one_blocking_thread().block_on(async {+ let busy =+ tokio::task::spawn_blocking(|| std::thread::sleep(Duration::from_millis(600)));+ let t = Instant::now();+ let v = bounded(|| 7, Duration::from_millis(200)).await;+ assert_eq!(v, Some(7));+ assert!(+ t.elapsed() >= Duration::from_millis(500),+ "{:?}",+ t.elapsed()+ );+ busy.await.unwrap();+ });+ }++ #[test]+ fn the_probe_answers_off_the_async_threads() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("missing");+ let v = one_blocking_thread().block_on(probe(path.clone()));+ assert_eq!(+ v.map(|v| v.file_system),+ volume_of(&path).map(|v| v.file_system)+ );+ }++ #[cfg(windows)]+ #[test]+ fn a_drive_that_isnt_there_has_no_volume() {+ let free = (b'D'..=b'Z')+ .rev()+ .map(|l| format!("{}:\\", l as char))+ .find(|root| !Path::new(root).exists())+ .expect("a drive letter not in use");+ assert_eq!(volume_of(&Path::new(&free).join("Downloads")), None);+ }++ #[cfg(windows)]+ #[test]+ fn a_share_is_probed_like_a_drive() {+ // `\\?\C:\…`, and C: as the administrative share `\\localhost\C$\…` when it is there.+ let dir = tempfile::tempdir().unwrap();+ let local = volume_of(dir.path()).unwrap();+ let verbatim = volume_of(&std::fs::canonicalize(dir.path()).unwrap()).unwrap();+ assert_eq!(verbatim.file_system, local.file_system);+ let path = dir.path().to_string_lossy().into_owned();+ if let Some(rest) = path.strip_prefix("C:\\") {+ let share = std::path::PathBuf::from(format!(r"\\localhost\C$\{rest}"));+ if share.is_dir() {+ let v = volume_of(&share).expect("the share's volume");+ assert!(+ v.free.abs_diff(local.free) < 1 << 30,+ "{v:?} against {local:?}"+ );+ assert!(!v.file_system.is_empty(), "{v:?}");+ }+ }}}diff --git a/crates/engine/src/download.rs b/crates/engine/src/download.rsindex 173acaa9..d4991484 100644--- a/crates/engine/src/download.rs+++ b/crates/engine/src/download.rs@@ -1648,8 +1648,7 @@ async fn open_destination(// Will it fit? Refuse now rather than fail half-way (a drive we can't identify is skipped).if let Some(size) = size {// Off the async threads, and bounded: a stale network drive can hang the volume probe.- let probe = tokio::task::spawn_blocking(move || disk::volume_of(&folder));- if let Ok(Ok(Some(volume))) = tokio::time::timeout(disk::PROBE_TIMEOUT, probe).await {+ if let Some(volume) = disk::probe(folder).await {disk::check(&volume, size)?;}}diff --git a/crates/engine/src/sparse.rs b/crates/engine/src/sparse.rsindex 308c6d89..e839dec1 100644--- a/crates/engine/src/sparse.rs+++ b/crates/engine/src/sparse.rs@@ -6,8 +6,9 @@//! first second, so every large download paid it. A sparse file has no such fill. Elsewhere//! (`ftruncate` already makes sparse files) this is a no-op.//!-//! The engine's only unsafe code: one `DeviceIoControl` call (and, in its test, one-//! `GetCompressedFileSizeW`).+//! The engine's unsafe code: one `DeviceIoControl` call here (and, in its test, one+//! `GetCompressedFileSizeW`), and the free-space probe's calls in `crate::disk`: two on Windows,+//! one on macOS (with its CoreFoundation key, and the release of what it returns).#![allow(unsafe_code)]use std::fs::File;diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rsindex 8356183d..174c6439 100644--- a/crates/engine/tests/e2e.rs+++ b/crates/engine/tests/e2e.rs@@ -321,14 +321,34 @@ async fn a_host_connection_limit_is_learned_and_reused() {.expect("every request ends");assert!(s.log().iter().any(|e| e.outcome == "fault:max_conns"));assert_eq!(limits.cap("127.0.0.1"), Some(2), "{:?}", limits.learned());- // The next download from the host opens only what it allows: nothing is refused.+ // The next download from the host opens only what it allows: nothing is refused for a+ // connection too many. A connection that reconnects (its part done, it takes over or+ // splits another) can still be refused once: the server sees that the client dropped its+ // previous response only when it next writes to it, and on a starved CPU the new request+ // can come first (#224). That refusal is told by the server's count at the time: one of+ // the responses holding the slots had been sent up to where another part begins, so the+ // client had all it needed of it and had dropped it, or was about to.s.clear_log();let (second, size) = fetch(&s, "/gen/4M/b.bin?seed=31", 31, opts).await;assert_eq!(size, 4 << 20);+ let starts: Vec<u64> = second+ .iter()+ .filter(|e| matches!(e.status, 200 | 206))+ .map(|e| e.body_start)+ .collect();+ let done = |h: &mdm_labserver::Held| starts.iter().any(|&s| h.from < s && s <= h.sent_to);+ let too_many: Vec<_> = second+ .iter()+ .filter(|e| e.outcome == "fault:max_conns" && !e.held.iter().any(done))+ .collect();assert!(- !second.iter().any(|e| e.outcome == "fault:max_conns"),- "{:?}",- second.iter().map(|e| &e.outcome).collect::<Vec<_>>()+ too_many.is_empty(),+ "refused: {:?}; requests: {:?}",+ too_many.iter().map(|e| &e.held).collect::<Vec<_>>(),+ second+ .iter()+ .map(|e| (e.body_start, e.bytes_sent, &e.outcome))+ .collect::<Vec<_>>());}diff --git a/crates/labserver/src/lib.rs b/crates/labserver/src/lib.rsindex cbae74bd..77261cba 100644--- a/crates/labserver/src/lib.rs+++ b/crates/labserver/src/lib.rs@@ -13,4 +13,4 @@ mod server;mod streams;pub use faults::Faults;-pub use server::{Config, HELP, LabServer, LogEntry, LogSink, SlotHold};+pub use server::{Config, HELP, Held, LabServer, LogEntry, LogSink, SlotHold};diff --git a/crates/labserver/src/server.rs b/crates/labserver/src/server.rsindex 8ccc2fca..4fbacd81 100644--- a/crates/labserver/src/server.rs+++ b/crates/labserver/src/server.rs@@ -99,12 +99,26 @@ pub struct LogEntry {pub outcome: String,pub rate: Option<u64>,pub drop_at: Option<u64>,+ /// For a `fault:max_conns` refusal: the client's slots as the server counted them then.+ /// The server only sees that a client dropped a response when it next writes to it, so a+ /// response the client is done with can still hold a slot (#224).+ #[serde(default)]+ pub held: Vec<Held>,/// Counts the request as in flight until its entry is logged ([`LabServer::settled`]).#[serde(skip)]#[doc(hidden)]pub in_flight: InFlight,}+/// One of a client's `max_conns` slots at a refusal ([`LogEntry::held`]): the response holding+/// it began at file offset `from` and had been sent up to `sent_to` (exclusive). A slot held by a+/// test ([`LabServer::hold_slot`]), or a response not begun yet, shows as `0..0`.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct Held {+ pub from: u64,+ pub sent_to: u64,+}+/// A request begun and not logged yet: one of the server's in-flight count while it lives (a/// request dropped before it is logged counts out too). A copy doesn't count.#[derive(Default)]@@ -187,7 +201,8 @@ pub(crate) struct Shared {/// Requests each signed link with `uses` has served (path and query).link_uses: Mutex<HashMap<String, u64>>,conn_reqs: Mutex<HashMap<SocketAddr, u64>>,- active: Mutex<HashMap<IpAddr, u32>>,+ /// Each client's `max_conns` slots in use.+ active: Mutex<HashMap<IpAddr, Vec<Arc<SlotUse>>>>,log: Mutex<Vec<LogEntry>>,on_log: Option<LogSink>,/// The fake Drive's virus-scan pages' `uuid`s handed out (`drive`).@@ -263,6 +278,7 @@ impl Shared {outcome: String::new(),rate: None,drop_at: None,+ held: Vec::new(),in_flight: InFlight(Some(self.pending.clone())),}}@@ -464,12 +480,8 @@ impl LabServer {/// Take one of `ip`'s `max_conns` slots, as another client's response would, until the/// guard is dropped: a test holds a slot for exactly as long as it needs.pub fn hold_slot(&self, ip: IpAddr) -> SlotHold {- *self.shared.active.lock().unwrap().entry(ip).or_insert(0) += 1;SlotHold {- _slot: ActiveSlot {- shared: self.shared.clone(),- ip,- },+ _slot: ActiveSlot::take(&self.shared, ip),}}@@ -729,17 +741,58 @@ pub struct SlotHold {_slot: ActiveSlot,}+/// What holds a slot: how far its response has been sent ([`Held`]).+#[derive(Default)]+struct SlotUse {+ from: AtomicU64,+ sent_to: AtomicU64,+}++impl SlotUse {+ fn held(&self) -> Held {+ Held {+ from: self.from.load(Ordering::SeqCst),+ sent_to: self.sent_to.load(Ordering::SeqCst),+ }+ }+}+/// Releases a client's concurrent-response slot (for `max_conns`) when dropped.struct ActiveSlot {shared: Arc<Shared>,ip: IpAddr,+ used: Arc<SlotUse>,+}++impl ActiveSlot {+ /// Take one of `ip`'s slots, however many it has.+ fn take(shared: &Arc<Shared>, ip: IpAddr) -> Self {+ let mut active = shared.active.lock().unwrap();+ Self::take_locked(shared, active.entry(ip).or_default(), ip)+ }++ fn take_locked(shared: &Arc<Shared>, slots: &mut Vec<Arc<SlotUse>>, ip: IpAddr) -> Self {+ let used = Arc::new(SlotUse::default());+ slots.push(used.clone());+ ActiveSlot {+ shared: shared.clone(),+ ip,+ used,+ }+ }++ /// The response holding the slot begins at file offset `at`.+ fn begins(&self, at: u64) {+ self.used.from.store(at, Ordering::SeqCst);+ self.used.sent_to.store(at, Ordering::SeqCst);+ }}impl Drop for ActiveSlot {fn drop(&mut self) {let mut active = self.shared.active.lock().unwrap();- if let Some(n) = active.get_mut(&self.ip) {- *n = n.saturating_sub(1);+ if let Some(slots) = active.get_mut(&self.ip) {+ slots.retain(|u| !Arc::ptr_eq(u, &self.used));}}}@@ -1035,17 +1088,14 @@ pub(crate) async fn serve(}let slot = {let mut active = shared.active.lock().unwrap();- let cur = active.entry(entry.peer.ip()).or_insert(0);- if f.max_conns.is_some_and(|max| *cur >= max) {+ let slots = active.entry(entry.peer.ip()).or_default();+ if f.max_conns.is_some_and(|max| slots.len() >= max as usize) {+ entry.held = slots.iter().map(|u| u.held()).collect();drop(active);shared.record(entry, 503, "fault:max_conns");return StatusCode::SERVICE_UNAVAILABLE.into_response();}- *cur += 1;- ActiveSlot {- shared: shared.clone(),- ip: entry.peer.ip(),- }+ ActiveSlot::take_locked(&shared, slots, entry.peer.ip())};if f.once == Some(true) {let key = format!("{}?{query}", entry.path);@@ -1146,6 +1196,7 @@ pub(crate) async fn serve(entry.rate = rate;entry.drop_at = drop_at;entry.status = status.as_u16();+ slot.begins(start);let transfer = Transfer {shared: shared.clone(),@@ -1338,6 +1389,9 @@ impl Transfer {content::fill(t.seed, t.pos, &mut buf);t.pos += n;t.sent += n;+ if let Some(slot) = &t.slot {+ slot.used.sent_to.store(t.pos, Ordering::SeqCst);+ }Some((Ok(Bytes::from(buf)), t))})}diff --git a/crates/labserver/tests/http.rs b/crates/labserver/tests/http.rsindex facc5dc6..9529bd43 100644--- a/crates/labserver/tests/http.rs+++ b/crates/labserver/tests/http.rs@@ -136,6 +136,53 @@ async fn drop_after() {assert_eq!(log[0].bytes_sent, 10 * 1024);}+#[tokio::test]+async fn a_refusal_shows_how_far_the_slots_responses_were_sent() {+ // #224: the engine's test tells a reconnect the server refused because it still counted the+ // response it replaces (sent up to where another connection's part begins) from a+ // connection too many.+ let s = server("max_conns=2&rate=200K").await;+ let c = reqwest::Client::new();+ let mut first = c+ .get(s.url("/gen/1M"))+ .header("range", "bytes=4096-")+ .send()+ .await+ .unwrap();+ assert_eq!(first.status(), 206);+ let mut got = 0;+ while got < 20_000 {+ got += first.chunk().await.unwrap().unwrap().len() as u64;+ }+ let ip = "127.0.0.1".parse().unwrap();+ let hold = s.hold_slot(ip);+ let refused = c.get(s.url("/gen/1M")).send().await.unwrap();+ assert_eq!(refused.status(), 503);+ drop(hold);+ drop(first);+ let log = wait_log(&s, 2).await;+ let r = log.iter().find(|e| e.outcome == "fault:max_conns").unwrap();+ assert_eq!(r.held.len(), 2, "{:?}", r.held);+ let response = r+ .held+ .iter()+ .find(|h| h.from == 4096)+ .expect("the response");+ assert!(+ (4096 + got..=1 << 20).contains(&response.sent_to),+ "{response:?}, {got} bytes received"+ );+ assert!(+ r.held.contains(&mdm_labserver::Held::default()),+ "the test's slot"+ );+ // Other entries have none.+ assert!(+ log.iter()+ .all(|e| e.outcome == "fault:max_conns" || e.held.is_empty())+ );+}+#[tokio::test]async fn max_conns_and_fail_every() {let s = server("max_conns=1&rate=20K").await;