kind of like tap but different and in rust
at main 77 lines 2.2 kB view raw
1use fjall::{Keyspace, OwnedWriteBatch}; 2use miette::{IntoDiagnostic, Result}; 3 4use crate::filter::{ 5 COLLECTION_PREFIX, DID_PREFIX, EXCLUDE_PREFIX, FilterConfig, FilterMode, MODE_KEY, SEP, 6 SIGNAL_PREFIX, SetUpdate, filter_key, 7}; 8 9pub fn apply_patch( 10 batch: &mut OwnedWriteBatch, 11 ks: &Keyspace, 12 mode: Option<FilterMode>, 13 dids: Option<SetUpdate>, 14 signals: Option<SetUpdate>, 15 collections: Option<SetUpdate>, 16 excludes: Option<SetUpdate>, 17) -> Result<()> { 18 if let Some(mode) = mode { 19 batch.insert(ks, MODE_KEY, rmp_serde::to_vec(&mode).into_diagnostic()?); 20 } 21 22 apply_set_update(batch, ks, DID_PREFIX, dids)?; 23 apply_set_update(batch, ks, SIGNAL_PREFIX, signals)?; 24 apply_set_update(batch, ks, COLLECTION_PREFIX, collections)?; 25 apply_set_update(batch, ks, EXCLUDE_PREFIX, excludes)?; 26 27 Ok(()) 28} 29 30fn apply_set_update( 31 batch: &mut OwnedWriteBatch, 32 ks: &Keyspace, 33 prefix: u8, 34 update: Option<SetUpdate>, 35) -> Result<()> { 36 let Some(update) = update else { return Ok(()) }; 37 38 match update { 39 SetUpdate::Set(values) => { 40 let scan_prefix = [prefix, SEP]; 41 for guard in ks.prefix(scan_prefix) { 42 let (k, _) = guard.into_inner().into_diagnostic()?; 43 batch.remove(ks, k); 44 } 45 for val in values { 46 batch.insert(ks, filter_key(prefix, &val), []); 47 } 48 } 49 SetUpdate::Patch(map) => { 50 for (val, add) in map { 51 let key = filter_key(prefix, &val); 52 if add { 53 batch.insert(ks, key, []); 54 } else { 55 batch.remove(ks, key); 56 } 57 } 58 } 59 } 60 61 Ok(()) 62} 63 64pub fn load(ks: &Keyspace) -> Result<FilterConfig> { 65 FilterConfig::load(ks) 66} 67 68pub fn read_set(ks: &Keyspace, prefix: u8) -> Result<Vec<String>> { 69 let scan_prefix = [prefix, SEP]; 70 let mut out = Vec::new(); 71 for guard in ks.prefix(scan_prefix) { 72 let (k, _) = guard.into_inner().into_diagnostic()?; 73 let val = std::str::from_utf8(&k[2..]).into_diagnostic()?.to_owned(); 74 out.push(val); 75 } 76 Ok(out) 77}