Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "server", "server/migration"]

[workspace.package]
version = "0.2.17"
version = "0.2.18"
edition = "2024"
license = "Apache-2.0"
repository = "https://github.com/DocSpring/visualci"
Expand Down
2 changes: 1 addition & 1 deletion app/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

171 changes: 138 additions & 33 deletions crates/visualci-cli/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,57 @@ use visualci_core::snapshot_text::Format;
pub const DEFAULT_API_URL: &str = "https://api.visualci.com";
const BATCH: usize = 500;

static VERBOSE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// `--verbose`: print how long hashing, each API call and the uploads take.
pub fn set_verbose(on: bool) {
VERBOSE.store(on, std::sync::atomic::Ordering::Relaxed);
}

fn verbose() -> bool {
VERBOSE.load(std::sync::atomic::Ordering::Relaxed)
}

/// Run `f`, and with `--verbose` print how long it took.
pub fn timed<T>(label: impl FnOnce() -> String, f: impl FnOnce() -> T) -> T {
if !verbose() {
return f();
}
let start = Instant::now();
let out = f();
eprintln!("visualci: {} ({} ms)", label(), start.elapsed().as_millis());
out
}

/// `f` over every item on all the machine's cores, results in the items' order. An error stops the run and the
/// first failing item's error (in order) is returned.
pub fn par_map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> Result<R> + Sync) -> Result<Vec<R>> {
let threads = std::thread::available_parallelism().map_or(1, std::num::NonZero::get).min(items.len());
if threads <= 1 {
return items.iter().map(&f).collect();
}
let f = &f;
std::thread::scope(|scope| {
let handles: Vec<_> = items
.chunks(items.len().div_ceil(threads))
.map(|part| scope.spawn(move || part.iter().map(f).collect::<Result<Vec<R>>>()))
.collect();
let mut out = Vec::with_capacity(items.len());
for h in handles {
out.extend(h.join().map_err(|_| anyhow::anyhow!("a hashing thread panicked"))??);
}
Ok(out)
})
}

/// Every snapshot's registration and bytes (`registration`), decoded and fingerprinted in parallel, in order.
///
/// # Errors
/// The first snapshot (in order) whose file can't be read or classified.
pub fn registrations(snapshots: &[Snapshot]) -> Result<Vec<(serde_json::Value, Vec<u8>)>> {
timed(|| format!("hashed {} snapshots", snapshots.len()), || par_map(snapshots, registration))
}

