cache_retired.rs (2742B)
1 use super::{SqliteStorage, cache}; 2 use radroots_storage::{ 3 Error, 4 event::EventSourceToken, 5 projection::{ 6 ProjectionGeneration, ProjectionId, 7 cache::{ProjectionCacheCollection, ProjectionCacheScope}, 8 }, 9 }; 10 use sqlx::{Sqlite, Transaction}; 11 12 const SELECTION: &str = "SELECT CASE WHEN length(generation)=32 THEN generation END 13 FROM radroots_runtime_projection_generations INDEXED BY radroots_runtime_projection_retired_generation_idx 14 WHERE projection_id=? AND phase='retired' AND (? IS NULL OR generation!=?) 15 ORDER BY generation LIMIT 1"; 16 17 async fn next( 18 transaction: &mut Transaction<'_, Sqlite>, 19 id: &ProjectionId, 20 active: Option<ProjectionGeneration>, 21 ) -> Result<Option<ProjectionGeneration>, Error> { 22 let active = active.map(|generation| generation.as_bytes().to_vec()); 23 let value: Option<Option<Vec<u8>>> = sqlx::query_scalar(SELECTION) 24 .bind(id.as_str()) 25 .bind(active.clone()) 26 .bind(active) 27 .fetch_optional(&mut **transaction) 28 .await 29 .map_err(cache::map)?; 30 value 31 .map(|value| { 32 let bytes = value.ok_or(Error::CorruptProjectionRecord)?; 33 ProjectionGeneration::new( 34 bytes 35 .try_into() 36 .map_err(|_| Error::CorruptProjectionRecord)?, 37 ) 38 .map_err(|_| Error::CorruptProjectionRecord) 39 }) 40 .transpose() 41 } 42 43 pub(super) async fn collect( 44 store: &SqliteStorage, 45 id: ProjectionId, 46 source: EventSourceToken, 47 active: Option<ProjectionGeneration>, 48 ) -> Result<ProjectionCacheCollection, Error> { 49 store.require_projection_writer()?; 50 let mut transaction = store 51 .pool() 52 .begin_with("BEGIN IMMEDIATE") 53 .await 54 .map_err(cache::map)?; 55 cache::fence_owner(&mut transaction, store, &id, source, active).await?; 56 if !cache::owner(&mut transaction, &id).await? { 57 return Err(Error::ProjectionRevisionConflict); 58 } 59 let mut result = if let Some(retired) = next(&mut transaction, &id, active).await? { 60 cache::collect_in( 61 &mut transaction, 62 store, 63 &ProjectionCacheScope::new(id.clone(), retired, source, active)?, 64 cache::CollectionKind::Generation, 65 ) 66 .await? 67 } else { 68 ProjectionCacheCollection { 69 removed_rows: 0, 70 removed_value_bytes: 0, 71 more: false, 72 usage: cache::usage(&mut transaction).await?, 73 } 74 }; 75 result.more |= next(&mut transaction, &id, active).await?.is_some(); 76 transaction.commit().await.map_err(cache::map)?; 77 Ok(result) 78 } 79 80 #[cfg(test)] 81 #[path = "cache_retired_owner_tests.rs"] 82 mod tests;