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
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//! A PDF blob's fingerprint (sc-8999), as the renderer computes it from the file in its sandbox: a client may send only
//! a file's SHA-256, and a later run that sends the same file is matched by its hash with no upload.

use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.query("ALTER TABLE blobs ADD COLUMN pdf_fingerprint text").unprepared().await?;
Ok(())
}
1 change: 1 addition & 0 deletions app/src/domain/baselines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,7 @@ pub async fn approved_elsewhere(build_id: i64) -> laravel::Result<HashMap<i64, A
AND bl.platform = s.platform \
AND bl.approval = 'review' AND bl.branch <> b.branch AND bl.snapshot_id IS NOT NULL \
JOIN snapshots s2 ON s2.id = bl.snapshot_id AND s2.source_fingerprint = s.source_fingerprint \
AND s.source_fingerprint <> '' \
JOIN builds b2 ON b2.id = bl.build_id \
LEFT JOIN users u ON u.id = bl.approved_by \
LEFT JOIN reviews r ON r.id = bl.review_id \
Expand Down
70 changes: 67 additions & 3 deletions app/src/domain/blobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,52 @@ pub async fn register(sha256: &str, size: i64, content_type: &str) -> laravel::R
Blob::find_or_fail(sha256.to_string()).await
}

/// A file a client is about to name: its hash, size and content type.
pub struct NewBlob {
pub sha256: String,
pub size: i64,
pub content_type: String,
}

/// [`register`] for many files at once, in two statements whatever their number: the upsert, and one read of every row
/// back, by hash. A hash listed twice is registered once, with its first size and content type.
///
/// # Errors
/// On a database error.
pub async fn register_many(files: &[NewBlob]) -> laravel::Result<std::collections::HashMap<String, Blob>> {
let mut seen = std::collections::HashSet::new();
let files: Vec<&NewBlob> = files.iter().filter(|f| seen.insert(f.sha256.as_str())).collect();
let mut out = std::collections::HashMap::with_capacity(files.len());
// Three bindings a file: well inside PostgreSQL's 65,535.
for chunk in files.chunks(10_000) {
db::query!(
"INSERT INTO blobs (sha256, size, content_type) VALUES {...chunk(sha256, size, content_type)} \
ON CONFLICT (sha256) DO UPDATE SET deleting = false, updated_at = now(), \
uploaded_at = CASE WHEN blobs.deleting THEN NULL ELSE blobs.uploaded_at END \
WHERE blobs.deleting OR blobs.updated_at < now() - interval '1 hour'"
)
.insert()
.await?;
let shas: Vec<String> = chunk.iter().map(|f| f.sha256.clone()).collect();
out.extend(
Blob::query().filter(Blob::sha256.is_in(shas)).get().await?.into_iter().map(|b| (b.sha256.clone(), b)),
);
}
Ok(out)
}

/// The source fingerprint a snapshot of this kind gets from its blob, when the server knows it: an image's pixel
/// fingerprint, a PDF's fingerprint (the renderer's), and a text's SHA-256 (always known).
#[must_use]
pub fn known_fingerprint(kind: &str, blob: Option<&Blob>, sha256: &str) -> Option<String> {
match kind {
"text" => Some(sha256.to_string()),
"image" => blob.and_then(|b| b.pixel_fingerprint.clone()),
"document" => blob.and_then(|b| b.pdf_fingerprint.clone()),
_ => None,
}
}

#[must_use]
pub fn is_uploaded(blob: &Blob) -> bool {
blob.uploaded_at.is_some() && !blob.deleting
Expand All @@ -44,18 +90,36 @@ pub async fn existing(shas: &[String]) -> laravel::Result<std::collections::Hash
}