pub struct Client {
api_url: String,
token: String,
Expand Down Expand Up @@ -106,13 +157,23 @@ impl Client {
}

fn post(&self, path: &str, body: &serde_json::Value) -> Result<serde_json::Value> {
let response = self.authed(self.http.post(format!("{}{path}", self.api_url))).json(body).send()?;
read(response, path)
timed(
|| format!("POST {path}"),
|| {
let response = self.authed(self.http.post(format!("{}{path}", self.api_url))).json(body).send()?;
read(response, path)
},
)
}

fn get(&self, path: &str) -> Result<serde_json::Value> {
let response = self.authed(self.http.get(format!("{}{path}", self.api_url))).send()?;
read(response, path)
timed(
|| format!("GET {path}"),
|| {
let response = self.authed(self.http.get(format!("{}{path}", self.api_url))).send()?;
read(response, path)
},
)
}

/// The MCP server: `$VISUALCI_MCP_URL`, else the API's URL with its `api.` host renamed `mcp.` (production), else
Expand Down Expand Up @@ -218,13 +279,7 @@ impl Client {
pub fn add_snapshots(&self, build_id: &str, snapshots: &[Snapshot]) -> Result<(usize, usize)> {
let mut uploaded = 0;
for chunk in snapshots.chunks(BATCH) {
let mut files = Vec::with_capacity(chunk.len());
let mut params = Vec::with_capacity(chunk.len());
for s in chunk {
let (p, bytes) = registration(s)?;
params.push(p);
files.push(bytes);
}
let (params, files): (Vec<_>, Vec<_>) = registrations(chunk)?.into_iter().unzip();
let response =
self.post(&format!("/api/v1/builds/{build_id}/snapshots"), &json!({ "snapshots": params }))?;
let results = response["snapshots"].as_array().cloned().unwrap_or_default();
Expand All @@ -238,29 +293,36 @@ impl Client {
})
.collect();
uploaded += uploads.len();
std::thread::scope(|scope| -> Result<()> {
let handles: Vec<_> = uploads
.chunks(uploads.len().div_ceil(8).max(1))
.map(|part| {
scope.spawn(move || -> Result<()> {
for (url, content_type, bytes) in part {
self.http
.put(url)
.header("content-type", content_type.as_str())
.body(bytes.clone())
.send()?
.error_for_status()
.context("uploading a snapshot")?;
}
Ok(())
})
let upload_bytes: usize = uploads.iter().map(|(_, _, b)| b.len()).sum();
let count = uploads.len();
timed(
|| format!("uploaded {count} files, {} KB", upload_bytes / 1024),
|| {
std::thread::scope(|scope| -> Result<()> {
let handles: Vec<_> = uploads
.chunks(uploads.len().div_ceil(8).max(1))
.map(|part| {
scope.spawn(move || -> Result<()> {
for (url, content_type, bytes) in part {
self.http
.put(url)
.header("content-type", content_type.as_str())
.body(bytes.clone())
.send()?
.error_for_status()
.context("uploading a snapshot")?;
}
Ok(())
})
})
.collect();
for h in handles {
h.join().map_err(|_| anyhow::anyhow!("upload thread panicked"))??;
}
Ok(())
})
.collect();
for h in handles {
h.join().map_err(|_| anyhow::anyhow!("upload thread panicked"))??;
}
Ok(())
})?;
},
)?;
}
Ok((snapshots.len(), uploaded))
}
Expand Down Expand Up @@ -596,6 +658,49 @@ fn looks_binary(head: &[u8]) -> bool {

#[cfg(test)]
mod tests {
#[test]
fn parallel_registrations_match_the_sequential_ones() {
let dir = std::env::temp_dir().join(format!("visualci-par-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let snap = |name: &str, path: std::path::PathBuf, content: Option<Vec<u8>>| Snapshot {
name: name.into(),
platform: "linux".into(),
path,
threshold: Some(0.1),
engine: None,
format: None,
content,
ignore: None,
};
let mut snaps = Vec::new();
for i in 0..40u32 {
let img = image::RgbaImage::from_fn(64, 48, |x, y| {
image::Rgba([(x * i) as u8, (y + i) as u8, (x ^ y ^ i) as u8, 255])
});
let path = dir.join(format!("shot-{i}.png"));
img.save(&path).unwrap();
snaps.push(snap(&format!("shot-{i}"), path, None));
if i % 7 == 0 {
let text = dir.join(format!("data-{i}.json"));
std::fs::write(&text, format!("{{\"i\": {i}}}")).unwrap();
snaps.push(snap(&format!("data-{i}"), text, None));
snaps.push(snap(&format!("inline-{i}"), dir.join("x.snap"), Some(format!("v{i}").into_bytes())));
}
}
let sequential: Vec<_> = snaps.iter().map(|s| registration(s).unwrap()).collect();
let parallel = registrations(&snaps).unwrap();
assert_eq!(parallel, sequential);
// Distinct images got distinct fingerprints, so the order really was checked.
assert_ne!(parallel[0].0["fingerprint"], parallel[1].0["fingerprint"]);

// The first failing snapshot's error, as the sequential loop gave.
snaps.insert(5, snap("missing-a", dir.join("missing-a.png"), None));
snaps.push(snap("missing-b", dir.join("missing-b.png"), None));
let err = format!("{:#}", registrations(&snaps).unwrap_err());
assert!(err.contains("missing-a.png"), "{err}");
std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn finds_the_mcp_server_from_the_api_url() {
assert_eq!(super::mcp_url_for("https://api.visualci.com"), "https://mcp.visualci.com/mcp");
Expand Down
17 changes: 11 additions & 6 deletions crates/visualci-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ use crate::client::{Client, Snapshot};
#[derive(Parser)]
#[command(name = "visualci", version, about = "Visual regression testing for documents, browsers and apps")]
struct Cli {
/// Print how long hashing, each API call and the uploads take.
#[arg(long, global = true)]
verbose: bool,
#[command(subcommand)]
command: Command,
}
Expand Down Expand Up @@ -469,7 +472,9 @@ fn main() {
}

fn run() -> Result<()> {
match Cli::parse().command {
let cli = Cli::parse();
client::set_verbose(cli.verbose);
match cli.command {
Command::Fingerprint { files } => {
for file in files {
let value = fingerprint(&file)?;
Expand Down Expand Up @@ -842,10 +847,10 @@ fn send_snapshots(client: &Client, build_id: &str, snapshots: &[Snapshot]) -> Re
return Ok(());
}
let group_depth = config_file::discover().ok().flatten().and_then(|f| f.config.group_depth);
let entries = snapshots
.iter()
.map(|s| client::registration(s).and_then(|(params, _)| client::entry_of(&params)))
.collect::<Result<Vec<_>>>()?;
let entries = client::timed(
|| format!("hashed {} snapshots for the group check", snapshots.len()),
|| client::par_map(snapshots, |s| client::registration(s).and_then(|(params, _)| client::entry_of(&params))),
)?;
let check = client.check_groups(build_id, &entries, group_depth)?;
if let Some(n) = check.same_as_build {
eprintln!("{} snapshots: nothing changed since build #{n}", snapshots.len());
Expand All @@ -866,7 +871,7 @@ fn send_snapshots(client: &Client, build_id: &str, snapshots: &[Snapshot]) -> Re
Ok(())
}

/// The device-code sign-in:/// The device-code sign-in:/// The device-code sign-in: ask for a code pair, show the link and code, wait for the person to approve it in the
/// The device-code sign-in: ask for a code pair, show the link and code, wait for the person to approve it in the
/// browser, then keep the personal access token it gives.
fn login(api: &str, no_browser: bool) -> Result<()> {
let http = reqwest::blocking::Client::builder()
Expand Down
2 changes: 1 addition & 1 deletion server/frontend/content/docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ description: Every visualci command and option, and the environment variables th

Install it on Linux or macOS with `curl -fsSL https://visualci.com/install.sh | sh` (set `VISUALCI_VERSION=0.2.12` to pin a release, and `VISUALCI_INSTALL_DIR` for somewhere other than `/usr/local/bin`), or anywhere with Rust with `cargo install --git https://github.com/DocSpring/visualci visualci-cli`. `visualci --help` and `visualci <command> --help` print the same options.

Every command that talks to the server takes `--token` (default `$VISUALCI_TOKEN`, a project token, else the token `visualci login` kept) and `--api-url` (default `$VISUALCI_API_URL`, else `https://api.visualci.com`). With a personal token, it also needs the project: `--project org/project`, `$VISUALCI_PROJECT`, or `project:` in visualci.yml. Errors exit with status 2.
Every command that talks to the server takes `--token` (default `$VISUALCI_TOKEN`, a project token, else the token `visualci login` kept) and `--api-url` (default `$VISUALCI_API_URL`, else `https://api.visualci.com`). With a personal token, it also needs the project: `--project org/project`, `$VISUALCI_PROJECT`, or `project:` in visualci.yml. Errors exit with status 2. `--verbose` prints how long each step takes: hashing the files, each call to the server, and the uploads.

## visualci login

Expand Down
Loading