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.18"
version = "0.2.19"
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.

120 changes: 112 additions & 8 deletions crates/visualci-cli/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ use visualci_core::snapshot_text::Format;

pub const DEFAULT_API_URL: &str = "https://api.visualci.com";
const BATCH: usize = 500;
/// At most this many uploads to storage at once: more makes the store refuse writes (429) sooner.
const UPLOADS: usize = 8;

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

Expand Down Expand Up @@ -300,17 +302,11 @@ impl Client {
|| {
std::thread::scope(|scope| -> Result<()> {
let handles: Vec<_> = uploads
.chunks(uploads.len().div_ceil(8).max(1))
.chunks(uploads.len().div_ceil(UPLOADS).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")?;
self.put_blob(url, content_type, bytes).context("uploading a snapshot")?;
}
Ok(())
})
Expand All @@ -327,6 +323,35 @@ impl Client {
Ok((snapshots.len(), uploaded))
}

/// Upload one file to its storage URL. The store limits how fast one client may write (R2 answers 429, 3 Dec
/// 2026: a CI run's upload failed on one), and has bad moments: a 429, a 5xx or a dropped connection is tried
/// again, up to six times in all, waiting longer each time or as long as `Retry-After` asks (at most 30 s).
/// `--verbose` prints each retry.
fn put_blob(&self, url: &str, content_type: &str, bytes: &[u8]) -> Result<()> {
const TRIES: u32 = 6;
let mut attempt = 1;
loop {
let sent = self.http.put(url).header("content-type", content_type).body(bytes.to_vec()).send();
let wait = match sent {
Ok(response) if response.status().is_success() => return Ok(()),
Ok(response) if retryable(response.status()) && attempt < TRIES => {
retry_after(&response).unwrap_or_else(|| backoff(attempt))
}
Ok(response) => return Err(response.error_for_status().unwrap_err().into()),
Err(e) if (e.is_timeout() || e.is_connect() || e.is_request()) && attempt < TRIES => backoff(attempt),
Err(e) => return Err(e.into()),
};
if verbose() {
eprintln!(
"visualci: upload refused (try {attempt} of {TRIES}), trying again in {:.1} s",
wait.as_secs_f64()
);
}
std::thread::sleep(wait);
attempt += 1;
}
}

/// Poll until the build passes or fails under its CI mode, or until the timeout.
pub fn wait(&self, id: &str, timeout: Duration) -> Result<Build> {
let start = Instant::now();
Expand Down Expand Up @@ -656,8 +681,87 @@ fn looks_binary(head: &[u8]) -> bool {
head.contains(&0) || std::str::from_utf8(head).is_err_and(|e| e.error_len().is_some())
}

/// A storage write worth trying again: too many requests, or the store's own trouble.
fn retryable(status: reqwest::StatusCode) -> bool {
status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error()
}

/// How long `Retry-After` (in seconds) asks to wait, at most 30 s.
fn retry_after(response: &reqwest::blocking::Response) -> Option<Duration> {
let seconds: u64 = response.headers().get(reqwest::header::RETRY_AFTER)?.to_str().ok()?.trim().parse().ok()?;
Some(Duration::from_secs(seconds.min(30)))
}

/// 0.5 s, 1 s, 2 s, 4 s, then 8 s between tries.
fn backoff(attempt: u32) -> Duration {
Duration::from_millis(500 * 2u64.pow((attempt - 1).min(4)))
}

#[cfg(test)]
mod tests {
/// A storage server for one test: answers each PUT with the next status in `statuses` (then 200), and counts
/// them.
fn store(statuses: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
use std::io::{BufRead, BufReader, Read, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}/blob", listener.local_addr().unwrap());
let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let count = seen.clone();
std::thread::spawn(move || {
for stream in listener.incoming() {
let mut stream = stream.unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut length = 0;
loop {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") {
length = v.trim().parse().unwrap();
}
if line == "\r\n" || line.is_empty() {
break;
}
}
let mut body = vec![0; length];
reader.read_exact(&mut body).unwrap();
let n = count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let status = statuses.get(n).copied().unwrap_or(200);
write!(
stream,
"HTTP/1.1 {status} X\r\nretry-after: 0\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"
)
.unwrap();
}
});
(url, seen)
}

fn client() -> Client {
Client { api_url: String::new(), token: String::new(), project: None, http: reqwest::blocking::Client::new() }
}

#[test]
fn a_refused_upload_is_tried_again() {
let (url, seen) = store(vec![429, 503]);
client().put_blob(&url, "image/png", b"png").unwrap();
assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 3);
}

#[test]
fn an_upload_refused_six_times_fails() {
let (url, seen) = store(vec![429; 10]);
let error = client().put_blob(&url, "image/png", b"png").unwrap_err();
assert!(error.to_string().contains("429"), "{error}");
assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 6);
}

#[test]
fn a_bad_request_is_not_tried_again() {
let (url, seen) = store(vec![403]);
assert!(client().put_blob(&url, "image/png", b"png").is_err());
assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1);
}

#[test]
fn parallel_registrations_match_the_sequential_ones() {
let dir = std::env::temp_dir().join(format!("visualci-par-{}", std::process::id()));
Expand Down
Loading