/// Check the store for blobs not yet confirmed, and mark the ones that arrived with bytes matching their hash (one
/// that doesn't match is deleted, to be uploaded again). Returns the hashes still missing.
/// that doesn't match is deleted, to be uploaded again). Returns the hashes still missing. The rows are read in one
/// query, so a build whose files are all stored already costs no request to the store and no query per file.
///
/// # Errors
/// On a database or storage error.
pub async fn confirm_uploads(store: &BlobStore, hashes: &[String]) -> laravel::Result<Vec<String>> {
let mut rows = std::collections::HashMap::new();
for chunk in hashes.chunks(10_000) {
rows.extend(
Blob::query()
.filter(Blob::sha256.is_in(chunk.to_vec()))
.get()
.await?
.into_iter()
.map(|b| (b.sha256.clone(), b)),
);
}
let mut missing = Vec::new();
let mut checked = std::collections::HashSet::new();
for sha256 in hashes {
let Some(mut blob) = Blob::find(sha256.clone()).await? else {
let Some(blob) = rows.get_mut(sha256) else {
missing.push(sha256.clone());
continue;
};
if is_uploaded(&blob) {
if is_uploaded(blob) {
continue;
}
// A hash listed twice is checked once.
if !checked.insert(sha256.clone()) {
missing.push(sha256.clone());
continue;
}
if let Some(size) = store.verify(sha256).await? {
Expand Down
4 changes: 2 additions & 2 deletions app/src/domain/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ impl Seeder<'_> {
name: name.to_string(),
platform: if kind == "image" { "chrome-linux".to_string() } else { String::new() },
kind: kind.to_string(),
fingerprint,
fingerprint: Some(fingerprint),
sha256,
size,
content_type: content_type.to_string(),
Expand Down Expand Up @@ -481,7 +481,7 @@ impl Seeder<'_> {
let render =
super::renders::find_or_queue(project.id, &fingerprint, &renderer_key, &blob.sha256).await?;
if render.state != "done" {
super::renders::complete(render, &rendered).await?;
super::renders::complete(render, &rendered, None).await?;
}
params(name, "document", fingerprint, blob.sha256, blob.size, "application/pdf")
}
Expand Down
32 changes: 29 additions & 3 deletions app/src/domain/groups.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ pub struct CheckParams {
/// The shard sending these groups, for a sharded build: groups must not span shards.
#[serde(default)]
pub shard: Option<i32>,
/// What an image's entry hashes (sc-8999): `fingerprint` (the default: its pixel fingerprint, which published CLIs
/// decode every image for), or `sha256` (its file's hash, so the client decodes nothing). Documents and texts hash
/// their fingerprints either way.
#[serde(default)]
pub image_hash: Option<String>,
}

/// The server's answer.
Expand All @@ -60,11 +65,23 @@ pub struct Checked {
/// A stored snapshot as a manifest entry: the same fields, normalized the same way, as the CLI hashes.
#[must_use]
pub fn entry_of(s: &Snapshot) -> Entry {
entry_with(s, false)
}

/// [`entry_of`], with an image's entry naming its file's SHA-256 instead of its pixel fingerprint when
/// `images_by_sha256` (a client that sent `image_hash: sha256`).
#[must_use]
pub fn entry_with(s: &Snapshot, images_by_sha256: bool) -> Entry {
let fingerprint = if images_by_sha256 && s.kind == "image" {
s.source_blob.clone().unwrap_or_default()
} else {
s.source_fingerprint.clone()
};
Entry {
name: s.name.clone(),
platform: s.platform.clone(),
kind: s.kind.clone(),
fingerprint: s.source_fingerprint.clone(),
fingerprint,
format: s.format.clone(),
engine: s.engine.clone(),
threshold: s.threshold,
Expand All @@ -89,11 +106,20 @@ pub async fn check(build: &Build, project: &Project, params: &CheckParams) -> la
if build.group_depth.is_some() && build.group_depth != params.group_depth {
return Ok(Err("every shard must group names the same way (group_depth)".into()));
}
let images_by_sha256 = match params.image_hash.as_deref() {
None | Some("fingerprint") => false,
Some("sha256") => true,
Some(other) => return Ok(Err(format!("image_hash must be fingerprint or sha256, not {other:?}"))),
};
let grouping = grouping(params.group_depth);
// The baseline's side, from the server's own rows: each snapshot's approved version.
let (resolved, anchor) = super::baselines::resolve(build, project).await?;
let entries: Vec<Entry> =
resolved.values().map(|r| &r.snapshot).filter(|s| s.platform != CONFIG_PLATFORM).map(entry_of).collect();
let entries: Vec<Entry> = resolved
.values()
.map(|r| &r.snapshot)
.filter(|s| s.platform != CONFIG_PLATFORM)
.map(|s| entry_with(s, images_by_sha256))
.collect();
let baseline_groups: HashMap<String, String> =
manifest::groups(&entries, grouping).into_iter().map(|g| (g.key, g.hash)).collect();
let manifest_matched = !entries.is_empty()
Expand Down
4 changes: 3 additions & 1 deletion app/src/domain/inherited.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ pub async fn of_build(build: &Build, project: &Project) -> laravel::Result<Optio
if s.state == "removed" {
p.state == "removed"
} else {
p.state != "removed" && p.source_fingerprint == s.source_fingerprint
p.state != "removed"
&& !s.source_fingerprint.is_empty()
&& p.source_fingerprint == s.source_fingerprint
}
})
})
Expand Down
107 changes: 98 additions & 9 deletions app/src/domain/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,97 @@ async fn approved_settings_build(mut build: Build) -> laravel::Result<Build> {
Ok(build)
}

/// 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,
/// 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.
///
/// # Errors
/// On a database or storage error.
async fn fill_image_fingerprints(
snapshots: &mut [Snapshot],
missing: &[String],
store: &BlobStore,
) -> laravel::Result<()> {
let needs = |s: &Snapshot| {
s.kind == "image"
&& s.source_fingerprint.is_empty()
&& !matches!(s.state.as_str(), "failed" | "removed")
&& s.source_blob.as_ref().is_some_and(|b| !missing.contains(b))
};
let mut shas: Vec<String> = snapshots.iter().filter(|s| needs(s)).filter_map(|s| s.source_blob.clone()).collect();
if shas.is_empty() {
return Ok(());
}
shas.sort_unstable();
shas.dedup();
let mut found: HashMap<String, Result<String, String>> = HashMap::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);
}
}
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)) {
Some(Ok(fp)) => {
snapshot.source_fingerprint.clone_from(fp);
rows.push((snapshot.id, fp.clone()));
}
Some(Err(e)) => mark_failed(snapshot, &format!("the image couldn't be read: {e}")).await?,
None => mark_failed(snapshot, "the file was never uploaded").await?,
}
}
for chunk in rows.chunks(10_000) {
db::query!(
"UPDATE snapshots s SET source_fingerprint = v.fingerprint, updated_at = now() \
FROM (VALUES {...chunk(0, 1)}) AS v (id, fingerprint) WHERE s.id = v.id"
)
.update()
.await?;
}
Ok(())
}

