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
14 changes: 14 additions & 0 deletions app/database/migrations/2026_12_03_000400_diffs_used_at.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//! `diffs.used_at`: when a comparison last reused the cached diff. Retention leaves the overlay of a diff reused in the
//! last day alone, since the build reusing it isn't in the prune's keep sets.

use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.query(SCHEMA).unprepared().await?;
Ok(())
}

const SCHEMA: &str = r"
ALTER TABLE diffs ADD COLUMN used_at timestamp with time zone;
CREATE INDEX diffs_used_at ON diffs USING btree (used_at) WHERE used_at IS NOT NULL;
";
9 changes: 6 additions & 3 deletions app/src/domain/blobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,18 @@ use crate::models::Blob;
use crate::storage::BlobStore;

/// Record a blob a client or renderer is about to upload (or already has). Returns it. A blob retention marked for
/// deletion loses the mark and counts as not uploaded, so the client uploads it again; retention then leaves it.
/// deletion loses the mark and counts as not uploaded, so the client uploads it again. Registering also renews
/// `updated_at` (at most hourly), and retention doesn't mark a blob registered in the last day, so a file a build is
/// about to name is never deleted under it.
///
/// # Errors
/// On a database error.
pub async fn register(sha256: &str, size: i64, content_type: &str) -> laravel::Result<Blob> {
db::query!(
"INSERT INTO blobs (sha256, size, content_type) VALUES ({sha256}, {size}, {content_type}) \
ON CONFLICT (sha256) DO UPDATE SET deleting = false, uploaded_at = NULL, updated_at = now() \
WHERE blobs.deleting"
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?;
Expand Down
17 changes: 16 additions & 1 deletion app/src/domain/diffs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,18 @@ async fn find(base_image: &str, head_image: &str, key: &str) -> laravel::Result<
.await
}

/// Note that a comparison reuses this diff now (at most once an hour): retention leaves its overlay alone for a day
/// after.
async fn mark_used(diff_id: i64) -> laravel::Result<()> {
db::query!(
"UPDATE diffs SET used_at = now() \
WHERE id = {diff_id} AND (used_at IS NULL OR used_at < now() - interval '1 hour')"
)
.update()
.await?;
Ok(())
}

/// The diff of two images, computed (with its overlay stored as a blob) on first use. A diff whose overlay retention
/// deleted is computed again, and keeps its row.
///
Expand All @@ -44,7 +56,10 @@ pub async fn find_or_compute(
) -> laravel::Result<Diff> {
let key = options_key(&options);
let stale = match find(base_image, head_image, &key).await? {
Some(diff) if diff.overlay_blob.is_some() || result(&diff).is_none_or(|r| r.is_identical()) => return Ok(diff),
Some(diff) if diff.overlay_blob.is_some() || result(&diff).is_none_or(|r| r.is_identical()) => {
mark_used(diff.id).await?;
return Ok(diff);
}
other => other,
};
let (base_bytes, head_bytes) = (store.get(base_image).await?, store.get(head_image).await?);
Expand Down
97 changes: 85 additions & 12 deletions app/src/domain/downloads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,13 +273,54 @@ fn path_part(name: &str) -> String {
.join("/")
}

/// A snapshot's directory, suffixed `~2`, `~3`… when another snapshot's name made safe gave the same one (`a:b` and
/// `a?b` are both `a_b`).
fn unique_dir(used: &mut std::collections::HashSet<String>, dir: String) -> String {
if used.insert(dir.clone()) {
return dir;
/// The archive's paths so far, so every snapshot and page directory is one of its own. Names made safe can meet (`a:b`
/// and `a?b` are both `a_b`), a snapshot can be named like another's page (`x/page-2` beside page 2 of `x`), and a name
/// can be another's file (`x/head.png` beside `x`'s head image). A directory that would meet one already used, as a
/// directory or as a file, or whose files would meet a directory, is suffixed `~2`, `~3`… (the manifest names each
/// snapshot's paths).
#[derive(Default)]
struct Layout {
/// Snapshot and page directories handed out.
taken: std::collections::HashSet<String>,
/// Every directory above a path handed out.
parents: std::collections::HashSet<String>,
/// Files a directory handed out may hold: `<dir>/<side>.<ext>`.
files: std::collections::HashSet<String>,
}

const EXTENSIONS: &[&str] = &["png", "jpg", "webp"];

fn ancestors(path: &str) -> impl Iterator<Item = &str> {
path.char_indices().filter(|(_, c)| *c == '/').map(move |(i, _)| &path[..i])
}

impl Layout {
fn planned_files(dir: &str) -> impl Iterator<Item = String> + '_ {
SIDES.iter().flat_map(move |side| EXTENSIONS.iter().map(move |ext| format!("{dir}/{side}.{ext}")))
}

/// Whether `dir` can be handed out, holding files (`with_files`) or only page directories.
fn free(&self, dir: &str, with_files: bool) -> bool {
!self.taken.contains(dir)
&& !self.files.contains(dir)
&& !ancestors(dir).any(|a| self.files.contains(a))
&& (!with_files || Self::planned_files(dir).all(|f| !self.taken.contains(&f) && !self.parents.contains(&f)))
}

/// Hand out `dir`, or the first `dir~N` that's free.
fn take(&mut self, dir: &str, with_files: bool) -> String {
let chosen = if self.free(dir, with_files) {
dir.to_string()
} else {
(2..).map(|n| format!("{dir}~{n}")).find(|d| self.free(d, with_files)).unwrap_or_else(|| dir.to_string())
};
self.parents.extend(ancestors(&chosen).map(str::to_string));
if with_files {
self.files.extend(Self::planned_files(&chosen));
}
self.taken.insert(chosen.clone());
chosen
}
(2..).map(|n| format!("{dir}~{n}")).find(|d| used.insert(d.clone())).unwrap_or(dir)
}

fn extension(bytes: &[u8]) -> &'static str {
Expand Down Expand Up @@ -344,18 +385,20 @@ async fn write_archive(
let mut files = 0i32;
let mut entries = Vec::new();
let result: Result<(), String> = async {
let mut used = std::collections::HashSet::new();
let mut layout = Layout::default();
for s in &chosen {
let mut dir = path_part(&s.name);
if !s.platform.is_empty() {
dir = format!("{dir}@{}", path_part(&s.platform));
}
dir = unique_dir(&mut used, dir);
let pages = pages_of.get(&s.id).map(Vec::as_slice).unwrap_or_default();
let several = pages.len() > 1;
// A single page's files go in the snapshot's directory; several pages each get one beneath it.
let dir = layout.take(&dir, !several);
let mut listed = Vec::new();
for p in pages {
let page_dir = if several { format!("{dir}/page-{}", p.position + 1) } else { dir.clone() };
let page_dir =
if several { layout.take(&format!("{dir}/page-{}", p.position + 1), true) } else { dir.clone() };
let diff = p.diff_id.and_then(|id| diffs.get(&id));
let result = diff.and_then(super::diffs::result);
let regions = result.as_ref().map(|r| r.regions.as_slice()).unwrap_or_default();
Expand Down Expand Up @@ -457,12 +500,42 @@ mod tests {

#[test]
fn names_that_become_the_same_path_get_their_own_directories() {
let mut used = std::collections::HashSet::new();
let dirs: Vec<String> =
["a:b", "a?b", "a_b", "c"].iter().map(|n| unique_dir(&mut used, path_part(n))).collect();
let mut layout = Layout::default();
let dirs: Vec<String> = ["a:b", "a?b", "a_b", "c"].iter().map(|n| layout.take(&path_part(n), true)).collect();
assert_eq!(dirs, ["a_b", "a_b~2", "a_b~3", "c"]);
}

#[test]
fn a_snapshot_named_like_another_snapshots_page_gets_its_own_directory() {
// Page 2 of the two-page `x`, then a one-page snapshot named `x/page-2`.
let mut layout = Layout::default();
let x = layout.take("x", false);
let pages: Vec<String> = (1..=2).map(|n| layout.take(&format!("{x}/page-{n}"), true)).collect();
assert_eq!(pages, ["x/page-1", "x/page-2"]);
assert_eq!(layout.take("x/page-2", true), "x/page-2~2");

// The other way round: the one-page `x/page-2` first, then the two-page `x`.
let mut layout = Layout::default();
assert_eq!(layout.take("x/page-2", true), "x/page-2");
let x = layout.take("x", false);
let pages: Vec<String> = (1..=2).map(|n| layout.take(&format!("{x}/page-{n}"), true)).collect();
assert_eq!(pages, ["x/page-1", "x/page-2~2"]);
}

#[test]
fn a_snapshot_named_like_another_snapshots_file_gets_its_own_directory() {
// `x`'s head image is `x/head.png`: a snapshot named `x/head.png` can't be a directory there.
let mut layout = Layout::default();
assert_eq!(layout.take("x", true), "x");
assert_eq!(layout.take("x/head.png", true), "x/head.png~2");
// And the other way round: once `x/head.png` is a directory, `x` can't hold a file of that name.
let mut layout = Layout::default();
assert_eq!(layout.take("x/head.png", true), "x/head.png");
assert_eq!(layout.take("x", true), "x~2");
// Directories that only share a parent are fine.
assert_eq!(layout.take("x/other", true), "x/other");
}

#[test]
fn a_filter_fills_its_defaults_and_refuses_what_it_does_not_know() {
let f = Filter::default().normalized().unwrap();
Expand Down
52 changes: 44 additions & 8 deletions app/src/domain/retention.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,17 +234,25 @@ async fn candidates(days: i32) -> laravel::Result<Candidates> {
/// - a render goes only once no snapshot names it, and its snapshots' links go only when they're over a day old;
/// - a text goes only while it's over a day old (storing it again renews that) and no render reused in the last day
/// names it;
/// - a blob is marked `deleting` (rows locked, skipping any a registration holds), then its object is deleted and the
/// row with it, each under the row's lock and only while it's still marked. Registering the hash again clears the
/// mark and has the file uploaded again ([`super::blobs::register`]), so a build reusing the file keeps it.
/// - an overlay goes only when its diff wasn't reused in the last day;
/// - a blob is marked `deleting` (rows locked, skipping any a registration holds) unless something registered it in the
/// last day or anything names it, then its object is deleted and the row with it, under the row's lock, only while
/// it's still marked and still unnamed. Registering the hash clears the mark and has the file uploaded again
/// ([`super::blobs::register`]), so a build reusing the file keeps it. Marks left over (a skipped row, a store that
/// refused) are cleared at the end of the batch, and any from a run that stopped are cleared at the start: no mark
/// outlives its run.
///
/// With `dry_run`, only count.
///
/// # Errors
/// On a database error. A failed store delete is counted in the report, not returned: the blob stays marked, so it
/// counts as not uploaded until it's registered again or the next prune deletes it.
/// On a database error. A failed store delete is counted in the report, not returned: the blob stays, and the next
/// prune tries again.
pub async fn prune(store: Option<&BlobStore>, days: i32, dry_run: bool) -> laravel::Result<Report> {
let grace = TEXT_GRACE_HOURS;
// Marks a run that stopped part way left behind (prunes never overlap: the schedule runs one at a time).
if !dry_run {
db::query!("UPDATE blobs SET deleting = false WHERE deleting").update().await?;
}
let found = candidates(days).await?;
let mut report = Report::default();
if dry_run {
Expand Down Expand Up @@ -295,11 +303,18 @@ pub async fn prune(store: Option<&BlobStore>, days: i32, dry_run: bool) -> larav
)
.update()
.await?;
db::query!("UPDATE diffs SET overlay_blob = NULL WHERE overlay_blob IN ({...shas})").update().await?;
db::query!(
"UPDATE diffs SET overlay_blob = NULL \
WHERE overlay_blob IN ({...shas}) AND (used_at IS NULL OR used_at < now() - make_interval(hours => {grace}))"
)
.update()
.await?;
let rows = db::query!(
"UPDATE blobs SET deleting = true, updated_at = now() WHERE sha256 IN ( \
SELECT b.sha256 FROM blobs b WHERE b.sha256 IN ({...shas}) \
AND b.updated_at < now() - make_interval(hours => {grace}) \
AND NOT EXISTS (SELECT 1 FROM snapshots s WHERE s.source_blob = b.sha256) \
AND NOT EXISTS (SELECT 1 FROM diffs d WHERE d.overlay_blob = b.sha256) \
AND NOT EXISTS (SELECT 1 FROM renders r WHERE r.source_blob = b.sha256) \
AND NOT EXISTS (SELECT 1 FROM renders r, jsonb_array_elements(r.pages) pg \
WHERE r.used_at >= now() - make_interval(hours => {grace}) AND pg->>'image' = b.sha256) \
Expand All @@ -314,8 +329,8 @@ pub async fn prune(store: Option<&BlobStore>, days: i32, dry_run: bool) -> larav
.collect())
})
.await?;
for (sha256, size) in marked {
match delete_marked(store, &sha256).await? {
for (sha256, size) in &marked {
match delete_marked(store, sha256).await? {
Deleted::Yes => {
report.blobs += 1;
report.bytes += size;
Expand All @@ -324,6 +339,13 @@ pub async fn prune(store: Option<&BlobStore>, days: i32, dry_run: bool) -> larav
Deleted::StoreFailed => report.store_errors += 1,
}
}
// No mark outlives its run: what wasn't deleted (named again, locked by a registration, or the store refused)
// is a blob like any other again. Waits for a registration holding a row.
let left: Vec<String> = marked.into_iter().map(|(s, _)| s).collect();
for chunk in left.chunks(BATCH) {
let chunk = chunk.to_vec();
db::query!("UPDATE blobs SET deleting = false WHERE sha256 IN ({...chunk}) AND deleting").update().await?;
}
}
Ok(report)
}
Expand All @@ -348,6 +370,20 @@ async fn delete_marked(store: Option<&BlobStore>, sha256: &str) -> laravel::Resu
if locked.is_none() {
return Ok(Deleted::KeptForNow);
}
// Named since it was marked (a snapshot or diff committed after a registration that found it uploaded, or a page
// image of a render reused since): it stays.
let named: Option<i64> = db::query!(
"SELECT 1::BIGINT WHERE EXISTS (SELECT 1 FROM snapshots WHERE source_blob = {sha256}) \
OR EXISTS (SELECT 1 FROM renders WHERE source_blob = {sha256}) \
OR EXISTS (SELECT 1 FROM diffs WHERE overlay_blob = {sha256}) \
OR EXISTS (SELECT 1 FROM renders r, jsonb_array_elements(r.pages) pg \
WHERE r.used_at >= now() - interval '24 hours' AND pg->>'image' = {sha256})"
)
.scalar()
.await?;
if named.is_some() {
return Ok(Deleted::KeptForNow);
}
if let Some(store) = store
&& let Err(e) = store.delete(sha256).await
{
Expand Down
9 changes: 7 additions & 2 deletions app/src/http/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,13 @@ pub async fn uploads(Params(id): Params<i64>, headers: HeaderMap, body: axum::bo
let blob = crate::domain::blobs::register(&f.sha256, f.size, &f.content_type).await?;
if crate::domain::blobs::is_uploaded(&blob) {
// Already stored (perhaps another tenant's): the renderer shows it drew the same PNG by uploading the
// bytes to a key of this render's own, checked when it completes.
urls.insert(f.sha256.clone(), store.upload_url_for_key(&renders::proof_key(id, &f.sha256)).into());
// bytes to a key of this render's own, checked when it completes. The URL takes exactly the declared
// size.
let size = u64::try_from(f.size).unwrap_or_default();
urls.insert(
f.sha256.clone(),
store.upload_url_for_key(&renders::proof_key(id, &f.sha256), size).into(),
);
kinds.insert(f.sha256.clone(), "proof".into());
} else {
urls.insert(f.sha256.clone(), store.upload_url(&f.sha256)?.into());
Expand Down
2 changes: 2 additions & 0 deletions app/src/models/diffs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ pub struct Diff {
pub overlay_blob: Option<String>,
pub created_at: Timestamp,
pub updated_at: Timestamp,
/// When a comparison last reused it (retention leaves its overlay alone for a day after).
pub used_at: Option<Timestamp>,
}
10 changes: 7 additions & 3 deletions app/src/storage/blobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,14 @@ impl BlobStore {
Ok((!too_big && hex::encode(hasher.finalize()) == sha256).then_some(read))
}

/// A URL a client can PUT an object other than a blob to (a renderer's proof that it holds a PNG), for minutes.
/// A URL a client can PUT an object other than a blob to (a renderer's proof that it holds a PNG), for minutes. The
/// size is part of the signature (`Content-Length`), so the URL takes exactly that many bytes and nothing larger.
#[must_use]
pub fn upload_url_for_key(&self, key: &str) -> String {
self.public_bucket.put_object(Some(&self.credentials), key).sign(UPLOAD_TTL).to_string()
pub fn upload_url_for_key(&self, key: &str, size: u64) -> String {
let length = size.to_string();
let mut action = self.public_bucket.put_object(Some(&self.credentials), key);
action.headers_mut().insert("content-length", length.as_str());
action.sign(UPLOAD_TTL).to_string()
}

/// Store bytes under their SHA-256 and return it.
Expand Down
12 changes: 11 additions & 1 deletion app/tests/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,9 +286,19 @@ async fn completion_checked(app: Application) -> laravel::Result<()> {
r.assert_ok();
assert_eq!(r.json()["state"], "failed");

// Drawn for real (the same PNG, uploaded to the proof key): done.
// Drawn for real (the same PNG, uploaded to the proof key): done. The proof URL takes exactly the declared size.
let (render_id, claim_token) = fresh().await;
let urls = uploads(&app, render_id, &claim_token, &[&theirs]).await;
let mut larger = theirs.clone();
larger.extend_from_slice(&[0; 1024]);
let refused_upload = reqwest::Client::new()
.put(urls[&their_sha].as_str().unwrap())
.header("content-type", "image/png")
.body(larger)
.send()
.await
.unwrap();
assert!(!refused_upload.status().is_success(), "a larger body is refused: {}", refused_upload.status());
put(urls[&their_sha].as_str().unwrap(), theirs.clone(), "image/png").await;
let r = complete(&app, render_id, &claim_token, json!([page(&theirs, "")])).await;
assert_eq!(r.json()["state"], "done", "{}", r.text());
Expand Down
Loading
Loading