forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

thumbs_worker.rs203 lines, 8.4 KiBHistoryRawDownload
1//! The thumbnail worker. It takes the files whose thumbnail is `pending` (pictures of the types the decoder
2//! reads), makes a WebP thumbnail of each, stores it under `thumbs/<id>` and marks the file `ready`; a picture
3//! that cannot be decoded, or that is too large, is marked `failed`. It runs at most [`CONCURRENCY`] decodes at
4//! once, each on a blocking thread, and never runs an external program.
5//!
6//! Ordering: the thumbnail bytes are stored before the row says `ready`. If the file was purged while its
7//! thumbnail was made, the row update finds nothing and the stored bytes are deleted, so no row is left
8//! without its file.
9
10use std::sync::{Arc, LazyLock};
11use std::time::Duration;
12
13use futures_util::{StreamExt, stream};
14use in_core::error::{Error, Result};
15use in_core::staging::{Staged, StagedFile};
16use in_core::store::files::{File, thumb_blob_key};
17use in_core::thumbs::{MAX_SOURCE_BYTES, make_thumbnail};
18use tokio::sync::{Semaphore, watch};
19
20use crate::live::Topic;
21use crate::state::AppState;
22
23/// Most files taken from the queue in one round.
24pub const BATCH: usize = 16;
25
26/// Most thumbnails made at the same time. One, because a decode may hold a whole source picture
27/// ([`MAX_SOURCE_BYTES`], 64 MiB) and its decoder buffers ([`in_core::thumbs::MAX_ALLOC_BYTES`], 256 MiB); two
28/// together could reach about 640 MiB. One keeps the peak near 320 MiB.
29pub const CONCURRENCY: usize = 1;
30
31/// Longest a decode may run before its file is marked `failed`: ten seconds.
32pub const DECODE_TIMEOUT: Duration = Duration::from_secs(10);
33
34/// The decode slots. A slot is moved into the blocking decode, so it is released when the decoder returns,
35/// not when the caller stops waiting. A timed-out decode that still runs keeps its slot, and no other decode
36/// starts beside it, so stragglers cannot pile up.
37static DECODE_SLOTS: LazyLock<Arc<Semaphore>> =
38 LazyLock::new(|| Arc::new(Semaphore::new(CONCURRENCY)));
39
40/// How long the worker waits when the queue is empty before it looks again.
41pub const IDLE: Duration = Duration::from_secs(30);
42
43/// Largest thumbnail the worker stores. A 320 pixel lossless WebP is far below this.
44const MAX_THUMB_BYTES: u64 = 8 * 1024 * 1024;
45
46/// Runs rounds until the stop flag is set. A round that found work is followed at once by the next one.
47pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) {
48 loop {
49 let handled = match work_batch(&state).await {
50 Ok(count) => count,
51 Err(error) => {
52 tracing::warn!(error = %error, "thumbs: round failed");
53 0
54 }
55 };
56 let pause = if handled == 0 { IDLE } else { Duration::ZERO };
57 tokio::select! {
58 _ = stop.wait_for(|stopped| *stopped) => return,
59 () = tokio::time::sleep(pause) => {}
60 }
61 }
62}
63
64/// One round: up to [`BATCH`] pending files, [`CONCURRENCY`] at a time. Returns how many files it took.
65async fn work_batch(state: &AppState) -> Result<usize> {
66 let files = state.store.pending_thumbs(BATCH).await?;
67 let count = files.len();
68 stream::iter(files)
69 .for_each_concurrent(CONCURRENCY, |file| make_one(state, file))
70 .await;
71 Ok(count)
72}
73
74/// Makes the thumbnail of one file and records the outcome. Every taken file leaves `pending`, so the queue
75/// always shrinks.
76async fn make_one(state: &AppState, file: File) {
77 let outcome = build(state, &file).await;
78 let word = match outcome {
79 Ok(()) => "ready",
80 Err(ref error) => {
81 tracing::info!(file = %file.id, error = %error, "thumbs: no thumbnail");
82 "failed"
83 }
84 };
85 match state.store.set_thumb_state(&file.id, word).await {
86 Ok(true) => {}
87 Ok(false) => {
88 // The file was purged while its thumbnail was made. Its bytes are not named by any row now.
89 if word == "ready" {
90 let _ = state.blobs.delete(&thumb_blob_key(&file.id)).await;
91 }
92 }
93 Err(error) => tracing::warn!(file = %file.id, error = %error, "thumbs: state not saved"),
94 }
95 state.live.bump(&Topic::Drive(file.owner.clone()));
96}
97
98/// Decodes the stored picture and stores its thumbnail. Any failure is returned, and the caller marks the
99/// file `failed`.
100async fn build(state: &AppState, file: &File) -> Result<()> {
101 let size = u64::try_from(file.size).unwrap_or(u64::MAX);
102 if size > MAX_SOURCE_BYTES {
103 return Err(Error::Invalid("too_large".into()));
104 }
105 let source = read_source(state, file, size).await?;
106 let slot = Arc::clone(&DECODE_SLOTS)
107 .acquire_owned()
108 .await
109 .map_err(|e| Error::Io(std::io::Error::other(e)))?;
110 // The decoder is CPU work: it runs on a blocking thread, never on the async runtime.
111 let decode = tokio::task::spawn_blocking(move || {
112 let _slot = slot;
113 make_thumbnail(&source)
114 });
115 let webp = match tokio::time::timeout(DECODE_TIMEOUT, decode).await {
116 Ok(joined) => joined.map_err(|e| Error::Io(std::io::Error::other(e)))??,
117 // A blocking task cannot be stopped. Its result is dropped with the handle, and its slot is held
118 // until it returns.
119 Err(_) => return Err(Error::Invalid("decode_timeout".into())),
120 };
121 let mut staged = StagedFile::create(&state.config.data_dir, MAX_THUMB_BYTES).await?;
122 if let Err(error) = staged.write(&webp).await {
123 staged.abort().await;
124 return Err(error);
125 }
126 let Staged { path, .. } = staged.finish().await?;
127 if let Err(error) = state.blobs.put_file(&thumb_blob_key(&file.id), &path).await {
128 let _ = tokio::fs::remove_file(&path).await;
129 return Err(error);
130 }
131 Ok(())
132}
133
134/// The whole stored picture, read in frames. `size` is at most [`MAX_SOURCE_BYTES`].
135async fn read_source(state: &AppState, file: &File, size: u64) -> Result<Vec<u8>> {
136 let mut frames = state.blobs.open_range(&file.blob_key, 0, size).await?;
137 let mut bytes = Vec::with_capacity(size as usize);
138 while let Some(frame) = frames.next().await {
139 bytes.extend_from_slice(&frame?);
140 }
141 Ok(bytes)
142}
143
144#[cfg(test)]
145mod tests {
146 use super::*;
147 use crate::auth::test_support::signed_in;
148 use crate::boot::test_state;
149 use in_core::quota::DEFAULT_MEMBER_QUOTA;
150 use in_core::staging::{Staged, StagedFile};
151 use in_core::store::files::{NewFile, files_blob_key};
152 use in_core::store::new_id;
153
154 /// A PNG whose header claims 100000 by 100000 pixels, with valid chunk checksums.
155 const BOMB_PNG: &[u8] = &[
156 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44,
157 0x52, 0x00, 0x01, 0x86, 0xa0, 0x00, 0x01, 0x86, 0xa0, 0x08, 0x06, 0x00, 0x00, 0x00, 0xa8,
158 0x52, 0x0b, 0xc8, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x60,
159 0x60, 0x60, 0x60, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0xa5, 0xf6, 0x45, 0x40, 0x00, 0x00,
160 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
161 ];
162
163 /// A decompression bomb is marked `failed`, nothing is stored for it, and the queue is empty afterwards.
164 #[tokio::test]
165 async fn a_decompression_bomb_is_marked_failed_without_a_thumbnail() {
166 let (_dir, state) = test_state().await;
167 let _ = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await;
168 let id = new_id();
169 let mut staged = StagedFile::create(&state.config.data_dir, 1 << 20)
170 .await
171 .expect("staging");
172 staged.write(BOMB_PNG).await.expect("write");
173 let Staged { path, sha256, .. } = staged.finish().await.expect("finish");
174 state
175 .blobs
176 .put_file(&files_blob_key(&id), &path)
177 .await
178 .expect("blob");
179 state
180 .store
181 .insert_file(NewFile {
182 id: id.clone(),
183 owner: "ann".into(),
184 folder: None,
185 name: "bomb.png".into(),
186 mime: "image/png".into(),
187 size: BOMB_PNG.len() as i64,
188 sha256,
189 staged_claims: 0,
190 })
191 .await
192 .expect("row");
193
194 assert_eq!(work_batch(&state).await.expect("round"), 1);
195 let file = state.store.file(&id).await.expect("read").expect("row");
196 assert_eq!(file.thumb_state, "failed");
197 assert_eq!(
198 state.blobs.size(&thumb_blob_key(&id)).await.expect("size"),
199 None
200 );
201 assert_eq!(work_batch(&state).await.expect("round"), 0);
202 }
203}