/// Queue (or find) a document's render. A PDF sent without a fingerprint (sc-8999) takes its blob's, from an earlier
/// render of the file; a file never drawn before is drawn under its own hash (the same bytes always draw the same), and
/// the renderer reports its fingerprint ([`super::renders::complete`]).
///
/// # Errors
/// On a database error.
async fn queue_render(project_id: i64, renderer: &str, snapshot: &mut Snapshot) -> laravel::Result<Render> {
let blob = snapshot.source_blob.clone().unwrap_or_default();
if snapshot.source_fingerprint.is_empty()
&& let Some(source_fingerprint) = crate::models::Blob::find(blob.clone()).await?.and_then(|b| b.pdf_fingerprint)
{
update!(snapshot { source_fingerprint }).await?;
}
let key = if snapshot.source_fingerprint.is_empty() { blob.clone() } else { snapshot.source_fingerprint.clone() };
super::renders::find_or_queue(project_id, &key, renderer, &blob).await
}

/// Once a document's render is done: a PDF sent without a fingerprint takes the one the renderer reported for its
/// file, or the file's hash when it reported none (an older renderer), as the CLI fingerprints a PDF it can't parse.
///
/// # Errors
/// On a database error.
async fn fill_document_fingerprint(snapshot: &mut Snapshot) -> laravel::Result<()> {
if !snapshot.source_fingerprint.is_empty() {
return Ok(());
}
let blob = snapshot.source_blob.clone().unwrap_or_default();
let reported = crate::models::Blob::find(blob.clone()).await?.and_then(|b| b.pdf_fingerprint);
let source_fingerprint = reported.unwrap_or(blob);
update!(snapshot { source_fingerprint }).await
}

