diff --git a/Cargo.lock b/Cargo.lock index 1b616bd5..4ad411f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4993,6 +4993,7 @@ dependencies = [ "axum", "base64 0.22.1", "envschema", + "futures-util", "globset", "hex", "hmac 0.12.1", diff --git a/app/.env.example b/app/.env.example index 5080533c..b191cc3f 100644 --- a/app/.env.example +++ b/app/.env.example @@ -348,6 +348,14 @@ VISUALCI_STRIPE_WEBHOOK_SECRET= # Secret. The platform ranges check's token. # VISUALCI_PLATFORM_ADDRESSES_HEARTBEAT_TOKEN= +###################################################################################################################### +# Build processing +###################################################################################################################### + +# How many new image files one build's processing downloads and fingerprints at once. Each is decoded on a thread of +# its own, off the threads that serve requests and keep locks alive. +# VISUALCI_FINGERPRINT_CONCURRENCY=8 + ###################################################################################################################### # Laravel Rust ###################################################################################################################### diff --git a/app/Cargo.toml b/app/Cargo.toml index cc1645ee..37896d43 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -26,6 +26,8 @@ laravel_cache = { package = "laravel-rust-cache", version = "=0.1.4", default-fe # The same axum Laravel Rust runs on, for extractors (auth::Principal) axum = "0.8" base64 = "0.22" +# Bounded concurrent downloads (domain::blobs::fingerprint_files) +futures-util = "0.3" hex = "0.4" oauth-provider = "0.1.4" oauth-provider-laravel = { version = "=0.1.2", features = ["postgres"] } diff --git a/app/src/config.rs b/app/src/config.rs index 0eb4e965..c1306bf8 100644 --- a/app/src/config.rs +++ b/app/src/config.rs @@ -50,6 +50,8 @@ pub struct Config { pub limits: Limits, #[settings(nested)] pub heartbeats: Heartbeats, + #[settings(nested)] + pub processing: Processing, } /// S3-compatible storage for uploads, rendered pages and diff images: R2 in production, RustFS or MinIO in @@ -363,6 +365,16 @@ pub struct Limits { pub oauth_unused_clients_ceiling: i64, } +/// Processing builds (the worker). +#[derive(Clone, Settings)] +#[settings(title = "Build processing")] +pub struct Processing { + /// How many new image files one build's processing downloads and fingerprints at once. Each is decoded on a + /// thread of its own, off the threads that serve requests and keep locks alive. + #[env("VISUALCI_FINGERPRINT_CONCURRENCY", default = 8)] + pub fingerprint_concurrency: usize, +} + /// Each scheduled job pushes its result to a [Gatus](https://gatus.io) external endpoint, so a run that failed, or no /// run at all, alerts. Each pair is the endpoint's URL and its token; a job without a URL pushes nothing. #[derive(Clone, Settings)] @@ -592,6 +604,7 @@ pub fn install(config: &mut laravel::config::Config, env: &laravel::config::Env) .set(settings.live.clone()) .set(settings.limits.clone()) .set(settings.heartbeats.clone()) + .set(settings.processing.clone()) .set(settings); } diff --git a/app/src/domain/blobs.rs b/app/src/domain/blobs.rs index 88a6a2c4..377a5b00 100644 --- a/app/src/domain/blobs.rs +++ b/app/src/domain/blobs.rs @@ -1,6 +1,9 @@ //! Blob records: what's stored under each SHA-256, whether its bytes have arrived, and an image's size and pixel //! fingerprint (cached on first use). +use std::collections::HashMap; + +use futures_util::stream::{self, StreamExt}; use laravel::db; use laravel::model::update; @@ -148,22 +151,119 @@ pub async fn put(store: &BlobStore, bytes: Vec, content_type: &str) -> larav Ok(blob) } +/// An image file's pixel fingerprint, width and height. +pub type ImageInfo = (String, u32, u32); + +/// Decode an image and fingerprint its pixels. CPU-bound, so it runs on the blocking pool ([`decode`]): it gets only +/// the bytes, and calls nothing that needs the app's context (the database, the cache, `laravel::now()`). +fn decode_image(sha256: &str, bytes: &[u8]) -> Result { + let image = visualci_core::image_hash::decode(bytes).map_err(|e| format!("{sha256}: {e}"))?.to_rgba8(); + let fp = visualci_core::image_hash::fingerprint_rgba(&image); + let (w, h) = image.dimensions(); + Ok((fp, w, h)) +} + +/// [`decode_image`] off the async runtime's threads, so a large image (or hundreds of them) never stalls the other +/// work on the runtime, such as the processing lock's heartbeat. +async fn decode(sha256: String, bytes: Vec) -> Result { + tokio::task::spawn_blocking(move || decode_image(&sha256, &bytes)) + .await + .map_err(|e| format!("decoding the image stopped: {e}"))? +} + +/// Fingerprint image files: up to `concurrency` downloads (`fetch`) at a time, in the calling task, each file decoded +/// on the blocking pool. Each file's fingerprint and size, or why it couldn't be read. +pub async fn fingerprint_files( + shas: Vec, + concurrency: usize, + fetch: F, +) -> HashMap> +where + F: Fn(String) -> Fut, + Fut: Future>>, +{ + stream::iter(shas) + .map(|sha| { + let fetched = fetch(sha.clone()); + async move { + let info = match fetched.await { + Ok(bytes) => decode(sha.clone(), bytes).await, + Err(e) => Err(e.to_string()), + }; + (sha, info) + } + }) + .buffer_unordered(concurrency.max(1)) + .collect() + .await +} + +/// Each image blob's pixel fingerprint and size: the one on its row, or computed from the file +/// ([`fingerprint_files`], `VISUALCI_FINGERPRINT_CONCURRENCY` at a time) and written to the rows in a few statements. +/// A fingerprint already on a row stays (only a missing size is added). +/// +/// # Errors +/// On a database error. A file that can't be downloaded or decoded is its own `Err` in the map. +pub async fn image_infos( + blobs: Vec, + store: &BlobStore, +) -> laravel::Result>> { + let mut infos = HashMap::new(); + let mut known: HashMap> = HashMap::new(); + for blob in blobs { + match (&blob.pixel_fingerprint, blob.width, blob.height) { + (Some(fp), Some(w), Some(h)) => { + infos.insert(blob.sha256.clone(), Ok((fp.clone(), dimension(w), dimension(h)))); + } + _ => { + known.insert(blob.sha256.clone(), blob.pixel_fingerprint.clone()); + } + } + } + if known.is_empty() { + return Ok(infos); + } + let concurrency = laravel::config().section::().fingerprint_concurrency; + let shas: Vec = known.keys().cloned().collect(); + let computed = fingerprint_files(shas, concurrency, |sha| async move { store.get(&sha).await }).await; + let mut rows: Vec<(String, String, i32, i32)> = Vec::new(); + for (sha, info) in computed { + let info = info.map(|(fp, w, h)| (known.get(&sha).cloned().flatten().unwrap_or(fp), w, h)); + if let Ok((fp, w, h)) = &info { + rows.push(( + sha.clone(), + fp.clone(), + i32::try_from(*w).unwrap_or(i32::MAX), + i32::try_from(*h).unwrap_or(i32::MAX), + )); + } + if let Err(e) = &info { + tracing::warn!(blob = %sha, error = %e, "an image file couldn't be fingerprinted"); + } + infos.insert(sha, info); + } + for chunk in rows.chunks(5_000) { + db::query!( + "UPDATE blobs b SET pixel_fingerprint = COALESCE(b.pixel_fingerprint, v.fingerprint), width = v.width, \ + height = v.height, updated_at = now() \ + FROM (VALUES {...chunk(0, 1, 2, 3)}) AS v (sha256, fingerprint, width, height) WHERE b.sha256 = v.sha256" + ) + .update() + .await?; + } + Ok(infos) +} + +fn dimension(n: i32) -> u32 { + u32::try_from(n).unwrap_or(0) +} + /// The image's pixel fingerprint and size, computed (and cached on the row) on first use. /// /// # Errors /// When the blob is missing or isn't an image. -pub async fn image_info(mut blob: Blob, store: &BlobStore) -> laravel::Result<(String, u32, u32)> { - if let (Some(fp), Some(w), Some(h)) = (&blob.pixel_fingerprint, blob.width, blob.height) { - return Ok((fp.clone(), u32::try_from(w).unwrap_or(0), u32::try_from(h).unwrap_or(0))); - } - let bytes = store.get(&blob.sha256).await?; - let image = visualci_core::image_hash::decode(&bytes) - .map_err(|e| laravel::Error::msg(format!("{}: {e}", blob.sha256)))? - .to_rgba8(); - let fp = visualci_core::image_hash::fingerprint_rgba(&image); - let (w, h) = image.dimensions(); - let pixel_fingerprint = Some(fp.clone()); - let (width, height) = (Some(i32::try_from(w).unwrap_or(i32::MAX)), Some(i32::try_from(h).unwrap_or(i32::MAX))); - update!(blob { pixel_fingerprint, width, height }).await?; - Ok((fp, w, h)) +pub async fn image_info(blob: Blob, store: &BlobStore) -> laravel::Result { + let sha = blob.sha256.clone(); + let mut infos = image_infos(vec![blob], store).await?; + infos.remove(&sha).unwrap_or_else(|| Err(format!("{sha}: not read"))).map_err(laravel::Error::msg) } diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index e05ad248..7a532518 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -331,7 +331,7 @@ async fn approved_settings_build(mut build: Build) -> laravel::Result { } /// Images sent without a fingerprint (sc-8999) take their blob's pixel fingerprint before anything compares them, -/// computed from the file (and kept on the blob, [`super::blobs::image_info`]) where the blob has none yet: a new file, +/// computed from the file (and kept on the blob, [`super::blobs::image_infos`]) where the blob has none yet: a new file, /// or a re-encoded one with the same pixels, which stays its own blob under its own hash. Each file is decoded once, /// outside any transaction, and the snapshots are updated in one statement. A file that isn't an image fails its /// snapshots, as comparing it would. @@ -356,17 +356,23 @@ async fn fill_image_fingerprints( shas.sort_unstable(); shas.dedup(); let mut found: HashMap> = HashMap::new(); + let mut unread = Vec::new(); for chunk in shas.chunks(10_000) { for blob in crate::models::Blob::query().filter(crate::models::Blob::sha256.is_in(chunk.to_vec())).get().await? { - let sha = blob.sha256.clone(); - let fingerprint = match blob.pixel_fingerprint.clone() { - Some(fp) => Ok(fp), - None => super::blobs::image_info(blob, store).await.map(|(fp, _, _)| fp).map_err(|e| e.to_string()), - }; - found.insert(sha, fingerprint); + match blob.pixel_fingerprint.clone() { + Some(fp) => { + found.insert(blob.sha256.clone(), Ok(fp)); + } + None => unread.push(blob), + } } } + // New files are downloaded a few at a time and decoded off the runtime's threads (incident, 4 Dec 2026: one at a + // time on the runtime, a new project's first build held the only worker for minutes). + for (sha, info) in super::blobs::image_infos(unread, store).await? { + found.insert(sha, info.map(|(fp, _, _)| fp)); + } let mut rows: Vec<(i64, String)> = Vec::new(); for snapshot in snapshots.iter_mut().filter(|s| needs(s)) { match snapshot.source_blob.as_ref().and_then(|b| found.get(b)) { @@ -458,8 +464,10 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> .filter(|s| s.render_id.is_none() && s.state != "removed") .filter_map(|s| s.source_blob.clone()) .collect(); + let started = std::time::Instant::now(); let missing = super::blobs::confirm_uploads(store, &needed).await?; fill_image_fingerprints(&mut snapshots, &missing, store).await?; + let fingerprints_ms = started.elapsed().as_millis(); let mut waiting = false; for snapshot in &mut snapshots { @@ -520,6 +528,7 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> return Ok(false); } + let compare_started = std::time::Instant::now(); let mut seen = HashSet::new(); for mut snapshot in snapshots { seen.insert((snapshot.name.clone(), snapshot.platform.clone())); @@ -536,6 +545,9 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> } } + let compare_ms = compare_started.elapsed().as_millis(); + let finish_started = std::time::Instant::now(); + // What the build didn't send: a subset build (CI skipped the jobs whose inputs didn't change) and the groups that // matched their baselines carry it forward unchanged; anything else was removed. let carry = groups::carry(&build).await?; @@ -660,7 +672,7 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> // The conclusion, in one short transaction of database work only, under the build's advisory lock (a review takes // it too): still processing (another run may have concluded it), it's charged, its unchanged groups are read from // the builds that hold them, and it's concluded, all or nothing. - Box::pin(db::transaction(async |_| { + let concluded = Box::pin(db::transaction(async |_| { lock(id).await?; let mut build = Build::find_or_fail(id).await?; if build.state != "processing" { @@ -689,7 +701,18 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> } Ok(true) })) - .await + .await; + // Where a slow run's time went: uploads and fingerprints, comparing, and the rest up to the conclusion. + tracing::info!( + build = id, + snapshots = seen.len(), + fingerprints_ms, + compare_ms, + finish_ms = finish_started.elapsed().as_millis(), + total_ms = started.elapsed().as_millis(), + "processed a build" + ); + concluded } /// Carry a base snapshot forward into a build as its own row, compared with the base (unchanged). diff --git a/app/src/domain/renders.rs b/app/src/domain/renders.rs index 8f08558a..efad61c7 100644 --- a/app/src/domain/renders.rs +++ b/app/src/domain/renders.rs @@ -225,29 +225,27 @@ pub async fn fail_exhausted_claims() -> laravel::Result> { Ok(failed) } -/// Process again every build waiting on this render: renders are per project, so that's the project's processing builds -/// (the ones whose snapshots use it, and the ones waiting for their base's PDF to be drawn again with their own -/// renderer settings). Processing a build that's still waiting does nothing. +/// Process again every build waiting on this render: the processing builds with a snapshot drawn by it, and, for a +/// render drawing a base's PDF again with a head's renderer settings (`redraw_base` in processing), the project's +/// processing builds with a document of the same name and platform as a snapshot of that file. Not every processing +/// build in the project: on 4 Dec 2026 that queued `ProcessBuild` for each of them about three times a second. +/// Processing a build that's still waiting does nothing. /// /// # Errors /// On a database or queue error. pub async fn wake_waiting(render: &Render) -> laravel::Result<()> { - let render_id = render.id; - let rows = match render.project_id { - Some(project_id) => { - db::query!("SELECT id FROM builds WHERE project_id = {project_id} AND state = 'processing'") - .select() - .await? - } - None => { - db::query!( - "SELECT DISTINCT b.id FROM builds b JOIN snapshots s ON s.build_id = b.id \ - WHERE s.render_id = {render_id} AND b.state = 'processing'" - ) - .select() - .await? - } - }; + let (render_id, project_id, blob) = (render.id, render.project_id, render.source_blob.as_str()); + let rows = db::query!( + "SELECT b.id FROM builds b JOIN snapshots s ON s.build_id = b.id \ + WHERE b.state = 'processing' AND s.render_id = {render_id} \ + UNION \ + SELECT b.id FROM builds b JOIN snapshots s ON s.build_id = b.id \ + WHERE b.state = 'processing' AND b.project_id = {project_id} AND s.kind = 'document' \ + AND (s.name, s.platform) IN ( \ + SELECT o.name, o.platform FROM snapshots o WHERE o.source_blob = {blob} AND o.kind = 'document')" + ) + .select() + .await?; for build_id in rows.iter().filter_map(|r| r.try_get::("id").ok()) { crate::jobs::process_build::ProcessBuild { build_id }.dispatch().await?; } diff --git a/app/tests/fingerprints.rs b/app/tests/fingerprints.rs index 11770984..e13cac9d 100644 --- a/app/tests/fingerprints.rs +++ b/app/tests/fingerprints.rs @@ -447,3 +447,219 @@ async fn groups_can_name_images_by_their_files_hash(app: Application) -> laravel refused.assert_status(400); Ok(()) } + +// Incident, 4 Dec 2026: a new project's first build (3,634 images sent by hash) downloaded and decoded its files one at +// a time on the async runtime's thread, and held the only worker for minutes. + +/// A 64x64 PNG of colour `i`, so each of many images is its own file with its own fingerprint. +fn numbered_png(i: usize) -> Vec { + let rgb = [u8::try_from(i % 256).unwrap(), u8::try_from(i / 256).unwrap(), 77]; + let image = image::RgbaImage::from_fn(64, 64, |x, y| { + if (x + y) % 9 == 0 { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([rgb[0], rgb[1], rgb[2], 255]) } + }); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).expect("a PNG encodes"); + bytes +} + +#[laravel::test] +async fn three_hundred_new_images_are_fingerprinted_while_requests_still_answer( + app: Application, +) -> laravel::Result<()> { + use futures_util::stream::{self, StreamExt}; + let started = std::time::Instant::now(); + fixtures::blob_store().await?; + let token = project_token().await?; + let files: Vec> = (0..300).map(numbered_png).collect(); + let id = create(&app, &token, "c1", "c0").await; + let params: Vec = + files.iter().enumerate().map(|(i, b)| image_by_sha(&format!("shot-{i:03}"), b).0).collect(); + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", format!("Bearer {token}")) + .json(json!({ "snapshots": params })) + .await; + registered.assert_ok(); + let answer = registered.json().clone(); + let uploads: Vec<(String, Vec)> = answer["snapshots"] + .as_array() + .unwrap() + .iter() + .zip(&files) + .map(|(a, b)| (a["upload_url"].as_str().expect("a new file").to_string(), b.clone())) + .collect(); + stream::iter(uploads) + .for_each_concurrent(16, |(url, bytes)| async move { put(&url, bytes, "image/png").await }) + .await; + + // Processing runs inline (the sync queue) in this task; a request made alongside it still answers quickly, as + // nothing heavy runs on the runtime's thread. + let finished = AtomicBool::new(false); + let processing = async { + let done = finalize(&app, &token, &id).await; + finished.store(true, Ordering::SeqCst); + done + }; + let probing = async { + let mut slowest = std::time::Duration::ZERO; + let mut probes = 0; + while !finished.load(Ordering::SeqCst) { + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + let asked = std::time::Instant::now(); + app.get("/up").await.assert_ok(); + slowest = slowest.max(asked.elapsed()); + probes += 1; + } + (slowest, probes) + }; + let (done, (slowest, probes)) = tokio::join!(processing, probing); + assert_eq!(done["state"], "completed", "{done}"); + assert!(probes > 0, "no request was made while the build processed"); + assert!(slowest < std::time::Duration::from_secs(1), "a request took {slowest:?} while the build processed"); + + let shas: Vec = files.iter().map(|b| visualci_core::sha256_hex(b)).collect(); + let blobs = Blob::query().filter(Blob::sha256.is_in(shas.clone())).get().await?; + assert_eq!(blobs.len(), 300); + for blob in &blobs { + let bytes = &files[shas.iter().position(|s| *s == blob.sha256).unwrap()]; + assert_eq!(blob.pixel_fingerprint, Some(pixel_fingerprint(bytes)), "{}", blob.sha256); + assert_eq!((blob.width, blob.height), (Some(64), Some(64)), "{}", blob.sha256); + } + let added: Option = + db::query!("SELECT COUNT(*) FROM snapshots s JOIN builds b ON b.id = s.build_id WHERE b.pid::text = {id} AND s.state = 'added' AND s.source_fingerprint <> ''") + .scalar() + .await?; + assert_eq!(added, Some(300)); + assert!(started.elapsed() < std::time::Duration::from_secs(30), "took {:?}", started.elapsed()); + Ok(()) +} + +#[tokio::test] +async fn fingerprinting_downloads_no_more_files_at_once_than_its_concurrency() { + let in_flight = AtomicUsize::new(0); + let most = AtomicUsize::new(0); + let shas: Vec = (0..40).map(|i| format!("{i:064x}")).collect(); + let started = std::time::Instant::now(); + let infos = app::domain::blobs::fingerprint_files(shas.clone(), 8, |sha| { + let (in_flight, most) = (&in_flight, &most); + async move { + let now = in_flight.fetch_add(1, Ordering::SeqCst) + 1; + most.fetch_max(now, Ordering::SeqCst); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + in_flight.fetch_sub(1, Ordering::SeqCst); + let i = usize::from_str_radix(&sha, 16).unwrap(); + Ok(numbered_png(i)) + } + }) + .await; + assert_eq!(most.load(Ordering::SeqCst), 8, "downloads at once"); + // 40 slow downloads, 8 at a time: five rounds, not forty. + assert!(started.elapsed() < std::time::Duration::from_secs(2), "took {:?}", started.elapsed()); + assert_eq!(infos.len(), 40); + for (i, sha) in shas.iter().enumerate() { + let (fp, w, h) = infos[sha].clone().expect("an image"); + assert_eq!((fp, w, h), (pixel_fingerprint(&numbered_png(i)), 64, 64)); + } +} + +#[tokio::test] +async fn fingerprinting_decodes_off_the_runtime_thread() { + // A large image takes a while to decode and fingerprint; this runtime has one thread, so a ticker on it stalls for + // that long if the decoding runs there. + let big = { + let image = + image::RgbaImage::from_fn(3000, 3000, |x, y| image::Rgba([(x % 256) as u8, (y % 256) as u8, 9, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).expect("a PNG encodes"); + bytes + }; + let one = std::time::Instant::now(); + pixel_fingerprint(&big); + let decoding = one.elapsed(); + assert!(decoding > std::time::Duration::from_millis(40), "decoding took only {decoding:?}: use a larger image"); + + let finished = AtomicBool::new(false); + let shas: Vec = (0..4).map(|i| format!("{i:064x}")).collect(); + let fingerprinting = async { + let infos = app::domain::blobs::fingerprint_files(shas, 1, |_| { + let bytes = big.clone(); + async move { Ok(bytes) } + }) + .await; + finished.store(true, Ordering::SeqCst); + infos + }; + let ticking = async { + let mut longest = std::time::Duration::ZERO; + let mut last = std::time::Instant::now(); + while !finished.load(Ordering::SeqCst) { + tokio::time::sleep(std::time::Duration::from_millis(1)).await; + longest = longest.max(last.elapsed()); + last = std::time::Instant::now(); + } + longest + }; + let (infos, longest) = tokio::join!(fingerprinting, ticking); + assert!(infos.values().all(Result::is_ok)); + assert!(longest < decoding / 2, "the runtime stalled for {longest:?}; one decode takes {decoding:?}"); +} + +#[laravel::test] +async fn a_finished_render_wakes_only_the_processing_builds_that_wait_on_it(_app: Application) -> laravel::Result<()> { + use app::jobs::process_build::ProcessBuild; + use laravel::model::create; + let project = fixtures::project(&fixtures::organization("wake").await?, "docs").await?; + for blob in ["blob-invoice", "blob-other", "blob-receipt-2", "blob-home"] { + app::domain::blobs::register(blob, 1, "application/pdf").await?; + } + let render = app::domain::renders::find_or_queue(project.id, "fp-invoice", "pdfium/150/1", "blob-invoice").await?; + let other = app::domain::renders::find_or_queue(project.id, "fp-other", "pdfium/150/1", "blob-other").await?; + let mut number = 0; + let mut build = async |state: &str| -> laravel::Result { + number += 1; + create!(Build { + pid: laravel::str::uuid7(), + project_id: project.id, + number: number, + commit_sha: format!("c{number}"), + branch: "main", + state: state, + }) + .await + }; + let snapshot = async |build: &Build, name: &str, kind: &str, blob: &str, render_id: Option| { + create!(Snapshot { + pid: laravel::str::uuid7(), + build_id: build.id, + group_key: "g", + name: name, + kind: kind, + source_fingerprint: format!("fp-{blob}"), + source_blob: Some(blob.to_string()), + render_id: render_id, + state: "pending", + }) + .await + }; + // Drawn by the render + let uses = build("processing").await?; + snapshot(&uses, "invoice.pdf", "document", "blob-invoice", Some(render.id)).await?; + // Waiting for its base's PDF (the render's file, in an earlier build) to be drawn with its own settings + let earlier = build("completed").await?; + snapshot(&earlier, "receipt.pdf", "document", "blob-invoice", Some(other.id)).await?; + let redraws = build("processing").await?; + snapshot(&redraws, "receipt.pdf", "document", "blob-receipt-2", Some(other.id)).await?; + // Neither: another document, an image, and a finished build that used the render + let unrelated = build("processing").await?; + snapshot(&unrelated, "other.pdf", "document", "blob-other", Some(other.id)).await?; + snapshot(&unrelated, "home.png", "image", "blob-home", None).await?; + let done = build("completed").await?; + snapshot(&done, "invoice.pdf", "document", "blob-invoice", Some(render.id)).await?; + + let jobs = laravel::queue::fake(); + app::domain::renders::wake_waiting(&render).await?; + let mut woken: Vec = jobs.pushed::().iter().map(|j| j.job().build_id).collect(); + woken.sort_unstable(); + assert_eq!(woken, vec![uses.id, redraws.id]); + Ok(()) +} diff --git a/frontend/content/docs/self-hosting/environment-variables.md b/frontend/content/docs/self-hosting/environment-variables.md index c472e400..9570a879 100644 --- a/frontend/content/docs/self-hosting/environment-variables.md +++ b/frontend/content/docs/self-hosting/environment-variables.md @@ -205,6 +205,14 @@ Each scheduled job pushes its result to a [Gatus](https://gatus.io) external end | `VISUALCI_PLATFORM_ADDRESSES_HEARTBEAT_URL` | string | | Reading known platforms' published egress ranges (hourly; healthy while the copy kept is under two days old). | | `VISUALCI_PLATFORM_ADDRESSES_HEARTBEAT_TOKEN` | string | | Secret. The platform ranges check's token. | +## Build processing + +Processing builds (the worker). + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_FINGERPRINT_CONCURRENCY` | integer | `8` | How many new image files one build's processing downloads and fingerprints at once. Each is decoded on a thread of its own, off the threads that serve requests and keep locks alive. | + ## Laravel Rust The framework reads these itself, under its own names.