//! The thumbnail worker. It takes the files whose thumbnail is `pending` (pictures of the types the decoder //! reads), makes a WebP thumbnail of each, stores it under `thumbs/` and marks the file `ready`; a picture //! that cannot be decoded, or that is too large, is marked `failed`. It runs at most [`CONCURRENCY`] decodes at //! once, each on a blocking thread, and never runs an external program. //! //! Ordering: the thumbnail bytes are stored before the row says `ready`. If the file was purged while its //! thumbnail was made, the row update finds nothing and the stored bytes are deleted, so no row is left //! without its file. use std::sync::{Arc, LazyLock}; use std::time::Duration; use futures_util::{StreamExt, stream}; use in_core::error::{Error, Result}; use in_core::staging::{Staged, StagedFile}; use in_core::store::files::{File, thumb_blob_key}; use in_core::thumbs::{MAX_SOURCE_BYTES, make_thumbnail}; use tokio::sync::{Semaphore, watch}; use crate::live::Topic; use crate::state::AppState; /// Most files taken from the queue in one round. pub const BATCH: usize = 16; /// Most thumbnails made at the same time. One, because a decode may hold a whole source picture /// ([`MAX_SOURCE_BYTES`], 64 MiB) and its decoder buffers ([`in_core::thumbs::MAX_ALLOC_BYTES`], 256 MiB); two /// together could reach about 640 MiB. One keeps the peak near 320 MiB. pub const CONCURRENCY: usize = 1; /// Longest a decode may run before its file is marked `failed`: ten seconds. pub const DECODE_TIMEOUT: Duration = Duration::from_secs(10); /// The decode slots. A slot is moved into the blocking decode, so it is released when the decoder returns, /// not when the caller stops waiting. A timed-out decode that still runs keeps its slot, and no other decode /// starts beside it, so stragglers cannot pile up. static DECODE_SLOTS: LazyLock> = LazyLock::new(|| Arc::new(Semaphore::new(CONCURRENCY))); /// How long the worker waits when the queue is empty before it looks again. pub const IDLE: Duration = Duration::from_secs(30); /// Largest thumbnail the worker stores. A 320 pixel lossless WebP is far below this. const MAX_THUMB_BYTES: u64 = 8 * 1024 * 1024; /// Runs rounds until the stop flag is set. A round that found work is followed at once by the next one. pub async fn run(state: AppState, mut stop: watch::Receiver) { loop { let handled = match work_batch(&state).await { Ok(count) => count, Err(error) => { tracing::warn!(error = %error, "thumbs: round failed"); 0 } }; let pause = if handled == 0 { IDLE } else { Duration::ZERO }; tokio::select! { _ = stop.wait_for(|stopped| *stopped) => return, () = tokio::time::sleep(pause) => {} } } } /// One round: up to [`BATCH`] pending files, [`CONCURRENCY`] at a time. Returns how many files it took. async fn work_batch(state: &AppState) -> Result { let files = state.store.pending_thumbs(BATCH).await?; let count = files.len(); stream::iter(files) .for_each_concurrent(CONCURRENCY, |file| make_one(state, file)) .await; Ok(count) } /// Makes the thumbnail of one file and records the outcome. Every taken file leaves `pending`, so the queue /// always shrinks. async fn make_one(state: &AppState, file: File) { let outcome = build(state, &file).await; let word = match outcome { Ok(()) => "ready", Err(ref error) => { tracing::info!(file = %file.id, error = %error, "thumbs: no thumbnail"); "failed" } }; match state.store.set_thumb_state(&file.id, word).await { Ok(true) => {} Ok(false) => { // The file was purged while its thumbnail was made. Its bytes are not named by any row now. if word == "ready" { let _ = state.blobs.delete(&thumb_blob_key(&file.id)).await; } } Err(error) => tracing::warn!(file = %file.id, error = %error, "thumbs: state not saved"), } state.live.bump(&Topic::Drive(file.owner.clone())); } /// Decodes the stored picture and stores its thumbnail. Any failure is returned, and the caller marks the /// file `failed`. async fn build(state: &AppState, file: &File) -> Result<()> { let size = u64::try_from(file.size).unwrap_or(u64::MAX); if size > MAX_SOURCE_BYTES { return Err(Error::Invalid("too_large".into())); } let source = read_source(state, file, size).await?; let slot = Arc::clone(&DECODE_SLOTS) .acquire_owned() .await .map_err(|e| Error::Io(std::io::Error::other(e)))?; // The decoder is CPU work: it runs on a blocking thread, never on the async runtime. let decode = tokio::task::spawn_blocking(move || { let _slot = slot; make_thumbnail(&source) }); let webp = match tokio::time::timeout(DECODE_TIMEOUT, decode).await { Ok(joined) => joined.map_err(|e| Error::Io(std::io::Error::other(e)))??, // A blocking task cannot be stopped. Its result is dropped with the handle, and its slot is held // until it returns. Err(_) => return Err(Error::Invalid("decode_timeout".into())), }; let mut staged = StagedFile::create(&state.config.data_dir, MAX_THUMB_BYTES).await?; if let Err(error) = staged.write(&webp).await { staged.abort().await; return Err(error); } let Staged { path, .. } = staged.finish().await?; if let Err(error) = state.blobs.put_file(&thumb_blob_key(&file.id), &path).await { let _ = tokio::fs::remove_file(&path).await; return Err(error); } Ok(()) } /// The whole stored picture, read in frames. `size` is at most [`MAX_SOURCE_BYTES`]. async fn read_source(state: &AppState, file: &File, size: u64) -> Result> { let mut frames = state.blobs.open_range(&file.blob_key, 0, size).await?; let mut bytes = Vec::with_capacity(size as usize); while let Some(frame) = frames.next().await { bytes.extend_from_slice(&frame?); } Ok(bytes) } #[cfg(test)] mod tests { use super::*; use crate::auth::test_support::signed_in; use crate::boot::test_state; use in_core::quota::DEFAULT_MEMBER_QUOTA; use in_core::staging::{Staged, StagedFile}; use in_core::store::files::{NewFile, files_blob_key}; use in_core::store::new_id; /// A PNG whose header claims 100000 by 100000 pixels, with valid chunk checksums. const BOMB_PNG: &[u8] = &[ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x01, 0x86, 0xa0, 0x00, 0x01, 0x86, 0xa0, 0x08, 0x06, 0x00, 0x00, 0x00, 0xa8, 0x52, 0x0b, 0xc8, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x60, 0x60, 0x60, 0x60, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0xa5, 0xf6, 0x45, 0x40, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, ]; /// A decompression bomb is marked `failed`, nothing is stored for it, and the queue is empty afterwards. #[tokio::test] async fn a_decompression_bomb_is_marked_failed_without_a_thumbnail() { let (_dir, state) = test_state().await; let _ = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; let id = new_id(); let mut staged = StagedFile::create(&state.config.data_dir, 1 << 20) .await .expect("staging"); staged.write(BOMB_PNG).await.expect("write"); let Staged { path, sha256, .. } = staged.finish().await.expect("finish"); state .blobs .put_file(&files_blob_key(&id), &path) .await .expect("blob"); state .store .insert_file(NewFile { id: id.clone(), owner: "ann".into(), folder: None, name: "bomb.png".into(), mime: "image/png".into(), size: BOMB_PNG.len() as i64, sha256, staged_claims: 0, }) .await .expect("row"); assert_eq!(work_batch(&state).await.expect("round"), 1); let file = state.store.file(&id).await.expect("read").expect("row"); assert_eq!(file.thumb_state, "failed"); assert_eq!( state.blobs.size(&thumb_blob_key(&id)).await.expect("size"), None ); assert_eq!(work_batch(&state).await.expect("round"), 0); } }