|
1 | 1 | //! Blob records: what's stored under each SHA-256, whether its bytes have arrived, and an image's size and pixel |
2 | 2 | //! fingerprint (cached on first use). |
3 | 3 |
|
| 4 | +use std::collections::HashMap; |
| 5 | + |
| 6 | +use futures_util::stream::{self, StreamExt}; |
4 | 7 | use laravel::db; |
5 | 8 | use laravel::model::update; |
6 | 9 |
|
@@ -148,22 +151,119 @@ pub async fn put(store: &BlobStore, bytes: Vec<u8>, content_type: &str) -> larav |
148 | 151 | Ok(blob) |
149 | 152 | } |
150 | 153 |
|
| 154 | +/// An image file's pixel fingerprint, width and height. |
| 155 | +pub type ImageInfo = (String, u32, u32); |
| 156 | + |
| 157 | +/// Decode an image and fingerprint its pixels. CPU-bound, so it runs on the blocking pool ([`decode`]): it gets only |
| 158 | +/// the bytes, and calls nothing that needs the app's context (the database, the cache, `laravel::now()`). |
| 159 | +fn decode_image(sha256: &str, bytes: &[u8]) -> Result<ImageInfo, String> { |
| 160 | + let image = visualci_core::image_hash::decode(bytes).map_err(|e| format!("{sha256}: {e}"))?.to_rgba8(); |
| 161 | + let fp = visualci_core::image_hash::fingerprint_rgba(&image); |
| 162 | + let (w, h) = image.dimensions(); |
| 163 | + Ok((fp, w, h)) |
| 164 | +} |
| 165 | + |
| 166 | +/// [`decode_image`] off the async runtime's threads, so a large image (or hundreds of them) never stalls the other |
| 167 | +/// work on the runtime, such as the processing lock's heartbeat. |
| 168 | +async fn decode(sha256: String, bytes: Vec<u8>) -> Result<ImageInfo, String> { |
| 169 | + tokio::task::spawn_blocking(move || decode_image(&sha256, &bytes)) |
| 170 | + .await |
| 171 | + .map_err(|e| format!("decoding the image stopped: {e}"))? |
| 172 | +} |
| 173 | + |
| 174 | +/// Fingerprint image files: up to `concurrency` downloads (`fetch`) at a time, in the calling task, each file decoded |
| 175 | +/// on the blocking pool. Each file's fingerprint and size, or why it couldn't be read. |
| 176 | +pub async fn fingerprint_files<F, Fut>( |
| 177 | + shas: Vec<String>, |
| 178 | + concurrency: usize, |
| 179 | + fetch: F, |
| 180 | +) -> HashMap<String, Result<ImageInfo, String>> |
| 181 | +where |
| 182 | + F: Fn(String) -> Fut, |
| 183 | + Fut: Future<Output = laravel::Result<Vec<u8>>>, |
| 184 | +{ |
| 185 | + stream::iter(shas) |
| 186 | + .map(|sha| { |
| 187 | + let fetched = fetch(sha.clone()); |
| 188 | + async move { |
| 189 | + let info = match fetched.await { |
| 190 | + Ok(bytes) => decode(sha.clone(), bytes).await, |
| 191 | + Err(e) => Err(e.to_string()), |
| 192 | + }; |
| 193 | + (sha, info) |
| 194 | + } |
| 195 | + }) |
| 196 | + .buffer_unordered(concurrency.max(1)) |
| 197 | + .collect() |
| 198 | + .await |
| 199 | +} |
| 200 | + |
| 201 | +/// Each image blob's pixel fingerprint and size: the one on its row, or computed from the file |
| 202 | +/// ([`fingerprint_files`], `VISUALCI_FINGERPRINT_CONCURRENCY` at a time) and written to the rows in a few statements. |
| 203 | +/// A fingerprint already on a row stays (only a missing size is added). |
| 204 | +/// |
| 205 | +/// # Errors |
| 206 | +/// On a database error. A file that can't be downloaded or decoded is its own `Err` in the map. |
| 207 | +pub async fn image_infos( |
| 208 | + blobs: Vec<Blob>, |
| 209 | + store: &BlobStore, |
| 210 | +) -> laravel::Result<HashMap<String, Result<ImageInfo, String>>> { |
| 211 | + let mut infos = HashMap::new(); |
| 212 | + let mut known: HashMap<String, Option<String>> = HashMap::new(); |
| 213 | + for blob in blobs { |
| 214 | + match (&blob.pixel_fingerprint, blob.width, blob.height) { |
| 215 | + (Some(fp), Some(w), Some(h)) => { |
| 216 | + infos.insert(blob.sha256.clone(), Ok((fp.clone(), dimension(w), dimension(h)))); |
| 217 | + } |
| 218 | + _ => { |
| 219 | + known.insert(blob.sha256.clone(), blob.pixel_fingerprint.clone()); |
| 220 | + } |
| 221 | + } |
| 222 | + } |
| 223 | + if known.is_empty() { |
| 224 | + return Ok(infos); |
| 225 | + } |
| 226 | + let concurrency = laravel::config().section::<crate::config::Processing>().fingerprint_concurrency; |
| 227 | + let shas: Vec<String> = known.keys().cloned().collect(); |
| 228 | + let computed = fingerprint_files(shas, concurrency, |sha| async move { store.get(&sha).await }).await; |
| 229 | + let mut rows: Vec<(String, String, i32, i32)> = Vec::new(); |
| 230 | + for (sha, info) in computed { |
| 231 | + let info = info.map(|(fp, w, h)| (known.get(&sha).cloned().flatten().unwrap_or(fp), w, h)); |
| 232 | + if let Ok((fp, w, h)) = &info { |
| 233 | + rows.push(( |
| 234 | + sha.clone(), |
| 235 | + fp.clone(), |
| 236 | + i32::try_from(*w).unwrap_or(i32::MAX), |
| 237 | + i32::try_from(*h).unwrap_or(i32::MAX), |
| 238 | + )); |
| 239 | + } |
| 240 | + if let Err(e) = &info { |
| 241 | + tracing::warn!(blob = %sha, error = %e, "an image file couldn't be fingerprinted"); |
| 242 | + } |
| 243 | + infos.insert(sha, info); |
| 244 | + } |
| 245 | + for chunk in rows.chunks(5_000) { |
| 246 | + db::query!( |
| 247 | + "UPDATE blobs b SET pixel_fingerprint = COALESCE(b.pixel_fingerprint, v.fingerprint), width = v.width, \ |
| 248 | + height = v.height, updated_at = now() \ |
| 249 | + FROM (VALUES {...chunk(0, 1, 2, 3)}) AS v (sha256, fingerprint, width, height) WHERE b.sha256 = v.sha256" |
| 250 | + ) |
| 251 | + .update() |
| 252 | + .await?; |
| 253 | + } |
| 254 | + Ok(infos) |
| 255 | +} |
| 256 | + |
| 257 | +fn dimension(n: i32) -> u32 { |
| 258 | + u32::try_from(n).unwrap_or(0) |
| 259 | +} |
| 260 | + |
151 | 261 | /// The image's pixel fingerprint and size, computed (and cached on the row) on first use. |
152 | 262 | /// |
153 | 263 | /// # Errors |
154 | 264 | /// When the blob is missing or isn't an image. |
155 | | -pub async fn image_info(mut blob: Blob, store: &BlobStore) -> laravel::Result<(String, u32, u32)> { |
156 | | - if let (Some(fp), Some(w), Some(h)) = (&blob.pixel_fingerprint, blob.width, blob.height) { |
157 | | - return Ok((fp.clone(), u32::try_from(w).unwrap_or(0), u32::try_from(h).unwrap_or(0))); |
158 | | - } |
159 | | - let bytes = store.get(&blob.sha256).await?; |
160 | | - let image = visualci_core::image_hash::decode(&bytes) |
161 | | - .map_err(|e| laravel::Error::msg(format!("{}: {e}", blob.sha256)))? |
162 | | - .to_rgba8(); |
163 | | - let fp = visualci_core::image_hash::fingerprint_rgba(&image); |
164 | | - let (w, h) = image.dimensions(); |
165 | | - let pixel_fingerprint = Some(fp.clone()); |
166 | | - let (width, height) = (Some(i32::try_from(w).unwrap_or(i32::MAX)), Some(i32::try_from(h).unwrap_or(i32::MAX))); |
167 | | - update!(blob { pixel_fingerprint, width, height }).await?; |
168 | | - Ok((fp, w, h)) |
| 265 | +pub async fn image_info(blob: Blob, store: &BlobStore) -> laravel::Result<ImageInfo> { |
| 266 | + let sha = blob.sha256.clone(); |
| 267 | + let mut infos = image_infos(vec![blob], store).await?; |
| 268 | + infos.remove(&sha).unwrap_or_else(|| Err(format!("{sha}: not read"))).map_err(laravel::Error::msg) |
169 | 269 | } |
0 commit comments