/// Process a finalized build as far as it can go: confirm uploads, queue renders, and once every render is done,
/// compare and conclude. Returns whether the build concluded (false while renders are outstanding). The caller holds
/// [`exclusive`]; this runs outside any transaction, so storage requests, decoding and diffing never hold a database
Expand Down Expand Up @@ -336,6 +427,7 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
.filter_map(|s| s.source_blob.clone())
.collect();
let missing = super::blobs::confirm_uploads(store, &needed).await?;
fill_image_fingerprints(&mut snapshots, &missing, store).await?;

let mut waiting = false;
for snapshot in &mut snapshots {
Expand All @@ -349,16 +441,14 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
mark_failed(snapshot, "the PDF was never uploaded").await?;
continue;
}
let blob = snapshot.source_blob.clone().unwrap_or_default();
let key = settings.renderer_key(snapshot.engine.as_deref(), renderer_version);
let render =
super::renders::find_or_queue(project.id, &snapshot.source_fingerprint, &key, &blob).await?;
let render = queue_render(project.id, &key, snapshot).await?;
let render_id = Some(render.id);
update!(snapshot { render_id }).await?;
}
let render = Render::find_or_fail(snapshot.render_id.unwrap_or_default()).await?;
match render.state.as_str() {
"done" => {}
"done" => fill_document_fingerprint(snapshot).await?,
"failed" => {
let error = format!("rendering failed: {}", render.error.unwrap_or_default());
mark_failed(snapshot, &error).await?;
Expand Down Expand Up @@ -896,7 +986,7 @@ pub async fn compare_now(
}
}
let settings = BuildSettings::new(&project, build);
let snapshots: Vec<Snapshot> = super::snapshots::of_build(build.id)
let mut snapshots: Vec<Snapshot> = super::snapshots::of_build(build.id)
.await?
.into_iter()
.filter(|s| wanted.iter().any(|(n, p)| *n == s.name && *p == s.platform))
Expand All @@ -907,6 +997,7 @@ pub async fn compare_now(
let needed: Vec<String> =
snapshots.iter().filter(|s| s.render_id.is_none()).filter_map(|s| s.source_blob.clone()).collect();
let missing = super::blobs::confirm_uploads(store, &needed).await?;
fill_image_fingerprints(&mut snapshots, &missing, store).await?;
let (resolved, _) = baselines::resolve(build, &project).await?;
let mut out = Vec::with_capacity(snapshots.len());
for mut snapshot in snapshots {
Expand All @@ -916,16 +1007,14 @@ pub async fn compare_now(
}
if snapshot.kind == "document" {
if snapshot.render_id.is_none() {
let blob = snapshot.source_blob.clone().unwrap_or_default();
let key = settings.renderer_key(snapshot.engine.as_deref(), renderer_version);
let render =
super::renders::find_or_queue(project.id, &snapshot.source_fingerprint, &key, &blob).await?;
let render = queue_render(project.id, &key, &mut snapshot).await?;
let render_id = Some(render.id);
update!(snapshot { render_id }).await?;
}
let render = Render::find_or_fail(snapshot.render_id.unwrap_or_default()).await?;
match render.state.as_str() {
"done" => {}
"done" => fill_document_fingerprint(&mut snapshot).await?,
"failed" => {
let error = format!("rendering failed: {}", render.error.unwrap_or_default());
mark_failed(&mut snapshot, &error).await?;
Expand Down
Loading
Loading