lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

lib.rs (8587B)


      1 #![doc = include_str!("../README.md")]
      2 #![forbid(unsafe_code)]
      3 
      4 use core::fmt;
      5 use radroots_storage::event::SourceGeneration;
      6 
      7 #[cfg(target_arch = "wasm32")]
      8 mod browser;
      9 #[cfg(target_arch = "wasm32")]
     10 pub use browser::Database;
     11 
     12 #[cfg(all(feature = "workspace", target_arch = "wasm32"))]
     13 pub use browser::{ReadSnapshot, RecordPrefix};
     14 
     15 #[cfg(all(feature = "workspace", target_arch = "wasm32"))]
     16 pub mod workspace;
     17 
     18 /// Maximum opaque record size; private codecs must enforce their lower limit.
     19 pub const RECORD_BYTES_MAX: usize = 64 * 1024;
     20 /// Maximum atomic batch width.
     21 pub const BATCH_RECORDS_MAX: usize = 32;
     22 /// Maximum retained input bytes across accepted work on one connection.
     23 pub const LIVE_BYTES_MAX: usize = 4 * 1024 * 1024;
     24 
     25 /// Fixed source-redacted host errors. No browser exception message is exposed.
     26 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
     27 #[non_exhaustive]
     28 pub enum Error {
     29     InvalidInput,
     30     Unavailable,
     31     MissingNamespace,
     32     NamespaceExists,
     33     IncompatibleSchema,
     34     Closed,
     35     Capacity,
     36     Conflict,
     37     GuardRefused,
     38     CorruptRecord,
     39     Aborted,
     40     CommitUnknown,
     41 }
     42 impl Error {
     43     pub const fn code(self) -> &'static str {
     44         match self {
     45             Self::InvalidInput => "invalid_input",
     46             Self::Unavailable => "indexeddb_unavailable",
     47             Self::MissingNamespace => "missing_namespace",
     48             Self::NamespaceExists => "namespace_exists",
     49             Self::IncompatibleSchema => "incompatible_schema",
     50             Self::Closed => "closed",
     51             Self::Capacity => "capacity_exhausted",
     52             Self::Conflict => "record_conflict",
     53             Self::GuardRefused => "transaction_precondition_refused",
     54             Self::CorruptRecord => "corrupt_record",
     55             Self::Aborted => "transaction_aborted",
     56             Self::CommitUnknown => "commit_unknown",
     57         }
     58     }
     59 }
     60 impl fmt::Display for Error {
     61     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     62         f.write_str(self.code())
     63     }
     64 }
     65 impl core::error::Error for Error {}
     66 
     67 /// Exact new-format namespace identity; never inferred from missing data.
     68 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
     69 pub struct Namespace(SourceGeneration);
     70 impl Namespace {
     71     pub const fn new(generation: SourceGeneration) -> Self {
     72         Self(generation)
     73     }
     74     pub fn name(self) -> String {
     75         use core::fmt::Write;
     76         let mut name = String::from("radroots.indexeddb.v1.");
     77         for byte in self.0.as_bytes() {
     78             let _ = write!(name, "{byte:02x}");
     79         }
     80         name
     81     }
     82 }
     83 
     84 /// Explicit first creation or exact existing-namespace opening.
     85 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
     86 pub enum OpenMode {
     87     CreateNew,
     88     Existing,
     89 }
     90 
     91 /// Opaque exact record identity, separate from any authorization claim.
     92 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
     93 pub struct RecordKey([u8; 32]);
     94 impl RecordKey {
     95     pub const fn new(bytes: [u8; 32]) -> Self {
     96         Self(bytes)
     97     }
     98     pub const fn as_bytes(&self) -> &[u8; 32] {
     99         &self.0
    100     }
    101 }
    102 
    103 /// One compare/exchange entry. None denotes absence/deletion; empty is data.
    104 /// Debug intentionally omits all bytes and identities.
    105 pub struct Mutation {
    106     key: RecordKey,
    107     expected: Option<Vec<u8>>,
    108     replacement: Option<Vec<u8>>,
    109 }
    110 impl Mutation {
    111     pub fn new(
    112         key: RecordKey,
    113         expected: Option<Vec<u8>>,
    114         replacement: Option<Vec<u8>>,
    115     ) -> Result<Self, Error> {
    116         if expected
    117             .as_ref()
    118             .is_some_and(|v| v.len() > RECORD_BYTES_MAX)
    119             || replacement
    120                 .as_ref()
    121                 .is_some_and(|v| v.len() > RECORD_BYTES_MAX)
    122         {
    123             return Err(Error::InvalidInput);
    124         }
    125         Ok(Self {
    126             key,
    127             expected,
    128             replacement,
    129         })
    130     }
    131     fn bytes(&self) -> usize {
    132         32 + self.expected.as_ref().map_or(0, Vec::len)
    133             + self.replacement.as_ref().map_or(0, Vec::len)
    134     }
    135 }
    136 impl fmt::Debug for Mutation {
    137     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    138         f.write_str("Mutation(<redacted>)")
    139     }
    140 }
    141 
    142 /// Validated bounded batch; duplicate keys are rejected before host work.
    143 pub struct Batch {
    144     entries: Vec<Mutation>,
    145     bytes: usize,
    146 }
    147 impl Batch {
    148     pub fn new(entries: Vec<Mutation>) -> Result<Self, Error> {
    149         if entries.is_empty() || entries.len() > BATCH_RECORDS_MAX {
    150             return Err(Error::InvalidInput);
    151         }
    152         let mut keys = std::collections::BTreeSet::new();
    153         let mut bytes = 0usize;
    154         for entry in &entries {
    155             if !keys.insert(entry.key) {
    156                 return Err(Error::InvalidInput);
    157             }
    158             bytes = bytes
    159                 .checked_add(entry.bytes())
    160                 .ok_or(Error::InvalidInput)?;
    161         }
    162         if bytes > LIVE_BYTES_MAX {
    163             return Err(Error::Capacity);
    164         }
    165         Ok(Self { entries, bytes })
    166     }
    167     pub const fn retained_bytes(&self) -> usize {
    168         self.bytes
    169     }
    170     pub fn len(&self) -> usize {
    171         self.entries.len()
    172     }
    173     pub fn is_empty(&self) -> bool {
    174         self.entries.is_empty()
    175     }
    176 }
    177 impl fmt::Debug for Batch {
    178     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    179         f.write_str("Batch(<redacted>)")
    180     }
    181 }
    182 
    183 /// Witness returned only after actual IndexedDB transaction completion.
    184 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    185 pub struct Commit {
    186     records: usize,
    187 }
    188 impl Commit {
    189     pub const fn records(self) -> usize {
    190         self.records
    191     }
    192 }
    193 
    194 #[cfg(test)]
    195 mod tests {
    196     use super::{
    197         BATCH_RECORDS_MAX, Batch, Error, LIVE_BYTES_MAX, Mutation, Namespace, RECORD_BYTES_MAX,
    198         RecordKey,
    199     };
    200     use radroots_storage::event::SourceGeneration;
    201     #[test]
    202     fn exact_namespace_and_bounded_redacted_batches() {
    203         let ns = Namespace::new(SourceGeneration::new([1; 32]).unwrap());
    204         assert_eq!(
    205             ns.name(),
    206             format!("radroots.indexeddb.v1.{}", "01".repeat(32))
    207         );
    208         let entry = |n, size| Mutation::new(RecordKey::new([n; 32]), None, Some(vec![7; size]));
    209         assert_eq!(RecordKey::new([2; 32]).as_bytes(), &[2; 32]);
    210         assert_eq!(
    211             entry(1, RECORD_BYTES_MAX + 1).unwrap_err(),
    212             Error::InvalidInput
    213         );
    214         assert_eq!(
    215             Mutation::new(
    216                 RecordKey::new([1; 32]),
    217                 Some(vec![0; RECORD_BYTES_MAX + 1]),
    218                 None
    219             )
    220             .unwrap_err(),
    221             Error::InvalidInput
    222         );
    223         assert_eq!(Batch::new(vec![]).unwrap_err(), Error::InvalidInput);
    224         assert_eq!(
    225             Batch::new(
    226                 (0..=BATCH_RECORDS_MAX)
    227                     .map(|n| entry(n as u8, 0).unwrap())
    228                     .collect()
    229             )
    230             .unwrap_err(),
    231             Error::InvalidInput
    232         );
    233         assert_eq!(
    234             Batch::new(vec![entry(1, 0).unwrap(), entry(1, 1).unwrap()]).unwrap_err(),
    235             Error::InvalidInput
    236         );
    237         let maximum = Batch::new(
    238             (0..BATCH_RECORDS_MAX)
    239                 .map(|n| {
    240                     Mutation::new(
    241                         RecordKey::new([n as u8; 32]),
    242                         Some(vec![0; RECORD_BYTES_MAX]),
    243                         Some(vec![1; RECORD_BYTES_MAX]),
    244                     )
    245                     .unwrap()
    246                 })
    247                 .collect(),
    248         );
    249         assert_eq!(maximum.unwrap_err(), Error::Capacity);
    250         let batch = Batch::new(vec![
    251             entry(1, RECORD_BYTES_MAX).unwrap(),
    252             Mutation::new(RecordKey::new([2; 32]), Some(vec![]), None).unwrap(),
    253         ])
    254         .unwrap();
    255         assert!(!batch.is_empty());
    256         assert_eq!(batch.len(), 2);
    257         assert_eq!(batch.retained_bytes(), RECORD_BYTES_MAX + 64);
    258         assert!(batch.retained_bytes() < LIVE_BYTES_MAX);
    259         assert_eq!(format!("{batch:?}"), "Batch(<redacted>)");
    260         assert_eq!(
    261             format!("{:?}", entry(4, 1).unwrap()),
    262             "Mutation(<redacted>)"
    263         );
    264         for error in [
    265             Error::InvalidInput,
    266             Error::Unavailable,
    267             Error::MissingNamespace,
    268             Error::NamespaceExists,
    269             Error::IncompatibleSchema,
    270             Error::Closed,
    271             Error::Capacity,
    272             Error::Conflict,
    273             Error::GuardRefused,
    274             Error::CorruptRecord,
    275             Error::Aborted,
    276             Error::CommitUnknown,
    277         ] {
    278             assert_eq!(error.to_string(), error.code());
    279         }
    280     }
    281 }