From 3a40898a424be3df9b6cc6d329d9d3675d79d4b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:43:03 -0800 Subject: [PATCH 001/257] craft-testkit: capture log records per thread or process wide behind the log feature Add the `log` feature with `craft_testkit::log`, the shared form of the `test_log.rs` helper in craft-libs `docx` and `wordmodel` (and WordCraft `doc` and `formats`) and of SoundCraft's process-wide logger in `clap-host/tests/editor_main_thread.rs`: - `warnings(f)` and `records(level, f)` return the closure's result with the records the calling thread logged while it ran. - `capture_global(level)` returns a handle whose `drain()` takes the records logged on every thread. `log::set_logger` can be called once per process, so the first capture fixes the mode for the test binary, and a call for the other mode returns `ModeConflict`. Compared with the copied helper: - An earlier foreign logger returns `LoggerAlreadySet` instead of an empty capture, and the closure does not run. - A capture raises the global maximum level and never lowers it. - A nested capture on the same thread returns `NestedCapture` instead of clearing the outer capture's records. - A panic in the closure ends the capture on that thread. Each capture keeps at most 4,096 records and 1 MiB of text and returns `Overflow { dropped }` past either limit. Message formatting stops at the byte limit. Only one `GlobalCapture` is alive at a time; dropping it ends the capture, and a record checked against one capture is not kept by the next. The module and its tests are native only. --- Cargo.lock | 3 + crates/testkit/Cargo.toml | 20 ++ crates/testkit/README.md | 54 +++++ crates/testkit/src/lib.rs | 6 + crates/testkit/src/log.rs | 360 ++++++++++++++++++++++++++++ crates/testkit/tests/log_foreign.rs | 33 +++ crates/testkit/tests/log_global.rs | 123 ++++++++++ crates/testkit/tests/log_thread.rs | 141 +++++++++++ 8 files changed, 740 insertions(+) create mode 100644 crates/testkit/src/log.rs create mode 100644 crates/testkit/tests/log_foreign.rs create mode 100644 crates/testkit/tests/log_global.rs create mode 100644 crates/testkit/tests/log_thread.rs diff --git a/Cargo.lock b/Cargo.lock index 7b8d513e3b..5d6d102d3d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2572,6 +2572,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "log", +] [[package]] name = "craft-text" diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d2a3b3179f..2b1484ea99 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -7,7 +7,27 @@ rust-version.workspace = true repository.workspace = true description = "Source-level platform regression guards and verification utilities for the Craft application suite" +[features] +# `log`: capture of the records a test logs, per thread or process wide. +log = ["dep:log"] + [dependencies] +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +log = { workspace = true, optional = true } + +[[test]] +name = "log_thread" +required-features = ["log"] + +[[test]] +name = "log_global" +harness = false +required-features = ["log"] + +[[test]] +name = "log_foreign" +required-features = ["log"] + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index d7208396b6..1c5e09c657 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -11,6 +11,60 @@ Source-level platform regression guards and verification utilities for the Craft 3. **`std_instant`**: Flags lines naming `std::time::Instant` outside comments without `web_time`. On `wasm32-unknown-unknown`, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), and build artifacts (`target/`, `.git/`). +## Log capture: `log` + +The `log` feature adds `craft_testkit::log` and the `log` dependency. The module is built on every target except `wasm32`. + +| Function | Captures | Returns | +|---|---|---| +| `warnings(f)` | warnings and errors logged on the calling thread while `f` runs | `Result<(T, Vec), CaptureError>` with the messages | +| `records(level, f)` | records at `level` or more severe logged on the calling thread while `f` runs | `Result<(T, Vec), CaptureError>` with level, target and message | +| `capture_global(level)` | records at `level` or more severe logged on any thread | `Result`; `drain()` takes the records captured since the last drain | + +`log::set_logger` can be called once per process, so the first capture to install the logger sets the mode for the whole test binary: per thread (`warnings`, `records`) or process wide (`capture_global`). The functions return these errors without running the closure or changing the maximum level: + +| Error | When | +|---|---| +| `LoggerAlreadySet` | another logger was installed first | +| `ModeConflict` | the binary already captures in the other mode | +| `NestedCapture` | `warnings` or `records` is called inside a capture on the same thread | +| `GlobalCaptureActive` | another `GlobalCapture` is alive; dropping it ends that capture, and the logger stays installed | + +A capture raises `log::max_level()` to the level it asks for and never lowers it. When the closure panics, the capture on that thread ends and the panic continues. Records from other threads do not appear in a per-thread capture. + +A capture keeps at most `MAX_RECORDS` (4,096) records and `MAX_BYTES` (1 MiB) of message and target text. Formatting a message stops once it passes `MAX_BYTES`. A record over either limit is dropped and counted, and the capture returns `CaptureError::Overflow { dropped }` instead of a partial list. For `drain`, the limits apply to each interval between drains. + +Run process-wide captures in a binary of their own, for example a `[[test]]` with `harness = false`: + +```rust +fn main() { + let capture = craft_testkit::log::capture_global(log::LevelFilter::Warn).expect("capture"); + std::thread::Builder::new() + .name("audio".into()) + .spawn(|| drop_the_plugin()) + .expect("spawn") + .join() + .expect("join"); + let records = capture.drain().expect("drain"); + assert!(records.iter().any(|r| r.message.contains("off the main thread"))); +} +``` + +### Origin + +| Module | Source repository | Path | Revision | +|---|---|---|---| +| `log` (per thread) | storytold/craft-libs | `crates/docx/src/test_log.rs` (the same file as `crates/wordmodel/src/test_log.rs` and WordCraft's `crates/doc/src/test_log.rs` and `crates/formats/src/test_log.rs`) | `e3e31693` | +| `log` (process wide) | storytold/soundcraft | `crates/clap-host/tests/editor_main_thread.rs:18-41` | `e6cbf761` | + +### Migration + +| Consumer | Uses | State | +|---|---|---| +| craft-libs `docx`, `wordmodel` | their private `test_log.rs` | Pending: a separate pull request switches both | +| WordCraft `doc`, `formats` | their private `test_log.rs` | Pending: a separate pull request in WordCraft | +| SoundCraft `clap-host` | the logger in `tests/editor_main_thread.rs` | Pending: a separate pull request in SoundCraft switches it to `capture_global` | + ## Epistemic Scope: Syntactic Guards vs Runtime Validation Source-level guards provide deterministic syntactic evidence about codebase structure: diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b0e61fc8b5..fad8f96902 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -14,6 +14,10 @@ //! where `std::time::Instant::now()` panics on `wasm32`. //! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests. //! +//! With the `log` feature, on targets other than `wasm32`, `log::warnings` and `log::records` +//! capture the records the calling thread logs while a closure runs, and `log::capture_global` +//! captures the records every thread logs. One test binary uses one of the two modes. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -25,6 +29,8 @@ //! rather than replace, platform integration tests and CI execution. pub mod guards; +#[cfg(all(feature = "log", not(target_arch = "wasm32")))] +pub mod log; pub use guards::{Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; diff --git a/crates/testkit/src/log.rs b/crates/testkit/src/log.rs new file mode 100644 index 0000000000..2b672c1aeb --- /dev/null +++ b/crates/testkit/src/log.rs @@ -0,0 +1,360 @@ +//! Capture of the records a test logs through the `log` crate. +//! +//! The module installs one `log::Log` implementation for the process. `log::set_logger` can be +//! called once per process, so a test binary uses one of two modes, and the first call that +//! installs the logger fixes the mode for the rest of the process: +//! +//! - Per thread: [`warnings`] and [`records`] run a closure and return its result with the records +//! logged on the calling thread while it ran. Records from other threads are not captured. +//! - Process wide: [`capture_global`] returns a [`GlobalCapture`] whose [`GlobalCapture::drain`] +//! takes the records logged on every thread since the last drain. +//! +//! A call for the other mode returns [`CaptureError::ModeConflict`]. When another logger is already +//! installed, every call returns [`CaptureError::LoggerAlreadySet`], runs no closure and leaves the +//! global maximum level as it is. +//! +//! A capture raises the global maximum level (`log::max_level`) to the level it asks for and never +//! lowers it, so a capture does not hide records from code that raised the level earlier. Each +//! capture filters by its own level. +//! +//! A capture keeps at most [`MAX_RECORDS`] records and [`MAX_BYTES`] bytes of message and target +//! text. Formatting a message stops once it passes [`MAX_BYTES`]. A record over either limit is +//! dropped and counted, and the capture then returns [`CaptureError::Overflow`] with the number +//! dropped instead of a partial list. + +use std::cell::RefCell; +use std::fmt; +use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; +use std::sync::{Mutex, MutexGuard, PoisonError}; + +use ::log::{Level, LevelFilter, Log, Metadata, Record}; + +/// The most records one capture keeps. +pub const MAX_RECORDS: usize = 4096; + +/// The most bytes of message and target text one capture keeps. +pub const MAX_BYTES: usize = 1 << 20; + +/// One captured record. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CapturedRecord { + /// The record's level. + pub level: Level, + /// The record's target, by default the module path of the call. + pub target: String, + /// The formatted message. + pub message: String, +} + +/// Why a capture could not run or could not return its records. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum CaptureError { + /// Another logger was installed in this process before this module's logger. + LoggerAlreadySet, + /// This process captures in the other mode: per thread or process wide. + ModeConflict, + /// [`warnings`] or [`records`] was called inside a capture on the same thread. + NestedCapture, + /// A [`GlobalCapture`] is still alive in this process. + GlobalCaptureActive, + /// The capture reached [`MAX_RECORDS`] or [`MAX_BYTES`] and dropped this many records. + Overflow { + /// The number of records dropped. + dropped: usize, + }, +} + +impl fmt::Display for CaptureError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::LoggerAlreadySet => f.write_str("another logger is already installed in this process"), + Self::ModeConflict => f.write_str("this process already captures logs in the other mode (per thread or process wide)"), + Self::NestedCapture => f.write_str("a log capture is already running on this thread"), + Self::GlobalCaptureActive => f.write_str("a process-wide log capture is already alive"), + Self::Overflow { dropped } => { + write!(f, "the log capture dropped {dropped} records over its limit of {MAX_RECORDS} records or {MAX_BYTES} bytes") + } + } + } +} + +impl std::error::Error for CaptureError {} + +const MODE_NONE: u8 = 0; +const MODE_THREAD: u8 = 1; +const MODE_GLOBAL: u8 = 2; + +/// The installed mode, read by the logger on every record. +static MODE: AtomicU8 = AtomicU8::new(MODE_NONE); + +/// Serializes installation and changes of the global maximum level. +static INSTALL: Mutex<()> = Mutex::new(()); + +/// The bits of [`GLOBAL_STATE`] that hold the level. +const LEVEL_BITS: u32 = 3; +const LEVEL_MASK: u64 = (1 << LEVEL_BITS) - 1; + +/// The process-wide capture's session number shifted left by [`LEVEL_BITS`], with its level as a +/// `LevelFilter` number in the low bits (`0`, `Off`, when no capture is alive). The logger reads +/// both in one load, so a record checked against one capture is never kept by a later one. +static GLOBAL_STATE: AtomicU64 = AtomicU64::new(0); + +static GLOBAL: Mutex = Mutex::new(Buffer::new()); + +/// Records kept within [`MAX_RECORDS`] and [`MAX_BYTES`], with a count of those dropped. +struct Buffer { + records: Vec, + bytes: usize, + dropped: usize, + /// For the process-wide buffer: whether a [`GlobalCapture`] is alive, and its session. + alive: bool, + session: u64, +} + +impl Buffer { + const fn new() -> Self { + Self { records: Vec::new(), bytes: 0, dropped: 0, alive: false, session: 0 } + } + + /// Keeps `record`, or counts it as dropped when it is `None` or over a limit. + fn push(&mut self, record: Option) { + let Some(record) = record else { + self.dropped = self.dropped.saturating_add(1); + return; + }; + let size = record.message.len().saturating_add(record.target.len()); + if self.records.len() >= MAX_RECORDS || size > MAX_BYTES.saturating_sub(self.bytes) { + self.dropped = self.dropped.saturating_add(1); + return; + } + self.bytes += size; + self.records.push(record); + } + + /// The kept records, or the overflow, leaving the buffer empty. + fn take(&mut self) -> Result, CaptureError> { + let records = std::mem::take(&mut self.records); + let dropped = std::mem::take(&mut self.dropped); + self.bytes = 0; + if dropped > 0 { Err(CaptureError::Overflow { dropped }) } else { Ok(records) } + } +} + +/// The per-thread capture running on a thread. +struct Scope { + level: LevelFilter, + buffer: Buffer, +} + +thread_local! { + static SCOPE: RefCell> = const { RefCell::new(None) }; +} + +/// A `fmt::Write` that keeps at most [`MAX_BYTES`] bytes and fails the write that would pass them. +struct Bounded { + text: String, + over: bool, +} + +impl fmt::Write for Bounded { + fn write_str(&mut self, s: &str) -> fmt::Result { + if s.len() > MAX_BYTES.saturating_sub(self.text.len()) { + self.over = true; + return Err(fmt::Error); + } + self.text.push_str(s); + Ok(()) + } +} + +/// The record with its message formatted, or `None` when its message or target passes +/// [`MAX_BYTES`]. +fn capture(record: &Record) -> Option { + let target = record.target(); + if target.len() > MAX_BYTES { + return None; + } + let mut message = Bounded { text: String::new(), over: false }; + // A `Display` implementation's own error leaves the text written so far. + let _ = fmt::write(&mut message, *record.args()); + if message.over { + return None; + } + Some(CapturedRecord { level: record.level(), target: target.to_owned(), message: message.text }) +} + +struct Capture; + +static CAPTURE: Capture = Capture; + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +fn thread_level() -> LevelFilter { + SCOPE.try_with(|s| s.try_borrow().ok().and_then(|s| s.as_ref().map(|s| s.level))).ok().flatten().unwrap_or(LevelFilter::Off) +} + +impl Log for Capture { + fn enabled(&self, metadata: &Metadata) -> bool { + match MODE.load(Ordering::Acquire) { + MODE_THREAD => metadata.level() <= thread_level(), + MODE_GLOBAL => metadata.level() as u64 <= GLOBAL_STATE.load(Ordering::Acquire) & LEVEL_MASK, + _ => false, + } + } + + fn log(&self, record: &Record) { + let level = record.level(); + // Each message is formatted before any capture state is borrowed or locked, so a + // `Display` implementation that logs does not find that state in use. + match MODE.load(Ordering::Acquire) { + MODE_THREAD => { + if level > thread_level() { + return; + } + let captured = capture(record); + let _ = SCOPE.try_with(|s| { + if let Ok(mut s) = s.try_borrow_mut() + && let Some(scope) = s.as_mut() + && level <= scope.level + { + scope.buffer.push(captured); + } + }); + } + MODE_GLOBAL => { + let state = GLOBAL_STATE.load(Ordering::Acquire); + if level as u64 > state & LEVEL_MASK { + return; + } + let captured = capture(record); + let mut buffer = lock(&GLOBAL); + if buffer.alive && buffer.session == state >> LEVEL_BITS { + buffer.push(captured); + } + } + _ => {} + } + } + + fn flush(&self) {} +} + +/// Installs the logger in `mode` if no mode is set, then raises the global maximum level to +/// `level`. Nothing changes when the logger cannot be installed or the mode differs. +fn install(mode: u8, level: LevelFilter) -> Result<(), CaptureError> { + let _guard = lock(&INSTALL); + match MODE.load(Ordering::Acquire) { + MODE_NONE => { + ::log::set_logger(&CAPTURE).map_err(|_| CaptureError::LoggerAlreadySet)?; + MODE.store(mode, Ordering::Release); + } + m if m == mode => {} + _ => return Err(CaptureError::ModeConflict), + } + if ::log::max_level() < level { + ::log::set_max_level(level); + } + Ok(()) +} + +/// Clears this thread's capture when dropped, including during a panic in the captured closure. +struct ScopeGuard; + +impl Drop for ScopeGuard { + fn drop(&mut self) { + let _ = SCOPE.try_with(|s| { + if let Ok(mut s) = s.try_borrow_mut() { + *s = None; + } + }); + } +} + +/// `f`'s result and the records at `level` or more severe that the calling thread logged while +/// `f` ran. +/// +/// Records logged on other threads are not captured. Returns an error without running `f` when +/// another logger is installed, when this process captures process wide, or when a capture is +/// already running on this thread. Returns [`CaptureError::Overflow`] after `f` has run when it +/// logged more than the limits allow; `f`'s result is dropped in that case. +/// +/// If `f` panics, the capture ends and the panic continues. +pub fn records(level: LevelFilter, f: impl FnOnce() -> T) -> Result<(T, Vec), CaptureError> { + let running = SCOPE.try_with(|s| s.try_borrow().map_or(true, |s| s.is_some())).unwrap_or(true); + if running { + return Err(CaptureError::NestedCapture); + } + install(MODE_THREAD, level)?; + let started = SCOPE + .try_with(|s| match s.try_borrow_mut() { + Ok(mut s) if s.is_none() => { + *s = Some(Scope { level, buffer: Buffer::new() }); + true + } + _ => false, + }) + .unwrap_or(false); + if !started { + return Err(CaptureError::NestedCapture); + } + let guard = ScopeGuard; + let out = f(); + let taken = + SCOPE.try_with(|s| s.try_borrow_mut().ok().and_then(|mut s| s.take()).map(|mut s| s.buffer.take())).ok().flatten().unwrap_or(Ok(Vec::new())); + drop(guard); + taken.map(|records| (out, records)) +} + +/// `f`'s result and the messages of the warnings and errors the calling thread logged while `f` +/// ran. +/// +/// The same as [`records`] at `LevelFilter::Warn`, keeping only each record's message. +pub fn warnings(f: impl FnOnce() -> T) -> Result<(T, Vec), CaptureError> { + records(LevelFilter::Warn, f).map(|(out, records)| (out, records.into_iter().map(|r| r.message).collect())) +} + +/// Starts capturing the records at `level` or more severe that any thread logs. +/// +/// Returns an error when another logger is installed, when this process captures per thread, or +/// when another [`GlobalCapture`] is alive. Dropping the handle stops the capture and discards +/// the records it holds; the logger stays installed, and a later call starts a new capture. +pub fn capture_global(level: LevelFilter) -> Result { + let mut buffer = lock(&GLOBAL); + if buffer.alive { + return Err(CaptureError::GlobalCaptureActive); + } + install(MODE_GLOBAL, level)?; + let session = buffer.session.wrapping_add(1) & (u64::MAX >> LEVEL_BITS); + *buffer = Buffer { alive: true, session, ..Buffer::new() }; + GLOBAL_STATE.store((session << LEVEL_BITS) | level as u64, Ordering::Release); + Ok(GlobalCapture { _private: () }) +} + +/// A live process-wide capture. See [`capture_global`]. +#[derive(Debug)] +pub struct GlobalCapture { + _private: (), +} + +impl GlobalCapture { + /// The records captured on every thread since the capture started or since the last drain, in + /// the order they reached the capture. + /// + /// Returns [`CaptureError::Overflow`] when records were dropped in that interval; the records + /// kept in that interval are then discarded, and the next interval starts empty. + pub fn drain(&self) -> Result, CaptureError> { + lock(&GLOBAL).take() + } +} + +impl Drop for GlobalCapture { + fn drop(&mut self) { + let mut buffer = lock(&GLOBAL); + let session = buffer.session; + GLOBAL_STATE.store(session << LEVEL_BITS, Ordering::Release); + *buffer = Buffer { session, ..Buffer::new() }; + } +} diff --git a/crates/testkit/tests/log_foreign.rs b/crates/testkit/tests/log_foreign.rs new file mode 100644 index 0000000000..24650a83a0 --- /dev/null +++ b/crates/testkit/tests/log_foreign.rs @@ -0,0 +1,33 @@ +//! Capture in a process where another logger was installed first. +#![cfg(not(target_arch = "wasm32"))] + +use craft_testkit::log::{CaptureError, capture_global, records, warnings}; +use log::{LevelFilter, Log, Metadata, Record}; + +struct Foreign; + +impl Log for Foreign { + fn enabled(&self, _: &Metadata) -> bool { + true + } + + fn log(&self, _: &Record) {} + + fn flush(&self) {} +} + +static FOREIGN: Foreign = Foreign; + +#[test] +fn every_capture_is_refused_and_nothing_changes() { + // The first call installs the foreign logger; this is the only test in the binary. + log::set_logger(&FOREIGN).expect("install the foreign logger"); + log::set_max_level(LevelFilter::Error); + + let mut ran = false; + assert_eq!(warnings(|| ran = true).map(|_| ()), Err(CaptureError::LoggerAlreadySet)); + assert_eq!(records(LevelFilter::Trace, || ran = true).map(|_| ()), Err(CaptureError::LoggerAlreadySet)); + assert_eq!(capture_global(LevelFilter::Trace).map(|_| ()), Err(CaptureError::LoggerAlreadySet)); + assert!(!ran, "a refused capture must not run its closure"); + assert_eq!(log::max_level(), LevelFilter::Error); +} diff --git a/crates/testkit/tests/log_global.rs b/crates/testkit/tests/log_global.rs new file mode 100644 index 0000000000..4345c2a2ce --- /dev/null +++ b/crates/testkit/tests/log_global.rs @@ -0,0 +1,123 @@ +//! Process-wide capture, in a binary without the test harness so the cases run one after another +//! on the main thread, as a `harness = false` consumer runs them. The process captures process +//! wide from the first case on. The module is native only, so on `wasm32` the binary runs nothing. + +fn main() { + // nextest lists custom-harness tests with `--list`; this binary is one test. + if std::env::args().any(|a| a == "--list") { + println!("log_global: test"); + return; + } + #[cfg(not(target_arch = "wasm32"))] + cases::run(); +} + +#[cfg(not(target_arch = "wasm32"))] +mod cases { + use std::fmt; + use std::sync::mpsc::{self, Receiver, Sender}; + + use craft_testkit::log::{CaptureError, CapturedRecord, MAX_RECORDS, capture_global, records, warnings}; + use log::{Level, LevelFilter}; + + pub fn run() { + a_record_from_another_thread_is_drained(); + the_level_filters_and_a_drain_empties_the_capture(); + a_second_live_capture_is_refused_and_a_new_one_starts_after_drop(); + a_record_checked_against_one_capture_is_not_kept_by_the_next(); + an_undrained_capture_reports_what_it_dropped(); + a_capture_does_not_lower_a_raised_maximum_level(); + per_thread_captures_are_refused_in_a_process_wide_process(); + println!("log_global: 7 cases passed"); + } + + fn a_record_from_another_thread_is_drained() { + let capture = capture_global(LevelFilter::Warn).expect("capture"); + std::thread::Builder::new() + .name("audio".into()) + .spawn(|| log::warn!(target: "clap_host", "editor dropped off the main thread")) + .expect("spawn") + .join() + .expect("join"); + assert_eq!( + capture.drain().expect("drain"), + [CapturedRecord { level: Level::Warn, target: "clap_host".into(), message: "editor dropped off the main thread".into() }] + ); + } + + fn the_level_filters_and_a_drain_empties_the_capture() { + let capture = capture_global(LevelFilter::Info).expect("capture"); + log::debug!("below info"); + log::info!("info"); + log::error!("error"); + let messages: Vec = capture.drain().expect("drain").into_iter().map(|r| r.message).collect(); + assert_eq!(messages, ["info", "error"]); + assert!(capture.drain().expect("second drain").is_empty()); + } + + fn a_second_live_capture_is_refused_and_a_new_one_starts_after_drop() { + let first = capture_global(LevelFilter::Warn).expect("capture"); + log::warn!("held by the first capture"); + assert_eq!(capture_global(LevelFilter::Warn).map(|_| ()), Err(CaptureError::GlobalCaptureActive)); + drop(first); + log::warn!("between captures"); + let second = capture_global(LevelFilter::Warn).expect("a new capture after drop"); + log::warn!("held by the second capture"); + let messages: Vec = second.drain().expect("drain").into_iter().map(|r| r.message).collect(); + assert_eq!(messages, ["held by the second capture"]); + } + + /// Signals on `started` when formatting begins, then waits on `go` before writing its text. + struct Gate { + started: Sender<()>, + go: Receiver<()>, + } + + impl fmt::Display for Gate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.started.send(()).expect("signal the start"); + self.go.recv().expect("wait for go"); + f.write_str("checked against the first capture") + } + } + + fn a_record_checked_against_one_capture_is_not_kept_by_the_next() { + let first = capture_global(LevelFilter::Warn).expect("capture"); + let (started_tx, started_rx) = mpsc::channel(); + let (go_tx, go_rx) = mpsc::channel(); + let gate = Gate { started: started_tx, go: go_rx }; + let logger = std::thread::spawn(move || log::warn!("{gate}")); + started_rx.recv().expect("formatting started"); + drop(first); + let second = capture_global(LevelFilter::Warn).expect("a new capture"); + go_tx.send(()).expect("release the formatter"); + logger.join().expect("join"); + assert!(second.drain().expect("drain").is_empty()); + } + + fn an_undrained_capture_reports_what_it_dropped() { + let capture = capture_global(LevelFilter::Warn).expect("capture"); + for i in 0..MAX_RECORDS + 2 { + log::warn!("{i}"); + } + assert_eq!(capture.drain(), Err(CaptureError::Overflow { dropped: 2 })); + log::warn!("after the overflow"); + let messages: Vec = capture.drain().expect("drain after an overflow").into_iter().map(|r| r.message).collect(); + assert_eq!(messages, ["after the overflow"]); + } + + fn a_capture_does_not_lower_a_raised_maximum_level() { + log::set_max_level(LevelFilter::Trace); + let capture = capture_global(LevelFilter::Warn).expect("capture"); + log::info!("below warn"); + assert_eq!(log::max_level(), LevelFilter::Trace); + assert!(capture.drain().expect("drain").is_empty()); + } + + fn per_thread_captures_are_refused_in_a_process_wide_process() { + let mut ran = false; + assert_eq!(warnings(|| ran = true).map(|_| ()), Err(CaptureError::ModeConflict)); + assert_eq!(records(LevelFilter::Trace, || ran = true).map(|_| ()), Err(CaptureError::ModeConflict)); + assert!(!ran, "a refused capture must not run its closure"); + } +} diff --git a/crates/testkit/tests/log_thread.rs b/crates/testkit/tests/log_thread.rs new file mode 100644 index 0000000000..9c472f806d --- /dev/null +++ b/crates/testkit/tests/log_thread.rs @@ -0,0 +1,141 @@ +//! Per-thread capture. Every test in this binary captures per thread, so the logger runs in that +//! mode for the whole process. +#![cfg(not(target_arch = "wasm32"))] + +use std::fmt; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use craft_testkit::log::{CaptureError, CapturedRecord, MAX_BYTES, MAX_RECORDS, capture_global, records, warnings}; +use log::{Level, LevelFilter}; + +#[test] +fn warnings_returns_the_result_and_the_warnings_and_errors() { + let (out, lines) = warnings(|| { + log::info!("not a warning"); + log::warn!("kept {} of {}", 3, 4); + log::error!("an error"); + log::debug!("not a warning either"); + 7 + }) + .expect("capture"); + assert_eq!(out, 7); + assert_eq!(lines, ["kept 3 of 4", "an error"]); +} + +#[test] +fn records_keep_level_and_target_at_the_requested_level() { + let ((), got) = records(LevelFilter::Info, || { + log::info!(target: "craft::test", "opened"); + log::debug!("dropped"); + log::warn!("short"); + }) + .expect("capture"); + assert_eq!( + got, + [ + CapturedRecord { level: Level::Info, target: "craft::test".into(), message: "opened".into() }, + CapturedRecord { level: Level::Warn, target: module_path!().into(), message: "short".into() }, + ] + ); +} + +// No test in this binary raises the maximum level above `Info`, so the nested-capture test can +// check that a refused `Trace` capture leaves it below `Trace`. + +#[test] +fn a_capture_does_not_lower_a_raised_maximum_level() { + log::set_max_level(LevelFilter::Info); + let ((), lines) = warnings(|| log::info!("below warn")).expect("capture"); + assert!(lines.is_empty()); + assert_eq!(log::max_level(), LevelFilter::Info); +} + +#[test] +fn a_nested_capture_is_refused_and_the_outer_one_keeps_its_records() { + let ran = AtomicBool::new(false); + let (inner, lines) = warnings(|| { + log::warn!("before"); + let inner = warnings(|| ran.store(true, Ordering::SeqCst)); + let deeper = records(LevelFilter::Trace, || ran.store(true, Ordering::SeqCst)); + log::warn!("after"); + (inner.map(|_| ()), deeper.map(|_| ())) + }) + .expect("outer capture"); + assert_eq!(inner, (Err(CaptureError::NestedCapture), Err(CaptureError::NestedCapture))); + assert!(!ran.load(Ordering::SeqCst), "a nested closure must not run"); + assert!(log::max_level() < LevelFilter::Trace, "a refused capture must not raise the maximum level"); + assert_eq!(lines, ["before", "after"]); +} + +#[test] +fn a_panic_ends_the_capture_and_the_next_one_starts_empty() { + let caught = catch_unwind(AssertUnwindSafe(|| { + warnings(|| { + log::warn!("left behind"); + panic!("closure failed"); + }) + })); + assert!(caught.is_err()); + let ((), lines) = warnings(|| log::warn!("next")).expect("a new capture after the panic"); + assert_eq!(lines, ["next"]); +} + +#[test] +fn records_from_other_threads_are_not_captured() { + let ((), lines) = warnings(|| { + std::thread::spawn(|| log::warn!("elsewhere")).join().expect("join"); + log::warn!("here"); + }) + .expect("capture"); + assert_eq!(lines, ["here"]); +} + +#[test] +fn records_over_the_count_limit_are_reported() { + let got = warnings(|| { + for i in 0..=MAX_RECORDS { + log::warn!("{i}"); + } + }); + assert_eq!(got.map(|_| ()), Err(CaptureError::Overflow { dropped: 1 })); + let ((), lines) = warnings(|| log::warn!("fits")).expect("a new capture after an overflow"); + assert_eq!(lines, ["fits"]); +} + +#[test] +fn a_message_over_the_byte_limit_is_reported() { + let long = "x".repeat(MAX_BYTES); + let got = warnings(|| { + log::warn!("short"); + log::warn!("{long}"); + }); + assert_eq!(got.map(|_| ()), Err(CaptureError::Overflow { dropped: 1 })); +} + +/// Writes one byte at a time until a write fails, counting the writes that succeed. +struct Endless<'a>(&'a AtomicUsize); + +impl fmt::Display for Endless<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for _ in 0..2 * MAX_BYTES { + f.write_str("x")?; + self.0.fetch_add(1, Ordering::SeqCst); + } + Ok(()) + } +} + +#[test] +fn formatting_a_message_stops_at_the_byte_limit() { + let written = AtomicUsize::new(0); + let got = warnings(|| log::warn!("{}", Endless(&written))); + assert_eq!(got.map(|_| ()), Err(CaptureError::Overflow { dropped: 1 })); + assert_eq!(written.load(Ordering::SeqCst), MAX_BYTES); +} + +#[test] +fn a_global_capture_is_refused_in_a_per_thread_process() { + warnings(|| ()).expect("per-thread capture installs the logger"); + assert_eq!(capture_global(LevelFilter::Warn).map(|_| ()), Err(CaptureError::ModeConflict)); +} From fc7882fc961a61ca94d4f64458afd61197de14da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:23:26 -0800 Subject: [PATCH 002/257] craft-testkit: describe where formatting a log message stops at the byte limit Formatting stops at the first write that would take the message past MAX_BYTES, so a message never passes the limit. --- crates/testkit/README.md | 2 +- crates/testkit/src/log.rs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 04f98831e8..1d238ccb40 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -32,7 +32,7 @@ The `log` feature adds `craft_testkit::log` and the `log` dependency. The module A capture raises `log::max_level()` to the level it asks for and never lowers it. When the closure panics, the capture on that thread ends and the panic continues. Records from other threads do not appear in a per-thread capture. -A capture keeps at most `MAX_RECORDS` (4,096) records and `MAX_BYTES` (1 MiB) of message and target text. Formatting a message stops once it passes `MAX_BYTES`. A record over either limit is dropped and counted, and the capture returns `CaptureError::Overflow { dropped }` instead of a partial list. For `drain`, the limits apply to each interval between drains. +A capture keeps at most `MAX_RECORDS` (4,096) records and `MAX_BYTES` (1 MiB) of message and target text. Formatting a message stops at the first write that would take it past `MAX_BYTES`. A record over either limit is dropped and counted, and the capture returns `CaptureError::Overflow { dropped }` instead of a partial list. For `drain`, the limits apply to each interval between drains. Run process-wide captures in a binary of their own, for example a `[[test]]` with `harness = false`: diff --git a/crates/testkit/src/log.rs b/crates/testkit/src/log.rs index 2b672c1aeb..d48410391f 100644 --- a/crates/testkit/src/log.rs +++ b/crates/testkit/src/log.rs @@ -18,9 +18,9 @@ //! capture filters by its own level. //! //! A capture keeps at most [`MAX_RECORDS`] records and [`MAX_BYTES`] bytes of message and target -//! text. Formatting a message stops once it passes [`MAX_BYTES`]. A record over either limit is -//! dropped and counted, and the capture then returns [`CaptureError::Overflow`] with the number -//! dropped instead of a partial list. +//! text. Formatting a message stops at the first write that would take it past [`MAX_BYTES`]. A +//! record over either limit is dropped and counted, and the capture then returns +//! [`CaptureError::Overflow`] with the number dropped instead of a partial list. use std::cell::RefCell; use std::fmt; From b6b174fda9e0e92be10606b2041d704da56e82fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:15:12 -0800 Subject: [PATCH 003/257] craft-testkit: add TempDir, a private test folder removed on drop TempDir::new(tag) makes a new folder craft-testkit-- in the system temporary directory with tempfile::Builder and returns an error instead of panicking. A taken name is skipped and its folder left alone. On Unix the folder has mode 0o700, and new() returns an error when the folder it made is a link, is open to other users or is owned by another user; such a folder is not removed. path() is the canonical path, so a temporary directory reached through a link works. file(name) rejects empty names, ".", "..", and names with "/", "\", ":" or NUL. Dropping the guard removes the folder, also when the test panics, and close() returns the removal error. The module is not built for wasm32. The tests of VectorCraft's TempDir and PdfCraft's ScratchDir that apply to this API keep their names. --- Cargo.lock | 3 + crates/testkit/Cargo.toml | 3 + crates/testkit/README.md | 31 +++ crates/testkit/src/lib.rs | 7 + crates/testkit/src/temp.rs | 442 +++++++++++++++++++++++++++++++++++++ 5 files changed, 486 insertions(+) create mode 100644 crates/testkit/src/temp.rs diff --git a/Cargo.lock b/Cargo.lock index c8aee49f29..8f53a06bfe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2573,6 +2573,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "tempfile", +] [[package]] name = "craft-text" diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d32ed735f4..cce60d08ae 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -10,5 +10,8 @@ publish = false [dependencies] +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +tempfile = "3" + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 36b87bb89d..dd41509e7e 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -11,6 +11,37 @@ Source-level platform regression guards and verification utilities for the Craft 3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. +## Test folders: `temp` + +`TempDir::new(tag)` makes a new, empty folder `craft-testkit--` in the system temporary directory and returns an error instead of panicking. Dropping it removes the folder with its contents, also when the test panics; `close()` removes it and returns the error. A folder with a name that is already taken is skipped and left as it is. On Unix the folder has mode 0o700, and `new` returns an error when the folder it made is a link, is open to other users or is owned by another user. `path()` returns the canonical path (`/private/var/...` on macOS, `\\?\...` on Windows). `file(name)` returns the path of `name` in the folder and returns `InvalidInput` for an empty name, `.`, `..`, or a name with `/`, `\`, `:` or NUL. The module is not built for `wasm32`. + +```rust +let dir = craft_testkit::TempDir::new("export")?; +std::fs::write(dir.file("out.png")?, &png)?; +``` + +| Module | Consumers | +|---|---| +| `temp` | VectorCraft, PdfCraft, CADCraft, `craft-media-testkit` | + +### Origin + +| Module | Source | Path | SHA | +|---|---|---|---| +| `temp` | storytold/vectorcraft | `crates/testkit/src/lib.rs` (`temp_dir`, `TempDir`) | `bada8e17` | +| `temp` | storytold/pdfcraft#6124 | `crates/testkit/src/scratch.rs` (`ScratchDir`) | `92e20711` | +| `temp` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` (`private_dir`) | `75a654f4` | +| `temp` | storytold/cadcraft | `crates/engine/tests/support/temp_dir.rs`, `crates/ui-egui/tests/support/temp_dir.rs` | `8e698902` | + +### Migration + +| Consumer | State | +|---|---| +| VectorCraft | Not switched. `temp_dir(tag)` shares one folder per tag in a process; its test of that is not moved. | +| PdfCraft | Not switched. `ScratchFile` has no counterpart; `TempDir::file` returns a path in a `TempDir`. | +| CADCraft | Not switched. Its `TempDir` empties a leftover folder of the same name; `temp` makes a new one. | +| `craft-media-testkit` | Not switched. `private_dir()` is unchanged. | + ## Epistemic Scope: Syntactic Guards vs Runtime Validation Source-level guards provide deterministic syntactic evidence about codebase structure: diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..94889a2551 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -15,6 +15,9 @@ //! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests, with //! size limits ([`guards::rust_sources_with_limits`]). It is not built for `wasm32`. //! +//! [`temp::TempDir`] is a new, private test folder that is removed with its contents when dropped, +//! also when the test panics. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -26,8 +29,12 @@ //! rather than replace, platform integration tests and CI execution. pub mod guards; +#[cfg(not(target_arch = "wasm32"))] +pub mod temp; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; #[cfg(not(target_arch = "wasm32"))] pub use guards::{SourceLimits, rust_sources, rust_sources_with_limits}; +#[cfg(not(target_arch = "wasm32"))] +pub use temp::TempDir; diff --git a/crates/testkit/src/temp.rs b/crates/testkit/src/temp.rs new file mode 100644 index 0000000000..1f3799b525 --- /dev/null +++ b/crates/testkit/src/temp.rs @@ -0,0 +1,442 @@ +//! Test folders that are removed with their contents when the test that made them ends. +//! +//! [`TempDir::new`] makes a new, empty folder in the system temporary directory with +//! [`tempfile::Builder`]: the name is `craft-testkit--` followed by random characters, and a +//! name that is already taken is skipped. A folder this module did not make is never emptied or +//! reused. On Unix the folder is made with mode 0o700, and before [`TempDir::new`] returns it checks +//! that the folder is a real folder, not a link, with no access for other users, and owned by the +//! user running the test. The checks apply to the created folder only, so a temporary directory +//! reached through a link (`/var` on macOS links to `/private/var`) works. +//! +//! [`TempDir::path`] returns the canonical path of the folder: `/private/var/...` on macOS, and a +//! `\\?\` path on Windows. Compare it with another canonical path, not with a join of +//! [`std::env::temp_dir`]. +//! +//! Dropping a [`TempDir`], also while a test panics, removes the folder with everything in it. A +//! link inside the folder is removed, not followed. Removal on drop is best effort: a file another +//! process holds open can stop it on Windows. [`TempDir::close`] removes the folder and returns the +//! error. A process that is killed or aborts leaves its folders behind, and later calls skip them. +//! +//! The checks read the folder once, after it is made. They do not protect against a process of the +//! same user that replaces the folder after the check. + +use std::io; +use std::path::{Path, PathBuf}; + +/// How many random characters follow the tag in a folder name. +const RANDOM_CHARS: usize = 10; + +/// The file [`TempDir::new`] makes, reads and removes in a new folder on Unix to learn which user +/// owns the files this process makes. +#[cfg(unix)] +const OWNER_PROBE: &str = ".craft-testkit-owner"; + +/// A new, empty folder in the system temporary directory, removed with its contents when dropped, +/// also when the test panics. +/// +/// Bind it to a variable that lives as long as the folder is needed. Used as a temporary, as in +/// `TempDir::new("x")?.file("a.png")`, it is dropped, and the folder removed, at the end of that +/// statement. +#[derive(Debug)] +pub struct TempDir { + /// The canonical path of the folder. + path: PathBuf, + /// Removes the folder when dropped. + dir: tempfile::TempDir, +} + +impl TempDir { + /// Makes a new folder named `craft-testkit--` in + /// [`std::env::temp_dir`]. Each call makes a folder of its own, also for calls with the same + /// tag at the same time. + /// + /// # Errors + /// + /// `InvalidInput` when `tag` is empty, `.` or `..`, or holds `/`, `\`, `:` or a NUL character. + /// The error from the file system when the folder cannot be made. An error when the folder that + /// was made is a link or another kind of entry, is open to other users, or is owned by another + /// user; such a folder is left in place. + pub fn new(tag: &str) -> io::Result { + Self::new_in(tag, &std::env::temp_dir(), RANDOM_CHARS) + } + + /// Makes the folder in `root`, with `random` random characters after the tag. + fn new_in(tag: &str, root: &Path, random: usize) -> io::Result { + one_name("tag", tag)?; + let prefix = format!("craft-testkit-{tag}-"); + let mut builder = tempfile::Builder::new(); + builder.prefix(&prefix).rand_bytes(random); + #[cfg(unix)] + builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700)); + Self::guard(builder.tempdir_in(root)?) + } + + /// Checks the folder `dir` made and returns it with its canonical path. A folder that fails the + /// check is left in place, since it may not be the one `dir` made. + fn guard(mut dir: tempfile::TempDir) -> io::Result { + if let Err(e) = verify(dir.path()) { + dir.disable_cleanup(true); + return Err(e); + } + let path = std::fs::canonicalize(dir.path())?; + Ok(Self { path, dir }) + } + + /// The canonical, absolute path of the folder. + pub fn path(&self) -> &Path { + &self.path + } + + /// The path of `name` in the folder. The file is not made. + /// + /// # Errors + /// + /// `InvalidInput` when `name` is empty, `.` or `..`, or holds `/`, `\`, `:` or a NUL + /// character, so the path always names an entry directly inside the folder. + pub fn file(&self, name: &str) -> io::Result { + one_name("file name", name)?; + Ok(self.path.join(name)) + } + + /// Removes the folder with everything in it. + /// + /// # Errors + /// + /// The error from the file system when the folder or something in it cannot be removed. + pub fn close(self) -> io::Result<()> { + self.dir.close() + } +} + +impl AsRef for TempDir { + fn as_ref(&self) -> &Path { + &self.path + } +} + +/// Returns `InvalidInput` unless `name` is one path component on every platform. +fn one_name(what: &str, name: &str) -> io::Result<()> { + if name.is_empty() || name == "." || name == ".." || name.contains(['/', '\\', ':', '\0']) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{what} {name:?} is not a single file name"))); + } + Ok(()) +} + +/// What [`verify`] reads about a folder, without following a link. +#[derive(Debug, Clone, Copy)] +struct Entry { + is_dir: bool, + is_symlink: bool, + /// The permission bits, on Unix. + mode: Option, + /// The user id of the owner, on Unix. + owner: Option, +} + +/// Checks that `path` is a folder this process made, as [`check`] describes. +fn verify(path: &Path) -> io::Result<()> { + let meta = std::fs::symlink_metadata(path)?; + #[cfg(unix)] + let (mode, owner) = (Some(std::os::unix::fs::PermissionsExt::mode(&meta.permissions())), Some(std::os::unix::fs::MetadataExt::uid(&meta))); + #[cfg(not(unix))] + let (mode, owner) = (None, None); + let entry = Entry { is_dir: meta.is_dir(), is_symlink: meta.file_type().is_symlink(), mode, owner }; + check(path, entry, || my_uid(path)) +} + +/// Returns an error unless `entry` is a real folder, not a link, with no access for group or other +/// users, owned by the user `me` returns. `me` runs only after the other checks pass. +fn check(path: &Path, entry: Entry, me: impl FnOnce() -> io::Result>) -> io::Result<()> { + if entry.is_symlink || !entry.is_dir { + return Err(io::Error::other(format!("{}: a link or another kind of entry is in place of the new folder", path.display()))); + } + if entry.mode.is_some_and(|mode| mode & 0o077 != 0) { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the new folder is open to other users", path.display()))); + } + if entry.owner != me()? { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the new folder is owned by another user", path.display()))); + } + Ok(()) +} + +/// The user id that owns a file this process makes, read from a probe file made new in `dir` and +/// removed again. +#[cfg(unix)] +fn my_uid(dir: &Path) -> io::Result> { + let probe = dir.join(OWNER_PROBE); + let meta = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?.metadata(); + std::fs::remove_file(&probe)?; + Ok(Some(std::os::unix::fs::MetadataExt::uid(&meta?))) +} + +/// Files have no Unix owner here. +#[cfg(not(unix))] +fn my_uid(_dir: &Path) -> io::Result> { + Ok(None) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entries(dir: &Path) -> usize { + std::fs::read_dir(dir).unwrap().count() + } + + #[test] + fn a_test_dir_is_removed_with_its_contents_when_dropped() { + let dir = TempDir::new("dropped").unwrap(); + let path = dir.path().to_path_buf(); + std::fs::create_dir_all(path.join("nested")).unwrap(); + std::fs::write(path.join("nested").join("a.txt"), b"a").unwrap(); + drop(dir); + assert!(!path.exists(), "{} is left", path.display()); + } + + #[test] + fn a_test_dir_is_removed_when_its_test_panics() { + let mut path = None; + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let dir = TempDir::new("panicked").unwrap(); + std::fs::write(dir.file("a.txt").unwrap(), b"a").unwrap(); + path = Some(dir.path().to_path_buf()); + panic!("the test fails"); + })); + assert_eq!(r.err().and_then(|p| p.downcast_ref::<&str>().copied()), Some("the test fails")); + let path = path.unwrap(); + assert!(!path.exists(), "{} is left", path.display()); + } + + #[test] + fn test_dirs_with_one_tag_are_separate_and_private() { + let (a, b) = (TempDir::new("shared-tag").unwrap(), TempDir::new("shared-tag").unwrap()); + assert_ne!(a.path(), b.path()); + std::fs::write(a.file("a.txt").unwrap(), b"a").unwrap(); + assert_eq!(entries(b.path()), 0, "one test's files are not in another's directory"); + #[cfg(unix)] + assert_eq!(std::os::unix::fs::PermissionsExt::mode(&std::fs::metadata(a.path()).unwrap().permissions()) & 0o777, 0o700); + drop(a); + assert!(b.path().is_dir(), "dropping one leaves the other"); + } + + #[test] + fn a_scratch_dir_is_removed_with_its_contents_when_dropped() { + let dir = TempDir::new("testkit-scratch").unwrap(); + let path = dir.path().to_path_buf(); + assert!(path.is_dir(), "{path:?} exists while the test holds it"); + assert_eq!(entries(&path), 0, "and starts empty"); + std::fs::create_dir_all(path.join("nested")).unwrap(); + std::fs::write(path.join("nested").join("a.pdf"), b"%PDF").unwrap(); + drop(dir); + assert!(!path.exists(), "{path:?} is gone, contents and all"); + } + + #[test] + fn scratch_dirs_with_the_same_name_are_separate_folders() { + let (a, b) = (TempDir::new("testkit-same").unwrap(), TempDir::new("testkit-same").unwrap()); + assert_ne!(a.path(), b.path()); + std::fs::write(a.file("x").unwrap(), b"a").unwrap(); + drop(b); + assert_eq!(std::fs::read(a.file("x").unwrap()).unwrap(), b"a", "dropping one leaves the other's files"); + } + + /// With one random character there are 62 names, and every one but `7` is taken: the new folder + /// is `7`, and the folders that were there keep their files. + #[test] + fn a_taken_name_is_skipped_and_its_folder_left_alone() { + let root = TempDir::new("taken-root").unwrap(); + let free = '7'; + let mut planted = Vec::new(); + for c in ('a'..='z').chain('A'..='Z').chain('0'..='9').filter(|&c| c != free) { + let folder = root.path().join(format!("craft-testkit-taken-{c}")); + // On a file system that ignores case, `A` is the folder `a` made. + match std::fs::create_dir(&folder) { + Ok(()) => std::fs::write(folder.join("theirs.pdf"), b"%PDF").unwrap(), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} + Err(e) => panic!("{}: {e}", folder.display()), + } + planted.push(folder); + } + let dir = TempDir::new_in("taken", root.path(), 1).unwrap(); + assert_eq!(dir.path().file_name().and_then(|n| n.to_str()), Some("craft-testkit-taken-7")); + assert_eq!(entries(dir.path()), 0, "and starts empty"); + drop(dir); + for folder in &planted { + assert_eq!(std::fs::read(folder.join("theirs.pdf")).unwrap(), b"%PDF", "{folder:?} kept its file"); + } + } + + #[test] + fn existing_folder_is_never_reused() { + let root = TempDir::new("reuse-root").unwrap(); + let theirs = root.path().join("craft-testkit-reuse-"); + std::fs::create_dir(&theirs).unwrap(); + std::fs::write(theirs.join("theirs.txt"), b"theirs").unwrap(); + // With no random characters the one name tried is the folder above. + let err = TempDir::new_in("reuse", root.path(), 0).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(theirs.join("theirs.txt")).unwrap(), b"theirs"); + assert_eq!(entries(&theirs), 1); + } + + #[test] + fn creation_failure_returns_error() { + let root = TempDir::new("failure-root").unwrap(); + let file = root.file("a-file").unwrap(); + std::fs::write(&file, b"not a folder").unwrap(); + assert!(TempDir::new_in("x", &file, RANDOM_CHARS).is_err(), "a file as the root"); + assert!(TempDir::new_in("x", &root.path().join("missing"), RANDOM_CHARS).is_err(), "a missing root"); + } + + #[test] + fn tag_rejects_empty_and_separators() { + for tag in ["", ".", "..", "a/b", "a\\b", "../x", "..\\x", "/x", "C:\\x", "C:x", "a\0b"] { + let err = TempDir::new(tag).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{tag:?}"); + } + } + + #[test] + fn file_rejects_absolute_parent_and_separators() { + let root = TempDir::new("file-root").unwrap(); + let dir = TempDir::new_in("file", root.path(), RANDOM_CHARS).unwrap(); + for name in ["", ".", "..", "a/b", "a\\b", "../outside.txt", "..\\outside.txt", "/x", "\\x", "C:\\x", "C:x", "a:stream", "a\0b"] { + let err = dir.file(name).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{name:?}"); + } + let a = dir.file("a.txt").unwrap(); + assert_eq!(a, dir.path().join("a.txt")); + assert!(!a.exists(), "file does not make the file"); + drop(dir); + assert_eq!(entries(root.path()), 0, "nothing was written next to the folder"); + } + + #[test] + fn path_is_canonical() { + let dir = TempDir::new("canonical").unwrap(); + assert!(dir.path().is_absolute()); + assert_eq!(dir.path(), std::fs::canonicalize(dir.path()).unwrap()); + assert_eq!(dir.path().parent().map(Path::to_path_buf), Some(std::fs::canonicalize(std::env::temp_dir()).unwrap())); + } + + #[cfg(windows)] + #[test] + fn windows_path_is_verbatim() { + let dir = TempDir::new("verbatim").unwrap(); + assert!(dir.path().to_string_lossy().starts_with(r"\\?\"), "{:?}", dir.path()); + } + + #[test] + fn same_tag_concurrent_creation_is_unique() { + let barrier = std::sync::Arc::new(std::sync::Barrier::new(16)); + let threads: Vec<_> = (0..16) + .map(|_| { + let barrier = std::sync::Arc::clone(&barrier); + std::thread::spawn(move || { + barrier.wait(); + TempDir::new("concurrent") + }) + }) + .collect(); + let dirs: Vec = threads.into_iter().map(|t| t.join().unwrap().unwrap()).collect(); + let paths: std::collections::BTreeSet<&Path> = dirs.iter().map(TempDir::path).collect(); + assert_eq!(paths.len(), 16); + assert!(dirs.iter().all(|d| entries(d.path()) == 0), "each starts empty"); + } + + #[test] + fn close_removes_the_folder() { + let dir = TempDir::new("close").unwrap(); + let path = dir.path().to_path_buf(); + std::fs::write(dir.file("a.txt").unwrap(), b"a").unwrap(); + dir.close().unwrap(); + assert!(!path.exists()); + } + + #[test] + fn close_reports_cleanup_failure() { + let dir = TempDir::new("close-failure").unwrap(); + std::fs::remove_dir(dir.path()).unwrap(); + assert!(dir.close().is_err(), "a folder that is already gone cannot be removed"); + } + + #[test] + fn wrong_owner_or_public_mode_is_rejected() { + let path = Path::new("folder"); + let private = Entry { is_dir: true, is_symlink: false, mode: Some(0o40700), owner: Some(1000) }; + assert!(check(path, private, || Ok(Some(1000))).is_ok()); + for mode in [0o40750, 0o40705, 0o40777] { + let err = check(path, Entry { mode: Some(mode), ..private }, || Ok(Some(1000))).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{mode:o}"); + } + let err = check(path, private, || Ok(Some(1001))).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied); + assert!(check(path, Entry { is_symlink: true, ..private }, || panic!("no probe through a link")).is_err()); + assert!(check(path, Entry { is_dir: false, ..private }, || panic!("no probe in a file")).is_err()); + let open = Entry { mode: Some(0o40777), ..private }; + assert!(check(path, open, || panic!("no probe in an open folder")).is_err()); + } + + #[cfg(unix)] + #[test] + fn new_dir_is_owner_private() { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let dir = TempDir::new("private").unwrap(); + let meta = std::fs::symlink_metadata(dir.path()).unwrap(); + assert_eq!(meta.permissions().mode() & 0o777, 0o700); + let mine = dir.file("mine.txt").unwrap(); + std::fs::write(&mine, b"a").unwrap(); + assert_eq!(meta.uid(), std::fs::metadata(&mine).unwrap().uid()); + std::fs::remove_file(&mine).unwrap(); + assert_eq!(entries(dir.path()), 0, "the owner probe is removed"); + } + + #[cfg(unix)] + #[test] + fn created_folder_symlink_is_rejected() { + let root = TempDir::new("link-root").unwrap(); + let real = root.path().join("real"); + std::fs::create_dir(&real).unwrap(); + std::fs::write(real.join("theirs.txt"), b"theirs").unwrap(); + let made = tempfile::Builder::new().prefix("craft-testkit-link-").tempdir_in(root.path()).unwrap(); + let link = made.path().to_path_buf(); + std::fs::remove_dir(&link).unwrap(); + std::os::unix::fs::symlink(&real, &link).unwrap(); + assert!(TempDir::guard(made).is_err()); + assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link is left in place"); + assert_eq!(std::fs::read(real.join("theirs.txt")).unwrap(), b"theirs"); + assert_eq!(entries(&real), 1, "no probe was made through the link"); + } + + #[cfg(unix)] + #[test] + fn temp_root_reached_through_symlink_works() { + let root = TempDir::new("symlink-root").unwrap(); + let real = root.path().join("real"); + std::fs::create_dir(&real).unwrap(); + let link = root.path().join("link"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let dir = TempDir::new_in("through-link", &link, RANDOM_CHARS).unwrap(); + assert_eq!(dir.path().parent(), Some(real.as_path()), "the path is canonical"); + assert!(dir.path().is_dir()); + let path = dir.path().to_path_buf(); + drop(dir); + assert!(!path.exists()); + assert!(real.is_dir() && link.is_symlink(), "the root and the link stay"); + } + + #[cfg(unix)] + #[test] + fn drop_does_not_follow_inner_symlink() { + let root = TempDir::new("inner-link-root").unwrap(); + let outside = root.path().join("outside"); + std::fs::create_dir(&outside).unwrap(); + std::fs::write(outside.join("keep.txt"), b"keep").unwrap(); + let dir = TempDir::new_in("inner-link", root.path(), RANDOM_CHARS).unwrap(); + std::os::unix::fs::symlink(&outside, dir.file("link").unwrap()).unwrap(); + let path = dir.path().to_path_buf(); + drop(dir); + assert!(!path.exists()); + assert_eq!(std::fs::read(outside.join("keep.txt")).unwrap(), b"keep"); + } +} From 67129ca6b5d7ba3ea1deb3f8d56ee74eab84b149 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:13:46 -0800 Subject: [PATCH 004/257] craft-testkit: list temp in the Origin and Migration tables and the crate list The temp module's sources and consumers are rows in the README's existing Origin and Migration tables, whose Guard column is now Module. The root README's craft-testkit entry names the temp module. --- README.md | 3 ++- crates/testkit/README.md | 28 +++++++++------------------- 2 files changed, 11 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index adbb6c120e..e88d227ec6 100644 --- a/README.md +++ b/README.md @@ -347,7 +347,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit `color` and `write`; re-exports them for existing users. - [`craft-testkit`](crates/testkit/README.md): test support for the apps' own tests. Its `guards` module reports source patterns that broke platforms before: muda's predefined Quit item, WGSL float literals - out of range, and `std::time::Instant` in code the web build runs. Not published. + out of range, and `std::time::Instant` in code the web build runs. Its `temp` module makes a new, + private test folder that is removed with its contents when dropped. Not published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). diff --git a/crates/testkit/README.md b/crates/testkit/README.md index dd41509e7e..81fd01af41 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -24,24 +24,6 @@ std::fs::write(dir.file("out.png")?, &png)?; |---|---| | `temp` | VectorCraft, PdfCraft, CADCraft, `craft-media-testkit` | -### Origin - -| Module | Source | Path | SHA | -|---|---|---|---| -| `temp` | storytold/vectorcraft | `crates/testkit/src/lib.rs` (`temp_dir`, `TempDir`) | `bada8e17` | -| `temp` | storytold/pdfcraft#6124 | `crates/testkit/src/scratch.rs` (`ScratchDir`) | `92e20711` | -| `temp` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` (`private_dir`) | `75a654f4` | -| `temp` | storytold/cadcraft | `crates/engine/tests/support/temp_dir.rs`, `crates/ui-egui/tests/support/temp_dir.rs` | `8e698902` | - -### Migration - -| Consumer | State | -|---|---| -| VectorCraft | Not switched. `temp_dir(tag)` shares one folder per tag in a process; its test of that is not moved. | -| PdfCraft | Not switched. `ScratchFile` has no counterpart; `TempDir::file` returns a path in a `TempDir`. | -| CADCraft | Not switched. Its `TempDir` empties a leftover folder of the same name; `temp` makes a new one. | -| `craft-media-testkit` | Not switched. `private_dir()` is unchanged. | - ## Epistemic Scope: Syntactic Guards vs Runtime Validation Source-level guards provide deterministic syntactic evidence about codebase structure: @@ -114,10 +96,18 @@ fn no_std_instant_in_code_the_web_build_runs() { | Module | Source | Path | Commit | |---|---|---|---| | `guards` | storytold/craft-libs#163 (zachshallbetter), with the rules of PhotoCraft's shader float test and FilmCraft's web clock test | `crates/testkit/src/guards.rs` | `e92825e427` | +| `temp` | storytold/vectorcraft | `crates/testkit/src/lib.rs` (`temp_dir`, `TempDir`) | `bada8e1710` | +| `temp` | storytold/pdfcraft#6124 | `crates/testkit/src/scratch.rs` (`ScratchDir`) | `92e2071199` | +| `temp` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` (`private_dir`) | `75a654f4f8` | +| `temp` | storytold/cadcraft | `crates/engine/tests/support/temp_dir.rs`, `crates/ui-egui/tests/support/temp_dir.rs` | `8e69890223` | ## Migration -| Consumer | Guard | Replaces | State | +| Consumer | Module | Replaces | State | |---|---|---|---| | PhotoCraft | `wgsl_float_literals` | `crates/gpu/src/tests.rs` scanner | Not started | | FilmCraft | `std_instant` | `crates/engine/src/wasm_clock_tests.rs` search | Not started | +| VectorCraft | `temp` | `temp_dir` and `TempDir` in `crates/testkit/src/lib.rs` | Not started. `temp_dir(tag)` shares one folder per tag in a process; its test of that is not moved. | +| PdfCraft | `temp` | `ScratchDir` in `crates/testkit/src/scratch.rs` (#6124) | Not started. `ScratchFile` has no counterpart; `TempDir::file` returns a path in a `TempDir`. | +| CADCraft | `temp` | `crates/engine/tests/support/temp_dir.rs`, `crates/ui-egui/tests/support/temp_dir.rs` | Not started. Its `TempDir` empties a leftover folder of the same name; `temp` makes a new one. | +| `craft-media-testkit` | `temp` | `private_dir()` in `crates/media-testkit/src/lib.rs` | Not started. `private_dir()` is unchanged. | From 6386c62f7eb1768d846c483c942b2d2da725ba0c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:15:11 -0800 Subject: [PATCH 005/257] craft-xtask: add the crate-layer check against a table the app supplies The new `layers` module checks each workspace crate's dependencies against the app's `Policy`: exact package names and their class (layer, standalone, testkit, build tool, exempt), ordered same-layer chains or a flat mode, sideways pairs, UI crates and the layer they start at, dev-only and standalone exceptions, format allowlists, and which packages may use test tooling or the build-tool crate. Normal, build and dev dependencies are all checked, and same-layer edges that form a cycle are reported. `from_metadata` reads `cargo metadata --no-deps` strictly: workspace membership comes from manifest directories, so a registry or outside path crate with a member's name stays external, and missing or unknown fields are errors. `cargo_metadata` reads at most a set number of bytes from the child. `wasm_set` picks the packages the app's wasm step builds. The engine tests of the apps' copies move in under their own names, with synthetic policies. `serde_json` is now a normal dependency of the crate. --- crates/xtask/Cargo.toml | 6 +- crates/xtask/README.md | 105 ++- crates/xtask/src/layers.rs | 1570 ++++++++++++++++++++++++++++++++++++ crates/xtask/src/lib.rs | 4 + 4 files changed, 1680 insertions(+), 5 deletions(-) create mode 100644 crates/xtask/src/layers.rs diff --git a/crates/xtask/Cargo.toml b/crates/xtask/Cargo.toml index 6b561b543b..74f5826cc1 100644 --- a/crates/xtask/Cargo.toml +++ b/crates/xtask/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true license.workspace = true rust-version.workspace = true repository.workspace = true -description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes and a per-step JSON report" +description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, the crate-layer check, an optional slot lock shared across processes and a per-step JSON report" [lints] workspace = true @@ -15,11 +15,11 @@ default = [] # One-at-a-time (or N-at-a-time) gate runs per machine, through file locks in a caller-chosen folder. lock = [] # The per-step JSON report, replaced atomically. -report = ["dep:serde_json", "dep:craft-atomic"] +report = ["dep:craft-atomic"] [dependencies] craft-atomic = { workspace = true, optional = true } -serde_json = { workspace = true, optional = true } +serde_json = { workspace = true } [dev-dependencies] tempfile = "3" diff --git a/crates/xtask/README.md b/crates/xtask/README.md index 75228c3d66..280111c04c 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -7,10 +7,11 @@ The crate is native only and is a dependency of an app's `xtask` package only. | Module | Feature | Contents | |---|---|---| | `runner` | always | `Step`, `run_steps` (steps in order, stop at the first failure, the `ok`, `FAIL` and `skip` summary), `root`, `cargo`, `run`, `run_cancelable`, `nextest_or_test`, `doctest`, `Cancel` | +| `layers` | always | `Policy`, `Class`, `check`, `wasm_set`, `from_metadata`, `cargo_metadata`, `read_json`: the crate-layer check against a table the app supplies | | `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses | | `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` | -No feature is on by default. `report` adds `serde_json` and `craft-atomic`. +No feature is on by default. The crate depends on `serde_json`; `report` adds `craft-atomic`. ## Use @@ -59,6 +60,99 @@ or file could not be opened or locked) or `Report` (the run passed but the repor written). A report that cannot be written after a failed run is printed to stderr, and the run keeps its `Step` error. +## Layers + +The app owns its table, its exceptions, the `cargo xtask layers` command, the printing and the +`cargo check --target` call of its wasm step. The library reads the workspace, checks it and picks +the wasm packages: + +```rust,no_run +use craft_xtask::layers::{self, Class, Policy}; + +const TABLE: &[(&str, Class)] = &[ + ("app-geom", Class::Layer(0)), + ("app-color", Class::Layer(0)), + ("app-doc", Class::Layer(1)), + ("app-engine", Class::Layer(5)), + ("app-ui", Class::Layer(6)), + ("app-testkit", Class::Testkit), + ("app", Class::Exempt), + ("xtask", Class::BuildTool), +]; +const POLICY: Policy<'static> = Policy { + ordered_chains: &[&["app-geom", "app-color"]], + ui_crates: &["egui*", "eframe", "winit", "rfd"], + ui_min_layer: 6, + testkit_layer: 6, + testkit_crates: &["craft-testkit"], + testkit_normal_users: &["xtask"], + build_tool_crates: &["craft-xtask"], + wasm_max_layer: Some(5), + wasm_extra: &["app-ui"], + ..Policy::new(TABLE) +}; + +fn layers(root: &std::path::Path) -> Result<(), String> { + let meta = layers::cargo_metadata(root, layers::DEFAULT_METADATA_LIMIT).map_err(|e| e.to_string())?; + let crates = layers::from_metadata(&meta).map_err(|e| e.to_string())?; + let violations = layers::check(&POLICY, &crates).map_err(|e| e.to_string())?; + for v in &violations { + eprintln!("{v}"); + } + if violations.is_empty() { Ok(()) } else { Err(format!("{} layer violations", violations.len())) } +} +``` + +- Table names are exact package names. A name may appear once. A table entry that matches no + workspace package is an error unless `optional` lists it, and an empty table or an empty workspace + is an error. Every name in `optional`, `ordered_chains`, `sideways`, `dev_exceptions`, + `standalone_deps`, `format_allowed`, `testkit_normal_users` and `wasm_extra` must be in the table; + the names in `ui_crates`, `ui_dev_allowed`, `testkit_crates` and `build_tool_crates` are not + checked against the table. +- `Class::Layer(n)` crates depend on lower layers. `Class::Standalone(n)` crates depend only on the + standalone crates `standalone_deps` lists for them, at layer `n` or lower, and on test tooling as a + dev-dependency. `Class::Testkit` crates sit at `testkit_layer` for their own dependencies, and other + crates use them, and the external `testkit_crates`, only as dev-dependencies, except the packages in + `testkit_normal_users`. `Class::BuildTool` packages (the app's `xtask`) are exempt from the layers + and are the only packages that may depend on another build tool or on `build_tool_crates`. + `Class::Exempt` packages (apps, CLIs, web shells) are exempt from the layers and the UI rule only. +- Same-layer dependencies: `SameLayer::Ordered` allows a later member of an `ordered_chains` chain to + use an earlier one, and each `sideways` pair `(from, to)`. `SameLayer::Allowed` allows every + same-layer dependency. Either way, same-layer dependencies that form a cycle are reported. +- Normal, build and dev dependencies are all checked. `dev_exceptions` pairs pass as + dev-dependencies only, and `ui_dev_allowed` UI crates pass as dev-dependencies at any layer. A + same-layer dev exception still counts toward cycles. A crate's workspace dependency on itself is + skipped. `format_allowed` limits a crate's normal and build + dependencies on workspace crates to a list, on top of the layer rule. +- `ui_crates` entries match a name exactly, or, ending in `*`, by prefix. UI crates are allowed from + `ui_min_layer`. +- `from_metadata` reads `cargo metadata --format-version 1 --no-deps`. A dependency is a workspace + member when its `path` is a member's manifest directory (`\` and `/` compare equal), so a registry + crate or an outside path crate with a member's name stays external, and a renamed member is matched + by its package `name`. A missing `packages`, `workspace_members`, `dependencies`, `name`, `id`, + `manifest_path` or `kind`, an unknown `kind`, a package missing from `workspace_members` and a + repeated package are errors. +- `cargo_metadata` and `read_json` read at most the given number of bytes (`DEFAULT_METADATA_LIMIT` + is 64 MiB) from the child's stdout, end the child when it writes more, and return an error for a + spawn failure, a failure exit status or output that is not JSON. Stderr is inherited. +- `check` returns the violations sorted by kind and fields, without duplicates; their `Display` text + names the packages, layers and dependency kind. `wasm_set` returns the layered and standalone + packages at or below `wasm_max_layer` and the `wasm_extra` packages the workspace has, sorted, with + no test or build tooling. An empty set is an error. It does not check that the packages build for + wasm. + +The source copies differ in a few rules. An app that switches lists the results that change: + +- DesignCraft and its copies skip an unregistered workspace dependency, take a path dependency as a + workspace member whatever its directory, read a missing `dependencies` as empty and an unknown kind + as normal, and take the first of two table rows with one name. Each of these is an error or a + violation here. +- No source copy reports a same-layer cycle, or a test-tooling or build-tool dependency of an exempt + package. +- DesignCraft reports a standalone crate's dev-dependency on test tooling; this crate allows it, as + PdfCraft does. PhotoCraft's `STANDALONE_EXCEPTIONS` pairs become `standalone_deps` entries. +- EffectCraft keeps a flat table with its own same-layer pairs and does not check dev-dependencies. + ## Lock `RunOptions::with_lock(LockConfig::new(dir, slots, owner_label))` takes one of `slots` lock files in @@ -98,7 +192,13 @@ Machine, GPU, corpus and skip details stay in the app's own report. | `runner`: the step loop and summary, `root`, `cargo`, `run`, the nextest probe and fallback, doctests | DesignCraft `xtask/src/main.rs:68-82`, `:160-201`, `:204-249` at [8b169f8](https://github.com/storytold/designcraft/blob/8b169f8ee7832e60ed1ac4c9f5dd34f954d3a992/xtask/src/main.rs) | | `lock` and its tests `one_slot_is_exclusive_until_dropped`, `more_slots_admit_more_runs` | LightCraft `xtask/src/ci_lock.rs` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci_lock.rs) | | `report`: the per-step fields | LightCraft `xtask/src/ci.rs:347-414` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci.rs#L347-L414) | -| The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report | written here | +| `layers`: `Class`, `Dep`, `Crate`, `Violation`, `check`, `from_metadata`, the ordered chains and UI prefixes, and the tests `clean_downward_graph_passes`, `upward_dependency_flagged`, `sideways_dependency_flagged`, `l0_foundation_chain_allowed_one_way`, `self_dev_dependency_ignored`, `upward_dev_dependency_flagged`, `ui_crates_below_l6_flagged`, `unregistered_crate_is_error`, `testkit_only_as_dev_dependency`, `apps_and_xtask_exempt`, `metadata_parsing` | DesignCraft `xtask/src/layers.rs` at [4bc6f8a](https://github.com/storytold/designcraft/blob/4bc6f8a730f1f12321f5a442b94f30513d7a3f93/xtask/src/layers.rs) | +| `layers`: numbered standalone crates and their lists, sideways pairs, UI dev-dependencies, and the tests in `layers::tests::pdfcraft` | PdfCraft `xtask/src/layers.rs` at [ee9bf28](https://github.com/storytold/pdfcraft/blob/ee9bf2812671f9f7b53e631f4f9f8b6543bf7995/xtask/src/layers.rs) | +| `layers`: standalone exceptions and the tests in `layers::tests::photocraft` | PhotoCraft `xtask/src/layers.rs` at [58d11d9](https://github.com/storytold/photocraft/blob/58d11d91ea46041650058284163008d534431329/xtask/src/layers.rs) | +| `layers`: format allowlists and the tests in `layers::tests::gridcraft` | GridCraft `xtask/src/layers.rs` at [06c2b14](https://github.com/storytold/gridcraft/blob/06c2b1440b0134ec184561dcc2275fdb5f18a5af/xtask/src/layers.rs) | +| `layers`: dev-only exceptions | DeckCraft `xtask/src/layers.rs` at [4b93429](https://github.com/storytold/deckcraft/blob/4b93429c9ec3921042f5d4ff27efa5ae999336fb/xtask/src/layers.rs) | +| `layers`: `SameLayer::Allowed` and `sideways` for a flat table (EffectCraft allows every same-layer dependency in L0 and listed pairs above it) | EffectCraft `xtask/src/main.rs` at [d4e33b2](https://github.com/storytold/effectcraft/blob/d4e33b2bda4515d456408b9bd8afb7e536770a40/xtask/src/main.rs) | +| The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report; in `layers`, the policy checks, membership by manifest directory, the strict metadata reader, the bounded metadata command, cycle detection, the build-tool class and `wasm_set` | written here | ## Migration @@ -107,6 +207,7 @@ No app uses this crate yet. | App | Status | |---|---| | DesignCraft | Planned: `cmd_ci`, `root`, `cargo`, `run`, `cmd_test` and `cmd_doctest` move to `runner`, with `TestMode::PreferNextest`. The step list, `TEST_TARGETS` and the i18n report stay in the app. | +| DesignCraft, CADCraft, VectorCraft, DeckCraft, WordCraft, PdfCraft, PhotoCraft, GridCraft, EffectCraft | Planned: `xtask/src/layers.rs` (EffectCraft: the check in `xtask/src/main.rs`) moves to `layers`. The table, chains, exceptions, UI layer and the tests of the app's own policy stay in the app. | | LightCraft | Planned: `ci_lock.rs` moves to `lock`, with `LIGHTCRAFT_CI_LOCK` and `LIGHTCRAFT_CI_SLOTS` read by the app. The machine, GPU, corpus and skip report stays in the app. | Maintainers: the craft-libs maintainers, until a responsible maintainer or team is agreed in the diff --git a/crates/xtask/src/layers.rs b/crates/xtask/src/layers.rs new file mode 100644 index 0000000000..456462baff --- /dev/null +++ b/crates/xtask/src/layers.rs @@ -0,0 +1,1570 @@ +//! The crate-layer check: each workspace crate depends only on crates in lower layers. +//! +//! The app supplies a [`Policy`]: its table of exact package names and their [`Class`], the +//! same-layer edges it allows, its UI crates and the layer they start at, and its exceptions. This +//! module reads the workspace from `cargo metadata` ([`cargo_metadata`], [`from_metadata`]), checks +//! it against the policy ([`check`]) and picks the packages the app's wasm step builds +//! ([`wasm_set`]). The app keeps its `cargo xtask layers` command, the printing, the gate step and +//! the `cargo check --target` call. +//! +//! The rule engine works on a small metadata-independent model ([`Crate`], [`Dep`]), so an app's +//! tests can check its policy on synthetic graphs. +//! +//! ``` +//! use craft_xtask::layers::{self, Class, Crate, Dep, DepKind, Policy}; +//! +//! const TABLE: &[(&str, Class)] = &[ +//! ("app-geom", Class::Layer(0)), +//! ("app-doc", Class::Layer(1)), +//! ("app", Class::Exempt), +//! ("xtask", Class::BuildTool), +//! ]; +//! const POLICY: Policy<'static> = Policy { ui_crates: &["egui*", "winit"], ui_min_layer: 2, ..Policy::new(TABLE) }; +//! +//! let dep = |name: &str| Dep { name: name.into(), kind: DepKind::Normal, workspace: name.starts_with("app") }; +//! let crates = [ +//! Crate { name: "app-geom".into(), deps: vec![dep("app-doc")] }, +//! Crate { name: "app-doc".into(), deps: vec![dep("app-geom")] }, +//! Crate { name: "app".into(), deps: vec![dep("app-doc"), dep("egui")] }, +//! Crate { name: "xtask".into(), deps: vec![] }, +//! ]; +//! let violations = layers::check(&POLICY, &crates)?; +//! assert_eq!(violations.len(), 1); +//! assert_eq!(violations[0].to_string(), "app-geom (L0) -> app-doc (L1) [normal]: a crate may depend only on lower layers, or on a same-layer crate the policy allows"); +//! # Ok::<(), layers::Error>(()) +//! ``` + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::fmt; +use std::io::Read; +use std::path::Path; +use std::process::{Command, Stdio}; + +use serde_json::Value; + +/// The default limit on the bytes [`cargo_metadata`] reads from `cargo metadata`: 64 MiB. +pub const DEFAULT_METADATA_LIMIT: usize = 64 * 1024 * 1024; + +/// Where a workspace package sits. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Class { + /// A layered crate. It may depend on crates in lower layers, and on same-layer crates the + /// policy allows. + Layer(u8), + /// A crate in the given layer that may depend only on the workspace crates + /// [`Policy::standalone_deps`] lists for it, and on test tooling as a dev-dependency. + Standalone(u8), + /// Test tooling. It sits at [`Policy::testkit_layer`] for its own dependencies. Other crates + /// may use it only as a dev-dependency, except those in [`Policy::testkit_normal_users`]. + Testkit, + /// Build tooling such as the app's `xtask`: exempt from the layer rules, and the only class + /// that may depend on another build-tool package or on [`Policy::build_tool_crates`]. + BuildTool, + /// Apps and other top-level packages: exempt from the layer and UI rules. The test-tooling and + /// build-tool rules still apply. + Exempt, +} + +impl Class { + fn layer(self, policy: &Policy<'_>) -> Option { + match self { + Class::Layer(l) | Class::Standalone(l) => Some(l), + Class::Testkit => Some(policy.testkit_layer), + Class::BuildTool | Class::Exempt => None, + } + } + + fn same_layer_member(self) -> Option { + match self { + Class::Layer(l) | Class::Standalone(l) => Some(l), + Class::Testkit | Class::BuildTool | Class::Exempt => None, + } + } +} + +impl fmt::Display for Class { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Class::Layer(l) => write!(f, "L{l}"), + Class::Standalone(l) => write!(f, "L{l} standalone"), + Class::Testkit => f.write_str("testkit"), + Class::BuildTool => f.write_str("build tool"), + Class::Exempt => f.write_str("exempt"), + } + } +} + +/// Which dependencies between two crates of the same layer pass. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SameLayer { + /// Any same-layer dependency passes, as long as the same-layer edges form no cycle. + Allowed, + /// Only a later member of an [`Policy::ordered_chains`] chain using an earlier member, and the + /// [`Policy::sideways`] pairs, pass. + Ordered, +} + +/// The kind of a dependency, as `cargo metadata` reports it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum DepKind { + /// A `[dependencies]` entry. + Normal, + /// A `[dev-dependencies]` entry. + Dev, + /// A `[build-dependencies]` entry. + Build, +} + +impl DepKind { + /// `normal`, `dev` or `build`. + pub fn as_str(self) -> &'static str { + match self { + DepKind::Normal => "normal", + DepKind::Dev => "dev", + DepKind::Build => "build", + } + } +} + +/// One dependency of a workspace crate. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Dep { + /// The package name of the dependency (not a `rename` alias). + pub name: String, + /// The dependency's kind. + pub kind: DepKind, + /// `true` when the dependency is a workspace member. + pub workspace: bool, +} + +/// One workspace package and its dependencies. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Crate { + /// The package name. + pub name: String, + /// Its dependencies, every kind. + pub deps: Vec, +} + +/// An app's layer policy. Every name is an exact package name. +/// +/// Start from [`Policy::new`] and set the fields the app needs: +/// `Policy { ui_crates: UI, ui_min_layer: 6, ..Policy::new(TABLE) }`. +#[derive(Debug, Clone, Copy)] +pub struct Policy<'a> { + /// Every workspace package and its class. A name may appear once. + pub table: &'a [(&'a str, Class)], + /// Table entries that may be missing from the workspace. Any other table entry that matches no + /// workspace package is an error. + pub optional: &'a [&'a str], + /// Which same-layer dependencies pass. + pub same_layer: SameLayer, + /// Chains of same-layer crates: a later member may depend on an earlier one. + pub ordered_chains: &'a [&'a [&'a str]], + /// Allowed same-layer dependencies, as `(from, to)`. + pub sideways: &'a [(&'a str, &'a str)], + /// External UI crates. An entry ending in `*` matches names that start with the rest; any other + /// entry matches one name exactly. + pub ui_crates: &'a [&'a str], + /// The first layer that may depend on a UI crate. + pub ui_min_layer: u8, + /// UI crates that any crate may use as a dev-dependency. + pub ui_dev_allowed: &'a [&'a str], + /// Dev-dependencies `(from, to)` that pass whatever the layers of the two crates. + pub dev_exceptions: &'a [(&'a str, &'a str)], + /// The workspace crates each [`Class::Standalone`] crate may depend on. Each one must itself be + /// standalone, in the same layer or lower. + pub standalone_deps: &'a [(&'a str, &'a [&'a str])], + /// Crates whose normal and build dependencies on workspace crates are limited to a list, on top + /// of the layer rule. + pub format_allowed: &'a [(&'a str, &'a [&'a str])], + /// The layer [`Class::Testkit`] crates sit at for their own dependencies. + pub testkit_layer: u8, + /// External test-tooling crates, which follow the same rule as [`Class::Testkit`] packages. + pub testkit_crates: &'a [&'a str], + /// Packages that may depend on test tooling as a normal or build dependency. + pub testkit_normal_users: &'a [&'a str], + /// External build-tool crates (such as `craft-xtask`), which only [`Class::BuildTool`] + /// packages may depend on. + pub build_tool_crates: &'a [&'a str], + /// The highest layer [`wasm_set`] selects, or `None` for no layered crate. + pub wasm_max_layer: Option, + /// Further packages [`wasm_set`] selects. + pub wasm_extra: &'a [&'a str], +} + +impl<'a> Policy<'a> { + /// A policy with `table`, [`SameLayer::Ordered`], no exceptions, no UI crates, test tooling + /// above every layer and no wasm layer. + pub const fn new(table: &'a [(&'a str, Class)]) -> Self { + Policy { + table, + optional: &[], + same_layer: SameLayer::Ordered, + ordered_chains: &[], + sideways: &[], + ui_crates: &[], + ui_min_layer: 0, + ui_dev_allowed: &[], + dev_exceptions: &[], + standalone_deps: &[], + format_allowed: &[], + testkit_layer: u8::MAX, + testkit_crates: &[], + testkit_normal_users: &[], + build_tool_crates: &[], + wasm_max_layer: None, + wasm_extra: &[], + } + } + + /// The class of the package `name`, or `None` when the table does not list it. + pub fn classify(&self, name: &str) -> Option { + self.table.iter().find(|(n, _)| *n == name).map(|(_, c)| *c) + } + + fn is_ui_crate(&self, name: &str) -> bool { + self.ui_crates.iter().any(|p| match p.strip_suffix('*') { + Some(prefix) => name.starts_with(prefix), + None => name == *p, + }) + } + + fn same_layer_allowed(&self, from: &str, to: &str) -> bool { + match self.same_layer { + SameLayer::Allowed => true, + SameLayer::Ordered => { + self.sideways.contains(&(from, to)) + || self.ordered_chains.iter().any(|chain| match (chain.iter().position(|n| *n == from), chain.iter().position(|n| *n == to)) { + (Some(f), Some(t)) => t < f, + _ => false, + }) + } + } + } + + fn standalone_allowed(&self, from: &str, to: &str) -> bool { + self.standalone_deps.iter().any(|(f, ok)| *f == from && ok.contains(&to)) + } + + fn may_use_testkit_normally(&self, class: Class, name: &str) -> bool { + class == Class::Testkit || self.testkit_normal_users.contains(&name) + } +} + +/// A broken rule. +/// +/// Every field is a plain value, and [`check`] returns the violations sorted by variant and then by +/// field, without duplicates. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub enum Violation { + /// A workspace package that is not in the table. + Unregistered { + /// The package. + krate: String, + }, + /// A dependency on a workspace package that is neither in the table nor among the packages + /// checked. + UnknownDependency { + /// The depending package. + krate: String, + /// The dependency. + dep: String, + /// The dependency's kind. + kind: DepKind, + }, + /// A dependency on a crate in the same layer or higher that the policy does not allow. + Upward { + /// The depending package. + krate: String, + /// The dependency. + dep: String, + /// The depending package's layer. + from: u8, + /// The dependency's layer. + to: u8, + /// The dependency's kind. + kind: DepKind, + }, + /// A layered crate that depends on an [`Class::Exempt`] package. + OnExempt { + /// The depending package. + krate: String, + /// The dependency. + dep: String, + /// The dependency's kind. + kind: DepKind, + }, + /// A standalone crate's workspace dependency that [`Policy::standalone_deps`] does not list. + StandaloneHasWorkspaceDep { + /// The standalone package. + krate: String, + /// The dependency. + dep: String, + /// The dependency's kind. + kind: DepKind, + }, + /// A normal or build dependency that is not in the crate's [`Policy::format_allowed`] list. + FormatDep { + /// The limited package. + krate: String, + /// The dependency. + dep: String, + /// The dependency's kind. + kind: DepKind, + }, + /// Test tooling used as a normal or build dependency. + TestkitAsNormalDep { + /// The depending package. + krate: String, + /// The test tooling. + dep: String, + /// The dependency's kind. + kind: DepKind, + }, + /// A build-tool package or crate used by a package that is not build tooling. + BuildToolDep { + /// The depending package. + krate: String, + /// The build tool. + dep: String, + /// The dependency's kind. + kind: DepKind, + }, + /// A UI crate used below [`Policy::ui_min_layer`]. + UiBelowMinLayer { + /// The depending package. + krate: String, + /// The UI crate. + dep: String, + /// The depending package's layer. + layer: u8, + /// The first layer that may use a UI crate. + min: u8, + /// The dependency's kind. + kind: DepKind, + }, + /// Same-layer dependencies that each pass on their own but form a cycle. + SameLayerCycle { + /// The packages in the cycle, sorted. + crates: Vec, + }, +} + +impl fmt::Display for Violation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Violation::Unregistered { krate } => write!(f, "{krate}: not in the layer table"), + Violation::UnknownDependency { krate, dep, kind } => { + write!(f, "{krate} -> {dep} [{}]: {dep} is a workspace package that is not in the layer table", kind.as_str()) + } + Violation::Upward { krate, dep, from, to, kind } => write!( + f, + "{krate} (L{from}) -> {dep} (L{to}) [{}]: a crate may depend only on lower layers, or on a same-layer crate the policy allows", + kind.as_str() + ), + Violation::OnExempt { krate, dep, kind } => { + write!(f, "{krate} -> {dep} [{}]: a layered crate may not depend on an exempt package", kind.as_str()) + } + Violation::StandaloneHasWorkspaceDep { krate, dep, kind } => { + write!(f, "{krate} -> {dep} [{}]: a standalone crate may depend only on the workspace crates the policy lists for it", kind.as_str()) + } + Violation::FormatDep { krate, dep, kind } => { + write!(f, "{krate} -> {dep} [{}]: not in the workspace dependencies the policy allows {krate}", kind.as_str()) + } + Violation::TestkitAsNormalDep { krate, dep, kind } => { + write!(f, "{krate} -> {dep} [{}]: test tooling may only be a dev-dependency", kind.as_str()) + } + Violation::BuildToolDep { krate, dep, kind } => { + write!(f, "{krate} -> {dep} [{}]: only build tooling may depend on {dep}", kind.as_str()) + } + Violation::UiBelowMinLayer { krate, dep, layer, min, kind } => { + write!(f, "{krate} (L{layer}) -> {dep} [{}]: UI crates are allowed only from L{min}", kind.as_str()) + } + Violation::SameLayerCycle { crates } => write!(f, "same-layer dependency cycle among {}", crates.join(", ")), + } + } +} + +/// Why the check could not run. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + /// The policy, or the policy together with the workspace, cannot be checked: an empty table, a + /// repeated or unknown name, a table entry that matches no package, an empty workspace. + Policy(String), + /// The `cargo metadata` output is missing a field this module needs, or holds a value it does + /// not know. + Metadata(String), + /// The metadata command could not be started, failed, or wrote more than the byte limit. + Process(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Policy(m) => write!(f, "layer policy: {m}"), + Error::Metadata(m) => write!(f, "cargo metadata: {m}"), + Error::Process(m) => f.write_str(m), + } + } +} + +impl std::error::Error for Error {} + +fn policy_error(message: impl Into) -> Error { + Error::Policy(message.into()) +} + +/// Checks the policy against itself and the workspace, and returns the table as a map. +fn validate<'p>(policy: &Policy<'p>, crates: &[Crate]) -> Result, Error> { + if policy.table.is_empty() { + return Err(policy_error("the table is empty")); + } + if crates.is_empty() { + return Err(policy_error("the workspace has no packages")); + } + let mut table = HashMap::with_capacity(policy.table.len()); + for &(name, class) in policy.table { + if name.is_empty() { + return Err(policy_error("the table has an empty name")); + } + if table.insert(name, class).is_some() { + return Err(policy_error(format!("{name} appears more than once in the table"))); + } + } + let mut members = HashSet::with_capacity(crates.len()); + for c in crates { + if !members.insert(c.name.as_str()) { + return Err(policy_error(format!("the workspace lists {} more than once", c.name))); + } + } + let known = |field: &str, name: &str| -> Result { + table.get(name).copied().ok_or_else(|| policy_error(format!("{field} names {name}, which is not in the table"))) + }; + for name in policy.optional { + known("optional", name)?; + } + for &(name, _) in policy.table { + if !members.contains(name) && !policy.optional.contains(&name) { + return Err(policy_error(format!("{name} is in the table but not in the workspace; list it in `optional` if it may be missing"))); + } + } + for chain in policy.ordered_chains { + let mut layer = None; + for name in *chain { + let l = known("ordered_chains", name)? + .same_layer_member() + .ok_or_else(|| policy_error(format!("ordered_chains names {name}, which is not a layered crate")))?; + if layer.is_some_and(|first| first != l) { + return Err(policy_error(format!("ordered_chains puts {name} in a chain with crates of another layer"))); + } + layer = Some(l); + } + } + for &(from, to) in policy.sideways { + let (f, t) = (known("sideways", from)?.same_layer_member(), known("sideways", to)?.same_layer_member()); + if f.is_none() || f != t { + return Err(policy_error(format!("sideways pair {from} -> {to} is not two layered crates of one layer"))); + } + } + for &(from, to) in policy.dev_exceptions { + known("dev_exceptions", from)?; + known("dev_exceptions", to)?; + } + for &(from, list) in policy.standalone_deps { + let Class::Standalone(from_layer) = known("standalone_deps", from)? else { + return Err(policy_error(format!("standalone_deps names {from}, which is not standalone"))); + }; + for to in list { + match known("standalone_deps", to)? { + Class::Standalone(l) if l <= from_layer => {} + _ => return Err(policy_error(format!("standalone_deps lets {from} use {to}, which is not standalone at L{from_layer} or lower"))), + } + } + } + for &(from, list) in policy.format_allowed { + if known("format_allowed", from)?.layer(policy).is_none() { + return Err(policy_error(format!("format_allowed names {from}, which is exempt from the layer rules"))); + } + for to in list { + known("format_allowed", to)?; + } + } + for name in policy.testkit_normal_users { + known("testkit_normal_users", name)?; + } + for name in policy.wasm_extra { + if matches!(known("wasm_extra", name)?, Class::Testkit | Class::BuildTool) { + return Err(policy_error(format!("wasm_extra names {name}, which is test or build tooling"))); + } + } + for p in policy.ui_crates { + let stem = p.strip_suffix('*').unwrap_or(p); + if stem.is_empty() || stem.contains('*') { + return Err(policy_error(format!("ui_crates entry `{p}` must be a name, or a name prefix followed by one `*`"))); + } + } + Ok(table) +} + +/// The checks of one package, with what they need from the policy. +struct Checker<'a, 'p> { + policy: &'a Policy<'p>, + table: &'a HashMap<&'p str, Class>, + members: &'a HashSet<&'a str>, + out: Vec, + same_layer_edges: BTreeMap<&'a str, BTreeSet<&'a str>>, +} + +impl<'a> Checker<'a, '_> { + fn workspace_dep(&mut self, c: &'a Crate, class: Class, d: &'a Dep) { + let (krate, dep, kind) = (c.name.clone(), d.name.clone(), d.kind); + // The allowlist applies to every normal and build dependency on a workspace crate, before + // any class rule can accept the edge. + if kind != DepKind::Dev + && let Some((_, allowed)) = self.policy.format_allowed.iter().find(|(n, _)| *n == c.name) + && !allowed.contains(&d.name.as_str()) + { + self.out.push(Violation::FormatDep { krate: krate.clone(), dep: dep.clone(), kind }); + } + let Some(dep_class) = self.table.get(d.name.as_str()).copied() else { + // A member that is not in the table is reported once, on its own entry. + if !self.members.contains(d.name.as_str()) { + self.out.push(Violation::UnknownDependency { krate, dep, kind }); + } + return; + }; + match dep_class { + Class::BuildTool => { + if class != Class::BuildTool { + self.out.push(Violation::BuildToolDep { krate, dep, kind }); + } + return; + } + Class::Testkit => { + if kind != DepKind::Dev && !self.policy.may_use_testkit_normally(class, &c.name) { + self.out.push(Violation::TestkitAsNormalDep { krate, dep, kind }); + } + return; + } + Class::Layer(_) | Class::Standalone(_) | Class::Exempt => {} + } + let Some(from) = class.layer(self.policy) else { return }; + if let Class::Standalone(_) = class { + if !self.policy.standalone_allowed(&c.name, &d.name) { + self.out.push(Violation::StandaloneHasWorkspaceDep { krate, dep, kind }); + } else if dep_class.layer(self.policy) == Some(from) { + self.same_layer_edges.entry(&c.name).or_default().insert(&d.name); + } + return; + } + let Some(to) = dep_class.layer(self.policy) else { + self.out.push(Violation::OnExempt { krate, dep, kind }); + return; + }; + if kind == DepKind::Dev && self.policy.dev_exceptions.contains(&(c.name.as_str(), d.name.as_str())) { + if to == from { + self.same_layer_edges.entry(&c.name).or_default().insert(&d.name); + } + return; + } + if to < from { + return; + } + if to == from && class.same_layer_member().is_some() && self.policy.same_layer_allowed(&c.name, &d.name) { + self.same_layer_edges.entry(&c.name).or_default().insert(&d.name); + return; + } + self.out.push(Violation::Upward { krate, dep, from, to, kind }); + } + + fn external_dep(&mut self, c: &Crate, class: Class, d: &Dep) { + let (name, kind) = (d.name.as_str(), d.kind); + if self.policy.build_tool_crates.contains(&name) && class != Class::BuildTool { + self.out.push(Violation::BuildToolDep { krate: c.name.clone(), dep: d.name.clone(), kind }); + } + if self.policy.testkit_crates.contains(&name) && kind != DepKind::Dev && !self.policy.may_use_testkit_normally(class, &c.name) { + self.out.push(Violation::TestkitAsNormalDep { krate: c.name.clone(), dep: d.name.clone(), kind }); + } + let Some(layer) = class.layer(self.policy) else { return }; + let dev_allowed = kind == DepKind::Dev && self.policy.ui_dev_allowed.contains(&name); + if layer < self.policy.ui_min_layer && self.policy.is_ui_crate(name) && !dev_allowed { + self.out.push(Violation::UiBelowMinLayer { krate: c.name.clone(), dep: d.name.clone(), layer, min: self.policy.ui_min_layer, kind }); + } + } +} + +/// Checks every package in `crates` against `policy`. +/// +/// Returns the violations sorted, without duplicates. Every dependency kind is checked; a crate's +/// workspace dependency on itself (a dev-dependency that turns on its own features) is skipped. +/// Same-layer edges that pass, dev exceptions included, are checked for cycles. +/// +/// Returns an error when the policy cannot be applied to this workspace: see [`Error::Policy`]. +pub fn check(policy: &Policy<'_>, crates: &[Crate]) -> Result, Error> { + let table = validate(policy, crates)?; + let members: HashSet<&str> = crates.iter().map(|c| c.name.as_str()).collect(); + let mut checker = Checker { policy, table: &table, members: &members, out: Vec::new(), same_layer_edges: BTreeMap::new() }; + for c in crates { + let Some(class) = table.get(c.name.as_str()).copied() else { + checker.out.push(Violation::Unregistered { krate: c.name.clone() }); + continue; + }; + for d in &c.deps { + if d.workspace && d.name == c.name { + continue; + } + if d.workspace { + checker.workspace_dep(c, class, d); + } else { + checker.external_dep(c, class, d); + } + } + } + let mut out = checker.out; + for crates in cycles(&checker.same_layer_edges) { + out.push(Violation::SameLayerCycle { crates }); + } + out.sort(); + out.dedup(); + Ok(out) +} + +/// The strongly connected components with more than one member, each sorted, found with an +/// iterative Tarjan walk so that a long chain cannot overflow the stack. +fn cycles(edges: &BTreeMap<&str, BTreeSet<&str>>) -> Vec> { + let nodes: Vec<&str> = + edges.iter().flat_map(|(from, to)| std::iter::once(*from).chain(to.iter().copied())).collect::>().into_iter().collect(); + let id: HashMap<&str, usize> = nodes.iter().enumerate().map(|(i, n)| (*n, i)).collect(); + let adj: Vec> = + nodes.iter().map(|n| edges.get(n).map(|to| to.iter().filter_map(|t| id.get(t).copied()).collect()).unwrap_or_default()).collect(); + const UNSEEN: usize = usize::MAX; + let mut index = vec![UNSEEN; nodes.len()]; + let mut low = vec![0; nodes.len()]; + let mut on_stack = vec![false; nodes.len()]; + let mut stack = Vec::new(); + let mut next = 0; + let mut out = Vec::new(); + for root in 0..nodes.len() { + if index[root] != UNSEEN { + continue; + } + let mut work = vec![(root, 0usize)]; + index[root] = next; + low[root] = next; + next += 1; + stack.push(root); + on_stack[root] = true; + while let Some(top) = work.last_mut() { + let v = top.0; + if let Some(&w) = adj[v].get(top.1) { + top.1 += 1; + if index[w] == UNSEEN { + index[w] = next; + low[w] = next; + next += 1; + stack.push(w); + on_stack[w] = true; + work.push((w, 0)); + } else if on_stack[w] { + low[v] = low[v].min(index[w]); + } + continue; + } + work.pop(); + if let Some(&(parent, _)) = work.last() { + low[parent] = low[parent].min(low[v]); + } + if low[v] == index[v] { + let mut component = Vec::new(); + while let Some(w) = stack.pop() { + on_stack[w] = false; + component.push(nodes[w].to_owned()); + if w == v { + break; + } + } + if component.len() > 1 { + component.sort(); + out.push(component); + } + } + } + } + out +} + +/// The packages the app's wasm step builds: the workspace's layered and standalone crates at or +/// below [`Policy::wasm_max_layer`], and the [`Policy::wasm_extra`] packages the workspace has, +/// sorted and without duplicates. Test and build tooling are never selected. +/// +/// The set says which packages the app means to build for wasm, not that they build. An empty set +/// is an error, as is a policy that [`check`] would refuse. +pub fn wasm_set(policy: &Policy<'_>, crates: &[Crate]) -> Result, Error> { + let table = validate(policy, crates)?; + let mut out = BTreeSet::new(); + for c in crates { + let selected = match table.get(c.name.as_str()) { + Some(Class::Layer(l) | Class::Standalone(l)) => policy.wasm_max_layer.is_some_and(|max| *l <= max), + Some(Class::Exempt) => false, + Some(Class::Testkit | Class::BuildTool) | None => continue, + }; + if selected || policy.wasm_extra.contains(&c.name.as_str()) { + out.insert(c.name.clone()); + } + } + if out.is_empty() { + return Err(policy_error("the wasm set is empty")); + } + Ok(out.into_iter().collect()) +} + +fn metadata_error(message: impl Into) -> Error { + Error::Metadata(message.into()) +} + +fn str_field<'v>(v: &'v Value, key: &str, what: &str) -> Result<&'v str, Error> { + v.get(key).and_then(Value::as_str).ok_or_else(|| metadata_error(format!("{what} has no `{key}` string"))) +} + +/// A path with `/` separators and no trailing separator, so that Windows and Unix paths compare. +fn normalize_path(path: &str) -> String { + let p = path.replace('\\', "/"); + p.trim_end_matches('/').to_owned() +} + +fn dep_kind(d: &Value, what: &str) -> Result { + match d.get("kind") { + Some(Value::Null) => Ok(DepKind::Normal), + Some(Value::String(k)) if k == "dev" => Ok(DepKind::Dev), + Some(Value::String(k)) if k == "build" => Ok(DepKind::Build), + Some(other) => Err(metadata_error(format!("{what} has the unknown kind {other}"))), + None => Err(metadata_error(format!("{what} has no `kind`"))), + } +} + +/// Builds the model from the output of `cargo metadata --format-version 1 --no-deps`. +/// +/// A dependency is a workspace member when its `path` is the directory of a member's +/// `manifest_path`; a registry or git dependency with a member's name, and a path dependency +/// outside the workspace, are external. A renamed dependency is matched by its package `name`. +/// Missing or unknown fields, a package that is not in `workspace_members` and a repeated package +/// name are errors. The crates come back sorted by name. +pub fn from_metadata(meta: &Value) -> Result, Error> { + let pkgs = meta.get("packages").and_then(Value::as_array).ok_or_else(|| metadata_error("no `packages` array"))?; + let member_ids = meta.get("workspace_members").and_then(Value::as_array).ok_or_else(|| metadata_error("no `workspace_members` array"))?; + let mut ids = HashSet::with_capacity(member_ids.len()); + for id in member_ids { + let id = id.as_str().ok_or_else(|| metadata_error("a `workspace_members` entry is not a string"))?; + ids.insert(id); + } + let mut dirs: HashMap = HashMap::with_capacity(pkgs.len()); + let mut names = HashSet::with_capacity(pkgs.len()); + let mut seen_ids = HashSet::with_capacity(pkgs.len()); + for p in pkgs { + let name = str_field(p, "name", "a package")?; + if name.is_empty() { + return Err(metadata_error("a package has an empty name")); + } + let what = format!("package {name}"); + let id = str_field(p, "id", &what)?; + if !ids.contains(id) { + return Err(metadata_error(format!("{what} is not in `workspace_members`"))); + } + if !names.insert(name) || !seen_ids.insert(id) { + return Err(metadata_error(format!("{what} appears more than once"))); + } + let manifest = normalize_path(str_field(p, "manifest_path", &what)?); + let Some(dir) = manifest.strip_suffix("/Cargo.toml") else { + return Err(metadata_error(format!("{what} has a `manifest_path` that does not end in Cargo.toml"))); + }; + dirs.insert(dir.to_owned(), name); + } + if let Some(id) = ids.iter().find(|id| !seen_ids.contains(*id)) { + return Err(metadata_error(format!("workspace member {id} has no package entry"))); + } + let mut out = Vec::with_capacity(pkgs.len()); + for p in pkgs { + let name = str_field(p, "name", "a package")?; + let what = format!("package {name}"); + let raw = p.get("dependencies").and_then(Value::as_array).ok_or_else(|| metadata_error(format!("{what} has no `dependencies` array")))?; + let mut deps = Vec::with_capacity(raw.len()); + for d in raw { + let dname = str_field(d, "name", &format!("a dependency of {name}"))?; + if dname.is_empty() { + return Err(metadata_error(format!("a dependency of {name} has an empty name"))); + } + let dwhat = format!("dependency {dname} of {name}"); + let kind = dep_kind(d, &dwhat)?; + let member = match d.get("path") { + None | Some(Value::Null) => None, + Some(Value::String(path)) => dirs.get(&normalize_path(path)).copied(), + Some(_) => return Err(metadata_error(format!("{dwhat} has a `path` that is not a string"))), + }; + if let Some(member) = member + && member != dname + { + return Err(metadata_error(format!("{dwhat} points at the directory of member {member}"))); + } + deps.push(Dep { name: dname.to_owned(), kind, workspace: member.is_some() }); + } + out.push(Crate { name: name.to_owned(), deps }); + } + out.sort_by(|a, b| a.name.cmp(&b.name)); + Ok(out) +} + +/// Runs `cmd` with stdout piped and stderr inherited, reads at most `max_bytes` of its output and +/// parses it as JSON. +/// +/// Returns [`Error::Process`] when the command cannot be started, writes more than `max_bytes` +/// (the child is then ended), or exits with a failure status, and [`Error::Metadata`] when its +/// output is not JSON. `label` names the command in each message. +pub fn read_json(mut cmd: Command, label: &str, max_bytes: usize) -> Result { + cmd.stdin(Stdio::null()).stdout(Stdio::piped()); + let mut child = cmd.spawn().map_err(|e| Error::Process(format!("{label}: failed to spawn: {e}")))?; + let mut buf = Vec::new(); + let read = match child.stdout.take() { + Some(stdout) => stdout.take(u64::try_from(max_bytes).unwrap_or(u64::MAX).saturating_add(1)).read_to_end(&mut buf).map(|_| ()), + None => Err(std::io::Error::other("no stdout pipe")), + }; + let failure = match read { + Err(e) => Some(format!("{label}: reading its output failed: {e}")), + Ok(()) if buf.len() > max_bytes => Some(format!("{label}: wrote more than {max_bytes} bytes")), + Ok(()) => None, + }; + if let Some(message) = failure { + // The child may still be writing; end it so that the wait returns. + let _ = child.kill(); + let _ = child.wait(); + return Err(Error::Process(message)); + } + let status = child.wait().map_err(|e| Error::Process(format!("{label}: waiting for it failed: {e}")))?; + if !status.success() { + return Err(Error::Process(format!("{label}: exited with {status}"))); + } + serde_json::from_slice(&buf).map_err(|e| metadata_error(format!("{label}: the output is not JSON: {e}"))) +} + +/// Runs `cargo metadata --format-version 1 --no-deps` in `root` (through [`crate::runner::cargo`]) +/// and returns its parsed output, reading at most `max_bytes` (see [`DEFAULT_METADATA_LIMIT`]). +pub fn cargo_metadata(root: &Path, max_bytes: usize) -> Result { + let mut cmd = crate::runner::cargo(root); + cmd.args(["metadata", "--format-version", "1", "--no-deps"]); + read_json(cmd, "cargo metadata --format-version 1 --no-deps", max_bytes) +} + +#[cfg(test)] +mod tests { + use super::DepKind::{Build, Dev, Normal}; + use super::*; + + /// A synthetic policy in the shape of the class-based apps: two L0 foundations in a chain, two + /// L1 crates in a chain, sideways-free L2 crates, UI from L6, test tooling at L6. + const TABLE: &[(&str, Class)] = &[ + ("app-geom", Class::Layer(0)), + ("app-color", Class::Layer(0)), + ("app-doc", Class::Layer(1)), + ("app-fonts", Class::Layer(1)), + ("app-compose", Class::Layer(2)), + ("app-images", Class::Layer(2)), + ("app-render", Class::Layer(3)), + ("app-engine", Class::Layer(5)), + ("app-ui-egui", Class::Layer(6)), + ("app-mcp", Class::Layer(6)), + ("app-testkit", Class::Testkit), + ("app", Class::Exempt), + ("app-cli", Class::Exempt), + ("app-web", Class::Exempt), + ("xtask", Class::BuildTool), + ]; + const ALL: &[&str] = &[ + "app-geom", + "app-color", + "app-doc", + "app-fonts", + "app-compose", + "app-images", + "app-render", + "app-engine", + "app-ui-egui", + "app-mcp", + "app-testkit", + "app", + "app-cli", + "app-web", + "xtask", + ]; + const POLICY: Policy<'static> = Policy { + optional: ALL, + ordered_chains: &[&["app-geom", "app-color"], &["app-doc", "app-fonts"]], + ui_crates: &["craft-ui", "craft-window", "egui", "eframe", "winit", "egui_kittest", "rfd", "bevy*"], + ui_min_layer: 6, + testkit_layer: 6, + ..Policy::new(TABLE) + }; + + fn c(name: &str, deps: &[(&str, DepKind, bool)]) -> Crate { + Crate { name: name.into(), deps: deps.iter().map(|(n, k, w)| Dep { name: (*n).into(), kind: *k, workspace: *w }).collect() } + } + + fn check_with(policy: &Policy<'_>, crates: &[Crate]) -> Vec { + match super::check(policy, crates) { + Ok(v) => v, + Err(e) => panic!("{e}"), + } + } + + fn check(crates: &[Crate]) -> Vec { + check_with(&POLICY, crates) + } + + #[test] + fn clean_downward_graph_passes() { + let g = [ + c("app-geom", &[("kurbo", Normal, false)]), + c("app-doc", &[("app-geom", Normal, true)]), + c("app-engine", &[("app-doc", Normal, true), ("app-testkit", Dev, true)]), + c("app-ui-egui", &[("app-engine", Normal, true), ("egui", Normal, false)]), + c("app-cli", &[("app-ui-egui", Normal, true)]), + ]; + assert!(check(&g).is_empty(), "{:?}", check(&g)); + } + + #[test] + fn upward_dependency_flagged() { + let v = check(&[c("app-doc", &[("app-engine", Normal, true)])]); + assert!(matches!(v[..], [Violation::Upward { from: 1, to: 5, .. }]), "{v:?}"); + } + + #[test] + fn sideways_dependency_flagged() { + let v = check(&[c("app-compose", &[("app-images", Normal, true)])]); + assert!(matches!(v[..], [Violation::Upward { from: 2, to: 2, .. }]), "{v:?}"); + } + + #[test] + fn l0_foundation_chain_allowed_one_way() { + assert!(check(&[c("app-color", &[("app-geom", Normal, true)])]).is_empty()); + let v = check(&[c("app-geom", &[("app-color", Normal, true)])]); + assert!(matches!(v[..], [Violation::Upward { from: 0, to: 0, .. }]), "{v:?}"); + } + + #[test] + fn self_dev_dependency_ignored() { + assert!(check(&[c("app-doc", &[("app-doc", Dev, true)])]).is_empty()); + } + + #[test] + fn external_dependency_named_like_its_crate_is_checked() { + let policy = Policy { ui_crates: &["winit"], ui_min_layer: 6, ..Policy::new(&[("winit", Class::Layer(1))]) }; + let v = check_with(&policy, &[c("winit", &[("winit", Normal, false)])]); + assert!(matches!(v[..], [Violation::UiBelowMinLayer { .. }]), "{v:?}"); + } + + #[test] + fn upward_dev_dependency_flagged() { + let v = check(&[c("app-geom", &[("app-doc", Dev, true)])]); + assert!(matches!(v[..], [Violation::Upward { kind: Dev, .. }]), "{v:?}"); + } + + #[test] + fn ui_crates_below_l6_flagged() { + for dep in ["craft-ui", "egui", "eframe", "winit", "egui_kittest", "rfd", "bevy_ecs", "bevy"] { + let v = check(&[c("app-engine", &[(dep, Normal, false)])]); + assert!(matches!(v[..], [Violation::UiBelowMinLayer { layer: 5, min: 6, .. }]), "{dep}: {v:?}"); + } + assert!(check(&[c("app-engine", &[("egui_extras_not", Normal, false)])]).is_empty()); + assert!(check(&[c("app-mcp", &[("winit", Normal, false)])]).is_empty()); + } + + #[test] + fn unregistered_crate_is_error() { + let v = check(&[c("app-mystery", &[])]); + assert!(matches!(&v[..], [Violation::Unregistered { krate }] if krate == "app-mystery"), "{v:?}"); + assert!(v[0].to_string().contains("not in the layer table")); + } + + #[test] + fn testkit_only_as_dev_dependency() { + let v = check(&[c("app-render", &[("app-testkit", Normal, true)])]); + assert!(matches!(v[..], [Violation::TestkitAsNormalDep { .. }]), "{v:?}"); + let v = check(&[c("app-render", &[("app-testkit", Build, true)])]); + assert!(matches!(v[..], [Violation::TestkitAsNormalDep { kind: Build, .. }]), "{v:?}"); + assert!(check(&[c("app-render", &[("app-testkit", Dev, true)])]).is_empty()); + // Test tooling may use anything below its own layer, but not a crate in that layer. + assert!(check(&[c("app-testkit", &[("app-engine", Normal, true)])]).is_empty()); + assert!(!check(&[c("app-testkit", &[("app-ui-egui", Normal, true)])]).is_empty()); + // An app is exempt from the layers, not from the test-tooling rule. + let v = check(&[c("app", &[("app-testkit", Normal, true)])]); + assert!(matches!(v[..], [Violation::TestkitAsNormalDep { .. }]), "{v:?}"); + } + + #[test] + fn apps_and_xtask_exempt() { + for app in ["app", "app-cli", "app-web", "xtask"] { + let v = check(&[c(app, &[("egui", Normal, false), ("app-ui-egui", Normal, true)])]); + assert!(v.is_empty(), "{app}: {v:?}"); + } + } + + fn package(name: &str, dir: &str, deps: Value) -> Value { + serde_json::json!({ "name": name, "id": format!("path+file://{dir}#{name}@0.1.0"), "manifest_path": format!("{dir}/Cargo.toml"), "dependencies": deps }) + } + + fn metadata(packages: Vec) -> Value { + let ids: Vec = packages.iter().map(|p| p["id"].clone()).collect(); + serde_json::json!({ "packages": packages, "workspace_members": ids }) + } + + fn parse(meta: &Value) -> Vec { + match from_metadata(meta) { + Ok(g) => g, + Err(e) => panic!("{e}"), + } + } + + #[test] + fn metadata_parsing() { + let meta = metadata(vec![ + package( + "app-doc", + "/x/crates/doc", + serde_json::json!([ + { "name": "app-geom", "kind": null, "path": "/x/crates/geom" }, + { "name": "serde", "kind": null }, + { "name": "proptest", "kind": "dev" }, + { "name": "cc", "kind": "build" }, + ]), + ), + package("app-geom", "/x/crates/geom", serde_json::json!([])), + ]); + let g = parse(&meta); + assert_eq!(g.len(), 2); + let doc = g.iter().find(|c| c.name == "app-doc").unwrap(); + assert!(doc.deps[0].workspace && !doc.deps[1].workspace); + assert_eq!(doc.deps[2].kind, Dev); + assert_eq!(doc.deps[3].kind, Build); + assert!(check(&g).is_empty()); + } + + #[test] + fn registry_name_collision_is_external() { + let meta = metadata(vec![ + package( + "app-doc", + "/x/crates/doc", + serde_json::json!([{ "name": "app-engine", "kind": null, "source": "registry+https://github.com/rust-lang/crates.io-index" }]), + ), + package("app-engine", "/x/crates/engine", serde_json::json!([])), + ]); + let g = parse(&meta); + assert!(!g[0].deps[0].workspace, "{g:?}"); + assert!(check(&g).is_empty()); + } + + #[test] + fn renamed_workspace_dependency_is_checked() { + let meta = metadata(vec![ + package( + "app-doc", + "/x/crates/doc", + serde_json::json!([{ "name": "app-engine", "rename": "engine", "kind": null, "path": "/x/crates/engine" }]), + ), + package("app-engine", "/x/crates/engine", serde_json::json!([])), + ]); + let g = parse(&meta); + assert!(g[0].deps[0].workspace && g[0].deps[0].name == "app-engine", "{g:?}"); + let v = check(&g); + assert!(matches!(v[..], [Violation::Upward { from: 1, to: 5, .. }]), "{v:?}"); + } + + #[test] + fn outside_path_dependency_is_external() { + let meta = metadata(vec![ + package("app-doc", "/x/crates/doc", serde_json::json!([{ "name": "app-engine", "kind": null, "path": "/elsewhere/engine" }])), + package("app-engine", "/x/crates/engine", serde_json::json!([])), + ]); + assert!(!parse(&meta)[0].deps[0].workspace); + } + + #[test] + fn windows_manifest_path_matches_member() { + let meta = serde_json::json!({ + "packages": [ + { "name": "app-doc", "id": "a", "manifest_path": "C:\\x\\crates\\doc\\Cargo.toml", + "dependencies": [{ "name": "app-geom", "kind": null, "path": "C:\\x\\crates\\geom\\" }] }, + { "name": "app-geom", "id": "b", "manifest_path": "C:\\x\\crates\\geom\\Cargo.toml", "dependencies": [] }, + ], + "workspace_members": ["a", "b"], + }); + assert!(parse(&meta)[0].deps[0].workspace); + } + + fn metadata_err(meta: &Value) -> String { + match from_metadata(meta) { + Ok(g) => panic!("parsed: {g:?}"), + Err(Error::Metadata(m)) => m, + Err(e) => panic!("{e}"), + } + } + + #[test] + fn missing_dependencies_is_error() { + let mut p = package("app-doc", "/x/doc", serde_json::json!([])); + if let Some(o) = p.as_object_mut() { + o.remove("dependencies"); + } + assert!(metadata_err(&metadata(vec![p])).contains("dependencies")); + } + + #[test] + fn unknown_kind_is_error() { + let meta = metadata(vec![package("app-doc", "/x/doc", serde_json::json!([{ "name": "serde", "kind": "target" }]))]); + assert!(metadata_err(&meta).contains("unknown kind")); + let meta = metadata(vec![package("app-doc", "/x/doc", serde_json::json!([{ "name": "serde" }]))]); + assert!(metadata_err(&meta).contains("no `kind`")); + } + + #[test] + fn missing_dependency_name_is_error() { + let meta = metadata(vec![package("app-doc", "/x/doc", serde_json::json!([{ "kind": null }]))]); + assert!(metadata_err(&meta).contains("`name`")); + let meta = metadata(vec![package("app-doc", "/x/doc", serde_json::json!([{ "name": "", "kind": null }]))]); + assert!(metadata_err(&meta).contains("empty name")); + } + + #[test] + fn unregistered_member_is_error() { + // A package that `workspace_members` does not list, and a member without a package entry. + let mut meta = metadata(vec![package("app-doc", "/x/doc", serde_json::json!([]))]); + meta["workspace_members"] = serde_json::json!([]); + assert!(metadata_err(&meta).contains("not in `workspace_members`")); + let mut meta = metadata(vec![package("app-doc", "/x/doc", serde_json::json!([]))]); + meta["workspace_members"] = serde_json::json!(["path+file:///x/doc#app-doc@0.1.0", "gone"]); + assert!(metadata_err(&meta).contains("gone")); + } + + #[test] + fn duplicate_member_is_error() { + let meta = metadata(vec![package("app-doc", "/x/a", serde_json::json!([])), package("app-doc", "/x/b", serde_json::json!([]))]); + assert!(metadata_err(&meta).contains("more than once")); + let Err(Error::Policy(m)) = super::check(&POLICY, &[c("app-doc", &[]), c("app-doc", &[])]) else { panic!("a repeated crate passed") }; + assert!(m.contains("more than once"), "{m}"); + } + + #[test] + fn unknown_workspace_dependency_is_error() { + let v = check(&[c("app-doc", &[("app-ghost", Normal, true)])]); + assert!(matches!(&v[..], [Violation::UnknownDependency { dep, .. }] if dep == "app-ghost"), "{v:?}"); + // When the unknown crate is checked too, it is reported once, on its own entry. + let v = check(&[c("app-doc", &[("app-ghost", Normal, true)]), c("app-ghost", &[])]); + assert!(matches!(&v[..], [Violation::Unregistered { krate }] if krate == "app-ghost"), "{v:?}"); + } + + fn policy_err(policy: &Policy<'_>, crates: &[Crate]) -> String { + match super::check(policy, crates) { + Ok(v) => panic!("checked: {v:?}"), + Err(Error::Policy(m)) => m, + Err(e) => panic!("{e}"), + } + } + + #[test] + fn empty_policy_is_error() { + assert!(policy_err(&Policy::new(&[]), &[c("app-doc", &[])]).contains("table is empty")); + assert!(policy_err(&POLICY, &[]).contains("no packages")); + } + + #[test] + fn duplicate_policy_entry_is_error() { + let table = [("app-doc", Class::Layer(1)), ("app-doc", Class::Layer(2))]; + assert!(policy_err(&Policy::new(&table), &[c("app-doc", &[])]).contains("more than once")); + } + + #[test] + fn unknown_policy_entry_is_error() { + let table = [("app-doc", Class::Layer(1)), ("app-dco", Class::Layer(1))]; + assert!(policy_err(&Policy::new(&table), &[c("app-doc", &[])]).contains("app-dco")); + // An entry the policy names as optional may be missing. + assert!(check_with(&Policy { optional: &["app-dco"], ..Policy::new(&table) }, &[c("app-doc", &[])]).is_empty()); + // Every list must name table entries. + for policy in [ + Policy { ordered_chains: &[&["app-doc", "app-x"]], ..Policy::new(&table[..1]) }, + Policy { sideways: &[("app-doc", "app-x")], ..Policy::new(&table[..1]) }, + Policy { dev_exceptions: &[("app-doc", "app-x")], ..Policy::new(&table[..1]) }, + Policy { optional: &["app-x"], ..Policy::new(&table[..1]) }, + Policy { testkit_normal_users: &["app-x"], ..Policy::new(&table[..1]) }, + Policy { wasm_extra: &["app-x"], ..Policy::new(&table[..1]) }, + Policy { format_allowed: &[("app-doc", &["app-x"])], ..Policy::new(&table[..1]) }, + ] { + assert!(policy_err(&policy, &[c("app-doc", &[])]).contains("app-x"), "{policy:?}"); + } + assert!(policy_err(&Policy { ui_crates: &["*"], ..Policy::new(&table[..1]) }, &[c("app-doc", &[])]).contains("ui_crates")); + assert!(policy_err(&Policy { format_allowed: &[("app", &[])], ..POLICY }, &[c("app", &[])]).contains("exempt")); + } + + #[test] + fn allowed_same_layer_cycle_is_error() { + let flat = Policy { same_layer: SameLayer::Allowed, ..POLICY }; + assert!(check_with(&flat, &[c("app-compose", &[("app-images", Normal, true)])]).is_empty()); + let g = [c("app-compose", &[("app-images", Normal, true)]), c("app-images", &[("app-compose", Dev, true)])]; + let v = check_with(&flat, &g); + assert!(matches!(&v[..], [Violation::SameLayerCycle { crates }] if crates == &["app-compose", "app-images"]), "{v:?}"); + // Overlapping sideways pairs under the ordered policy form the same kind of cycle. + let pairs = Policy { sideways: &[("app-compose", "app-images"), ("app-images", "app-compose")], ..POLICY }; + let v = check_with(&pairs, &g); + assert!(matches!(&v[..], [Violation::SameLayerCycle { .. }]), "{v:?}"); + // So does a same-layer dev exception that closes a loop. + let excepted = Policy { sideways: &[("app-compose", "app-images")], dev_exceptions: &[("app-images", "app-compose")], ..POLICY }; + let v = check_with(&excepted, &g); + assert!(matches!(&v[..], [Violation::SameLayerCycle { .. }]), "{v:?}"); + } + + #[test] + fn large_workspace_is_bounded() { + // A same-layer chain far deeper than a recursive walk could follow, closed into one cycle. + const N: usize = 50_000; + let names: Vec = (0..N).map(|i| format!("p{i:05}")).collect(); + let table: Vec<(&str, Class)> = names.iter().map(|n| (n.as_str(), Class::Layer(0))).collect(); + let crates: Vec = (0..N) + .map(|i| Crate { name: names[i].clone(), deps: vec![Dep { name: names[(i + 1) % N].clone(), kind: Normal, workspace: true }] }) + .collect(); + let v = check_with(&Policy { same_layer: SameLayer::Allowed, ..Policy::new(&table) }, &crates); + assert!(matches!(&v[..], [Violation::SameLayerCycle { crates }] if crates.len() == N)); + } + + #[test] + fn build_dependency_is_checked() { + let v = check(&[c("app-doc", &[("app-engine", Build, true)])]); + assert!(matches!(v[..], [Violation::Upward { kind: Build, .. }]), "{v:?}"); + let v = check(&[c("app-engine", &[("winit", Build, false)])]); + assert!(matches!(v[..], [Violation::UiBelowMinLayer { kind: Build, .. }]), "{v:?}"); + } + + #[test] + fn testkit_normal_only_for_named_tooling() { + let policy = Policy { testkit_crates: &["craft-testkit"], testkit_normal_users: &["xtask"], build_tool_crates: &["craft-xtask"], ..POLICY }; + assert!( + check_with(&policy, &[c("xtask", &[("craft-testkit", Normal, false), ("app-testkit", Normal, true), ("craft-xtask", Normal, false)])]) + .is_empty() + ); + let v = check_with(&policy, &[c("app-engine", &[("craft-testkit", Normal, false)])]); + assert!(matches!(v[..], [Violation::TestkitAsNormalDep { .. }]), "{v:?}"); + assert!(check_with(&policy, &[c("app-engine", &[("craft-testkit", Dev, false)])]).is_empty()); + // The build-tool library is for build tooling only, whatever the kind or the class. + for user in ["app-engine", "app", "app-testkit"] { + for kind in [Normal, Dev, Build] { + let v = check_with(&policy, &[c(user, &[("craft-xtask", kind, false)])]); + assert!(matches!(v[..], [Violation::BuildToolDep { .. }]), "{user} {kind:?}: {v:?}"); + } + } + let v = check_with(&policy, &[c("app", &[("xtask", Normal, true)])]); + assert!(matches!(v[..], [Violation::BuildToolDep { .. }]), "{v:?}"); + } + + #[test] + fn dev_exception_allows_only_the_named_dev_edge() { + let policy = Policy { dev_exceptions: &[("app-render", "app-engine")], ..POLICY }; + assert!(check_with(&policy, &[c("app-render", &[("app-engine", Dev, true)])]).is_empty()); + // Not as a normal or build dependency, and not for another pair. + for (from, kind) in [("app-render", Normal), ("app-render", Build), ("app-doc", Dev)] { + let v = check_with(&policy, &[c(from, &[("app-engine", kind, true)])]); + assert!(matches!(v[..], [Violation::Upward { .. }]), "{from} {kind:?}: {v:?}"); + } + } + + #[test] + fn layered_crate_may_not_use_an_exempt_package() { + let v = check(&[c("app-ui-egui", &[("app-cli", Normal, true)])]); + assert!(matches!(v[..], [Violation::OnExempt { .. }]), "{v:?}"); + } + + #[test] + fn wasm_set_is_sorted_and_unique() { + let policy = Policy { wasm_max_layer: Some(5), wasm_extra: &["app-web", "app-ui-egui"], ..POLICY }; + let g = [ + c("app-web", &[]), + c("app-engine", &[]), + c("app-geom", &[]), + c("app-ui-egui", &[]), + c("app-mcp", &[]), + c("app-testkit", &[]), + c("xtask", &[]), + c("app", &[]), + ]; + assert_eq!(wasm_set(&policy, &g), Ok(["app-engine", "app-geom", "app-ui-egui", "app-web"].map(String::from).to_vec())); + // No layer and no extra the workspace has selects nothing, which is an error. + assert!(matches!(wasm_set(&POLICY, &g), Err(Error::Policy(_)))); + let tooling = Policy { wasm_extra: &["app-testkit"], ..POLICY }; + assert!(matches!(wasm_set(&tooling, &g), Err(Error::Policy(m)) if m.contains("tooling"))); + } + + #[test] + fn oversized_metadata_is_error() { + let _guard = crate::spawn_guard(); + let exe = std::env::current_exe().expect("test executable"); + let mut cmd = Command::new(exe); + cmd.arg("--list").stderr(Stdio::null()); + assert!(matches!(read_json(cmd, "child", 8), Err(Error::Process(m)) if m == "child: wrote more than 8 bytes")); + } + + #[test] + fn non_json_metadata_is_error() { + let _guard = crate::spawn_guard(); + let exe = std::env::current_exe().expect("test executable"); + let mut cmd = Command::new(exe); + cmd.arg("--list").stderr(Stdio::null()); + assert!(matches!(read_json(cmd, "child", DEFAULT_METADATA_LIMIT), Err(Error::Metadata(m)) if m.starts_with("child: the output is not JSON"))); + } + + #[test] + fn metadata_exit_failure_is_error() { + let _guard = crate::spawn_guard(); + let exe = std::env::current_exe().expect("test executable"); + let mut cmd = Command::new(exe); + cmd.arg("--craft-xtask-unknown-flag").stderr(Stdio::null()); + assert!(matches!(read_json(cmd, "child", DEFAULT_METADATA_LIMIT), Err(Error::Process(m)) if m.starts_with("child: exited with "))); + let missing = std::env::temp_dir().join("craft-xtask-no-such-program"); + assert!(matches!(read_json(Command::new(missing), "missing", 1), Err(Error::Process(m)) if m.starts_with("missing: failed to spawn: "))); + } + + /// Generic moves of PdfCraft's tests: numbered standalone crates, listed sideways pairs, UI + /// dev-dependencies and test support at the UI layer. + mod pdfcraft { + use super::super::DepKind::{Dev, Normal}; + use super::super::{Class, Crate, Policy, Violation}; + use super::{c, check_with}; + + const TABLE: &[(&str, Class)] = &[ + ("p-geom", Class::Standalone(0)), + ("p-filters", Class::Standalone(0)), + ("p-extra", Class::Standalone(0)), + ("p-cos", Class::Standalone(1)), + ("p-model", Class::Layer(2)), + ("p-forms", Class::Layer(3)), + ("p-js", Class::Layer(3)), + ("p-edit", Class::Layer(4)), + ("p-redact", Class::Layer(4)), + ("p-engine", Class::Layer(6)), + ("p-ui", Class::Layer(7)), + ("p-testkit", Class::Testkit), + ("p-oracle", Class::Testkit), + ("p", Class::Exempt), + ("xtask", Class::BuildTool), + ]; + const ALL: &[&str] = &[ + "p-geom", + "p-filters", + "p-extra", + "p-cos", + "p-model", + "p-forms", + "p-js", + "p-edit", + "p-redact", + "p-engine", + "p-ui", + "p-testkit", + "p-oracle", + "p", + "xtask", + ]; + const POLICY: Policy<'static> = Policy { + optional: ALL, + sideways: &[("p-redact", "p-edit")], + standalone_deps: &[("p-cos", &["p-filters", "p-geom"])], + ui_crates: &["egui", "winit", "egui_kittest", "wgpu*"], + ui_min_layer: 7, + ui_dev_allowed: &["egui_kittest"], + testkit_layer: 7, + ..Policy::new(TABLE) + }; + + fn check(crates: &[Crate]) -> Vec { + check_with(&POLICY, crates) + } + + #[test] + fn upward_and_sideways_edges_flagged() { + let v = check(&[c("p-model", &[("p-engine", Normal, true)])]); + assert!(matches!(v[..], [Violation::Upward { from: 2, to: 6, .. }]), "{v:?}"); + let v = check(&[c("p-forms", &[("p-js", Normal, true)])]); + assert!(matches!(v[..], [Violation::Upward { from: 3, to: 3, .. }]), "{v:?}"); + } + + #[test] + fn listed_sideways_edges_allowed() { + assert!(check(&[c("p-redact", &[("p-edit", Normal, true)])]).is_empty()); + assert!(!check(&[c("p-edit", &[("p-redact", Normal, true)])]).is_empty()); + } + + #[test] + fn cos_may_use_only_its_listed_foundation() { + assert!(check(&[c("p-cos", &[("p-filters", Normal, true), ("p-geom", Dev, true)])]).is_empty()); + let v = check(&[c("p-cos", &[("p-extra", Normal, true)])]); + assert!(matches!(v[..], [Violation::StandaloneHasWorkspaceDep { .. }]), "{v:?}"); + let v = check(&[c("p-filters", &[("p-geom", Normal, true)])]); + assert!(matches!(v[..], [Violation::StandaloneHasWorkspaceDep { .. }]), "{v:?}"); + // A standalone crate is usable from higher layers. + assert!(check(&[c("p-model", &[("p-cos", Normal, true)])]).is_empty()); + } + + #[test] + fn ui_crates_below_l7_flagged() { + for dep in ["egui", "winit", "wgpu", "wgpu-core"] { + let v = check(&[c("p-engine", &[(dep, Normal, false)])]); + assert!(matches!(v[..], [Violation::UiBelowMinLayer { layer: 6, min: 7, .. }]), "{dep}: {v:?}"); + } + assert!(check(&[c("p-ui", &[("winit", Normal, false)])]).is_empty()); + assert!(check(&[c("p-engine", &[("egui_kittest", Dev, false)])]).is_empty()); + assert!(!check(&[c("p-engine", &[("egui_kittest", Normal, false)])]).is_empty()); + assert!(check(&[c("p-testkit", &[("egui", Normal, false)])]).is_empty()); + } + + #[test] + fn test_support_only_as_dev_dependency() { + assert!(!check(&[c("p-cos", &[("p-testkit", Normal, true)])]).is_empty()); + assert!(check(&[c("p-model", &[("p-oracle", Dev, true)])]).is_empty()); + let v = check(&[c("p-model", &[("p-oracle", Normal, true)])]); + assert!(matches!(v[..], [Violation::TestkitAsNormalDep { .. }]), "{v:?}"); + // A standalone crate may use test support in its own tests, and no other workspace + // crate outside its list however it is depended on. + assert!(check(&[c("p-cos", &[("p-oracle", Dev, true)])]).is_empty()); + assert!(check(&[c("p-geom", &[("p-testkit", Dev, true)])]).is_empty()); + let v = check(&[c("p-cos", &[("p-model", Dev, true)])]); + assert!(matches!(v[..], [Violation::StandaloneHasWorkspaceDep { .. }]), "{v:?}"); + // Test support may use other test support. + assert!(check(&[c("p-oracle", &[("p-testkit", Normal, true)])]).is_empty()); + } + + #[test] + fn unregistered_crate_is_error() { + let v = check(&[c("p-mystery", &[])]); + assert!(matches!(&v[..], [Violation::Unregistered { krate }] if krate == "p-mystery"), "{v:?}"); + } + + #[test] + fn apps_exempt() { + for app in ["p", "xtask"] { + assert!(check(&[c(app, &[("egui", Normal, false), ("p-ui", Normal, true)])]).is_empty(), "{app}"); + } + } + } + + /// Generic moves of PhotoCraft's standalone tests. + mod photocraft { + use super::super::DepKind::{Dev, Normal}; + use super::super::{Class, Crate, Policy, Violation}; + use super::{c, check_with}; + + const TABLE: &[(&str, Class)] = &[ + ("h-geom", Class::Layer(0)), + ("h-io", Class::Layer(1)), + ("h-psd", Class::Standalone(0)), + ("h-codecs", Class::Standalone(0)), + ("h-heif", Class::Standalone(0)), + ]; + const POLICY: Policy<'static> = Policy { + optional: &["h-geom", "h-io", "h-psd", "h-codecs", "h-heif"], + standalone_deps: &[("h-codecs", &["h-heif"])], + ..Policy::new(TABLE) + }; + + fn check(crates: &[Crate]) -> Vec { + check_with(&POLICY, crates) + } + + #[test] + fn standalone_crates_have_no_workspace_deps() { + for s in ["h-psd", "h-codecs", "h-heif"] { + let v = check(&[c(s, &[("h-geom", Normal, true)])]); + assert!(matches!(v[..], [Violation::StandaloneHasWorkspaceDep { .. }]), "{s}: {v:?}"); + assert!(check(&[c(s, &[("image", Normal, false)])]).is_empty()); + } + } + + #[test] + fn standalone_exception_is_exactly_codecs_to_heif() { + assert!(check(&[c("h-codecs", &[("h-heif", Normal, true)])]).is_empty()); + assert!(check(&[c("h-codecs", &[("h-heif", Dev, true)])]).is_empty()); + for (from, to) in [("h-heif", "h-codecs"), ("h-psd", "h-heif"), ("h-heif", "h-geom")] { + let v = check(&[c(from, &[(to, Normal, true)])]); + assert!(matches!(v[..], [Violation::StandaloneHasWorkspaceDep { .. }]), "{from} -> {to}: {v:?}"); + } + // The exception does not open the standalone crate to layered crates. + let v = check(&[c("h-codecs", &[("h-geom", Normal, true)])]); + assert!(matches!(v[..], [Violation::StandaloneHasWorkspaceDep { .. }]), "{v:?}"); + // A standalone dependency list may only name standalone crates. + let bad = Policy { standalone_deps: &[("h-codecs", &["h-geom"])], ..POLICY }; + assert!(super::super::check(&bad, &[c("h-codecs", &[])]).is_err()); + } + + #[test] + fn format_allowlist_applies_to_standalone_crates() { + let limited = Policy { format_allowed: &[("h-codecs", &[])], ..POLICY }; + let v = check_with(&limited, &[c("h-codecs", &[("h-heif", Normal, true)])]); + assert!(matches!(&v[..], [Violation::FormatDep { dep, .. }] if dep == "h-heif"), "{v:?}"); + assert!(check_with(&limited, &[c("h-codecs", &[("h-heif", Dev, true)])]).is_empty()); + } + + #[test] + fn format_allowlist_applies_to_allowed_test_tooling() { + const TABLE: &[(&str, Class)] = &[("t-format", Class::Layer(1)), ("t-testkit", Class::Testkit)]; + let policy = Policy { testkit_normal_users: &["t-format"], format_allowed: &[("t-format", &[])], ..Policy::new(TABLE) }; + let v = check_with(&policy, &[c("t-format", &[("t-testkit", Normal, true)]), c("t-testkit", &[])]); + assert!(matches!(&v[..], [Violation::FormatDep { dep, .. }] if dep == "t-testkit"), "{v:?}"); + } + + #[test] + fn standalone_is_usable_from_higher_layers() { + assert!(check(&[c("h-io", &[("h-psd", Normal, true)])]).is_empty()); + let v = check(&[c("h-geom", &[("h-codecs", Normal, true)])]); + assert!(matches!(v[..], [Violation::Upward { from: 0, to: 0, .. }]), "{v:?}"); + } + } + + /// Generic moves of GridCraft's chain and format tests. + mod gridcraft { + use super::super::DepKind::{Dev, Normal}; + use super::super::{Class, Crate, Policy, Violation}; + use super::{c, check_with}; + + const TABLE: &[(&str, Class)] = &[ + ("g-core", Class::Layer(0)), + ("g-numfmt", Class::Layer(0)), + ("g-model", Class::Layer(1)), + ("g-formula", Class::Layer(1)), + ("g-calc", Class::Layer(1)), + ("g-xlsx", Class::Layer(2)), + ]; + const POLICY: Policy<'static> = Policy { + optional: &["g-core", "g-numfmt", "g-model", "g-formula", "g-calc", "g-xlsx"], + ordered_chains: &[&["g-core", "g-numfmt"], &["g-model", "g-calc"]], + format_allowed: &[("g-xlsx", &["g-core", "g-formula", "g-model"])], + ..Policy::new(TABLE) + }; + + fn check(crates: &[Crate]) -> Vec { + check_with(&POLICY, crates) + } + + #[test] + fn intra_layer_chains_allowed_one_way() { + assert!(check(&[c("g-numfmt", &[("g-core", Normal, true)])]).is_empty()); + let v = check(&[c("g-core", &[("g-numfmt", Normal, true)])]); + assert!(matches!(v[..], [Violation::Upward { from: 0, to: 0, .. }]), "{v:?}"); + assert!(check(&[c("g-calc", &[("g-model", Normal, true)])]).is_empty()); + assert!(!check(&[c("g-model", &[("g-calc", Normal, true)])]).is_empty()); + assert!(!check(&[c("g-calc", &[("g-xlsx", Normal, true)])]).is_empty()); + } + + #[test] + fn format_crate_limited_to_core_formula_model() { + let v = check(&[c("g-xlsx", &[("g-numfmt", Normal, true)])]); + assert!(matches!(&v[..], [Violation::FormatDep { dep, .. }] if dep == "g-numfmt"), "{v:?}"); + assert!(check(&[c("g-xlsx", &[("g-numfmt", Dev, true)])]).is_empty()); + assert!(check(&[c("g-xlsx", &[("g-model", Normal, true)])]).is_empty()); + } + } +} diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs index 2ed8390e00..b1ba97730d 100644 --- a/crates/xtask/src/lib.rs +++ b/crates/xtask/src/lib.rs @@ -9,6 +9,9 @@ //! - [`runner`]: the gate's step runner. [`runner::run_steps`] runs the steps in order, stops at the //! first failure and prints the `ok`, `FAIL` and `skip` summary. [`runner::root`], //! [`runner::cargo`], [`runner::run`] and [`runner::nextest_or_test`] build and run the commands. +//! - [`layers`]: the crate-layer check. The app supplies its table of packages and layers as a +//! [`layers::Policy`]; [`layers::check`] reports each dependency the policy does not allow, and +//! [`layers::wasm_set`] picks the packages the app's wasm step builds. //! - `lock` (feature `lock`): a fixed number of slots, held across processes through file locks, so //! that gate runs in several checkouts of one machine take turns. //! - `report` (feature `report`): the per-step JSON report, replaced atomically. @@ -35,6 +38,7 @@ //! } //! ``` +pub mod layers; #[cfg(feature = "lock")] pub mod lock; #[cfg(feature = "report")] From 61141bcf72970cee9b682d3126b95604570610e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:43:23 -0800 Subject: [PATCH 006/257] craft-xtask: check pinned dependencies from cargo metadata Add a pins module, behind the pins feature, for the apps' pdf-deps xtask commands. Each app passes its own table: the version, source and allowed features of each pinned package, and packages it forbids, either when resolved at all or when reached from a root package over normal and build edges. Unlisted packages are allowed. run_target_features checks the features one target enables through cargo tree, and host_target reads the host from rustc -vV. Every command's standard output is read within a configurable limit (64 MiB for metadata and tree output by default); a larger output stops the command and returns an error. Standard error is drained, and its first 64 KiB are kept for the message. The DeckCraft, VectorCraft, DesignCraft and EffectCraft tests move in under their own names, with their tables as fixtures. --- crates/xtask/Cargo.toml | 4 +- crates/xtask/README.md | 59 +- crates/xtask/src/lib.rs | 4 + crates/xtask/src/pins.rs | 1217 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 1282 insertions(+), 2 deletions(-) create mode 100644 crates/xtask/src/pins.rs diff --git a/crates/xtask/Cargo.toml b/crates/xtask/Cargo.toml index 6b561b543b..680cc3bb4b 100644 --- a/crates/xtask/Cargo.toml +++ b/crates/xtask/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true license.workspace = true rust-version.workspace = true repository.workspace = true -description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes and a per-step JSON report" +description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes, a per-step JSON report and a check of pinned dependencies" [lints] workspace = true @@ -16,6 +16,8 @@ default = [] lock = [] # The per-step JSON report, replaced atomically. report = ["dep:serde_json", "dep:craft-atomic"] +# Pinned dependencies and forbidden packages, checked in `cargo metadata` (`cargo xtask pdf-deps`). +pins = ["dep:serde_json"] [dependencies] craft-atomic = { workspace = true, optional = true } diff --git a/crates/xtask/README.md b/crates/xtask/README.md index 75228c3d66..72208948a8 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -9,8 +9,9 @@ The crate is native only and is a dependency of an app's `xtask` package only. | `runner` | always | `Step`, `run_steps` (steps in order, stop at the first failure, the `ok`, `FAIL` and `skip` summary), `root`, `cargo`, `run`, `run_cancelable`, `nextest_or_test`, `doctest`, `Cancel` | | `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses | | `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` | +| `pins` | `pins` | `run`, `check`, `run_target_features`, `host_target`: the version, source and features of pinned dependencies, and packages the app forbids, read from `cargo metadata` within size limits | -No feature is on by default. `report` adds `serde_json` and `craft-atomic`. +No feature is on by default. `report` adds `serde_json` and `craft-atomic`, and `pins` adds `serde_json`. ## Use @@ -91,6 +92,56 @@ cancel while waiting) runs no step and writes no report. The report looks like t so a reader never sees a partial report, and a failed write leaves the previous report in place. Machine, GPU, corpus and skip details stay in the app's own report. +## Pins + +`cargo xtask pdf-deps` checks that pinned dependencies resolve to the pinned version and source, with +the allowed features, and that packages the app forbids are not in the graph. The app enables the +`pins` feature, keeps its own table and passes it with a function that builds its `cargo` command: + +```rust +use craft_xtask::pins::{FeatureRule, Forbidden, Name, Pin, Policy, Scope}; + +const REV: &str = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef"; + +Some("pdf-deps") => { + let source = craft_xtask::pins::git_source("https://github.com/storytold/craft-libs", REV); + let pins = [Pin { name: "craft-pdf", version: "0.1.0", source: &source, features: FeatureRule::Exactly(&["read"]) }]; + let forbidden = [Forbidden { name: Name::Exact("krilla"), scope: Scope::Active }]; + craft_xtask::pins::run(cargo, &Policy { pins: &pins, forbidden: &forbidden }, &Default::default()) + .map_err(|e| e.to_string()) +} +``` + +- `run` runs `cargo metadata --locked --format-version 1` and passes the JSON to `check`. +- Each `Pin` name has exactly one package, with the pinned `version` and `source`. `git_source(url, rev)` + gives the source Cargo writes for a git dependency pinned to a full commit hash, and `CRATES_IO` the + source for crates.io. +- `FeatureRule::Contains` requires the listed features and allows others. `FeatureRule::Exactly` + allows the listed features only. Both read the package's node in `resolve.nodes`. +- `Scope::Active` rejects a forbidden package that has a resolved node, development dependencies + included. `Scope::ProductionFrom(root)` rejects a forbidden package reached from `root` over normal + or build edges; one reached only through development edges is allowed. `Name::Family("hayro")` + matches `hayro` and every `hayro-*` name. +- Packages the policy does not name are allowed, and an empty policy accepts any metadata. +- JSON that does not parse, or lacks a field a rule needs (`resolve.nodes`, a package `id`, a node's + `features` or `deps`, an edge's `dep_kinds`), is an error. +- Cargo merges every target's features into one metadata result. `run_target_features` runs + `cargo tree --target ` from a root package and checks that each line for one package has + exactly the given features; `host_target` reads the host target from `rustc -vV`. +- `Limits` bounds each command's output. More standard output than the limit stops the command and + returns an error. Standard error is read to its end, and its first `stderr_bytes` are kept for the + error message: + + | Limit | Default | + |---|---| + | `metadata_bytes`: the `cargo metadata` JSON, also for JSON passed to `check` | 64 MiB | + | `tree_bytes`: one `cargo tree` output | 64 MiB | + | `version_bytes`: the `rustc -vV` output | 64 KiB | + | `stderr_bytes`: standard error kept for a message | 64 KiB | + +- `pins::Error` tells apart a command that could not start, could not be read, exited without + success or printed too much; output that is not valid; and a `Violation` of the policy. + ## Origin | Part | Source | @@ -99,6 +150,11 @@ Machine, GPU, corpus and skip details stay in the app's own report. | `lock` and its tests `one_slot_is_exclusive_until_dropped`, `more_slots_admit_more_runs` | LightCraft `xtask/src/ci_lock.rs` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci_lock.rs) | | `report`: the per-step fields | LightCraft `xtask/src/ci.rs:347-414` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci.rs#L347-L414) | | The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report | written here | +| `pins`: exact feature sets, the production walk over normal and build edges, the per-target `cargo tree` feature check, and their five tests | DeckCraft `xtask/src/pdf_deps.rs` at `aa3a1baa01` | +| `pins`: one package per name with an exact version and source, and its three tests | VectorCraft `xtask/src/pdf_deps.rs` at `34627134fa` | +| `pins`: required features that allow others, and its five tests | DesignCraft `xtask/src/pdf_deps.rs` at `18246dddd2` | +| `pins`: packages forbidden when resolved, and its five tests | EffectCraft `xtask/src/pdf_deps.rs` at `f31a6b0aef` | +| `pins`: the output size limits, an empty feature list in `cargo tree`, and the errors for missing fields, features that are not strings, edges without a kind and packages without a name | written here | ## Migration @@ -108,6 +164,7 @@ No app uses this crate yet. |---|---| | DesignCraft | Planned: `cmd_ci`, `root`, `cargo`, `run`, `cmd_test` and `cmd_doctest` move to `runner`, with `TestMode::PreferNextest`. The step list, `TEST_TARGETS` and the i18n report stay in the app. | | LightCraft | Planned: `ci_lock.rs` moves to `lock`, with `LIGHTCRAFT_CI_LOCK` and `LIGHTCRAFT_CI_SLOTS` read by the app. The machine, GPU, corpus and skip report stays in the app. | +| DeckCraft, DesignCraft, EffectCraft, VectorCraft | Planned: `xtask/src/pdf_deps.rs` moves to `pins`. Each app keeps its `pdf-deps` command and its table, and runs `cargo xtask pdf-deps` before and after the switch. | Maintainers: the craft-libs maintainers, until a responsible maintainer or team is agreed in the review of this crate's first pull request. diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs index 2ed8390e00..9f08c4b7bd 100644 --- a/crates/xtask/src/lib.rs +++ b/crates/xtask/src/lib.rs @@ -12,6 +12,8 @@ //! - `lock` (feature `lock`): a fixed number of slots, held across processes through file locks, so //! that gate runs in several checkouts of one machine take turns. //! - `report` (feature `report`): the per-step JSON report, replaced atomically. +//! - `pins` (feature `pins`): the version, source and features of pinned dependencies, and packages +//! an app forbids, read from `cargo metadata` (`cargo xtask pdf-deps`). //! //! ```no_run //! use std::path::Path; @@ -37,6 +39,8 @@ #[cfg(feature = "lock")] pub mod lock; +#[cfg(feature = "pins")] +pub mod pins; #[cfg(feature = "report")] pub mod report; pub mod runner; diff --git a/crates/xtask/src/pins.rs b/crates/xtask/src/pins.rs new file mode 100644 index 0000000000..0109ae9c20 --- /dev/null +++ b/crates/xtask/src/pins.rs @@ -0,0 +1,1217 @@ +//! Pinned dependencies: the version, source and features of named packages in `cargo metadata`, and +//! packages an app forbids. +//! +//! The app passes a [`Policy`]: one [`Pin`] for each package it pins and one [`Forbidden`] rule for +//! each package (or family of packages) it keeps out. [`run`] runs +//! `cargo metadata --locked --format-version 1` with the app's `cargo` command and passes the JSON to +//! [`check`]: +//! +//! - Each pinned name has exactly one package in `packages`, with the pinned `version` and `source`. +//! The source is compared as text: `git_source(url, rev)` gives the form Cargo writes for a package +//! taken from a git repository at a full commit hash, and [`CRATES_IO`] the form for crates.io. +//! - [`FeatureRule::Contains`] and [`FeatureRule::Exactly`] read the features enabled on the package +//! from its node in `resolve.nodes`. `Contains` allows features beyond the listed ones, and +//! `Exactly` does not. +//! - [`Scope::Active`] rejects a forbidden package that has a node in `resolve.nodes`, development +//! dependencies included. [`Scope::ProductionFrom`] rejects a forbidden package reached from a root +//! package over normal and build edges; a package reached only through development edges is +//! allowed. +//! - Packages the policy does not name are allowed. An empty policy accepts any metadata. +//! +//! A rule that needs `resolve.nodes`, a package `id` or a node's `features` or `deps` returns an +//! [`Error::Output`] when the field is missing, and so does JSON that does not parse. +//! +//! Cargo merges the features of every target into one metadata result. To check the features one +//! target enables, [`run_target_features`] reads `cargo tree` for that target and +//! [`check_target_features`] compares the features of each line for the package; [`host_target`] +//! reads the host target from `rustc -vV`. +//! +//! Every command's output is read within a [`Limits`] size: more standard output than the limit stops +//! the command and returns [`Error::TooLarge`]. Standard error is read to its end while the command +//! runs, and its first [`Limits::stderr_bytes`] bytes are kept for the error message. + +use std::collections::{BTreeSet, HashMap, HashSet}; +use std::fmt; +use std::io::{self, Read}; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::thread::JoinHandle; + +use serde_json::Value; + +/// The `source` Cargo writes for a package from crates.io. +pub const CRATES_IO: &str = "registry+https://github.com/rust-lang/crates.io-index"; + +/// The `source` Cargo writes for a package from the git repository at `url`, pinned with +/// `rev = ""` where `rev` is a full commit hash: `git+?rev=#`. +pub fn git_source(url: &str, rev: &str) -> String { + format!("git+{url}?rev={rev}#{rev}") +} + +/// One pinned package. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Pin<'a> { + /// The package name. + pub name: &'a str, + /// The exact `version`. + pub version: &'a str, + /// The exact `source`, for example from [`git_source`] or [`CRATES_IO`]. + pub source: &'a str, + /// Which enabled features are allowed. + pub features: FeatureRule<'a>, +} + +/// How a [`Pin`] checks the package's enabled features. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FeatureRule<'a> { + /// The features are not checked. + Ignore, + /// Each listed feature is enabled; others may be enabled too. + Contains(&'a [&'a str]), + /// The listed features, and no others, are enabled. + Exactly(&'a [&'a str]), +} + +/// Which package names a [`Forbidden`] rule matches. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Name<'a> { + /// This name only. + Exact(&'a str), + /// This name and every name that starts with it followed by `-`: `Family("hayro")` matches + /// `hayro` and `hayro-syntax`. + Family(&'a str), +} + +impl Name<'_> { + /// Whether `name` matches. + pub fn matches(&self, name: &str) -> bool { + match *self { + Name::Exact(n) => name == n, + Name::Family(n) => name.strip_prefix(n).is_some_and(|rest| rest.is_empty() || rest.starts_with('-')), + } + } +} + +impl fmt::Display for Name<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Name::Exact(n) => f.write_str(n), + Name::Family(n) => write!(f, "{n} or {n}-*"), + } + } +} + +/// Where a [`Forbidden`] rule looks. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Scope<'a> { + /// Every package with a node in `resolve.nodes`, development dependencies included. + Active, + /// The packages reached from the named root package over normal and build edges. + ProductionFrom(&'a str), +} + +/// A package, or family of packages, that must not be in the graph. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Forbidden<'a> { + /// The names the rule matches. + pub name: Name<'a>, + /// Where it looks. + pub scope: Scope<'a>, +} + +/// An app's pins and forbidden packages. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Policy<'a> { + /// The pinned packages. + pub pins: &'a [Pin<'a>], + /// The forbidden packages. + pub forbidden: &'a [Forbidden<'a>], +} + +/// Size limits for the commands' output and the JSON [`check`] reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// Bytes of `cargo metadata` JSON, checked before it is parsed. Default 64 MiB. + pub metadata_bytes: usize, + /// Bytes of output from one `cargo tree`. Default 64 MiB. + pub tree_bytes: usize, + /// Bytes of output from `rustc -vV`. Default 64 KiB. + pub version_bytes: usize, + /// Bytes of a command's standard error kept for its error message; the rest is read and dropped. + /// Default 64 KiB. + pub stderr_bytes: usize, +} + +impl Default for Limits { + fn default() -> Self { + Limits { metadata_bytes: 64 << 20, tree_bytes: 64 << 20, version_bytes: 64 << 10, stderr_bytes: 64 << 10 } + } +} + +/// A package that breaks the [`Policy`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Violation { + /// A pinned name, or a root, has this many packages instead of one. + Count { + /// The package name. + name: String, + /// The number of packages with that name. + found: usize, + }, + /// A pinned package has another version. + Version { + /// The package name. + name: String, + /// The pinned version. + expected: String, + /// The version in the metadata. + found: String, + }, + /// A pinned package comes from another source. `found` is `None` for a path package. + Source { + /// The package name. + name: String, + /// The pinned source. + expected: String, + /// The source in the metadata. + found: Option, + }, + /// A package lacks required features or has features the rule does not allow. + Features { + /// The package name, or the `cargo tree` package text. + name: String, + /// Required features that are not enabled. + missing: Vec, + /// Enabled features that are not allowed. + extra: Vec, + }, + /// A forbidden package is in the graph. + Forbidden { + /// The package name. + name: String, + /// The rule's names. + rule: String, + /// The root it was reached from, for [`Scope::ProductionFrom`]. + root: Option, + }, +} + +impl fmt::Display for Violation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Violation::Count { name, found } => write!(f, "{name}: expected one resolved package, found {found}"), + Violation::Version { name, expected, found } => write!(f, "{name}: expected version {expected}, found {found}"), + Violation::Source { name, expected, found } => { + write!(f, "{name}: expected source {expected}, found {}", found.as_deref().unwrap_or("a path package")) + } + Violation::Features { name, missing, extra } => { + write!(f, "{name}: ")?; + if !missing.is_empty() { + write!(f, "missing features {}", missing.join(", "))?; + } + if !missing.is_empty() && !extra.is_empty() { + f.write_str("; ")?; + } + if !extra.is_empty() { + write!(f, "features not allowed {}", extra.join(", "))?; + } + Ok(()) + } + Violation::Forbidden { name, rule, root: None } => write!(f, "{name}: forbidden ({rule}) and resolved"), + Violation::Forbidden { name, rule, root: Some(root) } => { + write!(f, "{name}: forbidden ({rule}) and reached from {root} over normal or build dependencies") + } + } + } +} + +/// Why a check stopped. +#[derive(Debug)] +pub enum Error { + /// A command could not start. + Start { + /// The command, for example `cargo metadata`. + command: String, + /// The error starting it. + source: io::Error, + }, + /// A command's output could not be read, or the command could not be waited for. + Read { + /// The command. + command: String, + /// The error reading it. + source: io::Error, + }, + /// A command exited without success. + Exit { + /// The command. + command: String, + /// Its exit status. + status: ExitStatus, + /// The start of its standard error, at most [`Limits::stderr_bytes`]. + stderr: String, + }, + /// A command printed more than its limit, or the JSON given to [`check`] is larger than + /// [`Limits::metadata_bytes`]. + TooLarge { + /// The command. + command: String, + /// The limit in bytes. + limit: usize, + }, + /// A command's output is not what was expected: JSON that does not parse, or lacks a field a + /// rule needs. + Output { + /// The command. + command: String, + /// What is wrong. + why: String, + }, + /// The packages break the policy. + Violation(Violation), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Start { command, source } => write!(f, "{command}: could not start: {source}"), + Error::Read { command, source } => write!(f, "{command}: {source}"), + Error::Exit { command, status, stderr } if stderr.is_empty() => write!(f, "{command}: exited with {status}"), + Error::Exit { command, status, stderr } => write!(f, "{command}: exited with {status}: {stderr}"), + Error::TooLarge { command, limit } => write!(f, "{command}: more than the limit of {limit} bytes of output"), + Error::Output { command, why } => write!(f, "{command}: {why}"), + Error::Violation(v) => v.fmt(f), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Start { source, .. } | Error::Read { source, .. } => Some(source), + _ => None, + } + } +} + +impl From for Error { + fn from(v: Violation) -> Self { + Error::Violation(v) + } +} + +const METADATA: &str = "cargo metadata"; + +/// Runs `cargo metadata --locked --format-version 1` and checks its JSON against `policy`. +/// +/// `cargo` builds the app's `cargo` command (program, folder and environment); the arguments are added +/// to it. +pub fn run(cargo: impl FnOnce() -> Command, policy: &Policy<'_>, limits: &Limits) -> Result<(), Error> { + let json = metadata(cargo, limits)?; + check(&json, policy, limits) +} + +/// The output of `cargo metadata --locked --format-version 1`, read within +/// [`Limits::metadata_bytes`]. +pub fn metadata(cargo: impl FnOnce() -> Command, limits: &Limits) -> Result, Error> { + let mut cmd = cargo(); + cmd.args(["metadata", "--locked", "--format-version", "1"]); + output(cmd, METADATA, limits.metadata_bytes, limits.stderr_bytes) +} + +/// Checks `cargo metadata --format-version 1` JSON against `policy`: the pins first, in order, then +/// the forbidden rules. The first broken rule is returned. +pub fn check(metadata_json: &[u8], policy: &Policy<'_>, limits: &Limits) -> Result<(), Error> { + if metadata_json.len() > limits.metadata_bytes { + return Err(Error::TooLarge { command: METADATA.into(), limit: limits.metadata_bytes }); + } + let meta: Value = serde_json::from_slice(metadata_json).map_err(|e| invalid(format!("not JSON: {e}")))?; + let graph = Graph::new(&meta)?; + for pin in policy.pins { + graph.check_pin(pin)?; + } + for rule in policy.forbidden { + match rule.scope { + Scope::Active => graph.check_active(&rule.name)?, + Scope::ProductionFrom(root) => graph.check_production(&rule.name, root)?, + } + } + Ok(()) +} + +/// The packages and resolved nodes of one metadata result. +struct Graph<'m> { + packages: &'m [Value], + by_id: HashMap<&'m str, &'m Value>, + /// `None` when the JSON has no `resolve.nodes` (`--no-deps`). + nodes: Option>, +} + +impl<'m> Graph<'m> { + fn new(meta: &'m Value) -> Result { + let packages = meta.get("packages").and_then(Value::as_array).ok_or_else(|| invalid("packages is missing"))?; + let mut by_id = HashMap::new(); + for p in packages { + str_field(p, "name", "a package")?; + if let Some(id) = p.get("id").and_then(Value::as_str) + && by_id.insert(id, p).is_some() + { + return Err(invalid(format!("package {id} is listed twice"))); + } + } + let nodes = match meta.pointer("/resolve/nodes").and_then(Value::as_array) { + None => None, + Some(list) => { + let mut nodes = HashMap::new(); + for n in list { + let id = str_field(n, "id", "a resolved node")?; + if nodes.insert(id, n).is_some() { + return Err(invalid(format!("package {id} has two resolved nodes"))); + } + } + Some(nodes) + } + }; + Ok(Graph { packages, by_id, nodes }) + } + + /// The packages named `name`. + fn named(&self, name: &str) -> Vec<&'m Value> { + self.packages.iter().filter(|p| p.get("name").and_then(Value::as_str) == Some(name)).collect() + } + + /// The one package named `name`. + fn one(&self, name: &str) -> Result<&'m Value, Error> { + match self.named(name).as_slice() { + [package] => Ok(package), + other => Err(Violation::Count { name: name.into(), found: other.len() }.into()), + } + } + + fn node(&self, id: &str) -> Result<&'m Value, Error> { + let nodes = self.nodes.as_ref().ok_or_else(|| invalid("resolve.nodes is missing; run cargo metadata without --no-deps"))?; + nodes.get(id).copied().ok_or_else(|| invalid(format!("package {id} has no resolved node"))) + } + + fn check_pin(&self, pin: &Pin<'_>) -> Result<(), Error> { + let package = self.one(pin.name)?; + let version = str_field(package, "version", pin.name)?; + if version != pin.version { + return Err(Violation::Version { name: pin.name.into(), expected: pin.version.into(), found: version.into() }.into()); + } + let source = package.get("source").and_then(Value::as_str); + if source != Some(pin.source) { + return Err(Violation::Source { name: pin.name.into(), expected: pin.source.into(), found: source.map(str::to_owned) }.into()); + } + let (wanted, exact) = match pin.features { + FeatureRule::Ignore => return Ok(()), + FeatureRule::Contains(f) => (f, false), + FeatureRule::Exactly(f) => (f, true), + }; + let node = self.node(str_field(package, "id", pin.name)?)?; + let list = + node.get("features").and_then(Value::as_array).ok_or_else(|| invalid(format!("{}: the resolved node has no features", pin.name)))?; + let mut enabled = BTreeSet::new(); + for f in list { + enabled.insert(f.as_str().ok_or_else(|| invalid(format!("{}: a feature is not a string", pin.name)))?); + } + compare_features(pin.name, wanted, &enabled, exact) + } + + fn check_active(&self, name: &Name<'_>) -> Result<(), Error> { + let nodes = self.nodes.as_ref().ok_or_else(|| invalid("resolve.nodes is missing; run cargo metadata without --no-deps"))?; + for package in self.packages { + let package_name = str_field(package, "name", "a package")?; + if !name.matches(package_name) { + continue; + } + let id = str_field(package, "id", package_name)?; + if nodes.contains_key(id) { + return Err(Violation::Forbidden { name: package_name.into(), rule: name.to_string(), root: None }.into()); + } + } + Ok(()) + } + + fn check_production(&self, name: &Name<'_>, root: &str) -> Result<(), Error> { + let root_id = str_field(self.one(root)?, "id", root)?; + let mut pending = vec![root_id]; + let mut seen = HashSet::new(); + while let Some(id) = pending.pop() { + if !seen.insert(id) { + continue; + } + let package = self.by_id.get(id).ok_or_else(|| invalid(format!("dependency {id} has no package entry")))?; + let package_name = str_field(package, "name", id)?; + if name.matches(package_name) { + return Err(Violation::Forbidden { name: package_name.into(), rule: name.to_string(), root: Some(root.into()) }.into()); + } + let deps = + self.node(id)?.get("deps").and_then(Value::as_array).ok_or_else(|| invalid(format!("package {id} has no dependency edges")))?; + for dep in deps { + if production_edge(dep, id)? { + pending.push(str_field(dep, "pkg", id)?); + } + } + } + Ok(()) + } +} + +/// Whether a `deps` entry is a normal or build dependency for at least one target. A kind that is not +/// `dev` counts as production, so an unknown kind is followed. +fn production_edge(dep: &Value, from: &str) -> Result { + let kinds = dep.get("dep_kinds").and_then(Value::as_array).ok_or_else(|| invalid(format!("a dependency of {from} has no dep_kinds")))?; + if kinds.is_empty() { + return Err(invalid(format!("a dependency of {from} has no dep_kinds"))); + } + let mut production = false; + for k in kinds { + match k.get("kind") { + Some(Value::Null) => production = true, + Some(Value::String(kind)) => production |= kind != "dev", + _ => return Err(invalid(format!("a dependency of {from} has a dep_kinds entry without a kind"))), + } + } + Ok(production) +} + +fn compare_features(name: &str, wanted: &[&str], enabled: &BTreeSet<&str>, exact: bool) -> Result<(), Error> { + let wanted: BTreeSet<&str> = wanted.iter().copied().collect(); + let missing: Vec = wanted.difference(enabled).map(|f| (*f).to_owned()).collect(); + let extra: Vec = if exact { enabled.difference(&wanted).map(|f| (*f).to_owned()).collect() } else { Vec::new() }; + if missing.is_empty() && extra.is_empty() { Ok(()) } else { Err(Violation::Features { name: name.into(), missing, extra }.into()) } +} + +fn str_field<'v>(v: &'v Value, key: &str, of: &str) -> Result<&'v str, Error> { + v.get(key).and_then(Value::as_str).ok_or_else(|| invalid(format!("{of}: {key} is missing or not a string"))) +} + +fn invalid(why: impl Into) -> Error { + Error::Output { command: METADATA.into(), why: why.into() } +} + +/// The `cargo tree` call for [`run_target_features`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TargetFeatures<'a> { + /// The workspace package the tree starts from (`--package`). + pub root: &'a str, + /// Levels of dependencies below the root (`--depth`). + pub depth: u32, + /// The package whose features are checked. + pub package: &'a str, + /// The features it must have, and no others, on this target. + pub features: &'a [&'a str], +} + +/// Runs `cargo tree` for one target and checks the features of `spec.package` with +/// [`check_target_features`]. The command is +/// `cargo tree --locked --target --edges normal,build --package --depth +/// --no-dedupe --prefix none --format {p}|{f}`, and its output is read within +/// [`Limits::tree_bytes`]. +pub fn run_target_features(cargo: impl FnOnce() -> Command, target: &str, spec: &TargetFeatures<'_>, limits: &Limits) -> Result<(), Error> { + let command = format!("cargo tree --target {target}"); + let mut cmd = cargo(); + cmd.args(["tree", "--locked", "--target", target, "--edges", "normal,build", "--package", spec.root, "--depth"]) + .arg(spec.depth.to_string()) + .args(["--no-dedupe", "--prefix", "none", "--format", "{p}|{f}"]); + let out = output(cmd, &command, limits.tree_bytes, limits.stderr_bytes)?; + let tree = String::from_utf8(out).map_err(|_| Error::Output { command: command.clone(), why: "not UTF-8".into() })?; + check_target_features(&tree, spec.package, spec.features).map_err(|e| match e { + Error::Output { why, .. } => Error::Output { command, why }, + other => other, + }) +} + +/// Checks `cargo tree --format {p}|{f}` output: every line for `package` (text that starts with +/// ` v`) enables exactly `features`, and at least one line is for `package`. +pub fn check_target_features(tree: &str, package: &str, features: &[&str]) -> Result<(), Error> { + let prefix = format!("{package} v"); + let mut found = 0usize; + for line in tree.lines() { + let Some((text, list)) = line.rsplit_once('|') else { + continue; + }; + if !text.starts_with(&prefix) { + continue; + } + found += 1; + let enabled: BTreeSet<&str> = list.split(',').filter(|f| !f.is_empty()).collect(); + compare_features(text, features, &enabled, true)?; + } + if found == 0 { + return Err(Violation::Count { name: package.into(), found: 0 }.into()); + } + Ok(()) +} + +/// The host target from `rustc -vV` (its `host:` line), read within [`Limits::version_bytes`]. +/// `rustc` builds the app's `rustc` command; `-vV` is added to it. +pub fn host_target(rustc: impl FnOnce() -> Command, limits: &Limits) -> Result { + const COMMAND: &str = "rustc -vV"; + let mut cmd = rustc(); + cmd.arg("-vV"); + let out = output(cmd, COMMAND, limits.version_bytes, limits.stderr_bytes)?; + let text = String::from_utf8(out).map_err(|_| Error::Output { command: COMMAND.into(), why: "not UTF-8".into() })?; + text.lines() + .find_map(|line| line.strip_prefix("host: ")) + .map(|host| host.trim().to_owned()) + .filter(|host| !host.is_empty()) + .ok_or_else(|| Error::Output { command: COMMAND.into(), why: "no host line".into() }) +} + +/// Runs `cmd` and returns its standard output, or an error when it fails or prints more than +/// `limit` bytes. Standard error is read on another thread to its end, so a command that writes a +/// lot there does not stop on a full pipe; its first `stderr_limit` bytes are kept. +fn output(mut cmd: Command, command: &str, limit: usize, stderr_limit: usize) -> Result, Error> { + cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); + let mut child = cmd.spawn().map_err(|source| Error::Start { command: command.into(), source })?; + let stderr = child.stderr.take().map(|pipe| std::thread::spawn(move || read_head(pipe, stderr_limit))); + let read = match child.stdout.take() { + Some(stdout) => read_bounded(stdout, limit), + None => Err(io::Error::other("no output pipe")), + }; + // On an error the stderr thread is left to end when the pipe closes: a process the child started + // may hold the pipe open after the child is stopped. + let stdout = match read { + Ok(Some(stdout)) => stdout, + Ok(None) => { + stop(&mut child); + return Err(Error::TooLarge { command: command.into(), limit }); + } + Err(source) => { + stop(&mut child); + return Err(Error::Read { command: command.into(), source }); + } + }; + let status = child.wait().map_err(|source| Error::Read { command: command.into(), source })?; + if status.success() { + return Ok(stdout); + } + let stderr = stderr.map(join_head).unwrap_or_default(); + Err(Error::Exit { command: command.into(), status, stderr: String::from_utf8_lossy(&stderr).trim().to_owned() }) +} + +/// Everything `reader` gives, or `None` when that is more than `limit` bytes. The read stops one byte +/// past the limit. +fn read_bounded(reader: impl Read, limit: usize) -> io::Result>> { + let mut buf = Vec::new(); + reader.take(u64::try_from(limit).unwrap_or(u64::MAX).saturating_add(1)).read_to_end(&mut buf)?; + Ok((buf.len() <= limit).then_some(buf)) +} + +/// Reads `reader` to its end and returns its first `limit` bytes. +fn read_head(mut reader: impl Read, limit: usize) -> Vec { + let mut head = Vec::new(); + let mut chunk = [0u8; 8192]; + loop { + match reader.read(&mut chunk) { + Ok(0) => break, + Ok(n) => { + let room = limit.saturating_sub(head.len()); + head.extend_from_slice(chunk.get(..n.min(room)).unwrap_or_default()); + } + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(_) => break, + } + } + head +} + +fn join_head(handle: JoinHandle>) -> Vec { + handle.join().unwrap_or_default() +} + +/// Ends a child whose output is no longer read. +fn stop(child: &mut Child) { + let _ = child.kill(); + let _ = child.wait(); +} + +#[cfg(test)] +mod tests { + use super::{CRATES_IO, Error, FeatureRule, Forbidden, Limits, Name, Pin, Policy, Scope, Violation, check, check_target_features, git_source}; + use serde_json::{Value, json}; + + fn bytes(v: &Value) -> Vec { + serde_json::to_vec(v).unwrap() + } + + fn validate(m: &Value, policy: &Policy<'_>) -> Result<(), Error> { + check(&bytes(m), policy, &Limits::default()) + } + + fn violation(r: Result<(), Error>) -> Violation { + match r { + Err(Error::Violation(v)) => v, + other => panic!("expected a violation, got {other:?}"), + } + } + + fn output_error(r: Result<(), Error>) -> String { + match r { + Err(Error::Output { why, .. }) => why, + other => panic!("expected an output error, got {other:?}"), + } + } + + #[test] + fn an_empty_policy_accepts_any_metadata() { + let policy = Policy::default(); + assert!(validate(&json!({"packages": []}), &policy).is_ok()); + assert!(validate(&json!({"packages": [{"name": "a"}], "resolve": null}), &policy).is_ok()); + } + + #[test] + fn rejects_json_that_does_not_parse_or_lacks_packages() { + let policy = Policy::default(); + assert!(output_error(check(b"{not json", &policy, &Limits::default())).starts_with("not JSON")); + assert!(output_error(validate(&json!({}), &policy)).contains("packages")); + assert!(output_error(validate(&json!({"packages": [{"id": "x"}]}), &policy)).contains("name")); + } + + #[test] + fn rejects_metadata_larger_than_the_limit_before_parsing_it() { + let json = bytes(&json!({"packages": []})); + let limits = Limits { metadata_bytes: json.len() - 1, ..Limits::default() }; + assert!(matches!(check(&json, &Policy::default(), &limits), Err(Error::TooLarge { limit, .. }) if limit == json.len() - 1)); + let limits = Limits { metadata_bytes: json.len(), ..Limits::default() }; + assert!(check(&json, &Policy::default(), &limits).is_ok()); + } + + #[test] + fn family_names_match_the_name_and_its_dash_suffixes_only() { + let family = Name::Family("hayro"); + assert!(family.matches("hayro")); + assert!(family.matches("hayro-syntax")); + assert!(!family.matches("hayrox")); + assert!(!family.matches("not-hayro")); + assert!(Name::Exact("hayro").matches("hayro")); + assert!(!Name::Exact("hayro").matches("hayro-syntax")); + } + + #[test] + fn git_sources_name_the_revision_twice() { + assert_eq!(git_source("https://github.com/o/r", "abc"), "git+https://github.com/o/r?rev=abc#abc"); + } + + #[test] + fn target_features_without_any_enabled_match_an_empty_list() { + assert!(check_target_features("krilla v0.8.2|\n", "krilla", &[]).is_ok()); + assert!(check_target_features("krilla v0.8.2|\n", "krilla", &["rayon"]).is_err()); + // Another package whose name starts the same is not checked. + assert!(check_target_features("krilla v0.8.2|a\nkrilla-svg v0.1.0|b\n", "krilla", &["a"]).is_ok()); + } + + #[test] + fn a_production_root_must_resolve_once() { + let m = json!({"packages": [], "resolve": {"nodes": []}}); + let policy = Policy { pins: &[], forbidden: &[Forbidden { name: Name::Exact("x"), scope: Scope::ProductionFrom("app") }] }; + assert_eq!(violation(validate(&m, &policy)), Violation::Count { name: "app".into(), found: 0 }); + } + + #[test] + fn an_active_rule_needs_resolved_nodes_even_when_no_package_matches() { + let policy = Policy { pins: &[], forbidden: &[Forbidden { name: Name::Exact("x"), scope: Scope::Active }] }; + assert!(output_error(validate(&json!({"packages": [{"id": "a", "name": "a"}]}), &policy)).contains("resolve.nodes")); + assert!(validate(&json!({"packages": [{"id": "a", "name": "a"}], "resolve": {"nodes": []}}), &policy).is_ok()); + } + + #[test] + fn rejects_edges_without_a_kind() { + let m = json!({ + "packages": [{"id": "app", "name": "app"}, {"id": "dep", "name": "dep"}], + "resolve": {"nodes": [{"id": "app", "deps": [{"pkg": "dep", "dep_kinds": [{}]}]}, {"id": "dep", "deps": []}]} + }); + let policy = Policy { pins: &[], forbidden: &[Forbidden { name: Name::Exact("x"), scope: Scope::ProductionFrom("app") }] }; + assert!(output_error(validate(&m, &policy)).contains("kind")); + } + + #[test] + fn rejects_features_that_are_not_strings() { + let m = json!({ + "packages": [{"id": "p", "name": "p", "version": "1.0.0", "source": CRATES_IO}], + "resolve": {"nodes": [{"id": "p", "features": ["std", 1]}]} + }); + let pins = [Pin { name: "p", version: "1.0.0", source: CRATES_IO, features: FeatureRule::Contains(&["std"]) }]; + assert!(output_error(validate(&m, &Policy { pins: &pins, forbidden: &[] })).contains("not a string")); + } + + /// Fixtures and tests from DeckCraft's `xtask/src/pdf_deps.rs`. + mod deckcraft { + use super::super::{CRATES_IO, FeatureRule, Forbidden, Name, Pin, Policy, Scope, Violation, check_target_features, git_source}; + use super::{output_error, validate, violation}; + use serde_json::{Value, json}; + + const SHARED_REV: &str = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef"; + const FORBIDDEN: &[Forbidden<'static>] = &[Forbidden { name: Name::Family("hayro"), scope: Scope::ProductionFrom("deckcraft-pdf") }]; + + fn source() -> String { + git_source("https://github.com/storytold/craft-libs", SHARED_REV) + } + + fn pins(source: &str) -> [Pin<'_>; 3] { + [ + Pin { name: "craft-pdf", version: "0.1.0", source, features: FeatureRule::Exactly(&["write", "write-simple-text"]) }, + Pin { name: "krilla", version: "0.8.2", source, features: FeatureRule::Exactly(&["raster-images", "rayon", "simple-text"]) }, + Pin { name: "hayro-syntax", version: "0.7.2", source: CRATES_IO, features: FeatureRule::Exactly(&["std"]) }, + ] + } + + fn check(m: &Value) -> Result<(), super::Error> { + let source = source(); + let pins = pins(&source); + validate(m, &Policy { pins: &pins, forbidden: FORBIDDEN }) + } + + fn metadata() -> Value { + let source = source(); + json!({ + "packages": [ + {"id":"app", "name":"deckcraft-pdf"}, + {"id":"writer", "name":"craft-pdf", "version":"0.1.0", "source":source}, + {"id":"backend", "name":"krilla", "version":"0.8.2", "source":source}, + {"id":"parser", "name":"hayro-syntax", "version":"0.7.2", "source":CRATES_IO} + ], + "resolve":{"nodes":[ + {"id":"app", "deps":[{"pkg":"writer", "dep_kinds":[{"kind":null}]}, {"pkg":"parser", "dep_kinds":[{"kind":"dev"}]}]}, + {"id":"writer", "features":["write","write-simple-text"], "deps":[{"pkg":"backend", "dep_kinds":[{"kind":null}]}]}, + {"id":"backend", "features":["raster-images","rayon","simple-text"], "deps":[]}, + {"id":"parser", "features":["std"], "deps":[]} + ]} + }) + } + + #[test] + fn parallel_compression_is_required_only_on_native_targets() { + let serial = "krilla v0.8.2 (pinned)|raster-images,simple-text\n"; + let parallel = "krilla v0.8.2 (pinned)|raster-images,rayon,simple-text\n"; + let native: &[&str] = &["raster-images", "rayon", "simple-text"]; + let wasm: &[&str] = &["raster-images", "simple-text"]; + assert!(check_target_features(serial, "krilla", wasm).is_ok()); + assert!(check_target_features(parallel, "krilla", native).is_ok()); + assert!(check_target_features(serial, "krilla", native).is_err()); + assert!(check_target_features(parallel, "krilla", wasm).is_err()); + assert!(check_target_features("", "krilla", wasm).is_err()); + } + + #[test] + fn rejects_unpinned_or_duplicate_writer_sources() { + assert!(check(&metadata()).is_ok()); + for source in [Value::Null, json!(CRATES_IO), json!("git+https://github.com/storytold/craft-libs#other")] { + let mut m = metadata(); + m["packages"][1]["source"] = source; + assert!(matches!(violation(check(&m)), Violation::Source { .. })); + } + let mut m = metadata(); + let mut duplicate = m["packages"][2].clone(); + duplicate["id"] = json!("backend-2"); + m["packages"].as_array_mut().unwrap().push(duplicate); + assert_eq!(violation(check(&m)), Violation::Count { name: "krilla".into(), found: 2 }); + } + + #[test] + fn rejects_import_features_and_missing_text_shaping() { + for (node, features) in [ + (1, json!([])), + (1, json!(["write"])), + (1, json!(["write", "write-simple-text", "write-pdf"])), + (2, json!(["raster-images", "rayon", "simple-text", "pdf"])), + (2, json!(["raster-images"])), + (3, json!(["std", "images"])), + ] { + let mut m = metadata(); + m["resolve"]["nodes"][node]["features"] = features; + assert!(matches!(violation(check(&m)), Violation::Features { .. })); + } + } + + #[test] + fn rejects_dev_parser_promoted_to_production_directly_or_transitively() { + for kind in [Value::Null, json!("build")] { + let mut m = metadata(); + m["resolve"]["nodes"][0]["deps"][1]["dep_kinds"][0]["kind"] = kind; + assert!(matches!(violation(check(&m)), Violation::Forbidden { ref name, .. } if name == "hayro-syntax")); + } + let mut m = metadata(); + m["resolve"]["nodes"][2]["deps"] = json!([{"pkg":"parser", "dep_kinds":[{"kind":null}]}]); + assert!(matches!(violation(check(&m)), Violation::Forbidden { ref name, .. } if name == "hayro-syntax")); + // A dependency that is dev on one target and normal on another is production. + let mut m = metadata(); + m["resolve"]["nodes"][0]["deps"][1]["dep_kinds"] = json!([{"kind":"dev"}, {"kind":null, "target":"cfg(unix)"}]); + assert!(matches!(violation(check(&m)), Violation::Forbidden { .. })); + } + + #[test] + fn rejects_incomplete_dependency_metadata() { + let mut m = metadata(); + m["resolve"]["nodes"][2]["deps"] = json!([{"pkg":"missing", "dep_kinds":[{"kind":null}]}]); + assert!(output_error(check(&m)).contains("missing")); + let mut m = metadata(); + m["resolve"] = Value::Null; + assert!(output_error(check(&m)).contains("resolve.nodes")); + let mut m = metadata(); + m["packages"].as_array_mut().unwrap().retain(|p| p["name"] != "hayro-syntax"); + assert_eq!(violation(check(&m)), Violation::Count { name: "hayro-syntax".into(), found: 0 }); + let mut m = metadata(); + m["resolve"]["nodes"][1]["deps"][0]["dep_kinds"] = json!([]); + assert!(output_error(check(&m)).contains("dep_kinds")); + } + } + + /// Fixtures and tests from VectorCraft's `xtask/src/pdf_deps.rs`. + mod vectorcraft { + use super::super::{FeatureRule, Pin, Policy, git_source}; + use super::validate; + use serde_json::{Value, json}; + + const REV: &str = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"; + const PACKAGES: &[(&str, &str)] = &[ + ("craft-pdf", "0.1.0"), + ("krilla", "0.8.2"), + ("hayro-syntax", "0.7.2"), + ("hayro-interpret", "0.7.0"), + ("hayro-jbig2", "0.3.0"), + ("hayro-cmap", "0.1.0"), + ("hayro-postscript", "0.1.0"), + ]; + + fn source(rev: &str) -> String { + git_source("https://github.com/storytold/craft-libs", rev) + } + + fn check(m: &Value) -> Result<(), super::Error> { + let source = source(REV); + let pins: Vec> = + PACKAGES.iter().map(|&(name, version)| Pin { name, version, source: &source, features: FeatureRule::Ignore }).collect(); + validate(m, &Policy { pins: &pins, forbidden: &[] }) + } + + fn metadata() -> Value { + let packages: Vec<_> = PACKAGES.iter().map(|(name, version)| json!({"name":name, "version":version, "source":source(REV)})).collect(); + json!({"packages": packages}) + } + + #[test] + fn accepts_pinned_pdf_packages_without_changing_printer_transport() { + let mut m = metadata(); + m["packages"] + .as_array_mut() + .unwrap() + .push(json!({"name":"craft-print", "version":"0.1.0", "source":source("d991bf6792f8ade99c51358bf3c1d902c8cd96b5")})); + assert!(check(&m).is_ok()); + } + + #[test] + fn rejects_missing_or_duplicate_pdf_packages() { + for index in 0..PACKAGES.len() { + let mut m = metadata(); + m["packages"].as_array_mut().unwrap().remove(index); + assert!(check(&m).is_err()); + let mut m = metadata(); + let duplicate = m["packages"][index].clone(); + m["packages"].as_array_mut().unwrap().push(duplicate); + assert!(check(&m).is_err()); + } + } + + #[test] + fn rejects_registry_local_version_and_revision_drift() { + for index in 0..PACKAGES.len() { + for (field, value) in [ + ("source", Value::Null), + ("source", json!("registry+https://github.com/rust-lang/crates.io-index")), + ("source", json!("git+https://github.com/storytold/craft-libs?branch=main#other")), + ("source", json!(source("92d392cff132eaf53e13afff77f38b5c11b73aa0"))), + ("version", json!("0.99.0")), + ] { + let mut m = metadata(); + m["packages"][index][field] = value; + assert!(check(&m).is_err()); + } + } + } + } + + /// Fixtures and tests from DesignCraft's `xtask/src/pdf_deps.rs`. + mod designcraft { + use super::super::{FeatureRule, Pin, Policy, Violation, git_source}; + use super::{validate, violation}; + use serde_json::{Value, json}; + + const REV: &str = "a0916808f7d78bed8c7b90cdf937176015454a7f"; + const PACKAGES: &[(&str, &str)] = &[ + ("craft-pdf", "0.1.0"), + ("krilla", "0.8.2"), + ("hayro", "0.7.1"), + ("hayro-interpret", "0.7.0"), + ("hayro-syntax", "0.7.2"), + ("hayro-jbig2", "0.3.0"), + ("hayro-cmap", "0.1.0"), + ("hayro-postscript", "0.1.0"), + ]; + const FACADE_FEATURES: &[&str] = &["read", "interpret", "raster", "write", "write-pdf"]; + + fn check(m: &Value) -> Result<(), super::Error> { + let source = git_source("https://github.com/storytold/craft-libs", REV); + let pins: Vec> = PACKAGES + .iter() + .map(|&(name, version)| { + let features = if name == "craft-pdf" { FeatureRule::Contains(FACADE_FEATURES) } else { FeatureRule::Ignore }; + Pin { name, version, source: &source, features } + }) + .collect(); + validate(m, &Policy { pins: &pins, forbidden: &[] }) + } + + fn metadata() -> Value { + json!({"packages": PACKAGES.iter().map(|(name, version)| json!({"id":name,"name":name,"version":version, + "source":git_source("https://github.com/storytold/craft-libs", REV)})).collect::>(), "resolve": {"nodes": [{"id": "craft-pdf", "features": ["read", "interpret", "raster", "write", "write-pdf"]}]}}) + } + + #[test] + fn accepts_one_pinned_facade_and_reader() { + assert!(check(&metadata()).is_ok()); + // Features beyond the required ones are allowed. + let mut m = metadata(); + m["resolve"]["nodes"][0]["features"].as_array_mut().unwrap().push(json!("write-simple-text")); + assert!(check(&m).is_ok()); + } + + #[test] + fn rejects_unpatched_and_local_reader_sources() { + for source in [Value::Null, json!("registry+https://github.com/rust-lang/crates.io-index")] { + let mut m = metadata(); + m["packages"][1]["source"] = source; + assert!(matches!(violation(check(&m)), Violation::Source { .. })); + } + } + + #[test] + fn rejects_missing_duplicate_and_wrong_version_packages() { + for index in 0..PACKAGES.len() { + let mut m = metadata(); + m["packages"][index]["version"] = json!("99.0.0"); + assert!(matches!(violation(check(&m)), Violation::Version { .. })); + let mut m = metadata(); + let mut duplicate = m["packages"][index].clone(); + duplicate["id"] = json!("duplicate"); + m["packages"].as_array_mut().unwrap().push(duplicate); + assert!(matches!(violation(check(&m)), Violation::Count { found: 2, .. })); + let mut m = metadata(); + m["packages"].as_array_mut().unwrap().remove(index); + assert!(matches!(violation(check(&m)), Violation::Count { found: 0, .. })); + } + } + + #[test] + fn rejects_missing_reader_or_writer_features() { + for index in 0..5 { + let mut m = metadata(); + m["resolve"]["nodes"][0]["features"].as_array_mut().unwrap().remove(index); + assert!(matches!(violation(check(&m)), Violation::Features { .. })); + } + let mut m = metadata(); + m["resolve"] = Value::Null; + assert!(check(&m).is_err()); + } + + #[test] + fn rejects_facade_revision_drift_and_malformed_metadata() { + let mut m = metadata(); + m["packages"][0]["source"] = json!("git+https://github.com/storytold/craft-libs?branch=main#other"); + assert!(check(&m).is_err()); + assert!(check(&json!({})).is_err()); + } + } + + /// Fixtures and tests from EffectCraft's `xtask/src/pdf_deps.rs`. + mod effectcraft { + use super::super::{FeatureRule, Forbidden, Name, Pin, Policy, Scope, Violation, git_source}; + use super::{validate, violation}; + use serde_json::{Value, json}; + + const REV: &str = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef"; + const PACKAGES: &[(&str, &str)] = &[("craft-pdf", "0.1.0"), ("hayro-syntax", "0.7.2"), ("hayro-jbig2", "0.3.0")]; + const FORBIDDEN: &[Forbidden<'static>] = &[ + Forbidden { name: Name::Exact("hayro"), scope: Scope::Active }, + Forbidden { name: Name::Exact("hayro-interpret"), scope: Scope::Active }, + Forbidden { name: Name::Exact("hayro-cmap"), scope: Scope::Active }, + Forbidden { name: Name::Exact("krilla"), scope: Scope::Active }, + ]; + + fn check(m: &Value) -> Result<(), super::Error> { + let source = git_source("https://github.com/storytold/craft-libs", REV); + let pins: Vec> = PACKAGES + .iter() + .map(|&(name, version)| { + let features = match name { + "craft-pdf" => FeatureRule::Exactly(&["read"]), + "hayro-syntax" => FeatureRule::Exactly(&["std"]), + _ => FeatureRule::Ignore, + }; + Pin { name, version, source: &source, features } + }) + .collect(); + validate(m, &Policy { pins: &pins, forbidden: FORBIDDEN }) + } + + fn metadata() -> Value { + let packages: Vec<_> = PACKAGES + .iter() + .map(|(name, version)| json!({"id": name, "name": name, "version": version, "source": git_source("https://github.com/storytold/craft-libs", REV)})) + .collect(); + json!({"packages": packages, "resolve": {"nodes": [ + {"id": "hayro-syntax", "features": ["std"]}, {"id": "craft-pdf", "features": ["read"]} + ]}}) + } + + #[test] + fn accepts_the_pinned_parser_only_graph() { + assert!(check(&metadata()).is_ok()); + // A forbidden package without a resolved node is not active. + let mut m = metadata(); + m["packages"].as_array_mut().unwrap().push(json!({"id": "krilla", "name": "krilla"})); + assert!(check(&m).is_ok()); + } + + #[test] + fn rejects_unpinned_duplicate_and_missing_parsers() { + let mut m = metadata(); + m["packages"][0]["source"] = json!("registry"); + assert!(check(&m).is_err()); + let mut m = metadata(); + let mut duplicate = m["packages"][0].clone(); + duplicate["id"] = json!("craft-pdf-2"); + m["packages"].as_array_mut().unwrap().push(duplicate); + assert!(check(&m).is_err()); + m["packages"].as_array_mut().unwrap().retain(|p| p["name"] != "hayro-syntax"); + assert!(check(&m).is_err()); + } + + #[test] + fn rejects_shared_reader_source_drift() { + let mut m = metadata(); + m["packages"][0]["source"] = Value::Null; + assert!(matches!(violation(check(&m)), Violation::Source { found: None, .. })); + } + + #[test] + fn rejects_extra_features_and_missing_active_nodes() { + for (index, feature) in [(0, "images"), (1, "write"), (1, "raster")] { + let mut m = metadata(); + m["resolve"]["nodes"][index]["features"].as_array_mut().unwrap().push(json!(feature)); + assert!(matches!(violation(check(&m)), Violation::Features { ref extra, .. } if extra == &[feature.to_owned()])); + } + let mut m = metadata(); + m["resolve"]["nodes"].as_array_mut().unwrap().pop(); + assert!(check(&m).is_err()); + } + + #[test] + fn rejects_backend_asset_features_and_missing_resolution() { + for name in ["hayro", "hayro-interpret", "hayro-cmap", "krilla"] { + let mut m = metadata(); + m["packages"].as_array_mut().unwrap().push(json!({"id": name, "name": name})); + m["resolve"]["nodes"].as_array_mut().unwrap().push(json!({"id": name})); + assert!(matches!(violation(check(&m)), Violation::Forbidden { name: ref found, root: None, .. } if found == name)); + } + let mut m = metadata(); + m["resolve"] = Value::Null; + assert!(check(&m).is_err()); + } + } + + /// The commands run as children: the test binary itself, running [`fake_child`]. + mod process { + use super::super::{Error, Limits, TargetFeatures, Violation, host_target, metadata, run_target_features}; + use std::io::Write; + use std::process::Command; + + const MODE: &str = "CRAFT_XTASK_PINS_FAKE"; + + fn fake(mode: &str) -> Command { + let mut cmd = Command::new(std::env::current_exe().unwrap()); + cmd.args(["--ignored", "--exact", "--nocapture", "--test-threads=1", "pins::tests::process::fake_child", "--"]).env(MODE, mode); + cmd + } + + /// Stands in for `cargo` or `rustc` when [`MODE`] is set; does nothing otherwise. The harness + /// reads the arguments the library adds after `--` as more test filters, and with `--exact` + /// none of them selects another test. + #[test] + #[ignore = "a child process for the other process tests"] + fn fake_child() { + let Ok(mode) = std::env::var(MODE) else { + return; + }; + let chunk = [b'x'; 8192]; + match mode.as_str() { + "endless" => { + let mut out = std::io::stdout().lock(); + while out.write_all(&chunk).is_ok() {} + } + "fail" => { + let mut err = std::io::stderr().lock(); + for _ in 0..256 { + let _ = err.write_all(&chunk); + } + std::process::exit(3); + } + "host" => println!("rustc 1.0.0\nhost: fake-target\nrelease: 1.0.0"), + "tree" => println!("app-pdf v0.1.0|\ncraft-pdf v0.1.0|write\nkrilla v0.8.2|raster-images,simple-text"), + _ => {} + } + } + + #[test] + fn target_features_are_read_from_the_tree_command() { + let spec = TargetFeatures { root: "app-pdf", depth: 2, package: "krilla", features: &["raster-images", "simple-text"] }; + assert!(run_target_features(|| fake("tree"), "wasm32-unknown-unknown", &spec, &Limits::default()).is_ok()); + let spec = TargetFeatures { features: &["raster-images", "rayon", "simple-text"], ..spec }; + match run_target_features(|| fake("tree"), "x86_64-unknown-linux-gnu", &spec, &Limits::default()) { + Err(Error::Violation(Violation::Features { missing, extra, .. })) => { + assert_eq!(missing, ["rayon"]); + assert!(extra.is_empty()); + } + other => panic!("expected a feature violation, got {other:?}"), + } + } + + #[test] + fn output_past_the_limit_stops_the_command() { + let limits = Limits { metadata_bytes: 64 << 10, ..Limits::default() }; + match metadata(|| fake("endless"), &limits) { + Err(Error::TooLarge { command, limit }) => { + assert_eq!(command, "cargo metadata"); + assert_eq!(limit, 64 << 10); + } + other => panic!("expected TooLarge, got {other:?}"), + } + } + + #[test] + fn a_failing_command_keeps_the_start_of_a_long_stderr() { + let limits = Limits { stderr_bytes: 1000, ..Limits::default() }; + match metadata(|| fake("fail"), &limits) { + Err(Error::Exit { status, stderr, .. }) => { + assert_eq!(status.code(), Some(3)); + assert_eq!(stderr, "x".repeat(1000)); + } + other => panic!("expected Exit, got {other:?}"), + } + } + + #[test] + fn a_command_that_cannot_start_is_an_error() { + let r = metadata(|| Command::new("craft-xtask-pins-no-such-program"), &Limits::default()); + assert!(matches!(r, Err(Error::Start { .. }))); + } + + #[test] + fn the_host_target_is_read_from_its_line() { + assert_eq!(host_target(|| fake("host"), &Limits::default()).unwrap(), "fake-target"); + let limits = Limits { version_bytes: 4, ..Limits::default() }; + assert!(matches!(host_target(|| fake("host"), &limits), Err(Error::TooLarge { .. }))); + } + } +} From 892302138d8701d2c1e22d93f5f60fb622667fbe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:21:07 -0800 Subject: [PATCH 007/257] craft-testkit: prop::config runs property suites from a pinned seed The `prop` feature adds `craft_testkit::prop::config(cases)`, which returns a proptest `Config` with failure persistence off, the caller's case count and the seed 0x5eed_9a7f. `PROPTEST_CASES` and `PROPTEST_RNG_SEED` replace the count and the seed when set; for a value proptest cannot parse it prints a warning and uses 256 cases or a random seed. The module is not built for wasm32. The code comes from VectorCraft `crates/pathops/tests/common/mod.rs`, which has no tests of its own. `tests/prop.rs` runs the test binary again as a child with each variable set, so no test changes the process environment. --- Cargo.lock | 3 + crates/testkit/Cargo.toml | 11 +++ crates/testkit/README.md | 40 +++++++++++ crates/testkit/src/lib.rs | 6 ++ crates/testkit/src/prop.rs | 36 ++++++++++ crates/testkit/tests/prop.rs | 129 +++++++++++++++++++++++++++++++++++ 6 files changed, 225 insertions(+) create mode 100644 crates/testkit/src/prop.rs create mode 100644 crates/testkit/tests/prop.rs diff --git a/Cargo.lock b/Cargo.lock index fab3c89a3d..773dee41b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2576,6 +2576,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "proptest", +] [[package]] name = "craft-text" diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d32ed735f4..1e542092d1 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -8,7 +8,18 @@ repository.workspace = true description = "Source-level platform regression guards and verification utilities for the Craft application suite" publish = false +[features] +# `prop::config`: a proptest configuration with a pinned seed and no failure persistence. +prop = ["dep:proptest"] + [dependencies] +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +proptest = { workspace = true, optional = true } + +[[test]] +name = "prop" +required-features = ["prop"] + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 2cef797e6f..e5c41bc73a 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -11,6 +11,46 @@ Source-level platform regression guards and verification utilities for the Craft 3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`, under any name. The parts of a path may be split by whitespace, comments or line breaks. Other crates' `Instant` (such as `web_time::Instant` or `tokio::time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`; code before that attribute or after its item on the same line is still checked. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. +## Proptest configuration: `prop` + +The `prop` feature adds `craft_testkit::prop` and the `proptest` dependency. The module is built on every target except `wasm32`. + +`prop::config(cases)` returns a `proptest::test_runner::Config` with failure persistence off. It reads proptest's own variables: + +| Variable | Not set | Set | +|---|---|---| +| `PROPTEST_CASES` | `cases` | the value proptest parsed as a `u32`; for a value it cannot parse, proptest prints a warning and uses 256 | +| `PROPTEST_RNG_SEED` | `prop::SEED` (`0x5eed_9a7f`) | the value proptest parsed as a `u64`; for a value it cannot parse, proptest prints a warning and uses a random seed | + +A suite under `prop::config` repeats the same cases on every run. To run it with random seeds, set `PROPTEST_RNG_SEED` to a value that is not a number. No file under `proptest-regressions/` is read or written, so a minimal failure found with other seeds or counts is kept as a named regression test in the suite. + +```rust +use proptest::prelude::*; + +proptest! { + #![proptest_config(craft_testkit::prop::config(64))] + + #[test] + fn parse_never_panics(bytes in proptest::collection::vec(any::(), 0..256)) { + let _ = my_crate::parse(&bytes); + } +} +``` + +### Origin + +| Module | Source repository | Path | Revision | +|---|---|---|---| +| `prop` | storytold/vectorcraft | `crates/pathops/tests/common/mod.rs:3-19` | `34627134` | + +### Migration + +| Consumer | Suites | State | +|---|---|---| +| VectorCraft `pathops` | `tests/props.rs`, `tests/prop_pathops.rs` | Pending: a separate pull request switches them | +| craft-libs | the 34 `Config` values that set `cases` directly, and the seven committed `proptest-regressions` files outside `vendor/` | Pending: separate pull requests switch them, name each suite whose seed changes from random to pinned, and turn the committed cases into named tests | +| LightCraft, FilmCraft | the property suites that set their case count | Pending: a separate pull request in each repository | + ## Epistemic Scope: Syntactic Guards vs Runtime Validation Source-level guards provide deterministic syntactic evidence about codebase structure: diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..a8fa359481 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -15,6 +15,10 @@ //! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests, with //! size limits ([`guards::rust_sources_with_limits`]). It is not built for `wasm32`. //! +//! With the `prop` feature, on targets other than `wasm32`, `prop::config` returns a proptest +//! configuration with a pinned seed and failure persistence off. `PROPTEST_CASES` and +//! `PROPTEST_RNG_SEED` override the case count and the seed. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -26,6 +30,8 @@ //! rather than replace, platform integration tests and CI execution. pub mod guards; +#[cfg(all(feature = "prop", not(target_arch = "wasm32")))] +pub mod prop; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; diff --git a/crates/testkit/src/prop.rs b/crates/testkit/src/prop.rs new file mode 100644 index 0000000000..b7a64f2310 --- /dev/null +++ b/crates/testkit/src/prop.rs @@ -0,0 +1,36 @@ +//! Proptest configuration for property suites that must repeat the same cases on every run. +//! +//! [`config`] starts from proptest's `Config::default()`, which has already read the `PROPTEST_*` +//! variables, turns failure persistence off, and then: +//! +//! - uses the caller's case count unless `PROPTEST_CASES` is set, and +//! - pins the seed to [`SEED`] unless `PROPTEST_RNG_SEED` is set. +//! +//! When a variable is set, the field keeps the value proptest read from it. Proptest parses +//! `PROPTEST_CASES` as a `u32` and `PROPTEST_RNG_SEED` as a `u64`. For a value it cannot parse, +//! proptest prints a warning and keeps its own default: 256 cases, or a random seed. Setting +//! `PROPTEST_RNG_SEED` to a value that is not a number therefore runs the suite with random seeds. +//! +//! No file under `proptest-regressions/` is read or written. A minimal failure found with other +//! seeds or counts, for example with `PROPTEST_CASES=5000 PROPTEST_RNG_SEED=`, is kept as a named +//! regression test in the suite. + +use proptest::test_runner::{Config, RngSeed}; + +/// The seed [`config`] uses when `PROPTEST_RNG_SEED` is not set. +pub const SEED: u64 = 0x5eed_9a7f; + +/// A proptest configuration that runs `cases` cases from [`SEED`] with failure persistence off. +/// +/// `PROPTEST_CASES` replaces `cases` and `PROPTEST_RNG_SEED` replaces the seed when either is set. +/// Pass the result to `#![proptest_config(...)]` or to `TestRunner::new`. +pub fn config(cases: u32) -> Config { + let mut c = Config { failure_persistence: None, ..Config::default() }; + if std::env::var_os("PROPTEST_CASES").is_none() { + c.cases = cases; + } + if std::env::var_os("PROPTEST_RNG_SEED").is_none() { + c.rng_seed = RngSeed::Fixed(SEED); + } + c +} diff --git a/crates/testkit/tests/prop.rs b/crates/testkit/tests/prop.rs new file mode 100644 index 0000000000..8b65bcdcb1 --- /dev/null +++ b/crates/testkit/tests/prop.rs @@ -0,0 +1,129 @@ +//! Each test runs this test binary again as a child with the `PROPTEST_*` variables it needs, so no +//! test changes the environment of the process that runs it. The child runs `child_reports_config`, +//! which prints one `PROPCFG` line describing `config(7)`. + +use std::process::Command; + +use craft_testkit::prop::{SEED, config}; +use proptest::prelude::any; +use proptest::strategy::{Strategy, ValueTree}; +use proptest::test_runner::TestRunner; + +/// Set in a child's environment so that `child_reports_config` prints its line. +const CHILD: &str = "CRAFT_TESTKIT_PROP_CHILD"; + +/// The case count every child passes to `config`. +const CASES: u32 = 7; + +/// Variables removed from every child's environment before a test sets its own. +const PROPTEST_VARS: [&str; 3] = ["PROPTEST_CASES", "PROPTEST_RNG_SEED", "PROPTEST_DISABLE_FAILURE_PERSISTENCE"]; + +#[test] +fn child_reports_config() { + if std::env::var_os(CHILD).is_none() { + return; + } + let c = config(CASES); + let line = format!("cases={} seed={} persistence={}", c.cases, c.rng_seed, c.failure_persistence.is_some()); + let mut runner = TestRunner::new(c); + let draws: Vec = (0..4).map(|_| any::().new_tree(&mut runner).expect("draw a value").current().to_string()).collect(); + println!("PROPCFG {line} draws={}", draws.join(",")); +} + +/// The fields of one child's `PROPCFG` line. +#[derive(Debug, PartialEq)] +struct Report { + cases: String, + seed: String, + persistence: String, + draws: String, +} + +fn run_child(vars: &[(&str, &str)]) -> Report { + let exe = std::env::current_exe().expect("locate the test binary"); + let mut cmd = Command::new(exe); + cmd.args(["--exact", "child_reports_config", "--nocapture", "--test-threads=1"]).env(CHILD, "1"); + for var in PROPTEST_VARS { + cmd.env_remove(var); + } + for (name, value) in vars { + cmd.env(name, value); + } + let out = cmd.output().expect("run the child test"); + let stdout = String::from_utf8_lossy(&out.stdout); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "child failed with {vars:?}\nstdout:\n{stdout}\nstderr:\n{stderr}"); + let line = stdout + .lines() + .find_map(|l| l.split_once("PROPCFG ").map(|(_, rest)| rest)) + .unwrap_or_else(|| panic!("no PROPCFG line with {vars:?}\nstdout:\n{stdout}\nstderr:\n{stderr}")); + let field = |name: &str| { + line.split(' ') + .find_map(|part| part.strip_prefix(name).and_then(|rest| rest.strip_prefix('='))) + .unwrap_or_else(|| panic!("no {name} in {line:?}")) + .to_string() + }; + Report { cases: field("cases"), seed: field("seed"), persistence: field("persistence"), draws: field("draws") } +} + +#[test] +fn without_variables_the_caller_count_and_pinned_seed_apply() { + let r = run_child(&[]); + assert_eq!(r.cases, CASES.to_string()); + assert_eq!(r.seed, SEED.to_string()); + assert_eq!(r.persistence, "false"); +} + +#[test] +fn without_variables_every_run_draws_the_same_values() { + let first = run_child(&[]); + let second = run_child(&[]); + assert_eq!(first.draws, second.draws); +} + +#[test] +fn proptest_cases_replaces_the_caller_count() { + let r = run_child(&[("PROPTEST_CASES", "19")]); + assert_eq!(r.cases, "19"); + assert_eq!(r.seed, SEED.to_string()); + assert_eq!(r.persistence, "false"); +} + +#[test] +fn proptest_rng_seed_replaces_the_pinned_seed() { + let pinned = run_child(&[]); + let r = run_child(&[("PROPTEST_RNG_SEED", "12345")]); + assert_eq!(r.cases, CASES.to_string()); + assert_eq!(r.seed, "12345"); + assert_eq!(r.persistence, "false"); + assert_ne!(r.draws, pinned.draws); + assert_eq!(run_child(&[("PROPTEST_RNG_SEED", "12345")]).draws, r.draws); +} + +#[test] +fn both_variables_apply_together() { + let r = run_child(&[("PROPTEST_CASES", "19"), ("PROPTEST_RNG_SEED", "12345")]); + assert_eq!(r.cases, "19"); + assert_eq!(r.seed, "12345"); + assert_eq!(r.persistence, "false"); +} + +#[test] +fn an_unparsable_case_count_keeps_proptest_default() { + for value in ["many", "", "-1", "4294967296"] { + let r = run_child(&[("PROPTEST_CASES", value)]); + assert_eq!(r.cases, "256", "PROPTEST_CASES={value:?}"); + assert_eq!(r.seed, SEED.to_string(), "PROPTEST_CASES={value:?}"); + assert_eq!(r.persistence, "false", "PROPTEST_CASES={value:?}"); + } +} + +#[test] +fn an_unparsable_seed_runs_with_a_random_seed() { + for value in ["random", "", "18446744073709551616"] { + let r = run_child(&[("PROPTEST_RNG_SEED", value)]); + assert_eq!(r.cases, CASES.to_string(), "PROPTEST_RNG_SEED={value:?}"); + assert_eq!(r.seed, "random", "PROPTEST_RNG_SEED={value:?}"); + assert_eq!(r.persistence, "false", "PROPTEST_RNG_SEED={value:?}"); + } +} From f9575d9999c5656a8fa694b155c81f54103164e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:48:30 -0800 Subject: [PATCH 008/257] craft-testkit: the prop test target builds for wasm32 with no tests --- crates/testkit/tests/prop.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/testkit/tests/prop.rs b/crates/testkit/tests/prop.rs index 8b65bcdcb1..bd7dc6fcdc 100644 --- a/crates/testkit/tests/prop.rs +++ b/crates/testkit/tests/prop.rs @@ -2,6 +2,8 @@ //! test changes the environment of the process that runs it. The child runs `child_reports_config`, //! which prints one `PROPCFG` line describing `config(7)`. +#![cfg(not(target_arch = "wasm32"))] + use std::process::Command; use craft_testkit::prop::{SEED, config}; From c56151df8428e00c5eec394ab6e07f3e0dc1af44 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:12:18 -0800 Subject: [PATCH 009/257] ci: run Shared media, audio and video for changes under crates/testkit The media, audio and video workflows list crates/media-testkit/** in their path filters but not crates/testkit/**, so a change to craft-testkit alone starts none of them. Add crates/testkit/** next to crates/media-testkit/** in the push and pull_request filters of media.yml, audio.yml and video.yml. --- .github/workflows/audio.yml | 4 ++-- .github/workflows/media.yml | 4 ++-- .github/workflows/video.yml | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/audio.yml b/.github/workflows/audio.yml index d6a7ff5e25..763ae282ec 100644 --- a/.github/workflows/audio.yml +++ b/.github/workflows/audio.yml @@ -3,9 +3,9 @@ name: Shared audio on: push: branches: [main] - paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] + paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] pull_request: - paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] + paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] workflow_dispatch: permissions: diff --git a/.github/workflows/media.yml b/.github/workflows/media.yml index 4814e35ca8..08188c6e5d 100644 --- a/.github/workflows/media.yml +++ b/.github/workflows/media.yml @@ -3,9 +3,9 @@ name: Shared media on: push: branches: [main] - paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] + paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] pull_request: - paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] + paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] workflow_dispatch: permissions: diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index fa667bdfca..582264a37e 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -3,9 +3,9 @@ name: Shared video on: push: branches: [main] - paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] + paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] pull_request: - paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] + paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] workflow_dispatch: permissions: From ddf3f1b1c155e348a9d7af55712c2f1f9b5191d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:13:05 -0800 Subject: [PATCH 010/257] craft-testkit: the prop Origin row covers the source module through its closing brace --- crates/testkit/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index e5c41bc73a..5bd6b36205 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -41,7 +41,7 @@ proptest! { | Module | Source repository | Path | Revision | |---|---|---|---| -| `prop` | storytold/vectorcraft | `crates/pathops/tests/common/mod.rs:3-19` | `34627134` | +| `prop` | storytold/vectorcraft | `crates/pathops/tests/common/mod.rs:3-20` | `34627134` | ### Migration From 7f2e3c09edd04aba6859eb6fcd7044f4bd73c02e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 21:27:21 -0800 Subject: [PATCH 011/257] ci: put a space after the comma before the next path in the media, audio and video filters --- .github/workflows/audio.yml | 4 ++-- .github/workflows/media.yml | 4 ++-- .github/workflows/video.yml | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/audio.yml b/.github/workflows/audio.yml index 763ae282ec..919b57a3e1 100644 --- a/.github/workflows/audio.yml +++ b/.github/workflows/audio.yml @@ -3,9 +3,9 @@ name: Shared audio on: push: branches: [main] - paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] + paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] pull_request: - paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] + paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] workflow_dispatch: permissions: diff --git a/.github/workflows/media.yml b/.github/workflows/media.yml index 08188c6e5d..fb3681deb2 100644 --- a/.github/workflows/media.yml +++ b/.github/workflows/media.yml @@ -3,9 +3,9 @@ name: Shared media on: push: branches: [main] - paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] + paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] pull_request: - paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] + paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] workflow_dispatch: permissions: diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index 582264a37e..383f69f98a 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -3,9 +3,9 @@ name: Shared video on: push: branches: [main] - paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] + paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] pull_request: - paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**","Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] + paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] workflow_dispatch: permissions: From 9773d22ce1bf813814434d8e3bd0194f99f83d7c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 06:32:07 -0800 Subject: [PATCH 012/257] craft-xtask: read_json inherits stderr even when the caller set a pipe A caller that set stderr to a pipe on the command passed to read_json could hang it: the child stopped once the unread pipe filled, never closed its stdout, and the read never returned. read_json now sets stderr to inherit before it spawns, as its documentation says. A new test runs read_json, in a child process with stderr discarded, on a command whose stderr is a pipe and whose child writes 4 MiB to it. --- crates/xtask/README.md | 3 +- crates/xtask/src/layers.rs | 60 ++++++++++++++++++++++++++++++++++---- 2 files changed, 56 insertions(+), 7 deletions(-) diff --git a/crates/xtask/README.md b/crates/xtask/README.md index fda262a99d..90fbce2a65 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -135,7 +135,8 @@ fn layers(root: &std::path::Path) -> Result<(), String> { repeated package are errors. - `cargo_metadata` and `read_json` read at most the given number of bytes (`DEFAULT_METADATA_LIMIT` is 64 MiB) from the child's stdout, end the child when it writes more, and return an error for a - spawn failure, a failure exit status or output that is not JSON. Stderr is inherited. + spawn failure, a failure exit status or output that is not JSON. Stderr is inherited, also when the + caller set it to a pipe. - `check` returns the violations sorted by kind and fields, without duplicates; their `Display` text names the packages, layers and dependency kind. `wasm_set` returns the layered and standalone packages at or below `wasm_max_layer` and the `wasm_extra` packages the workspace has, sorted, with diff --git a/crates/xtask/src/layers.rs b/crates/xtask/src/layers.rs index 456462baff..c71998507a 100644 --- a/crates/xtask/src/layers.rs +++ b/crates/xtask/src/layers.rs @@ -815,13 +815,13 @@ pub fn from_metadata(meta: &Value) -> Result, Error> { } /// Runs `cmd` with stdout piped and stderr inherited, reads at most `max_bytes` of its output and -/// parses it as JSON. +/// parses it as JSON. A stderr setting on `cmd` is replaced. /// /// Returns [`Error::Process`] when the command cannot be started, writes more than `max_bytes` /// (the child is then ended), or exits with a failure status, and [`Error::Metadata`] when its /// output is not JSON. `label` names the command in each message. pub fn read_json(mut cmd: Command, label: &str, max_bytes: usize) -> Result { - cmd.stdin(Stdio::null()).stdout(Stdio::piped()); + cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::inherit()); let mut child = cmd.spawn().map_err(|e| Error::Process(format!("{label}: failed to spawn: {e}")))?; let mut buf = Vec::new(); let read = match child.stdout.take() { @@ -1305,8 +1305,8 @@ mod tests { let _guard = crate::spawn_guard(); let exe = std::env::current_exe().expect("test executable"); let mut cmd = Command::new(exe); - cmd.arg("--list").stderr(Stdio::null()); - assert!(matches!(read_json(cmd, "child", 8), Err(Error::Process(m)) if m == "child: wrote more than 8 bytes")); + cmd.arg("--list"); + assert!(matches!(read_json(cmd, "child", 8),Err(Error::Process(m)) if m == "child: wrote more than 8 bytes")); } #[test] @@ -1314,7 +1314,7 @@ mod tests { let _guard = crate::spawn_guard(); let exe = std::env::current_exe().expect("test executable"); let mut cmd = Command::new(exe); - cmd.arg("--list").stderr(Stdio::null()); + cmd.arg("--list"); assert!(matches!(read_json(cmd, "child", DEFAULT_METADATA_LIMIT), Err(Error::Metadata(m)) if m.starts_with("child: the output is not JSON"))); } @@ -1323,12 +1323,60 @@ mod tests { let _guard = crate::spawn_guard(); let exe = std::env::current_exe().expect("test executable"); let mut cmd = Command::new(exe); - cmd.arg("--craft-xtask-unknown-flag").stderr(Stdio::null()); + cmd.arg("--craft-xtask-unknown-flag"); assert!(matches!(read_json(cmd, "child", DEFAULT_METADATA_LIMIT), Err(Error::Process(m)) if m.starts_with("child: exited with "))); let missing = std::env::temp_dir().join("craft-xtask-no-such-program"); assert!(matches!(read_json(Command::new(missing), "missing", 1), Err(Error::Process(m)) if m.starts_with("missing: failed to spawn: "))); } + const PIPED_STDERR_READER: &str = "CRAFT_XTASK_PIPED_STDERR_READER"; + const STDERR_FLOOD_CHILD: &str = "CRAFT_XTASK_STDERR_FLOOD_CHILD"; + + /// This test binary, run as a child that runs only the ignored test `name`. + fn test_child(name: &str, env: &str) -> Command { + let exe = std::env::current_exe().expect("test executable"); + let mut c = Command::new(exe); + c.args(["--ignored", "--exact", name, "--nocapture"]).env(env, "1").stdin(Stdio::null()); + c + } + + #[test] + fn read_json_inherits_stderr_when_the_caller_pipes_it() { + let _guard = crate::spawn_guard(); + // The reader runs in a child whose stderr is null, so the flood it inherits is discarded. + let mut reader = test_child("layers::tests::piped_stderr_reader", PIPED_STDERR_READER); + reader.stdout(Stdio::null()).stderr(Stdio::null()); + assert!(reader.status().expect("reader child").success(), "read_json did not return for a child that floods a piped stderr"); + } + + /// Runs `read_json` on a child that floods its stderr, with stderr set to a pipe that nobody + /// reads; run by `read_json_inherits_stderr_when_the_caller_pipes_it`. + #[test] + #[ignore = "child process of read_json_inherits_stderr_when_the_caller_pipes_it"] + fn piped_stderr_reader() { + if std::env::var_os(PIPED_STDERR_READER).is_some() { + let mut cmd = test_child("layers::tests::stderr_flood_child", STDERR_FLOOD_CHILD); + cmd.stderr(Stdio::piped()); + // The child's stdout is the test harness's report, which is not JSON. + assert!( + matches!(read_json(cmd, "flood", DEFAULT_METADATA_LIMIT), Err(Error::Metadata(m)) if m.starts_with("flood: the output is not JSON")) + ); + } + } + + /// Writes 4 MiB to stderr, more than a pipe holds; run by `piped_stderr_reader`. + #[test] + #[ignore = "child process of piped_stderr_reader"] + fn stderr_flood_child() { + if std::env::var_os(STDERR_FLOOD_CHILD).is_some() { + let chunk = [b'.'; 64 * 1024]; + let mut err = std::io::stderr().lock(); + for _ in 0..64 { + std::io::Write::write_all(&mut err, &chunk).expect("stderr"); + } + } + } + /// Generic moves of PdfCraft's tests: numbered standalone crates, listed sideways pairs, UI /// dev-dependencies and test support at the UI layer. mod pdfcraft { From e1e4ab8a006204e219e6aaeb8cbacb0e85e7935e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:07:40 -0800 Subject: [PATCH 013/257] Share: a late account-link answer asks for nothing, and the docs state the stale-answer rule `receive` asked the service for destinations on every `Linked` answer, including one that arrived after its sheet closed, moved to another document or the account signed out. It now acts only when the open sheet is waiting for that request, and clears it. The sheet keeps every link in flight, since a second destination can be clicked before the first one answers; a refusal of either one is still reported. The share and cloud module docs now say that every answer carries the sequence number or account generation it was asked under, and that one whose request no longer stands is dropped. In the share docs, a withdrawal is named as the one answer applied by share id. A stray "this file." line is removed from the share module docs. --- crates/ui/src/cloud/mod.rs | 8 ++++++- crates/ui/src/share/mod.rs | 35 ++++++++++++++++++++--------- crates/ui/src/share/tests.rs | 43 ++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 11 deletions(-) diff --git a/crates/ui/src/cloud/mod.rs b/crates/ui/src/cloud/mod.rs index 2b1cd3d09f..324ca7c6fb 100644 --- a/crates/ui/src/cloud/mod.rs +++ b/crates/ui/src/cloud/mod.rs @@ -6,7 +6,7 @@ //! that says whose storage this is, a Save As page that picks a folder and //! names a file, and a save that refuses to overwrite somebody else's work. //! -//! Three things shape the implementation. +//! Four things shape the implementation. //! //! Nothing here opens a socket. Every call goes through [`CloudBackend`]. A //! host writes that half. This module never learns what it reaches. That keeps @@ -21,6 +21,12 @@ //! list under a heading reads to a user as a broken window. A feature the //! provider does not have is therefore absent, heading and all. //! +//! Nothing here acts on a stale answer. Every answer carries the account +//! generation its job was issued in, and [`pump`] drops one whose generation +//! is no longer current, so a reply that arrives after a sign-out or a new +//! sign-in is not applied to the session that replaced its own. A new kind of +//! answer follows the same rule. +//! //! The application supplies [`CloudApp`]. That is what it alone can answer. //! What its documents are, how bytes become one and back, and the words it //! shows them in. diff --git a/crates/ui/src/share/mod.rs b/crates/ui/src/share/mod.rs index 05d32e4de6..91c9673e38 100644 --- a/crates/ui/src/share/mod.rs +++ b/crates/ui/src/share/mod.rs @@ -5,12 +5,11 @@ //! look or change, add a note, decide whether an email goes out, and see who //! already has access so one of them can be taken away again. //! -//! Three things shape the implementation. +//! Four things shape the implementation. //! //! Nothing here opens a socket. Every call goes through [`ShareBackend`], and //! nothing here reaches the network. A host writes the backend, and this //! module never learns what it talks to. -//! this file. //! //! Nothing here blocks. Answers arrive on a channel and are read once per //! frame. Autocomplete waits [`DEBOUNCE`] after the last keystroke before it @@ -21,6 +20,17 @@ //! false until the service says sharing exists, and an app hides its Share //! control rather than offering a button that fails. Contacts and mail are //! reported separately and are hidden the same way. +//! +//! Nothing here acts on a stale answer. Every request carries a sequence +//! number, and its answer comes back with it. An answer is applied only while +//! the request it answers still stands: an answer to a query the +//! user has typed past, a link granted or an account linked for a sheet that +//! has since closed or moved to another document, and a capabilities answer +//! to a question asked before [`ShareDialog::refresh`], +//! [`ShareDialog::connect`] or [`ShareDialog::signed_out`] are dropped. A +//! withdrawal is the one answer applied by share id instead: the share is gone +//! on the service, so it leaves every list that still shows it. A new kind of +//! answer follows the sequence rule. use std::collections::HashMap; use std::sync::mpsc::{Receiver, Sender}; @@ -226,7 +236,9 @@ struct Sheet { /// Where it could be saved. `None` until the answer arrives. destinations: Option>, destinations_seq: Option, - link_seq: Option, + /// Account links in flight, by request. More than one can be: every + /// unlinked destination stays clickable while another one links. + linking: Vec, /// Which one is selected, by id. destination: Option, /// The name typed while the document still has nowhere to live. @@ -248,7 +260,7 @@ impl Sheet { Sheet { destinations: None, destinations_seq: None, - link_seq: None, + linking: Vec::new(), destination: None, save_as: title.clone(), saving: None, @@ -740,10 +752,13 @@ impl ShareDialog { } } Answer::Linked => { + // Only for the sheet that asked: after the sheet closed, moved + // to another document or the account signed out, a late + // answer asks the service for nothing. + let Some(sheet) = self.open.as_mut().filter(|sheet| sheet.linking.contains(&seq)) else { return }; // An account arrived, so the list is stale. - if let Some(sheet) = &mut self.open { - sheet.destinations = None; - } + sheet.linking.retain(|s| *s != seq); + sheet.destinations = None; let seq = self.issue(Request::Destinations); if let Some(sheet) = &mut self.open { sheet.destinations_seq = Some(seq); @@ -799,8 +814,8 @@ impl ShareDialog { sheet.destinations_seq = None; sheet.destinations = Some(Vec::new()); sheet.save_error = Some(reason); - } else if sheet.link_seq == Some(seq) { - sheet.link_seq = None; + } else if sheet.linking.contains(&seq) { + sheet.linking.retain(|s| *s != seq); sheet.save_error = Some(reason); } } @@ -842,7 +857,7 @@ impl ShareDialog { // application's business and not this crate's. let seq = self.issue(Request::Link { destination }); if let Some(sheet) = &mut self.open { - sheet.link_seq = Some(seq); + sheet.linking.push(seq); sheet.error = None; } } diff --git a/crates/ui/src/share/tests.rs b/crates/ui/src/share/tests.rs index 40d653b929..84a4ac2078 100644 --- a/crates/ui/src/share/tests.rs +++ b/crates/ui/src/share/tests.rs @@ -307,6 +307,49 @@ fn a_link_granted_after_the_sheet_moved_on_is_not_copied() { assert!(copied(&ctx).is_empty(), "nor after the sheet closed"); } +fn destinations_asked(backend: &Silent) -> usize { + backend.seen().iter().filter(|r| **r == Request::Destinations).count() +} + +fn last_link(dialog: &ShareDialog) -> u64 { + dialog.open.as_ref().and_then(|s| s.linking.last().copied()).expect("asked") +} + +#[test] +fn an_account_linked_for_a_sheet_that_moved_on_asks_for_nothing() { + let (ctx, mut dialog, _) = ready(); + dialog.apply(&ctx, vec![Act::Link("drive".into())]); + let first = last_link(&dialog); + // A second destination is clicked before the first one answers. + dialog.apply(&ctx, vec![Act::Link("mail".into())]); + let second = last_link(&dialog); + dialog.receive(&ctx, first, Ok(Answer::Linked)); + let sheet = dialog.open.as_ref().expect("open"); + assert!(sheet.destinations_seq.is_some(), "the sheet that asked fetches its destinations again"); + assert_eq!(sheet.linking, [second], "the later link is still in flight"); + dialog.receive(&ctx, second, Err("no account".into())); + let sheet = dialog.open.as_ref().expect("open"); + assert!(sheet.linking.is_empty()); + assert_eq!(sheet.save_error.as_deref(), Some("no account")); + + let (ctx, mut dialog, backend) = ready(); + dialog.apply(&ctx, vec![Act::Link("drive".into())]); + let linking = last_link(&dialog); + dialog.close(); + dialog.open("files/plan.docx", "Plan"); + let before = destinations_asked(&backend); + dialog.receive(&ctx, linking, Ok(Answer::Linked)); + assert_eq!(destinations_asked(&backend), before, "the budget's link answer must not ask anything for the plan"); + + let (ctx, mut dialog, backend) = ready(); + dialog.apply(&ctx, vec![Act::Link("drive".into())]); + let linking = last_link(&dialog); + dialog.signed_out(); + let before = destinations_asked(&backend); + dialog.receive(&ctx, linking, Ok(Answer::Linked)); + assert_eq!(destinations_asked(&backend), before, "nothing is asked for an account that signed out"); +} + /// Whether one frame of the sheet offers "Get a link" as a button that can /// be pressed, read off the accessibility tree. fn link_button_enabled(dialog: &mut ShareDialog) -> Option { From 6a4dc4c1814c404a6b5f0db52159c68ee417d7d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:21:56 -0800 Subject: [PATCH 014/257] craft-xtask: check_commits keeps a git repository's packages on one commit A pinned name with more than one package already fails as a Count violation, but apps resolve many craft-libs crates they never list in a pin table, each from whatever commit its dependent asked for. check_commits reads the cargo metadata JSON against OneCommit rules: every package whose source is the rule's git repository resolves from one commit (the text after the source's '#'). An Extra names a package allowed at its own commit, for a dependency an app declares at a second revision. A violation lists each commit with the packages resolved from it. Packages from other sources are not checked, and a source of the repository with no commit is an error. --- crates/xtask/README.md | 14 +++- crates/xtask/src/pins.rs | 148 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 159 insertions(+), 3 deletions(-) diff --git a/crates/xtask/README.md b/crates/xtask/README.md index a8afa366db..3c4eb219b0 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -10,7 +10,7 @@ The crate is native only and is a dependency of an app's `xtask` package only. | `assets` | always | `Policy`, `RowMode`, `check`, `run`, `list_files`, `read_document`, `is_asset`, `ASSET_EXT`: the asset attribution check against the document, folders and extensions the app supplies | | `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses | | `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` | -| `pins` | `pins` | `run`, `check`, `run_target_features`, `host_target`: the version, source and features of pinned dependencies, and packages the app forbids, read from `cargo metadata` within size limits | +| `pins` | `pins` | `run`, `check`, `check_commits`, `run_target_features`, `host_target`: the version, source and features of pinned dependencies, packages the app forbids, and one commit per git repository, read from `cargo metadata` within size limits | No feature is on by default. `report` adds `serde_json` and `craft-atomic`, and `pins` adds `serde_json`. @@ -207,6 +207,18 @@ Some("pdf-deps") => { or build edges; one reached only through development edges is allowed. `Name::Family("hayro")` matches `hayro` and every `hayro-*` name. - Packages the policy does not name are allowed, and an empty policy accepts any metadata. +- `check_commits` reads the same JSON against `OneCommit` rules. Every package whose source is the + rule's git repository must resolve from one commit, the text after the source's `#`. An `Extra` + names a package allowed at its own commit, for a dependency the app declares at a second revision + (DesignCraft's `craft-xml-dtd = { package = "craft-xml", … }`). A violation lists each commit with + the packages resolved from it: + + ```rust + let json = craft_xtask::pins::metadata(cargo, &limits)?; + let rule = OneCommit { url: "https://github.com/storytold/craft-libs", extra: &[Extra { name: "craft-xml", rev: DTD_REV }] }; + craft_xtask::pins::check_commits(&json, &[rule], &limits)?; + ``` + - JSON that does not parse, or lacks a field a rule needs (`resolve.nodes`, a package `id`, a node's `features` or `deps`, an edge's `dep_kinds`), is an error. - Cargo merges every target's features into one metadata result. `run_target_features` runs diff --git a/crates/xtask/src/pins.rs b/crates/xtask/src/pins.rs index 0109ae9c20..80c365cdc4 100644 --- a/crates/xtask/src/pins.rs +++ b/crates/xtask/src/pins.rs @@ -18,6 +18,10 @@ //! allowed. //! - Packages the policy does not name are allowed. An empty policy accepts any metadata. //! +//! [`check_commits`] reads the same JSON against a list of [`OneCommit`] rules: every package from +//! the rule's git repository resolves from one commit, apart from the [`Extra`] packages the rule +//! names at their own commit. +//! //! A rule that needs `resolve.nodes`, a package `id` or a node's `features` or `deps` returns an //! [`Error::Output`] when the field is missing, and so does JSON that does not parse. //! @@ -30,7 +34,7 @@ //! the command and returns [`Error::TooLarge`]. Standard error is read to its end while the command //! runs, and its first [`Limits::stderr_bytes`] bytes are kept for the error message. -use std::collections::{BTreeSet, HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::fmt; use std::io::{self, Read}; use std::process::{Child, Command, ExitStatus, Stdio}; @@ -127,6 +131,26 @@ pub struct Policy<'a> { pub forbidden: &'a [Forbidden<'a>], } +/// Packages from one git repository that resolve from one commit, for [`check_commits`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OneCommit<'a> { + /// The repository URL as the app's `Cargo.toml` writes it, for example + /// `https://github.com/storytold/craft-libs`. + pub url: &'a str, + /// Packages allowed at another commit. + pub extra: &'a [Extra<'a>], +} + +/// A package a [`OneCommit`] rule allows at a commit other than the one the rest resolve from, for a +/// dependency the app declares at a second revision. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Extra<'a> { + /// The package name. + pub name: &'a str, + /// The full commit hash. + pub rev: &'a str, +} + /// Size limits for the commands' output and the JSON [`check`] reads. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Limits { @@ -193,6 +217,13 @@ pub enum Violation { /// The root it was reached from, for [`Scope::ProductionFrom`]. root: Option, }, + /// Packages from one git repository resolve from more than one commit. + Commits { + /// The repository URL. + url: String, + /// Each commit, in sorted order, with the sorted names of the packages resolved from it. + commits: Vec<(String, Vec)>, + }, } impl fmt::Display for Violation { @@ -220,6 +251,14 @@ impl fmt::Display for Violation { Violation::Forbidden { name, rule, root: Some(root) } => { write!(f, "{name}: forbidden ({rule}) and reached from {root} over normal or build dependencies") } + Violation::Commits { url, commits } => { + write!(f, "{url}: packages resolve from {} commits:", commits.len())?; + for (i, (commit, names)) in commits.iter().enumerate() { + let sep = if i == 0 { " " } else { "; " }; + write!(f, "{sep}{commit} ({})", names.join(", "))?; + } + Ok(()) + } } } } @@ -338,6 +377,49 @@ pub fn check(metadata_json: &[u8], policy: &Policy<'_>, limits: &Limits) -> Resu Ok(()) } +/// Checks `cargo metadata --format-version 1` JSON against `rules`, in order: every package whose +/// `source` is the rule's git repository resolves from one commit, except the packages its +/// [`OneCommit::extra`] list names at their own commit. The commit is the part of the `source` after +/// its `#`. Packages from other sources, path packages included, are not checked. The first broken +/// rule is returned. +pub fn check_commits(metadata_json: &[u8], rules: &[OneCommit<'_>], limits: &Limits) -> Result<(), Error> { + if metadata_json.len() > limits.metadata_bytes { + return Err(Error::TooLarge { command: METADATA.into(), limit: limits.metadata_bytes }); + } + let meta: Value = serde_json::from_slice(metadata_json).map_err(|e| invalid(format!("not JSON: {e}")))?; + let packages = meta.get("packages").and_then(Value::as_array).ok_or_else(|| invalid("packages is missing"))?; + for rule in rules { + let mut commits: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new(); + for package in packages { + let name = str_field(package, "name", "a package")?; + let Some(source) = package.get("source").and_then(Value::as_str) else { continue }; + let Some(commit) = git_commit(source, rule.url)? else { continue }; + if rule.extra.iter().any(|extra| extra.name == name && extra.rev == commit) { + continue; + } + commits.entry(commit).or_default().insert(name); + } + if commits.len() > 1 { + let commits = commits.into_iter().map(|(commit, names)| (commit.to_owned(), names.into_iter().map(str::to_owned).collect())).collect(); + return Err(Violation::Commits { url: rule.url.into(), commits }.into()); + } + } + Ok(()) +} + +/// The commit of a `source` from the git repository at `url`: the text after its last `#`. `None` +/// for a source from anywhere else. +fn git_commit<'s>(source: &'s str, url: &str) -> Result, Error> { + let Some(rest) = source.strip_prefix("git+").and_then(|s| s.strip_prefix(url)) else { return Ok(None) }; + if !rest.starts_with(['?', '#']) { + return Ok(None); + } + match rest.rsplit_once('#') { + Some((_, commit)) if !commit.is_empty() => Ok(Some(commit)), + _ => Err(invalid(format!("source {source} names no commit"))), + } +} + /// The packages and resolved nodes of one metadata result. struct Graph<'m> { packages: &'m [Value], @@ -629,7 +711,10 @@ fn stop(child: &mut Child) { #[cfg(test)] mod tests { - use super::{CRATES_IO, Error, FeatureRule, Forbidden, Limits, Name, Pin, Policy, Scope, Violation, check, check_target_features, git_source}; + use super::{ + CRATES_IO, Error, Extra, FeatureRule, Forbidden, Limits, Name, OneCommit, Pin, Policy, Scope, Violation, check, check_commits, + check_target_features, git_source, + }; use serde_json::{Value, json}; fn bytes(v: &Value) -> Vec { @@ -726,6 +811,65 @@ mod tests { assert!(output_error(validate(&m, &policy)).contains("kind")); } + const LIBS: &str = "https://github.com/storytold/craft-libs"; + + fn libs_metadata(packages: &[(&str, &str)]) -> Value { + let packages: Vec = packages.iter().map(|(name, source)| json!({"name": name, "source": source})).collect(); + json!({ "packages": packages }) + } + + fn check_libs(m: &Value, extra: &[Extra<'_>]) -> Result<(), Error> { + check_commits(&bytes(m), &[OneCommit { url: LIBS, extra }], &Limits::default()) + } + + #[test] + fn packages_from_one_repository_resolve_from_one_commit() { + let a = git_source(LIBS, "aaa"); + let b = git_source(LIBS, "bbb"); + let ok = libs_metadata(&[("craft-xml", &a), ("craft-zip", &a), ("serde", CRATES_IO), ("app", "")]); + assert!(check_libs(&ok, &[]).is_ok()); + assert!(check_libs(&json!({"packages": [{"name": "app"}]}), &[]).is_ok(), "a path package has no source"); + + let split = libs_metadata(&[("craft-xml", &a), ("craft-zip", &b), ("craft-xml", &b)]); + assert_eq!( + violation(check_libs(&split, &[])), + Violation::Commits { + url: LIBS.into(), + commits: vec![("aaa".into(), vec!["craft-xml".into()]), ("bbb".into(), vec!["craft-xml".into(), "craft-zip".into()])] + } + ); + assert_eq!( + violation(check_libs(&split, &[])).to_string(), + "https://github.com/storytold/craft-libs: packages resolve from 2 commits: aaa (craft-xml); bbb (craft-xml, craft-zip)" + ); + } + + #[test] + fn an_extra_allows_one_package_at_its_own_commit_only() { + let main = git_source(LIBS, "aaa"); + let dtd = git_source(LIBS, "ddd"); + let m = libs_metadata(&[("craft-xml", &main), ("craft-zip", &main), ("craft-xml", &dtd)]); + assert!(check_libs(&m, &[Extra { name: "craft-xml", rev: "ddd" }]).is_ok()); + // The extra names one package at one commit: another package there is still a second commit. + let m = libs_metadata(&[("craft-xml", &main), ("craft-xml", &dtd), ("craft-zip", &dtd)]); + assert!(matches!(violation(check_libs(&m, &[Extra { name: "craft-xml", rev: "ddd" }])), Violation::Commits { .. })); + assert!(matches!(violation(check_libs(&m, &[Extra { name: "craft-xml", rev: "eee" }])), Violation::Commits { .. })); + } + + #[test] + fn a_commit_is_read_from_any_git_source_of_the_repository_only() { + // A branch or tag dependency still names its commit after `#`. + let m = libs_metadata(&[("craft-xml", &git_source(LIBS, "aaa")), ("craft-zip", &format!("git+{LIBS}?branch=main#bbb"))]); + assert!(matches!(violation(check_libs(&m, &[])), Violation::Commits { .. })); + // A repository whose URL only starts the same is another repository. + let m = + libs_metadata(&[("craft-xml", &git_source(LIBS, "aaa")), ("other", &git_source("https://github.com/storytold/craft-libs-extra", "bbb"))]); + assert!(check_libs(&m, &[]).is_ok()); + let m = libs_metadata(&[("craft-xml", &format!("git+{LIBS}?rev=aaa"))]); + assert!(output_error(check_libs(&m, &[])).contains("names no commit")); + assert!(output_error(check_libs(&json!({"packages": [{"source": CRATES_IO}]}), &[])).contains("name")); + } + #[test] fn rejects_features_that_are_not_strings() { let m = json!({ From 1b4dcb4afa10659855e86052b124e9a319ec75c5 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 20 Nov 2026 10:07:04 +0100 Subject: [PATCH 015/257] image-codecs: make JPEG 2000 decode an opt-in jp2 feature hayro-jpeg2000 was a plain dependency, so every crate that reached craft-image-codecs carried a JPEG 2000 decoder: craft-svg's tree feature, and through it any SVG or raster reader, including apps that export PDF and keep hayro out of their production graph with a guard. The decoder now sits behind jp2, off by default, in the shape sgi and sunraster already use: the module and the dependency are gated, caps().read reports the build, and a JP2 file without the feature is still detected and refused with the feature named. craft-file-formats gains the matching jp2 flag. Detection and the jp2_probe size reader need no decoder and stay on. --- crates/file-formats/Cargo.toml | 1 + crates/image-codecs/Cargo.toml | 5 ++++- crates/image-codecs/README.md | 1 + crates/image-codecs/src/codecs.rs | 1 + crates/image-codecs/src/format.rs | 8 ++++++- crates/image-codecs/src/lib.rs | 17 ++++++++++++--- crates/image-codecs/tests/it/jp2_feature.rs | 24 +++++++++++++++++++++ crates/image-codecs/tests/it/main.rs | 1 + 8 files changed, 53 insertions(+), 5 deletions(-) create mode 100644 crates/image-codecs/tests/it/jp2_feature.rs diff --git a/crates/file-formats/Cargo.toml b/crates/file-formats/Cargo.toml index afe7c6391d..293bcfaeea 100644 --- a/crates/file-formats/Cargo.toml +++ b/crates/file-formats/Cargo.toml @@ -27,6 +27,7 @@ default = [] raster-codecs = ["dep:craft-image-codecs"] heif = ["raster-codecs", "craft-image-codecs/heif"] avif = ["raster-codecs", "craft-image-codecs/avif"] +jp2 = ["raster-codecs", "craft-image-codecs/jp2"] pdf = [] svg = [] ora = ["dep:craft-ora"] diff --git a/crates/image-codecs/Cargo.toml b/crates/image-codecs/Cargo.toml index 46d5103426..f1f969ba0c 100644 --- a/crates/image-codecs/Cargo.toml +++ b/crates/image-codecs/Cargo.toml @@ -25,6 +25,9 @@ jxl = ["dep:craft-jxl"] # AVIF decode: craft-video's clean-room pure-Rust AV1 decoder. Native targets only (on wasm32 a # decoder panic aborts instead of becoming an error), so wasm32 builds leave AVIF unreadable. avif-decode = ["dep:craft-video", "craft-video/av1-decode"] +# JPEG 2000 decode via hayro-jpeg2000. Off by default so a crate that only reads SVG or raster +# pixels does not carry a JPEG 2000 decoder (a PDF reader family) into its graph. +jp2 = ["dep:hayro-jpeg2000"] [dependencies] craft-dds = { workspace = true } @@ -50,7 +53,7 @@ craft-jxl = { workspace = true, optional = true, features = ["decode"] } ravif = { version = "0.13", default-features = false, optional = true } rav1e = { version = "0.8", default-features = false, optional = true } avif-serialize = { version = "0.8", optional = true } -hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] } +hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"], optional = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] # DDS encodes rows of blocks on several threads, as the other parallel codecs here do on native targets. diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index 7d588336f1..27f74678d5 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -57,6 +57,7 @@ craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "< | Cineon | yes | yes | U16 (10-bit code values read and written exactly through U16) | Gray, RGB | no | no | no | no | no | no | no | built in | | DICOM | yes | **no** | U8, U16 | Gray, RGB | no | no | no | no | no | no | n/a | built in | | Amiga IFF (ILBM/PBM) | yes | yes (24-bit ILBM) | U8 | RGB, RGBA | yes (1-bit mask plane on write) | no | no | no | no | no | no | built in | +| JPEG 2000 (`.jp2`, `.j2k`) | with feature `jp2` | **no** | U8, U16 | Gray, GrayA, RGB, RGBA, CMYK | yes | no | no | no | no | no | no | `hayro-jpeg2000` (off by default, so an SVG or raster reader carries no PDF decoder family) | | Sun Raster (`.ras`) | with feature `sunraster` (incl. RLE and colour maps) | with feature `sunraster` (uncompressed) | U8 | Gray, RGB, RGBA | yes | no | no | no | no | no | no | `sunraster` (off by default) | | SGI (`.sgi`, `.rgb`, `.bw`) | with feature `sgi` | with feature `sgi` (RLE) | U8, U16 | Gray, Gray+A, RGB, RGBA | yes | no | no | no | no | no | no | `sgi` (off by default) | | JPEG-LS (`.jls`) | yes (any NEAR; one scan per component) | yes (lossless) | U8, U16 | Gray, RGB | no | no | no | no | no | no | no | built in | diff --git a/crates/image-codecs/src/codecs.rs b/crates/image-codecs/src/codecs.rs index 3fdf65ae34..817f63ce7e 100644 --- a/crates/image-codecs/src/codecs.rs +++ b/crates/image-codecs/src/codecs.rs @@ -13,6 +13,7 @@ pub(crate) mod gif_frames; pub(crate) mod gif_palette; pub(crate) mod heif; pub(crate) mod iff; +#[cfg(feature = "jp2")] pub(crate) mod jp2; pub(crate) mod jpeg; pub(crate) mod jpegls; diff --git a/crates/image-codecs/src/format.rs b/crates/image-codecs/src/format.rs index f43dae32c0..0e0ef4c6b2 100644 --- a/crates/image-codecs/src/format.rs +++ b/crates/image-codecs/src/format.rs @@ -350,7 +350,13 @@ pub fn caps(format: Format) -> FormatCaps { FormatCaps { read: cfg!(feature = "sgi"), write: cfg!(feature = "sgi"), depths: &[S::U8, S::U16], layouts: RGB_GRAY, alpha: true, ..base } } Format::JpegLs => FormatCaps { depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base }, - Format::Jp2 => FormatCaps { read: true, write: false, layouts: &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk, L::CmykA], icc: true, ..base }, + Format::Jp2 => FormatCaps { + read: cfg!(feature = "jp2"), + write: false, + layouts: &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk, L::CmykA], + icc: true, + ..base + }, } } diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index 2a91dc6ea8..707031a98c 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -75,11 +75,13 @@ pub use crate::resolution_probe::file_resolution; pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding}; pub use half::f16; +#[cfg(feature = "jp2")] +use crate::codecs::jp2; #[cfg(feature = "sgi")] use crate::codecs::sgi; #[cfg(feature = "sunraster")] use crate::codecs::sunraster; -use crate::codecs::{bmp, dds, dicom, dpx, exr, fits, heif, iff, jp2, jpeg, jpegls, jxl, pcx, png, pnm, tiff, via_image, webp, xpm}; +use crate::codecs::{bmp, dds, dicom, dpx, exr, fits, heif, iff, jpeg, jpegls, jxl, pcx, png, pnm, tiff, via_image, webp, xpm}; /// Detect the format and decode with default [`Limits`]. pub fn decode(bytes: &[u8]) -> Result { @@ -100,7 +102,7 @@ pub fn decode_as(format: Format, bytes: &[u8]) -> Result { /// Decode as a specific format. pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Result { // HEIF without the `heif` feature: its decoder stub says what is missing from this build. - if !caps(format).read && !matches!(format, Format::Heif | Format::Jxl) { + if !caps(format).read && !matches!(format, Format::Heif | Format::Jxl | Format::Jp2) { return Err(CodecError::unsupported(format, "decoding is not available for this format")); } let l = &opts.limits; @@ -141,7 +143,16 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res Format::JpegLs => jpegls::decode(bytes, l), Format::OpenExr => exr::decode(bytes, l), Format::Heif => heif::decode(bytes, l, opts.keep_orientation), - Format::Jp2 => jp2::decode(bytes, l), + Format::Jp2 => { + #[cfg(feature = "jp2")] + { + jp2::decode(bytes, l) + } + #[cfg(not(feature = "jp2"))] + { + Err(CodecError::unsupported(format, "JPEG 2000 support requires the jp2 feature")) + } + } Format::Jxl => jxl::decode(bytes, l), #[cfg(all(feature = "avif-decode", not(target_arch = "wasm32")))] Format::Avif => codecs::avif_decode::decode(bytes, l, opts.keep_orientation), diff --git a/crates/image-codecs/tests/it/jp2_feature.rs b/crates/image-codecs/tests/it/jp2_feature.rs new file mode 100644 index 0000000000..3cc8facc28 --- /dev/null +++ b/crates/image-codecs/tests/it/jp2_feature.rs @@ -0,0 +1,24 @@ +//! JPEG 2000 decode is opt-in: without the `jp2` feature a JP2 file is detected and refused with a +//! named reason rather than decoded, so a crate that only reads SVG keeps no JPEG 2000 decoder. + +use craft_image_codecs::*; + +/// JP2 signature box and file type box, and nothing else. +const JP2_HEAD: &[u8] = b"\0\0\0\x0cjP \r\n\x87\n\0\0\0\x14ftypjp2 \0\0\0\0jp2 "; + +#[test] +fn a_jp2_file_is_detected_without_the_feature() { + assert_eq!(detect(JP2_HEAD), Some(Format::Jp2)); +} + +#[test] +fn a_jp2_file_is_refused_with_the_feature_named() { + let err = decode_with(JP2_HEAD, &DecodeOptions::default()).expect_err("no image in a bare header"); + // With the feature, the bare header is a decode error, never "unsupported". + if !cfg!(feature = "jp2") + && let CodecError::Unsupported { format, reason } = err + { + assert_eq!(format, Format::Jp2); + assert!(reason.contains("jp2 feature"), "reason names the feature: {reason}"); + } +} diff --git a/crates/image-codecs/tests/it/main.rs b/crates/image-codecs/tests/it/main.rs index e3c0feaaf8..4a71f7c9ea 100644 --- a/crates/image-codecs/tests/it/main.rs +++ b/crates/image-codecs/tests/it/main.rs @@ -16,6 +16,7 @@ mod exr_stream; mod fidelity; mod gif_frames; mod heif; +mod jp2_feature; mod jpeg_inks; mod jpegls_oracle; mod limits; From 4dcf4fc13a36ac3c2ac9bf3c825b230f25486992 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 20 Nov 2026 13:20:29 +0100 Subject: [PATCH 016/257] image-codecs: fix the jp2 review findings The README promised native U16 samples, which jp2::decode does not produce and caps(Format::Jp2).depths does not advertise: list U8. The feature test used its error match as a guard, so a different variant would have skipped the assertions. Each feature branch now asserts what it expects and anything else fails. --- crates/image-codecs/README.md | 2 +- crates/image-codecs/tests/it/jp2_feature.rs | 17 +++++++++++------ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index 27f74678d5..d88722238a 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -57,7 +57,7 @@ craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "< | Cineon | yes | yes | U16 (10-bit code values read and written exactly through U16) | Gray, RGB | no | no | no | no | no | no | no | built in | | DICOM | yes | **no** | U8, U16 | Gray, RGB | no | no | no | no | no | no | n/a | built in | | Amiga IFF (ILBM/PBM) | yes | yes (24-bit ILBM) | U8 | RGB, RGBA | yes (1-bit mask plane on write) | no | no | no | no | no | no | built in | -| JPEG 2000 (`.jp2`, `.j2k`) | with feature `jp2` | **no** | U8, U16 | Gray, GrayA, RGB, RGBA, CMYK | yes | no | no | no | no | no | no | `hayro-jpeg2000` (off by default, so an SVG or raster reader carries no PDF decoder family) | +| JPEG 2000 (`.jp2`, `.j2k`) | with feature `jp2` | **no** | U8 | Gray, GrayA, RGB, RGBA, CMYK | yes | no | no | no | no | no | no | `hayro-jpeg2000` (off by default, so an SVG or raster reader carries no PDF decoder family) | | Sun Raster (`.ras`) | with feature `sunraster` (incl. RLE and colour maps) | with feature `sunraster` (uncompressed) | U8 | Gray, RGB, RGBA | yes | no | no | no | no | no | no | `sunraster` (off by default) | | SGI (`.sgi`, `.rgb`, `.bw`) | with feature `sgi` | with feature `sgi` (RLE) | U8, U16 | Gray, Gray+A, RGB, RGBA | yes | no | no | no | no | no | no | `sgi` (off by default) | | JPEG-LS (`.jls`) | yes (any NEAR; one scan per component) | yes (lossless) | U8, U16 | Gray, RGB | no | no | no | no | no | no | no | built in | diff --git a/crates/image-codecs/tests/it/jp2_feature.rs b/crates/image-codecs/tests/it/jp2_feature.rs index 3cc8facc28..9d75731c5d 100644 --- a/crates/image-codecs/tests/it/jp2_feature.rs +++ b/crates/image-codecs/tests/it/jp2_feature.rs @@ -14,11 +14,16 @@ fn a_jp2_file_is_detected_without_the_feature() { #[test] fn a_jp2_file_is_refused_with_the_feature_named() { let err = decode_with(JP2_HEAD, &DecodeOptions::default()).expect_err("no image in a bare header"); - // With the feature, the bare header is a decode error, never "unsupported". - if !cfg!(feature = "jp2") - && let CodecError::Unsupported { format, reason } = err - { - assert_eq!(format, Format::Jp2); - assert!(reason.contains("jp2 feature"), "reason names the feature: {reason}"); + if cfg!(feature = "jp2") { + // With the feature the bare header reaches the decoder and fails as undecodable. + assert!(matches!(err, CodecError::Malformed { .. } | CodecError::InvalidImage(_)), "decodes as far as the decoder: {err:?}"); + } else { + match err { + CodecError::Unsupported { format, reason } => { + assert_eq!(format, Format::Jp2); + assert!(reason.contains("jp2 feature"), "reason names the feature: {reason}"); + } + other => panic!("expected an unsupported format error, got {other:?}"), + } } } From 2176367fd7c3b5c3ce3ec4ca3018031cb3b80b10 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 20 Nov 2026 15:17:06 +0100 Subject: [PATCH 017/257] docs(image-codecs): JPEG 2000 keeps its ICC profile The format row said no while jp2::decode carries the profile into out.icc and caps(Format::Jp2) reports icc: true. Say yes, so a colour-managed consumer does not skip the decoder on the table alone. --- crates/image-codecs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index d88722238a..054df4f314 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -57,7 +57,7 @@ craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "< | Cineon | yes | yes | U16 (10-bit code values read and written exactly through U16) | Gray, RGB | no | no | no | no | no | no | no | built in | | DICOM | yes | **no** | U8, U16 | Gray, RGB | no | no | no | no | no | no | n/a | built in | | Amiga IFF (ILBM/PBM) | yes | yes (24-bit ILBM) | U8 | RGB, RGBA | yes (1-bit mask plane on write) | no | no | no | no | no | no | built in | -| JPEG 2000 (`.jp2`, `.j2k`) | with feature `jp2` | **no** | U8 | Gray, GrayA, RGB, RGBA, CMYK | yes | no | no | no | no | no | no | `hayro-jpeg2000` (off by default, so an SVG or raster reader carries no PDF decoder family) | +| JPEG 2000 (`.jp2`, `.j2k`) | with feature `jp2` | **no** | U8 | Gray, GrayA, RGB, RGBA, CMYK | yes | yes | no | no | no | no | no | `hayro-jpeg2000` (off by default, so an SVG or raster reader carries no PDF decoder family) | | Sun Raster (`.ras`) | with feature `sunraster` (incl. RLE and colour maps) | with feature `sunraster` (uncompressed) | U8 | Gray, RGB, RGBA | yes | no | no | no | no | no | no | `sunraster` (off by default) | | SGI (`.sgi`, `.rgb`, `.bw`) | with feature `sgi` | with feature `sgi` (RLE) | U8, U16 | Gray, Gray+A, RGB, RGBA | yes | no | no | no | no | no | no | `sgi` (off by default) | | JPEG-LS (`.jls`) | yes (any NEAR; one scan per component) | yes (lossless) | U8, U16 | Gray, RGB | no | no | no | no | no | no | no | built in | From d376ca2aaad10087f199faa11c4fae965f4533aa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:33:18 -0800 Subject: [PATCH 018/257] craft-menu: the minimal macOS app menu takes the app's translations mac::install_app_menu wrote About, Hide and Quit in English with format!() and left Services, Hide Others and Show All to muda's English defaults, so a localized app that installs it to make Cmd+Q ask first got an English app menu in every language. mac::install_app_menu_with takes a LayoutOptions and names the six items through LayoutOptions::label with the keys mac_layout already uses for the same items (About {app}, Services, Hide {app}, Hide Others, Show All, Quit {app}). install_app_menu calls it with English labels, so its menu is unchanged. --- crates/menu/README.md | 9 +++++++++ crates/menu/src/layout.rs | 27 ++++++++++++++++++++++++++ crates/menu/src/lib.rs | 3 ++- crates/menu/src/mac.rs | 29 ++++++++++++++++++++-------- crates/menu/src/tests.rs | 40 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 99 insertions(+), 9 deletions(-) diff --git a/crates/menu/README.md b/crates/menu/README.md index 063c2d0e40..7d64e35910 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -175,6 +175,15 @@ Hide Others, Show All and Quit, where Quit asks the app first. craft_menu::mac::install_app_menu(&cc.egui_ctx, "WordCraft")?; ``` +Its labels are English. `mac::install_app_menu_with` takes a `LayoutOptions` instead, and its +`label` translates `About {app}`, `Services`, `Hide {app}`, `Hide Others`, `Show All` and +`Quit {app}`, the keys `mac_layout` uses for the same items. + +```rust +#[cfg(target_os = "macos")] +craft_menu::mac::install_app_menu_with(&cc.egui_ctx, &LayoutOptions { label: &translate, ..LayoutOptions::new("WordCraft") })?; +``` + craft-menu owns muda's menu event handler. muda keeps the first one set per process, so the crate sets it once and both `mac::install` and `mac::install_app_menu` use it; a later `mac::install` replaces the minimal app menu, and a second `mac::install` returns `None`. diff --git a/crates/menu/src/layout.rs b/crates/menu/src/layout.rs index 51f45959e9..41a5a5b909 100644 --- a/crates/menu/src/layout.rs +++ b/crates/menu/src/layout.rs @@ -93,6 +93,33 @@ fn english(s: &'static str) -> String { s.into() } +/// The labels of the minimal macOS app menu (`mac::install_app_menu_with`), translated through +/// the keys [`mac_layout`] uses for its own app menu. The menu's title is the app's name. +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(not(any(test, target_os = "macos")), allow(dead_code))] +pub(crate) struct AppMenuLabels { + pub(crate) title: String, + pub(crate) about: String, + pub(crate) services: String, + pub(crate) hide: String, + pub(crate) hide_others: String, + pub(crate) show_all: String, + pub(crate) quit: String, +} + +#[cfg_attr(not(any(test, target_os = "macos")), allow(dead_code))] +pub(crate) fn app_menu_labels(options: &LayoutOptions) -> AppMenuLabels { + AppMenuLabels { + title: options.app_name.to_string(), + about: options.text("About {app}"), + services: options.text(Standard::Services.english()), + hide: options.text("Hide {app}"), + hide_others: options.text("Hide Others"), + show_all: options.text(Standard::ShowAll.english()), + quit: options.text("Quit {app}"), + } +} + /// A system or browser shortcut the app also uses for one of its commands. #[derive(Clone, Debug, PartialEq)] pub struct Clash { diff --git a/crates/menu/src/lib.rs b/crates/menu/src/lib.rs index 6e46250c16..897d5da5ad 100644 --- a/crates/menu/src/lib.rs +++ b/crates/menu/src/lib.rs @@ -45,7 +45,8 @@ //! ([`LayoutOptions::extra_shortcuts`]). //! //! The labels the layout writes itself are English unless the app passes its translations in -//! [`LayoutOptions::label`]. +//! [`LayoutOptions::label`]. `mac::install_app_menu_with` takes the same translations for the +//! minimal app menu. //! //! **Keys stay with egui.** AppKit runs a menu's key equivalents before the window sees the key, //! which would skip the app's own key rules (a focused text field keeps ⌘C, ⌘V and ⌘Z, dialogs diff --git a/crates/menu/src/mac.rs b/crates/menu/src/mac.rs index e5bdd306d9..3dfc06a921 100644 --- a/crates/menu/src/mac.rs +++ b/crates/menu/src/mac.rs @@ -45,7 +45,9 @@ use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSEventType}; use craft_keymap::{Chord, CommandRef, Key, Mods}; +use crate::LayoutOptions; use crate::driver::{Backend, Dispatch, Event, NativeMenu, native_ok}; +use crate::layout::app_menu_labels; use crate::model::{Builtin, Item, ItemKind, Menu, MenuBar, MenuRole, Node, Standard, native_id, structure_key, window_key}; /// Set by [`install`]: there is one full menu bar per process. @@ -117,7 +119,8 @@ pub fn install_with(ctx: &egui::Context, bar: &MenuBar, options: MacOptions) -> /// Replace winit's default macOS app menu with a minimal one whose Quit (⌘Q) asks the app first, /// for an app without a [`MenuBar`] of its own: About, Services, Hide, Hide Others, Show All and -/// Quit, labelled in English with `app_name` ("Quit WordCraft"). +/// Quit, labeled in English with `app_name` ("Quit WordCraft"). [`install_app_menu_with`] takes +/// the app's translations. /// /// winit's Quit ends the process without asking, so unsaved work is lost. This Quit has the id /// [`craft_quit::QUIT_MENU_ID`] and runs [`craft_quit::on_menu_event`]: it asks the root window to @@ -128,22 +131,32 @@ pub fn install_with(ctx: &egui::Context, bar: &MenuBar, options: MacOptions) -> /// Does nothing when this menu or a full menu bar ([`install`]) is already installed. On error /// winit's menu stays: the app still runs, but ⌘Q quits without asking. pub fn install_app_menu(ctx: &egui::Context, app_name: &str) -> Result<(), Box> { + install_app_menu_with(ctx, &LayoutOptions::new(app_name)) +} + +/// [`install_app_menu`] with the app's translations. [`LayoutOptions::label`] names the items +/// through the keys [`crate::mac_layout`] uses for its app menu: `About {app}`, `Services`, +/// `Hide {app}`, `Hide Others`, `Show All` and `Quit {app}`, with `{app}` replaced by +/// [`LayoutOptions::app_name`], which also titles the menu. [`LayoutOptions::extra_shortcuts`] +/// is not used. +pub fn install_app_menu_with(ctx: &egui::Context, options: &LayoutOptions) -> Result<(), Box> { if MainThreadMarker::new().is_none() { return Err("craft_menu::mac::install_app_menu runs on the main thread".into()); } if INSTALLED.load(Ordering::SeqCst) || APP_MENU.with_borrow(Option::is_some) { return Ok(()); } - let quit = MenuItem::with_id(craft_quit::QUIT_MENU_ID, format!("Quit {app_name}"), true, Some(Accelerator::new(Modifiers::META, Code::KeyQ))); - let app_menu = Submenu::new(app_name, true); + let labels = app_menu_labels(options); + let quit = MenuItem::with_id(craft_quit::QUIT_MENU_ID, labels.quit, true, Some(Accelerator::new(Modifiers::META, Code::KeyQ))); + let app_menu = Submenu::new(labels.title, true); app_menu.append_items(&[ - &PredefinedMenuItem::about(Some(&format!("About {app_name}")), None), + &PredefinedMenuItem::about(Some(&labels.about), None), &PredefinedMenuItem::separator(), - &PredefinedMenuItem::services(None), + &PredefinedMenuItem::services(Some(&labels.services)), &PredefinedMenuItem::separator(), - &PredefinedMenuItem::hide(Some(&format!("Hide {app_name}"))), - &PredefinedMenuItem::hide_others(None), - &PredefinedMenuItem::show_all(None), + &PredefinedMenuItem::hide(Some(&labels.hide)), + &PredefinedMenuItem::hide_others(Some(&labels.hide_others)), + &PredefinedMenuItem::show_all(Some(&labels.show_all)), &PredefinedMenuItem::separator(), &quit, ])?; diff --git a/crates/menu/src/tests.rs b/crates/menu/src/tests.rs index d0854f7391..2c78e8f604 100644 --- a/crates/menu/src/tests.rs +++ b/crates/menu/src/tests.rs @@ -162,6 +162,46 @@ fn an_untagged_quit_is_craft_quits_and_labels_are_translated() { assert_eq!(ids(&l.bar.menu(MenuRole::Window).unwrap().children), ["", "", "---", "", "---", "doc.0"]); } +/// The minimal app menu is English by default and takes the app's translations through the keys +/// the Mac layout uses for the same items. +#[test] +fn the_minimal_app_menu_labels_are_translated() { + use crate::layout::{AppMenuLabels, app_menu_labels}; + + let english = app_menu_labels(&LayoutOptions::new("Sample")); + let expected = AppMenuLabels { + title: "Sample".into(), + about: "About Sample".into(), + services: "Services".into(), + hide: "Hide Sample".into(), + hide_others: "Hide Others".into(), + show_all: "Show All".into(), + quit: "Quit Sample".into(), + }; + assert_eq!(english, expected); + + let german = |s: &'static str| match s { + "About {app}" => "Über {app}".to_string(), + "Services" => "Dienste".into(), + "Hide {app}" => "{app} ausblenden".into(), + "Hide Others" => "Andere ausblenden".into(), + "Show All" => "Alle einblenden".into(), + "Quit {app}" => "{app} beenden".into(), + other => panic!("no app menu label {other:?}"), + }; + let labels = app_menu_labels(&LayoutOptions { label: &german, ..LayoutOptions::new("Sample") }); + let expected = AppMenuLabels { + title: "Sample".into(), + about: "Über Sample".into(), + services: "Dienste".into(), + hide: "Sample ausblenden".into(), + hide_others: "Andere ausblenden".into(), + show_all: "Alle einblenden".into(), + quit: "Sample beenden".into(), + }; + assert_eq!(labels, expected); +} + /// App commands keep ⌘H, ⌘M, ⌘W and ⌘,: the system items give way, and each clash is reported. #[test] fn clashes_are_resolved_in_the_apps_favour() { From 799e53c5936edd2e7d4d9450398bbce50bfd63ff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:40:56 -0800 Subject: [PATCH 019/257] hayro-interpret: a soft mask set outside a form draws that form The self-draw check added with the PdfCraft port (patch 89) compared each form against every form being drawn on the page when it was drawn. A device interprets a soft mask, a tiling pattern or a Type 3 glyph when it applies it, which can be inside a form that the mask's content draws again: a soft mask set on the page whose group draws the same shared form as the page then draws. The mask's copy of the form was skipped, and the page reported ContentTruncated. Soft masks, tiling patterns and Type 3 glyphs now record the forms being drawn where the content set or showed them, and their content is checked against that record. A form that draws itself, directly, through another form, or through a soft mask, tiling pattern or Type 3 glyph set inside it, is still skipped and reported. --- vendor/README.craft-reader.md | 11 + vendor/hayro-interpret/SOURCE.json | 16 +- vendor/hayro-interpret/src/context.rs | 44 ++- vendor/hayro-interpret/src/font/mod.rs | 13 +- vendor/hayro-interpret/src/lib.rs | 2 + vendor/hayro-interpret/src/pattern.rs | 17 +- vendor/hayro-interpret/src/self_draw_tests.rs | 282 ++++++++++++++++++ vendor/hayro-interpret/src/soft_mask.rs | 16 +- 8 files changed, 388 insertions(+), 13 deletions(-) create mode 100644 vendor/hayro-interpret/src/self_draw_tests.rs diff --git a/vendor/README.craft-reader.md b/vendor/README.craft-reader.md index 405799ceb6..82e9c29302 100644 --- a/vendor/README.craft-reader.md +++ b/vendor/README.craft-reader.md @@ -88,6 +88,17 @@ colorants paint through their alternate space (`Plate::spots_as_process`) and no overprints. Masks in other color spaces are unchanged. A test in `crates/pdf/tests/plates.rs` checks process, spot, RGB and backdrop colors. +A craft-libs patch, labeled `Craft patch (self-draw scope)` in code comments, scopes the +self-draw check of hayro-interpret patch 89 for soft masks, tiling patterns and Type 3 glyphs. +Each of them records the forms being drawn where the content set or showed it +(`context::FormsDrawing`), and `SoftMask::interpret`, `SoftMask::interpret_plate`, +`TilingPattern::interpret` and `Type3Glyph::interpret` check the forms they draw against that +record instead of the forms the device is drawing when it calls them. A soft mask set on the page +and interpreted by a device while it draws a form now draws that form; before, the mask's copy of +the form was skipped and the page reported `ContentTruncated`. A form that draws itself, directly, +through another form, or through a soft mask, tiling pattern or Type 3 glyph set inside it, is +still skipped. Tests: `self_draw_tests.rs` in hayro-interpret. + The output-intent conversion of patch 36 goes through a `color::CmykConversion` trait, so that callers can convert with their own color management. `CmykSimulation::new` keeps #2770's moxcms conversion as the default, and `CmykSimulation::with_conversion` takes a diff --git a/vendor/hayro-interpret/SOURCE.json b/vendor/hayro-interpret/SOURCE.json index bffa37b555..71924358dd 100644 --- a/vendor/hayro-interpret/SOURCE.json +++ b/vendor/hayro-interpret/SOURCE.json @@ -188,7 +188,7 @@ "path": "src/context.rs", "source_sha256": "dc2be553958ee3f5e5e644a77a0301723bae9ca027a352c13b9caaf549cc0e56", "source_git_blob": "d6772baa15ebb95d3ba2d1f54ce5c250ad1e8137", - "sha256": "221174b2b65824e1489e8d0f61ac5c81b828caf7f5c7053e27c84a6657857f4c" + "sha256": "cf87f1889acca28e7d0e19b08e25ce9db3654de8f612b29f9a111bd06e01affd" }, { "path": "src/convert.rs", @@ -290,7 +290,7 @@ "path": "src/font/mod.rs", "source_sha256": "7e6411927d91205ca76c6b59f9d737cd1104d066f8cfcc0a87f481016ef30313", "source_git_blob": "7c8c8d086d59139df791cdb6952506473ec4b5a7", - "sha256": "c0c903cb8a33ab863412c407ad10181adec0d22b81c899fc5225de14d8878091" + "sha256": "903b2426fbbc1bc0ffbd3f1f2d1a3ce7fdd28aad424f38ba8592b866982de9f9" }, { "path": "src/font/outline.rs", @@ -386,7 +386,7 @@ "path": "src/lib.rs", "source_sha256": "ea3fa23b74f99b5382798f90b7e9f0e3edca354ee26ea92fe26a91ee5c0195c9", "source_git_blob": "24c3be295783d7a53ac6bc39d93e539883480cd4", - "sha256": "ea3fa23b74f99b5382798f90b7e9f0e3edca354ee26ea92fe26a91ee5c0195c9" + "sha256": "777f78daa1c2dbcb945bc2061bfd5748f3ee07a0efbe53de7fa7de29d2880f5f" }, { "path": "src/log.rs", @@ -404,7 +404,13 @@ "path": "src/pattern.rs", "source_sha256": "17b49a465275c20e6645dea9443f2cb3a64c594925fd860e74b80b44d5344e37", "source_git_blob": "9295f51709f8915951d7b9afca9411651d65a1f8", - "sha256": "e57d4de60126eafa0da2113af12bbbde1aabd15554f1ee26f6551b8219f4ede5" + "sha256": "7b89b41219c11eac781b64ec0584ccaebbd76aa9c570ba13a00e0cb06c59b4c5" + }, + { + "path": "src/self_draw_tests.rs", + "source_sha256": null, + "source_git_blob": null, + "sha256": "58930501e624b86fd45ddc82e464a959d989d6ef94eb7e62f8f8ad24c78ec8ec" }, { "path": "src/shading.rs", @@ -416,7 +422,7 @@ "path": "src/soft_mask.rs", "source_sha256": "6cd9c59c0cff580879c1f06ff40f3537c04b719bdb3ea59008fa1ab7559db5dd", "source_git_blob": "4d97d565b53c820fa927fbba8c3dda6acead7f34", - "sha256": "fe3da157602bf5b16a452ecbe1d8d554af992a5b9dfaa771dd23c2e2e66d730b" + "sha256": "54cb20d6ba5ab8e290e420833acfa9ce2e8e7274b74680e4b9481a093b5d1db9" }, { "path": "src/types.rs", diff --git a/vendor/hayro-interpret/src/context.rs b/vendor/hayro-interpret/src/context.rs index 7997e9c0de..66ae11e1cb 100644 --- a/vendor/hayro-interpret/src/context.rs +++ b/vendor/hayro-interpret/src/context.rs @@ -40,7 +40,9 @@ std::thread_local! { // PdfCraft patch (89): the form XObjects being drawn on this page, outermost first, across // the contexts of the tiling patterns, Type 3 glyphs, soft masks and groups painted while // they draw. A form already on it draws itself and is skipped. Its length is bounded by the - // nesting limits: every form on it is nested in the ones before it. + // nesting limits: every form on it is nested in the ones before it. While a device + // interprets a soft mask, tiling pattern or Type 3 glyph, it holds the forms that one was + // set in (`with_forms_drawing`). static FORMS_DRAWING: RefCell> = const { RefCell::new(Vec::new()) }; } @@ -159,6 +161,42 @@ pub(crate) fn take_nested_paint(depth: u32) -> bool { }) } +/// Craft patch (self-draw scope): the forms being drawn where a soft mask, a tiling pattern or a +/// Type 3 glyph was set in the content. A device may interpret any of them later, while it draws +/// another form: a soft mask set on the page is interpreted for each fill it applies to, inside +/// whatever form that fill is in. Its content is nested in the forms it was set in, so the +/// self-draw check of patch (89) runs against those (see [`with_forms_drawing`]). +#[derive(Clone, Default)] +pub(crate) struct FormsDrawing(Vec); + +impl FormsDrawing { + /// The forms being drawn now. + pub(crate) fn current() -> Self { + FORMS_DRAWING.with(|forms| Self(forms.try_borrow().map(|forms| forms.clone()).unwrap_or_default())) + } + + /// The forms, outermost first. + pub(crate) fn ids(&self) -> &[hayro_syntax::object::ObjectIdentifier] { + &self.0 + } +} + +/// Craft patch (self-draw scope): run `draw` with `forms` as the forms being drawn, and put +/// back the ones being drawn before. A form `draw` reaches is skipped only when it is among +/// `forms` or nested in itself within `draw`. +pub(crate) fn with_forms_drawing(forms: &FormsDrawing, draw: impl FnOnce() -> R) -> R { + let outer = FORMS_DRAWING.with(|stack| stack.try_borrow_mut().ok().map(|mut stack| core::mem::replace(&mut *stack, forms.0.clone()))); + let result = draw(); + if let Some(outer) = outer { + FORMS_DRAWING.with(|stack| { + if let Ok(mut stack) = stack.try_borrow_mut() { + *stack = outer; + } + }); + } + result +} + /// A cache used by the interpreter. /// /// Ideally, such a cache should be constructed once per PDF and then reused across @@ -363,7 +401,9 @@ impl<'a> Context<'a> { /// The forms being drawn are those of this page's context and of every context painting /// inside it (a tiling pattern, a Type 3 glyph, a soft mask or a group), so a form that /// reaches itself through one of those is skipped too, while a form drawn again after it - /// has finished draws as usual. + /// has finished draws as usual. A soft mask, tiling pattern or Type 3 glyph draws inside + /// the forms it was set in, wherever the device interprets it (Craft patch (self-draw + /// scope), [`FormsDrawing`]). pub(crate) fn enter_form( &mut self, id: Option, diff --git a/vendor/hayro-interpret/src/font/mod.rs b/vendor/hayro-interpret/src/font/mod.rs index e87382d976..a9ce0fe360 100644 --- a/vendor/hayro-interpret/src/font/mod.rs +++ b/vendor/hayro-interpret/src/font/mod.rs @@ -1,6 +1,7 @@ //! Interacting with the different kinds of PDF fonts. use crate::context::Context; +use crate::context::FormsDrawing; use crate::context::InterpreterCache; use crate::device::Device; use crate::font::cid::Type0Font; @@ -222,11 +223,16 @@ pub struct Type3Glyph<'a> { pub(crate) settings: InterpreterSettings, pub(crate) nesting_depth: u32, pub(crate) char_code: u32, + /// Craft patch (self-draw scope): the forms being drawn where the glyph was shown. + pub(crate) forms: FormsDrawing, } /// A glyph defined by PDF drawing instructions. impl<'a> Type3Glyph<'a> { /// Draw the type3 glyph to the given device. + /// + /// Craft patch (self-draw scope): the glyph procedure draws inside the forms the glyph was + /// shown in, wherever the device interprets it (see [`crate::SoftMask::interpret`]). pub fn interpret( &self, device: &mut impl Device<'a>, @@ -234,8 +240,10 @@ impl<'a> Type3Glyph<'a> { glyph_transform: Affine, paint: &Paint<'a>, ) { - self.font - .render_glyph(self, transform, glyph_transform, paint, device); + crate::context::with_forms_drawing(&self.forms, || { + self.font + .render_glyph(self, transform, glyph_transform, paint, device) + }); } /// Returns the Unicode code point for this glyph, if available: the `ToUnicode` cmap, then @@ -386,6 +394,7 @@ impl<'a> Font<'a> { settings: ctx.settings.clone(), nesting_depth, char_code, + forms: FormsDrawing::current(), }; Glyph::Type3(Box::new(shape_glyph)) diff --git a/vendor/hayro-interpret/src/lib.rs b/vendor/hayro-interpret/src/lib.rs index 03a0f44811..565fbc1c5d 100644 --- a/vendor/hayro-interpret/src/lib.rs +++ b/vendor/hayro-interpret/src/lib.rs @@ -40,6 +40,8 @@ mod device; mod function; mod interpret; mod ocg; +#[cfg(test)] +mod self_draw_tests; mod soft_mask; mod types; mod x_object; diff --git a/vendor/hayro-interpret/src/pattern.rs b/vendor/hayro-interpret/src/pattern.rs index bc3b99c943..288df7f54a 100644 --- a/vendor/hayro-interpret/src/pattern.rs +++ b/vendor/hayro-interpret/src/pattern.rs @@ -2,7 +2,7 @@ use crate::cache::Cache; use crate::color::{Color, ColorSpace, DefaultColorSpaces, Plate}; -use crate::context::{Context, InterpreterCache}; +use crate::context::{Context, FormsDrawing, InterpreterCache, with_forms_drawing}; use crate::device::Device; use crate::font::Glyph; use crate::interpret::state::{ActiveTransferFunction, State}; @@ -182,6 +182,8 @@ pub struct TilingPattern<'a> { pub(crate) settings: InterpreterSettings, pub(crate) xref: &'a XRef, nesting_depth: u32, + /// Craft patch (self-draw scope): the forms being drawn where the pattern was set. + forms: FormsDrawing, } impl TilingPattern<'_> { @@ -280,15 +282,28 @@ impl<'a> TilingPattern<'a> { cache: ctx.interpreter_cache.clone(), xref: ctx.xref, nesting_depth, + forms: FormsDrawing::current(), }) } /// Interpret the contents of the pattern into the given device. + /// + /// Craft patch (self-draw scope): the cell draws inside the forms the pattern was set in, + /// wherever the device interprets it (see [`SoftMask::interpret`]). pub fn interpret( &self, device: &mut impl Device<'a>, initial_transform: Affine, is_stroke: bool, + ) -> Option<()> { + with_forms_drawing(&self.forms, || self.interpret_cell(device, initial_transform, is_stroke)) + } + + fn interpret_cell( + &self, + device: &mut impl Device<'a>, + initial_transform: Affine, + is_stroke: bool, ) -> Option<()> { // PdfCraft patch: a tiling pattern can paint itself (directly, or through resources it // inherits when its own are missing), which recursed until the stack overflowed. Bound diff --git a/vendor/hayro-interpret/src/self_draw_tests.rs b/vendor/hayro-interpret/src/self_draw_tests.rs new file mode 100644 index 0000000000..e28b481f06 --- /dev/null +++ b/vendor/hayro-interpret/src/self_draw_tests.rs @@ -0,0 +1,282 @@ +//! Craft patch (self-draw scope) tests: a form that draws itself, directly or through another +//! form, a soft mask, a tiling pattern or a Type 3 glyph set inside it, is skipped and the page +//! reported truncated (patch (89)). A soft mask, tiling pattern or Type 3 glyph set outside a +//! form draws that form in full when the device interprets it while drawing the form. + +use crate::context::content_was_truncated; +use crate::font::{Glyph, Type3Glyph}; +use crate::pattern::Pattern; +use crate::{ + BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, + InterpreterSettings, InterpreterWarning, Paint, PathDrawMode, SoftMask, interpret_page, +}; +use hayro_syntax::Pdf; +use kurbo::{Affine, BezPath, Rect}; +use std::sync::{Arc, Mutex}; + +/// A PDF with one 100 by 100 page whose resources are `resources` and whose content is +/// `content`, followed by `objects` as objects 5, 6 and so on. +fn pdf(resources: &str, content: &str, objects: &[String]) -> Pdf { + let mut bodies = vec![ + "<< /Type /Catalog /Pages 2 0 R >>".to_string(), + "<< /Type /Pages /Count 1 /Kids [3 0 R] >>".to_string(), + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources {resources} >>"), + stream("", content), + ]; + bodies.extend_from_slice(objects); + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, body) in bodies.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", bodies.len() + 1).as_bytes()); + for offset in offsets { + out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice( + format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", bodies.len() + 1).as_bytes(), + ); + Pdf::new(out).expect("synthetic pdf") +} + +fn stream(entries: &str, content: &str) -> String { + format!("<< /Length {} {entries} >>\nstream\n{content}\nendstream", content.len()) +} + +/// A form 10 by 10 that draws `content` with the resources of whatever draws it. +fn form(content: &str) -> String { + stream("/Type /XObject /Subtype /Form /BBox [0 0 10 10]", content) +} + +/// A soft mask group that draws `content` with `resources`. +fn mask_group(resources: &str, content: &str) -> String { + stream( + &format!("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency >> /Resources {resources}"), + content, + ) +} + +/// A coloured tiling pattern whose cell draws `content` with `resources`. +fn tiling(resources: &str, content: &str) -> String { + stream( + &format!( + "/Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources {resources}" + ), + content, + ) +} + +/// A Type 3 font whose glyph `a` is drawn by the procedure in object `proc`, with `resources`. +fn type3(resources: &str, proc: usize) -> String { + format!( + "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << /a {proc} 0 R >> /Encoding << /Type /Encoding /Differences [97 /a] >> /FirstChar 97 /LastChar 97 /Widths [1000] /Resources {resources} >>" + ) +} + +/// The paths a device was given, by where they were drawn. +#[derive(Default, Debug, PartialEq)] +struct Drawn { + paths: usize, + in_masks: usize, + in_patterns: usize, + in_glyphs: usize, +} + +/// A device that interprets every soft mask it is given, every tiling pattern it fills with and +/// every Type 3 glyph it draws, each into a device of its own, at the time it is given them. With +/// `defer_glyphs`, it keeps the first Type 3 glyph and interprets it at the next path instead. +#[derive(Default)] +struct Recorder<'a> { + drawn: Drawn, + defer_glyphs: bool, + deferred: Option>>, +} + +impl Recorder<'_> { + fn absorb(&mut self, inner: &Recorder<'_>) -> usize { + let d = &inner.drawn; + self.drawn.in_masks += d.in_masks; + self.drawn.in_patterns += d.in_patterns; + self.drawn.in_glyphs += d.in_glyphs; + d.paths + } +} + +impl<'a> Device<'a> for Recorder<'a> { + fn set_soft_mask(&mut self, mask: Option>) { + if let Some(mask) = mask { + let mut inner = Recorder::default(); + mask.interpret(&mut inner); + self.drawn.in_masks += self.absorb(&inner); + } + } + + fn set_blend_mode(&mut self, _: BlendMode) {} + + fn draw_path(&mut self, _: &BezPath, transform: Affine, paint: &Paint<'a>, _: &PathDrawMode) { + self.drawn.paths += 1; + if let Paint::Pattern(pattern) = paint + && let Pattern::Tiling(tiling) = &**pattern + { + let mut inner = Recorder::default(); + tiling.interpret(&mut inner, transform, false); + self.drawn.in_patterns += self.absorb(&inner); + } + if let Some(glyph) = self.deferred.take() { + let mut inner = Recorder::default(); + glyph.interpret(&mut inner, Affine::IDENTITY, Affine::IDENTITY, paint); + self.drawn.in_glyphs += self.absorb(&inner); + } + } + + fn push_clip_path(&mut self, _: &ClipPath) {} + + fn push_transparency_group(&mut self, _: f32, _: Option>, _: BlendMode) {} + + fn draw_glyph(&mut self, glyph: &Glyph<'a>, transform: Affine, glyph_transform: Affine, paint: &Paint<'a>, _: &GlyphDrawMode) { + let Glyph::Type3(glyph) = glyph else { + return; + }; + if self.defer_glyphs { + self.deferred = Some(glyph.clone()); + return; + } + let mut inner = Recorder::default(); + glyph.interpret(&mut inner, transform, glyph_transform, paint); + self.drawn.in_glyphs += self.absorb(&inner); + } + + fn draw_image(&mut self, _: Image<'a, '_>, _: Affine) {} + + fn pop_clip_path(&mut self) {} + + fn pop_transparency_group(&mut self) {} +} + +/// Draws the page of `pdf` and returns what was drawn and whether the page was reported +/// truncated. +fn draw(pdf: &Pdf, defer_glyphs: bool) -> (Drawn, bool) { + let cache = InterpreterCache::new(); + let warnings = Arc::new(Mutex::new(Vec::new())); + let sink = warnings.clone(); + let settings = InterpreterSettings { + warning_sink: Arc::new(move |warning| sink.lock().expect("warnings").push(warning)), + ..InterpreterSettings::default() + }; + let mut ctx = Context::new(Affine::IDENTITY, Rect::new(0.0, 0.0, 100.0, 100.0), &cache, pdf.xref(), settings); + let mut device = Recorder { defer_glyphs, ..Recorder::default() }; + let page = &pdf.pages()[0]; + interpret_page(page, &mut ctx, &mut device); + let warnings = warnings.lock().expect("warnings"); + let truncated = warnings.iter().any(|w| matches!(w, InterpreterWarning::ContentTruncated)); + assert_eq!(truncated, content_was_truncated()); + (device.drawn, truncated) +} + +const SQUARE: &str = "0 0 10 10 re f"; + +// A form that names itself in its own resources is a reference cycle, which hayro-syntax reads +// as a missing object. The forms below have no resources of their own and reach themselves +// through the page's. + +#[test] +fn a_form_that_draws_itself_is_skipped() { + let pdf = pdf("<< /XObject << /F 5 0 R >> >>", "/F Do", &[form("0 0 10 10 re f /F Do")]); + let (drawn, truncated) = draw(&pdf, false); + assert_eq!(drawn, Drawn { paths: 1, ..Drawn::default() }); + assert!(truncated); +} + +#[test] +fn a_form_that_draws_itself_through_another_form_is_skipped() { + let pdf = pdf( + "<< /XObject << /F 5 0 R /H 6 0 R >> >>", + "/F Do", + &[form("0 0 10 10 re f /H Do"), form("/F Do")], + ); + let (drawn, truncated) = draw(&pdf, false); + assert_eq!(drawn, Drawn { paths: 1, ..Drawn::default() }); + assert!(truncated); +} + +#[test] +fn a_soft_mask_set_outside_a_form_draws_that_form() { + // The mask is set on the page and draws the form the page then draws; the device interprets + // it while it draws that form. + let pdf = pdf( + "<< /XObject << /F 5 0 R >> /ExtGState << /GS << /SMask << /S /Alpha /G 6 0 R >> >> >> >>", + "/GS gs /F Do", + &[form(SQUARE), mask_group("<< /XObject << /F 5 0 R >> >>", "/F Do")], + ); + let (drawn, truncated) = draw(&pdf, false); + assert!(drawn.in_masks > 0, "{drawn:?}"); + assert_eq!(drawn.paths, 1); + assert!(!truncated); +} + +#[test] +fn a_soft_mask_set_inside_a_form_that_it_draws_skips_that_form() { + let pdf = pdf( + "<< /XObject << /F 5 0 R >> /ExtGState << /GS << /SMask << /S /Alpha /G 6 0 R >> >> >> >>", + "/F Do", + &[form("/GS gs 0 0 10 10 re f"), mask_group("<< /XObject << /F 5 0 R >> >>", "/F Do")], + ); + let (drawn, truncated) = draw(&pdf, false); + assert_eq!(drawn, Drawn { paths: 1, ..Drawn::default() }); + assert!(truncated); +} + +#[test] +fn a_tiling_pattern_set_outside_a_form_draws_that_form() { + let pdf = pdf( + "<< /XObject << /F 5 0 R >> /Pattern << /P 6 0 R >> >>", + "/Pattern cs /P scn /F Do", + &[form(SQUARE), tiling("<< /XObject << /F 5 0 R >> >>", "/F Do")], + ); + let (drawn, truncated) = draw(&pdf, false); + assert!(drawn.in_patterns > 0, "{drawn:?}"); + assert!(!truncated); +} + +#[test] +fn a_tiling_pattern_set_inside_a_form_that_it_draws_skips_that_form() { + let pdf = pdf( + "<< /XObject << /F 5 0 R >> /Pattern << /P 6 0 R >> >>", + "/F Do", + &[form("/Pattern cs /P scn 0 0 10 10 re f"), tiling("<< /XObject << /F 5 0 R >> >>", "/F Do")], + ); + let (drawn, truncated) = draw(&pdf, false); + assert_eq!(drawn, Drawn { paths: 1, ..Drawn::default() }); + assert!(truncated); +} + +#[test] +fn a_type3_glyph_shown_outside_a_form_draws_that_form() { + // The device keeps the glyph shown on the page and interprets it while it draws the form. + let pdf = pdf( + "<< /XObject << /F 5 0 R >> /Font << /T 6 0 R >> >>", + "BT /T 10 Tf (a) Tj ET /F Do", + &[form(SQUARE), type3("<< /XObject << /F 5 0 R >> >>", 7), stream("", "1000 0 d0 /F Do")], + ); + let (drawn, truncated) = draw(&pdf, true); + assert!(drawn.in_glyphs > 0, "{drawn:?}"); + assert!(!truncated); +} + +#[test] +fn a_type3_glyph_shown_inside_a_form_that_it_draws_skips_that_form() { + let pdf = pdf( + "<< /XObject << /F 5 0 R >> /Font << /T 6 0 R >> >>", + "/F Do", + &[ + form("BT /T 10 Tf (a) Tj ET 0 0 10 10 re f"), + type3("<< /XObject << /F 5 0 R >> >>", 7), + stream("", "1000 0 d0 /F Do"), + ], + ); + let (drawn, truncated) = draw(&pdf, false); + assert_eq!(drawn, Drawn { paths: 1, ..Drawn::default() }); + assert!(truncated); +} diff --git a/vendor/hayro-interpret/src/soft_mask.rs b/vendor/hayro-interpret/src/soft_mask.rs index 6ecd81dbfd..1ddee0c9e2 100644 --- a/vendor/hayro-interpret/src/soft_mask.rs +++ b/vendor/hayro-interpret/src/soft_mask.rs @@ -1,5 +1,5 @@ use crate::color::{CmykSimulation, Color, ColorComponents, ColorSpace, DeviceFamily, Ink, Plate, device_cmyk_to_gray}; -use crate::context::{Context, InterpreterCache}; +use crate::context::{Context, FormsDrawing, InterpreterCache, with_forms_drawing}; use crate::device::Device; use crate::function::Function; use crate::interpret::state::State; @@ -83,6 +83,8 @@ struct Repr<'a> { device_cmyk: bool, /// Craft patch (CMYK masks): the page plate's printing condition, for [`SoftMask::plate`]. simulation: Option, + /// Craft patch (self-draw scope): the forms being drawn where the mask was set. + forms: FormsDrawing, } impl Hash for Repr<'_> { @@ -184,6 +186,7 @@ impl<'a> SoftMask<'a> { .plate .as_ref() .and_then(|p| p.simulation.clone()); + let forms = FormsDrawing::current(); let cache_key = hash128(&( simulation.as_ref().map(|s| s.digest()), dict.cache_key(), @@ -191,6 +194,8 @@ impl<'a> SoftMask<'a> { [bbox.x0.to_bits(), bbox.y0.to_bits(), bbox.x1.to_bits(), bbox.y1.to_bits()], resources_key, nesting_depth, + // Craft patch (self-draw scope): the mask skips the forms it was set in. + forms.ids(), )); Some(Self(Rc::new(Repr { @@ -216,6 +221,7 @@ impl<'a> SoftMask<'a> { nesting_depth, device_cmyk, simulation, + forms, }))) } @@ -256,10 +262,14 @@ impl<'a> SoftMask<'a> { state, self.0.nesting_depth, ); - draw_form_xobject(&self.0.parent_resources, &self.0.group, &mut ctx, device); + with_forms_drawing(&self.0.forms, || draw_form_xobject(&self.0.parent_resources, &self.0.group, &mut ctx, device)); } /// Interpret the contents of the mask into the given device. + /// + /// Craft patch (self-draw scope): the contents draw inside the forms the mask was set in, + /// so a device may interpret the mask while it draws any form: a mask that draws that form + /// draws it, and one that draws a form it was set in skips that form. pub fn interpret(&self, device: &mut impl Device<'a>) { let state = State::new(self.0.root_transform); let mut ctx = Context::new_with( @@ -272,7 +282,7 @@ impl<'a> SoftMask<'a> { self.0.nesting_depth, ); ctx.luminosity_in_device_cmyk = self.0.luminosity_in_device_cmyk; - draw_form_xobject(&self.0.parent_resources, &self.0.group, &mut ctx, device); + with_forms_drawing(&self.0.forms, || draw_form_xobject(&self.0.parent_resources, &self.0.group, &mut ctx, device)); } /// Return the object identifier of the mask. From a39059470ef5436856b4c081773c782d9e0b539e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:46:56 -0800 Subject: [PATCH 020/257] atomic: cut temporary names at 64 bytes so long non-Latin names save temp_name kept the first 64 characters of the destination name. With four-byte UTF-8 characters that is 256 bytes before the suffix, over the 255-byte name limit of APFS and ext4, so a save to a valid name such as 62 emoji plus ".json" (253 bytes) failed when the staging file was created. The stem now keeps at most 64 bytes, cut at a character boundary. --- crates/atomic/src/lib.rs | 42 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 08b881e17b..6a80715839 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -588,11 +588,22 @@ fn resolve_links(path: &Path) -> io::Result { Err(io::Error::new(io::ErrorKind::InvalidInput, format!("cannot save {}: too many levels of symbolic links", path.display()))) } +/// The most bytes of the destination name that a temporary name keeps. +const TEMP_STEM_BYTES: usize = 64; + /// Generates a unique, hidden temporary file name beside `file`. +/// +/// The name keeps at most the first 64 bytes of `file`, cut at a character boundary, so the +/// temporary name stays within the 255-byte name limit of common file systems for any +/// destination name. pub fn temp_name(file: &str) -> String { static COUNTER: AtomicU64 = AtomicU64::new(0); let n = COUNTER.fetch_add(1, Ordering::Relaxed); - let stem: String = file.chars().take(64).collect(); + let mut end = file.len().min(TEMP_STEM_BYTES); + while !file.is_char_boundary(end) { + end -= 1; + } + let stem = &file[..end]; #[cfg(not(target_arch = "wasm32"))] let pid = std::process::id(); #[cfg(target_arch = "wasm32")] @@ -1340,6 +1351,35 @@ mod tests { assert!(name.ends_with(".craft_tmp")); } + #[test] + fn temp_name_keeps_long_non_latin_names_under_the_name_limit() { + // 62 four-byte characters plus ".json" is a valid 253-byte name. + let file = format!("{}.json", "\u{1F600}".repeat(62)); + assert_eq!(file.len(), 253); + let name = temp_name(&file); + assert!(name.len() <= 255, "{} bytes", name.len()); + assert!(name.starts_with(&format!(".{}.", "\u{1F600}".repeat(16)))); + assert!(name.ends_with(".craft_tmp")); + } + + #[test] + fn temp_name_cuts_at_a_character_boundary() { + // 63 ASCII bytes then a two-byte character that would end at byte 65. + let file = format!("{}\u{e9}tail", "a".repeat(63)); + let name = temp_name(&file); + assert!(name.starts_with(&format!(".{}.", "a".repeat(63)))); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn saves_a_long_non_latin_name() { + let d = TempDir::new("long-name"); + let p = d.0.join(format!("{}.json", "\u{1F600}".repeat(62))); + assert!(atomic_write(&p, b"saved").is_ok()); + assert_eq!(std::fs::read(&p).ok(), Some(b"saved".to_vec())); + assert_no_temp(&d.0); + } + #[cfg(target_arch = "wasm32")] #[test] fn wasm_atomic_write_returns_unsupported() { From 25cb33ed525f9601c74dea2d1203c2f7fea760cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:41:11 -0800 Subject: [PATCH 021/257] craft-gpu-wgpu: open the device through craft-gpu-device and read its loss from DeviceHealth With `adapter-probe`, `WgpuContext::new` opens its device with `craft_gpu_device::open` for `Preference::Auto`, so it takes the same adapter, driver corrections and fallback order as other callers of that crate, and `probe_caps()` reports the adapter `craft_gpu_device::pick` chooses. The instance uses `craft_gpu_device::native_descriptor`'s backends (no OpenGL on Windows) unless `WGPU_BACKEND` names others. - `WgpuContext::from_opened` takes a `craft_gpu_device::Opened`, and `WgpuContext::with_device` takes a device, its queue and its `DeviceHealth` (for example egui's device). The caps are the device's own. - The context no longer sets a device-lost callback. A loss is read from the device's `DeviceHealth`, including one another user of that health records, and `health()` returns it. - `upload_buffer` and `request_read` also stop on any other fault the health records, as `GpuFault::Operation`, and allocation errors the context's error scopes catch are recorded in the health. `device_status()` still reports a loss only. - When the device reports such an error while `read_buffer` waits, or the wait fails, the read is dropped and returns that error instead of polling until a map that may not complete. - `adapter-probe` now depends on `craft-gpu-device`, which turns on wgpu's default native backends. --- Cargo.lock | 1 + crates/gpu-device/README.md | 3 +- crates/gpu-wgpu/Cargo.toml | 8 +- crates/gpu-wgpu/src/lib.rs | 215 ++++++++++++++++++++++------------- crates/gpu-wgpu/src/tests.rs | 117 +++++++++++++++++++ docs/gpu-backends.md | 12 +- 6 files changed, 270 insertions(+), 86 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f99595d8da..0b5c9b8eb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2273,6 +2273,7 @@ name = "craft-gpu-wgpu" version = "0.1.0" dependencies = [ "craft-gpu", + "craft-gpu-device", "craft-gpu-providers", "pollster 0.4.0", "wgpu", diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index 3c7da59b5c..5c8c2d8fe5 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -65,7 +65,8 @@ Licensed under MIT OR Apache-2.0. `Device::poll` raises on a lost device and record the loss. - wgpu keeps one device-lost callback per device, and a later `set_device_lost_callback` replaces the one `DeviceHealth::watch` set. A `craft-gpu` context on a watched device reads - `DeviceHealth::device_status` instead of setting its own callback. + `DeviceHealth::device_status` instead of setting its own callback, as `craft-gpu-wgpu`'s + `WgpuContext` does. - After an out-of-memory error, polls and waits keep running, so staging memory is reclaimed. The app reads `DeviceHealth::out_of_memory_count` when it handles the error, frees memory, and passes the count to `DeviceHealth::clear_out_of_memory`. The device is then healthy again, diff --git a/crates/gpu-wgpu/Cargo.toml b/crates/gpu-wgpu/Cargo.toml index ecf45c62f0..da5d9ca867 100644 --- a/crates/gpu-wgpu/Cargo.toml +++ b/crates/gpu-wgpu/Cargo.toml @@ -16,12 +16,14 @@ craft-gpu = { workspace = true } wgpu = { workspace = true, features = ["webgpu"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# Chooses and opens the device, and watches it for a loss (`adapter-probe`). +craft-gpu-device = { workspace = true, optional = true } pollster = { workspace = true, optional = true } wgpu = { workspace = true } [features] default = [] -adapter-probe = ["dep:pollster"] +adapter-probe = ["dep:pollster", "dep:craft-gpu-device"] native-vulkan = ["wgpu/vulkan"] native-dx12 = ["wgpu/dx12"] native-metal = ["wgpu/metal"] @@ -33,3 +35,7 @@ pollster = { workspace = true } # providers against a real WgpuContext, not just craft-gpu-null, per RFC-0022 acceptance # requirement 2. Dev-only: no cycle (craft-gpu-providers never depends on craft-gpu-wgpu). craft-gpu-providers = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +# The noop backend opens devices without a GPU in the tests. +wgpu = { workspace = true, features = ["noop"] } diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index ec0e71b276..e261f85bb5 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -1,10 +1,13 @@ //! wgpu-backed [`GpuContext`](craft_gpu::GpuContext). //! //! WebGPU on `wasm32`; native APIs when backend features are enabled. With the `adapter-probe` -//! feature (native only, pollster) and at least one `native-*` backend feature, -//! [`WgpuContext::new`] requests a real device and builds [`DeviceCaps`] from what that device -//! actually enabled (`Device::limits()` / `Device::features()`), never from the adapter's -//! advertised maximum. Without a usable adapter (the features above are off, no GPU is present, +//! feature (native only), [`WgpuContext::new`] opens a real device through `craft-gpu-device` +//! (its adapter choice for `Preference::Auto`, its driver corrections and its fallback order) and +//! builds [`DeviceCaps`] from what that device actually enabled (`Device::limits()` / +//! `Device::features()`), never from the adapter's advertised maximum. +//! [`WgpuContext::from_opened`] and [`WgpuContext::with_device`] take a device the caller opened. +//! A loss is read from the device's `craft_gpu_device::DeviceHealth`, which owns the device's +//! device-lost callback. Without a usable adapter (`adapter-probe` is off, no GPU is present, //! or on `wasm32` where real device creation needs the async worker-init path noted in //! `docs/gpu-backends.md`), the context degrades to the same in-memory staging behavior as //! `craft_gpu_null::NullContext` (not a dependency of this crate; named here only for context); @@ -32,29 +35,17 @@ fn probe_fallback(backend_name: &str, device_name: &str) -> DeviceCaps { #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] fn probe_caps_native() -> DeviceCaps { - let instance = native::instance(); - let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) { - Ok(adapter) => adapter, - Err(_) => return probe_fallback("wgpu", "no-adapter"), - }; - let info = adapter.get_info(); - let limits = adapter.limits(); - DeviceCaps { - backend_name: format!("{:?}", info.backend), - device_name: info.name, - max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size, - max_buffer_size: limits.max_buffer_size, - max_texture_dimension_2d: limits.max_texture_dimension_2d, - features: Vec::new(), - vendor_id: info.vendor, - software: info.device_type == wgpu::DeviceType::Cpu, - } + native::probe_caps_on(&native::instance()) } /// Adapter-advertised limits, when an adapter is available; otherwise conservative defaults. This /// is the quick, device-free probe for UI surfaces that want a number before any context exists /// (Settings). It is advisory only: these are the adapter's maximums, not a device's granted -/// ones. [`WgpuContext::caps`] is the authoritative, device-truth source once a context exists. +/// ones. With `adapter-probe` it reports the adapter `craft_gpu_device::pick` chooses for +/// `Preference::Auto` without opening a device on it; when a device then fails to open there, +/// [`WgpuContext::new`] opens the next adapter in `craft_gpu_device::ranked` order, or a software +/// one, which this probe does not report. [`WgpuContext::caps`] is the authoritative, device-truth +/// source once a context exists. pub fn probe_caps() -> DeviceCaps { #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] { @@ -74,11 +65,10 @@ pub fn probe_caps() -> DeviceCaps { #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] mod native { - use std::sync::{Arc, Mutex}; + use craft_gpu::DeviceCaps; + use craft_gpu_device::{Capabilities, DeviceHealth, Opened, Preference, Request}; - use craft_gpu::{DeviceCaps, GpuFault}; - - use crate::{Backing, DeviceBacking}; + use crate::{Backing, DeviceBacking, probe_fallback}; /// Features this context asks a device for. No provider dispatches a real WGSL job on wgpu /// yet (`craft-gpu-providers` ships CPU stand-ins, by design, until that lands); extend this @@ -86,60 +76,56 @@ mod native { /// [`create_device`]. const DESIRED_FEATURES: wgpu::Features = wgpu::Features::empty(); - /// An instance over whichever native backends were compiled in (`native-vulkan`, - /// `native-dx12`, `native-metal`, `native-gles`), honoring `WGPU_BACKEND` when set, so the + /// An instance over `craft_gpu_device::native_descriptor`'s backends (Vulkan, Metal and + /// DirectX 12, plus OpenGL except on Windows), honoring `WGPU_BACKEND` when set, so the /// same build can be pointed at a software Vulkan adapter (lavapipe/llvmpipe) in a local container run or a CI lane. - /// `new_without_display_handle` because this context never has a window (no surface is ever - /// requested); FilmCraft's own off-screen export device uses the same constructor for the - /// same reason (`filmcraft-gpu`'s `export_renderer.rs`, see `docs/gpu-backends.md`). + /// The descriptor has no display handle because this context never has a window (no surface + /// is ever requested); FilmCraft's own off-screen export device uses the same constructor for + /// the same reason (`filmcraft-gpu`'s `export_renderer.rs`, see `docs/gpu-backends.md`). pub(crate) fn instance() -> wgpu::Instance { - let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + let mut desc = craft_gpu_device::native_descriptor(); if let Some(backends) = wgpu::Backends::from_env() { desc.backends = backends; } wgpu::Instance::new(desc) } - /// Request a real device. `None` on the defined no-adapter path (no usable adapter): the - /// caller degrades to the staging backing, identical in shape to `craft-gpu-null`. + /// Open a real device on `instance` with `craft-gpu-device`'s choice for + /// `Preference::Auto`. `None` on the defined no-adapter path (no usable adapter): the caller + /// degrades to the staging backing, identical in shape to `craft-gpu-null`. /// - /// Never panics: `required_features` is intersected with what the adapter actually - /// advertises, and `required_limits` is set to the adapter's own limits (never more), so + /// Never panics: `craft_gpu_device::open` asks only for the features from + /// [`DESIRED_FEATURES`] the adapter has, and for the adapter's own limits (never more), so /// `request_device`'s documented panics ("features/limits not supported by this adapter") /// cannot trigger here. + pub(crate) fn create_device_on(instance: &wgpu::Instance) -> Option<(DeviceCaps, Backing)> { + let request = Request { label: Some("craft-gpu-wgpu"), optional_features: DESIRED_FEATURES, ..Default::default() }; + let opened = craft_gpu_device::open(instance, None, &Preference::Auto, &request).ok()?; + Some(backing_of(&opened)) + } + pub(crate) fn create_device() -> Option<(DeviceCaps, Backing)> { - let instance = instance(); - let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; - let features = DESIRED_FEATURES & adapter.features(); - let limits = adapter.limits(); - let desc = - wgpu::DeviceDescriptor { label: Some("craft-gpu-wgpu"), required_features: features, required_limits: limits, ..Default::default() }; - let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?; + create_device_on(&instance()) + } - let lost = Arc::new(Mutex::new(None)); - { - let lost = Arc::clone(&lost); - device.set_device_lost_callback(move |reason, message| { - if let Ok(mut slot) = lost.lock() { - *slot = Some(GpuFault::DeviceLost(format!("{reason:?}: {message}"))); - } - }); + pub(crate) fn backing_of(opened: &Opened) -> (DeviceCaps, Backing) { + backing_with(opened.device.clone(), opened.queue.clone(), opened.health.clone()) + } + + /// The device's own caps, and a backing that reads the loss from `health`. + pub(crate) fn backing_with(device: wgpu::Device, queue: wgpu::Queue, health: DeviceHealth) -> (DeviceCaps, Backing) { + let caps = craft_gpu_device::device_caps(&device); + (caps, Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), health, pending: Vec::new() })) + } + + /// The adapter `craft-gpu-device` would open for `Preference::Auto`, with its advertised + /// limits and no features (no device was opened to grant any). + pub(crate) fn probe_caps_on(instance: &wgpu::Instance) -> DeviceCaps { + let (adapters, _) = craft_gpu_device::list(instance, None); + match craft_gpu_device::pick(&adapters, None, &Preference::Auto) { + Ok((adapter, _)) => DeviceCaps { features: Vec::new(), ..Capabilities::of_adapter(&adapter).into_device_caps() }, + Err(_) => probe_fallback("wgpu", "no-adapter"), } - - let info = device.adapter_info(); - let device_limits = device.limits(); - let caps = DeviceCaps { - backend_name: format!("{:?}", info.backend), - device_name: info.name, - max_storage_buffer_binding_size: device_limits.max_storage_buffer_binding_size, - max_buffer_size: device_limits.max_buffer_size, - max_texture_dimension_2d: device_limits.max_texture_dimension_2d, - features: device.features().iter_names().map(|(name, _)| name.to_string()).collect(), - vendor_id: info.vendor, - software: info.device_type == wgpu::DeviceType::Cpu, - }; - let backing = Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), lost, pending: Vec::new() }); - Some((caps, backing)) } } @@ -169,9 +155,9 @@ struct DeviceBacking { /// matching the staging path and `craft-gpu-null` exactly, with no padding visible. `None` /// once freed: see the `Backing::Staging` doc for why the slot stays rather than shifting. buffers: Vec>, - /// Set by the device-lost callback registered in [`native::create_device`]; checked before - /// every call that would otherwise touch the (now invalid) device. - lost: std::sync::Arc>>, + /// The device's health from `craft-gpu-device`, which holds its device-lost callback; its + /// loss is checked before every call that would otherwise touch the (now invalid) device. + health: craft_gpu_device::DeviceHealth, pending: Vec, } @@ -251,6 +237,37 @@ impl WgpuContext { Self { caps, worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } } + /// A context on a device `craft_gpu_device::open` (or `open_async`) opened, sharing its + /// device, queue and [`DeviceHealth`](craft_gpu_device::DeviceHealth). The caps are the + /// device's own (`Opened::device_caps`). A loss the health records, from the device-lost + /// callback it set or from any other user of the device, is this context's + /// `GpuFault::DeviceLost`. + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + pub fn from_opened(worker_kind: WorkerKind, opened: &craft_gpu_device::Opened) -> Self { + let (caps, backing) = native::backing_of(opened); + Self { caps, worker_kind, backing, next_request: 0, ready: Vec::new() } + } + + /// A context on a device the caller opened, such as the one egui-wgpu's render state holds. + /// `health` is the device's [`DeviceHealth::watch`](craft_gpu_device::DeviceHealth::watch); + /// wgpu keeps one device-lost callback per device, so this context sets none of its own. The + /// caps are the device's own: the features and limits it was opened with, whatever they are. + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + pub fn with_device(worker_kind: WorkerKind, device: wgpu::Device, queue: wgpu::Queue, health: craft_gpu_device::DeviceHealth) -> Self { + let (caps, backing) = native::backing_with(device, queue, health); + Self { caps, worker_kind, backing, next_request: 0, ready: Vec::new() } + } + + /// The health of this context's device, when it has one: share it with the rest of the app, + /// and with `craft_gpu_device::Recovery` after a loss. + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + pub fn health(&self) -> Option<&craft_gpu_device::DeviceHealth> { + match &self.backing { + Backing::Device(d) => Some(&d.health), + Backing::Staging(_) => None, + } + } + /// True when this context holds a real device (`request_device` succeeded), false on the /// staging/no-adapter path. Settings UI can use this to show "no GPU" honestly instead of /// implying a device that was never created; tests use it to skip rather than fail when the @@ -272,7 +289,7 @@ impl WgpuContext { pub fn is_device_lost(&self) -> bool { #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] if let Backing::Device(d) = &self.backing { - return d.lost.lock().map(|g| g.is_some()).unwrap_or(false); + return d.health.device_status().is_err(); } false } @@ -280,7 +297,42 @@ impl WgpuContext { fn take_lost_fault(&self) -> Option { #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] if let Backing::Device(d) = &self.backing { - return d.lost.lock().ok().and_then(|g| g.clone()); + return d.health.device_status().err(); + } + None + } + + /// `read_buffer`'s wait for the device between polls. `DeviceHealth::wait` does not wait once + /// the device reported an error other than out of memory, or when its poll fails. Then the + /// read of `request` is dropped and fails with that error, instead of polling in a loop + /// until a map that may never complete; a loss is left to the next `poll_reads`, which + /// fails every pending read with it. + #[cfg(not(target_arch = "wasm32"))] + #[cfg_attr(not(feature = "adapter-probe"), allow(unused_variables, clippy::unused_self))] + fn wait_between_reads(&mut self, request: ReadRequest) -> Option { + #[cfg(feature = "adapter-probe")] + if let Backing::Device(d) = &mut self.backing + && !d.health.wait(&d.device, None) + { + d.health.probe(&d.device); + if d.health.device_status().is_err() { + return None; + } + d.pending.retain(|p| p.request != request); + return Some( + d.health.fault().map(GpuFault::from).unwrap_or_else(|| GpuFault::Operation("read_buffer: waiting for the device failed".into())), + ); + } + None + } + + /// Why no new work may go to the device: a loss as `GpuFault::DeviceLost`, and any other + /// fault its health recorded (an uncaptured error, or an out-of-memory error the app has not + /// cleared with `DeviceHealth::clear_out_of_memory`) as `GpuFault::Operation`. + fn take_work_fault(&self) -> Option { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + if let Backing::Device(d) = &self.backing { + return d.health.fault().map(GpuFault::from); } None } @@ -297,7 +349,7 @@ impl GpuContext for WgpuContext { #[cfg_attr(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")), allow(unused_variables))] fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result { - if let Some(fault) = self.take_lost_fault() { + if let Some(fault) = self.take_work_fault() { return Err(fault); } match &mut self.backing { @@ -334,6 +386,8 @@ impl GpuContext for WgpuContext { mapped_at_creation: false, }); if let Some(err) = pollster::block_on(create_scope.pop()) { + // The scope kept it from the device's health; every user of the device sees it. + d.health.caught(&d.device, &err); return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error creating the buffer: {err}"))); } // write_buffer makes its own staging allocation to carry `bytes` to the device, a @@ -356,6 +410,7 @@ impl GpuContext for WgpuContext { // is still a submission as far as that flush is concerned, so it is enough. d.queue.submit(std::iter::empty()); if let Some(err) = pollster::block_on(write_scope.pop()) { + d.health.caught(&d.device, &err); return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error writing the buffer: {err}"))); } let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; @@ -383,7 +438,7 @@ impl GpuContext for WgpuContext { } fn request_read(&mut self, handle: HandleId) -> Result { - if let Some(fault) = self.take_lost_fault() { + if let Some(fault) = self.take_work_fault() { return Err(fault); } match &mut self.backing { @@ -432,6 +487,7 @@ impl GpuContext for WgpuContext { mapped_at_creation: false, }); if let Some(err) = pollster::block_on(create_scope.pop()) { + d.health.caught(&d.device, &err); return Err(GpuFault::Operation(format!("request_read: device reported an allocation error creating the staging buffer: {err}"))); } // The copy and its submission get their own scope rather than reusing the one @@ -441,6 +497,7 @@ impl GpuContext for WgpuContext { encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, copy_len); d.queue.submit(Some(encoder.finish())); if let Some(err) = pollster::block_on(copy_scope.pop()) { + d.health.caught(&d.device, &err); return Err(GpuFault::Operation(format!("request_read: device reported an allocation error copying the buffer: {err}"))); } let state = std::sync::Arc::new(std::sync::Mutex::new(None)); @@ -495,11 +552,14 @@ impl GpuContext for WgpuContext { let mut outcomes = std::mem::take(&mut self.ready); #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] if let Backing::Device(d) = &mut self.backing { - if let Some(fault) = d.lost.lock().ok().and_then(|g| g.clone()) { + // A non-blocking poll that also runs after an error other than a loss was recorded, + // and records a loss instead of panicking when the device is gone. The loss check + // follows it, so a loss the poll found fails the pending reads now. + d.health.probe(&d.device); + if let Err(fault) = d.health.device_status() { outcomes.extend(d.pending.drain(..).map(|p| ReadOutcome { request: p.request, handle: p.handle, result: Err(fault.clone()) })); return outcomes; } - let _ = d.device.poll(wgpu::PollType::Poll); let mut remaining = Vec::with_capacity(d.pending.len()); for pending in d.pending.drain(..) { let is_ready = pending.state.lock().map(|g| g.is_some()).unwrap_or(false); @@ -536,9 +596,8 @@ impl GpuContext for WgpuContext { // Block on the GPU between polls instead of busy-spinning the CPU. A no-op when // `backing` is `Staging` (nothing to wait for; the request already resolved above) // or when wgpu is itself WebGPU under the hood, which self-polls. - #[cfg(feature = "adapter-probe")] - if let Backing::Device(d) = &self.backing { - let _ = d.device.poll(wgpu::PollType::wait_indefinitely()); + if let Some(fault) = self.wait_between_reads(request) { + return Err(fault); } } } diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs index 6f0b74f88e..e91bb9b63b 100644 --- a/crates/gpu-wgpu/src/tests.rs +++ b/crates/gpu-wgpu/src/tests.rs @@ -365,3 +365,120 @@ fn real_device_empty_buffer_and_interleaved_read_buffer_behave_like_staging() { } assert!(seen_a, "a's completion must still arrive through poll_reads after b's read_buffer"); } + +/// Devices from `craft-gpu-device`, on wgpu's noop backend, so these run without a GPU. +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +mod device_from_craft_gpu_device { + use craft_gpu::{GpuContext, GpuFault, WorkerKind}; + use craft_gpu_device::{DeviceHealth, Fault, Preference, Request}; + + use crate::{Backing, WgpuContext, native}; + + /// An instance whose only adapter is wgpu's noop one, which wgpu 30 lists as a software + /// adapter. + fn noop() -> wgpu::Instance { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, ..Default::default() }; + wgpu::Instance::new(desc) + } + + fn opened() -> craft_gpu_device::Opened { + craft_gpu_device::open(&noop(), None, &Preference::Software, &Request::default()).expect("the noop adapter opens") + } + + #[test] + fn the_default_device_is_the_one_craft_gpu_device_opens() { + let (caps, backing) = native::create_device_on(&noop()).expect("the noop adapter opens"); + let Backing::Device(d) = &backing else { panic!("a device backing") }; + assert_eq!(caps, craft_gpu_device::device_caps(&d.device)); + assert!(caps.software, "{caps:?}"); + assert!(d.health.is_ok() && d.health.device_status().is_ok()); + // no adapter at all: the staging path + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + assert!(native::create_device_on(&wgpu::Instance::new(desc)).is_none()); + } + + #[test] + fn the_probe_reports_the_adapter_craft_gpu_device_picks() { + let opened = opened(); + let caps = native::probe_caps_on(&noop()); + assert_eq!(caps.device_name, opened.candidate.name); + assert!(caps.software && caps.features.is_empty(), "{caps:?}"); + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + assert_eq!(native::probe_caps_on(&wgpu::Instance::new(desc)).device_name, "no-adapter"); + } + + #[test] + fn a_context_on_an_opened_device_reads_the_loss_from_its_health() { + let opened = opened(); + let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened); + assert!(ctx.has_device()); + assert_eq!(ctx.caps(), opened.device_caps()); + assert_eq!(ctx.device_status(), Ok(())); + // a loss another user of the device records is this context's loss too + opened.health.mark(Fault::Lost("the driver reset the GPU".into())); + assert!(ctx.health().is_some_and(|h| h.device_status().is_err())); + assert_eq!(ctx.device_status(), Err(GpuFault::DeviceLost("the driver reset the GPU".into()))); + assert!(ctx.is_device_lost()); + assert!(matches!(ctx.upload_buffer("after-loss", b"x"), Err(GpuFault::DeviceLost(_)))); + } + + #[test] + fn a_destroyed_device_is_lost_through_the_health_that_watches_it() { + let opened = opened(); + let health = DeviceHealth::watch(&opened.device); + let mut ctx = WgpuContext::with_device(WorkerKind::DedicatedWorker, opened.device.clone(), opened.queue.clone(), health.clone()); + assert_eq!(ctx.caps(), opened.device_caps()); + opened.device.destroy(); + let _ = ctx.poll_reads(); + assert!(health.device_status().is_err(), "{health:?}"); + assert!(matches!(ctx.device_status(), Err(GpuFault::DeviceLost(_)))); + assert!(matches!(ctx.request_read(craft_gpu::HandleId(0)), Err(GpuFault::DeviceLost(_)))); + } + + #[test] + fn no_work_goes_to_a_device_whose_health_recorded_an_error() { + let opened = opened(); + let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened); + let handle = ctx.upload_buffer("before", b"abcd").expect("upload on a healthy device"); + // an out-of-memory error stops new work until the app clears it + opened.health.mark(Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into())); + assert!(matches!(ctx.upload_buffer("oom", b"x"), Err(GpuFault::Operation(_)))); + assert!(matches!(ctx.request_read(handle), Err(GpuFault::Operation(_)))); + assert_eq!(ctx.device_status(), Ok(()), "only a loss is a device_status fault"); + ctx.free_buffer(handle); + opened.health.clear_out_of_memory(opened.health.out_of_memory_count()); + let handle = ctx.upload_buffer("after", b"abcd").expect("upload once the error is cleared"); + assert_eq!(ctx.buffer_len(handle), Ok(4)); + // another error stops it for good + opened.health.mark(Fault::Error("Validation Error".into())); + assert_eq!(ctx.upload_buffer("validation", b"x"), Err(GpuFault::Operation("Validation Error".into()))); + assert_eq!(ctx.device_status(), Ok(())); + } + + #[test] + fn a_read_waiting_when_the_device_reports_an_error_fails_instead_of_polling_forever() { + let opened = opened(); + let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened); + let handle = ctx.upload_buffer("pending", b"abcd").expect("upload"); + let request = ctx.request_read(handle).expect("request_read"); + opened.health.mark(Fault::Error("Validation Error".into())); + assert_eq!(ctx.wait_between_reads(request), Some(GpuFault::Operation("Validation Error".into()))); + let Backing::Device(d) = &ctx.backing else { panic!("a device backing") }; + assert!(d.pending.iter().all(|p| p.request != request), "the failed read is dropped"); + // a loss is left to poll_reads, which fails every pending read with it + let other = ctx.request_read(handle); + assert!(other.is_err()); + opened.health.mark(Fault::Lost("gone".into())); + assert_eq!(ctx.wait_between_reads(request), None); + } + + #[test] + fn a_staging_context_has_no_health() { + let ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default()); + assert!(ctx.health().is_none()); + } +} diff --git a/docs/gpu-backends.md b/docs/gpu-backends.md index 6e2246e918..774992f922 100644 --- a/docs/gpu-backends.md +++ b/docs/gpu-backends.md @@ -8,12 +8,12 @@ Feature flags on `craft-gpu-wgpu`: -- `adapter-probe`: native only; uses pollster to `request_adapter`/`request_device` and build real [`DeviceCaps`](../crates/gpu/src/caps.rs) from the created device (falls back to the staging path when no GPU, e.g. CI with no backend feature enabled). -- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles`: enable the matching wgpu backend. `adapter-probe` alone compiles the probing code but finds no adapter unless at least one of these is also on. +- `adapter-probe`: native only; opens the device through [`craft-gpu-device`](../crates/gpu-device/README.md) and builds real [`DeviceCaps`](../crates/gpu/src/caps.rs) from the created device (falls back to the staging path when no adapter opens). `craft-gpu-device` depends on wgpu with its default features, so this feature also turns on wgpu's default native backends. The context's instance uses `craft_gpu_device::native_descriptor`'s backends (no OpenGL on Windows) unless `WGPU_BACKEND` names others. +- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles`: enable the matching wgpu backend. ## Real device, device-truth caps (RFC-0022 requirement 1) -With `adapter-probe` and a `native-*` backend, `WgpuContext::new` calls `Adapter::request_device` after `request_adapter`, creating a real device. `DeviceCaps` is built from the created `Device`'s own `limits()` / `features()`, never from the adapter's advertised maximum: an adapter can advertise more than a device grants. `required_features` is the adapter's features intersected with what this context asks for (currently nothing, since no provider dispatches a real WGSL job yet, see [gpu-providers.md](./gpu-providers.md)); `required_limits` is the adapter's own limits. Both choices mean `request_device` cannot panic on an unsupported feature or limit here. +With `adapter-probe`, `WgpuContext::new` opens a real device with `craft_gpu_device::open` for `Preference::Auto`: the same adapter choice, driver corrections and fallback order as every other caller of that crate, so the suite has one device selector. `probe_caps()` reports the adapter `craft_gpu_device::pick` chooses, without opening a device on it; when a device fails to open there, `WgpuContext::new` opens the next adapter in `ranked` order or a software one, and its `caps()` name that device. `WgpuContext::from_opened` takes a device the app opened with `craft-gpu-device` (with the user's own `Preference`, or after a `Recovery` step), and `WgpuContext::with_device` takes any device with its `DeviceHealth`. `DeviceCaps` is built from the created `Device`'s own `limits()` / `features()` (`craft_gpu_device::device_caps`), never from the adapter's advertised maximum: an adapter can advertise more than a device grants. `WgpuContext::new` asks for the adapter's features intersected with what this context asks for (currently nothing, since no provider dispatches a real WGSL job yet, see [gpu-providers.md](./gpu-providers.md)), and for the adapter's own limits. Both choices mean `request_device` cannot panic on an unsupported feature or limit here. A context on a device the caller opened takes the features and limits that device was opened with. Buffers are real `wgpu::Buffer`s (`STORAGE | COPY_SRC | COPY_DST`). The host-staged `Vec>` form survives only on the no-device path. @@ -23,7 +23,7 @@ Buffers are real `wgpu::Buffer`s (`STORAGE | COPY_SRC | COPY_DST`). The host-sta ## Device loss (RFC-0022 requirement 1) -`WgpuContext` registers `Device::set_device_lost_callback` when it creates a real device. Loss (a driver reset, OS-level eviction, or an explicit `destroy()`) surfaces as `GpuFault::DeviceLost`, from the next buffer call and from `poll_reads()`, never as a panic. +`WgpuContext` reads a device loss from the device's `craft_gpu_device::DeviceHealth`, which sets the device's one device-lost callback and records a loss without panicking; the context sets no callback of its own. Loss (a driver reset, OS-level eviction, an explicit `destroy()`, or a loss another user of the same `DeviceHealth` records) surfaces as `GpuFault::DeviceLost`, from the next buffer call, from `poll_reads()` and from `device_status()`, never as a panic. `WgpuContext::health()` gives that `DeviceHealth`, for `craft_gpu_device::Recovery` and the rest of the app. Any other fault the `DeviceHealth` records (an uncaptured error, or an out-of-memory error the app has not cleared with `DeviceHealth::clear_out_of_memory`) makes `upload_buffer` and `request_read` return `GpuFault::Operation`; `device_status()` reports a loss only, and `poll_reads()` and `free_buffer` keep running. An allocation error the context's own error scopes catch is recorded in the `DeviceHealth` as well (`DeviceHealth::caught`). Once a context has reported `GpuFault::DeviceLost`, every `DeviceCaps` it reported before that point is stale. The stated recovery, per the trait docs on [`GpuContext`](../crates/gpu/src/context.rs): @@ -39,7 +39,7 @@ No backend here supports continuing to dispatch jobs against a context that alre `read_buffer` stays as a blocking convenience with a default body built on those two primitives, for callers that need bytes now (the CPU-stand-in providers in `craft-gpu-providers`). Both bundled backends override that default body. The default has nowhere to put completions belonging to other outstanding requests. The overrides keep those queued for the next `poll_reads`: - `craft-gpu-null`: overrides to take only its own completion; every request resolves immediately, with nothing to wait for. -- `craft-gpu-wgpu`, native, with a real device: overrides to block by calling `Device::poll(PollType::wait_indefinitely())` between polls. It waits on the GPU without busy-spinning the CPU, re-queuing other requests' completions. +- `craft-gpu-wgpu`, native, with a real device: overrides to block by calling `DeviceHealth::wait` (a `Device::poll` that waits for all submitted work) between polls. It waits on the GPU without busy-spinning the CPU, re-queuing other requests' completions. When the device reports an error other than a loss or running out of memory while the read is pending, or the wait itself fails, `read_buffer` drops the read and returns that error as `GpuFault::Operation`; a loss fails it with `GpuFault::DeviceLost`. - `craft-gpu-wgpu`, native, staging path (no device): resolves immediately, same as the null context. - `craft-gpu-wgpu`, `wasm32`: **serves the staging read.** The only backing on this target today is the in-memory staging store, since real device creation needs the async worker-init path that has not landed. Staging reads resolve synchronously. `read_buffer` returns their bytes. Only a read that did not resolve synchronously returns `GpuFault::Operation`. That refusal will matter once a real device backing exists there: `wasm32` is single-threaded and blocking the one thread the browser needs to run `map_async`'s own completion callback on would hang the tab. A caller on a future device backing must drive `request_read` + `poll_reads` from the worker's own message loop. @@ -58,4 +58,4 @@ The question that decides whether a render-path app can adopt `WgpuContext` as-i **FilmCraft's answer today is "it depends on which device."** Its on-screen monitor compositor adopts egui's own device: both the native desktop app and the web app call `app.set_wgpu(cc.wgpu_render_state.clone())` (or the equivalent on native), so the compositor draws through the exact `Device`/`Queue` `eframe`'s `RenderState` already created. One device, shared, no second adapter opened for the window. Its **export** path is deliberately the opposite: a separate, off-screen `wgpu::Device` with no surface, created once and kept for the process (`export_renderer.rs`), specifically because export runs independent of the UI's lifecycle (worker threads, no window) and must keep working even if the UI's device were ever lost or recreated. -`WgpuContext::new` in this PR always opens its own device (or degrades to staging) and has no constructor that accepts an externally-supplied `(Device, Queue)`. That is **documented here as the named follow-up, not implemented in this PR**: accepting an existing device/queue pair (with `DeviceCaps` built from that pair, the same device-truth way `create_device` builds it today) is a small, additive constructor that does not change `GpuContext`'s trait shape, but it needs a decision this PR's scope doesn't force: whether the shared constructor should require the caller to prove the features/limits it needs were already granted (since a second caller can't call `request_device` again on a device that already exists), or whether it should accept whatever was granted and fail a job if it needs more. FilmCraft's own split (share for render, separate for export) is a reasonable default for this layer too: a render-path app wanting GPU compute on the same frame it draws with egui should share; a worker-isolated batch job (the first named consumer, `craft-libs#662`'s worker-host) has no window and no reason to share, and keeps its own device exactly as implemented here. +`WgpuContext::with_device` accepts an existing `(Device, Queue)` pair with its `DeviceHealth`, and `WgpuContext::from_opened` accepts a `craft_gpu_device::Opened`. Neither changes `GpuContext`'s trait shape. They take whatever the device was granted: `DeviceCaps` is built from that device, and a job that needs a feature the caps do not name takes its portable path or fails. A render-path app that wants GPU compute on the same frame it draws with egui passes egui's device to `with_device`, with the `DeviceHealth::watch` of that device. A worker-isolated batch job (the first named consumer, `craft-libs#662`'s worker-host) has no window and keeps its own device from `WgpuContext::new`. From e35bdcf8ea5b31173067100342b1b16b20f68b75 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:48:48 -0800 Subject: [PATCH 022/257] fonts-build: EmbeddedFace::new and with_index build a face without a struct literal EmbeddedFace has only public fields, so a test or a hand-written table that needs a face writes a struct literal, and every such literal stops compiling when a field is added to the struct. EmbeddedFace::new(family, style, scripts, bytes) returns a face at index 0, and with_index(n) sets the index of a face in a collection. Both are const fn, so they also work in a static table. The README and the type's docs name them for tests and tables written by hand. --- crates/fonts-build/README.md | 5 ++++- crates/fonts-build/src/lib.rs | 20 ++++++++++++++++++++ crates/fonts-build/src/tests.rs | 10 ++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/fonts-build/README.md b/crates/fonts-build/README.md index 941426b3c1..9c91b730f2 100644 --- a/crates/fonts-build/README.md +++ b/crates/fonts-build/README.md @@ -99,7 +99,10 @@ below), and `Embed::documents(&["Noto Sans", …])` only the families it names ( `write` returns the embedded `ManifestEntry`s, for build-time checks such as "the interface face is present". The generated file is a slice expression of `EmbeddedFace { family, style, scripts, index, bytes }` literals; any struct with those fields and that name in scope works too. -`EmbeddedFace` itself has `name()`, `has_script(tag)`, `is_cjk()` and `weight()`. +`EmbeddedFace` itself has `name()`, `has_script(tag)`, `is_cjk()` and `weight()`. Tests and +tables written by hand build a face with `EmbeddedFace::new(family, style, scripts, bytes)`, +plus `.with_index(n)` for a face in a collection; both are `const fn`. Code that uses `new` +keeps compiling when a field with a default is added; a struct literal does not. ## Document fonts diff --git a/crates/fonts-build/src/lib.rs b/crates/fonts-build/src/lib.rs index fffd8f0985..724a2bb9ef 100644 --- a/crates/fonts-build/src/lib.rs +++ b/crates/fonts-build/src/lib.rs @@ -83,6 +83,26 @@ pub struct EmbeddedFace { } impl EmbeddedFace { + /// A face at index 0 of `bytes`, for tests and for tables written by hand. Code that builds + /// faces with `new` keeps compiling when a field with a default is added; a struct literal + /// does not. + /// + /// ``` + /// use craft_fonts_build::EmbeddedFace; + /// + /// static FACE: EmbeddedFace = EmbeddedFace::new("Sans", "Bold", &["Latn"], b"").with_index(2); + /// assert_eq!((FACE.name().as_str(), FACE.index), ("Sans Bold", 2)); + /// ``` + pub const fn new(family: &'static str, style: &'static str, scripts: &'static [&'static str], bytes: &'static [u8]) -> Self { + Self { family, style, scripts, index: 0, bytes } + } + + /// The same face at `index` in a font collection (`.ttc`). + #[must_use] + pub const fn with_index(self, index: u32) -> Self { + Self { index, ..self } + } + /// `" + + + + + + + + "#, + ); + assert_eq!(got.shapes.len(), 3); + assert_eq!(got.groups.len(), 2); + assert_eq!(got.groups[0].source_id.as_deref(), Some("decor")); + assert_eq!(got.groups[0].label.as_deref(), Some("Decorative motif")); + assert_eq!( + got.groups[0].attributes, + vec![ + GroupMetadata { attribute: GroupAttribute::unqualified("data-group"), value: "15".into() }, + GroupMetadata { attribute: GroupAttribute::namespaced("urn:editor-metadata", "group-id"), value: "42".into() }, + ] + ); + assert!(got.groups[0].parent.is_none()); + assert_eq!(got.groups[1].source_id.as_deref(), Some("details")); + assert_eq!(got.groups[1].parent, Some(0)); + assert!(got.groups[1].attributes.is_empty()); + assert_eq!(got.shapes.iter().map(|s| s.group).collect::>(), [Some(1), Some(0), None]); + } + + #[test] + fn repeated_use_groups_have_distinct_membership_at_each_site() { + let got = read( + r##" + + + + + + "##, + ); + assert_eq!(got.shapes.len(), 2); + assert_eq!(got.groups.len(), 5); + assert_eq!(got.groups.iter().map(|g| g.parent).collect::>(), [None, Some(0), Some(1), Some(0), Some(3)]); + assert_eq!(got.shapes.iter().map(|s| s.group).collect::>(), [Some(2), Some(4)]); + assert_eq!(got.groups[1].source_id, got.groups[3].source_id); + assert!(bounds(&got, 1).x0 > bounds(&got, 0).x0); + } + #[test] fn local_use_instances_take_x_y_transform_and_symbol_viewboxes() { let got = read(