absurder_sql/storage/
metadata.rs1use crate::types::DatabaseError;
5#[cfg(not(target_arch = "wasm32"))]
6use parking_lot::Mutex;
7#[cfg(target_arch = "wasm32")]
8use std::cell::RefCell;
9use std::collections::HashMap;
10
11#[allow(unused_macros)]
13#[cfg(target_arch = "wasm32")]
14macro_rules! lock_mutex {
15 ($mutex:expr) => {
16 $mutex
17 .try_borrow_mut()
18 .expect("RefCell borrow failed - reentrancy detected in metadata.rs")
19 };
20}
21
22#[allow(unused_macros)]
23#[cfg(not(target_arch = "wasm32"))]
24macro_rules! lock_mutex {
25 ($mutex:expr) => {
26 $mutex.lock()
27 };
28}
29
30#[cfg(target_arch = "wasm32")]
31#[allow(unused_imports)]
32use js_sys::Date;
33
34#[cfg(not(target_arch = "wasm32"))]
35#[allow(unused_imports)]
36use std::time::{SystemTime, UNIX_EPOCH};
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
40#[allow(dead_code)]
41pub enum ChecksumAlgorithm {
42 FastHash,
43 CRC32,
44}
45
46#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
48pub struct BlockMetadataPersist {
49 pub checksum: u64,
50 #[allow(dead_code)]
51 pub last_modified_ms: u64,
52 #[allow(dead_code)]
53 pub version: u32,
54 #[allow(dead_code)]
55 pub algo: ChecksumAlgorithm,
56}
57
58pub struct ChecksumManager {
60 #[cfg(target_arch = "wasm32")]
61 checksums: RefCell<HashMap<u64, u64>>,
62 #[cfg(not(target_arch = "wasm32"))]
63 checksums: Mutex<HashMap<u64, u64>>,
64
65 #[cfg(target_arch = "wasm32")]
66 checksum_algos: RefCell<HashMap<u64, ChecksumAlgorithm>>,
67 #[cfg(not(target_arch = "wasm32"))]
68 checksum_algos: Mutex<HashMap<u64, ChecksumAlgorithm>>,
69
70 checksum_algo_default: ChecksumAlgorithm,
72}
73
74impl ChecksumManager {
75 pub fn new(default_algorithm: ChecksumAlgorithm) -> Self {
77 Self {
78 #[cfg(target_arch = "wasm32")]
79 checksums: RefCell::new(HashMap::new()),
80 #[cfg(not(target_arch = "wasm32"))]
81 checksums: Mutex::new(HashMap::new()),
82
83 #[cfg(target_arch = "wasm32")]
84 checksum_algos: RefCell::new(HashMap::new()),
85 #[cfg(not(target_arch = "wasm32"))]
86 checksum_algos: Mutex::new(HashMap::new()),
87
88 checksum_algo_default: default_algorithm,
89 }
90 }
91
92 pub fn with_data(
94 checksums: HashMap<u64, u64>,
95 checksum_algos: HashMap<u64, ChecksumAlgorithm>,
96 default_algorithm: ChecksumAlgorithm,
97 ) -> Self {
98 Self {
99 #[cfg(target_arch = "wasm32")]
100 checksums: RefCell::new(checksums),
101 #[cfg(not(target_arch = "wasm32"))]
102 checksums: Mutex::new(checksums),
103
104 #[cfg(target_arch = "wasm32")]
105 checksum_algos: RefCell::new(checksum_algos),
106 #[cfg(not(target_arch = "wasm32"))]
107 checksum_algos: Mutex::new(checksum_algos),
108
109 checksum_algo_default: default_algorithm,
110 }
111 }
112
113 pub fn compute_checksum_with(data: &[u8], algo: ChecksumAlgorithm) -> u64 {
115 match algo {
116 ChecksumAlgorithm::FastHash => {
117 use std::collections::hash_map::DefaultHasher;
118 use std::hash::Hash;
119 use std::hash::Hasher;
120 let mut hasher = DefaultHasher::new();
121 data.hash(&mut hasher);
122 hasher.finish()
123 }
124 ChecksumAlgorithm::CRC32 => {
125 let mut hasher = crc32fast::Hasher::new();
126 hasher.update(data);
127 hasher.finalize() as u64
128 }
129 }
130 }
131
132 pub fn store_checksum(&self, block_id: u64, data: &[u8]) {
134 let algo = {
135 let algos = lock_mutex!(self.checksum_algos);
136 algos
137 .get(&block_id)
138 .copied()
139 .unwrap_or(self.checksum_algo_default)
140 };
141 let csum = Self::compute_checksum_with(data, algo);
142 lock_mutex!(self.checksums).insert(block_id, csum);
143 lock_mutex!(self.checksum_algos).insert(block_id, algo);
144 }
145
146 pub fn validate_checksum(&self, block_id: u64, data: &[u8]) -> Result<(), DatabaseError> {
148 let expected_opt = lock_mutex!(self.checksums).get(&block_id).copied();
149 if let Some(expected) = expected_opt {
150 let algo = lock_mutex!(self.checksum_algos)
151 .get(&block_id)
152 .copied()
153 .unwrap_or(self.checksum_algo_default);
154 let actual = Self::compute_checksum_with(data, algo);
155 if expected != actual {
156 let known_algos = [ChecksumAlgorithm::FastHash, ChecksumAlgorithm::CRC32];
158 for alt in known_algos.iter().copied().filter(|a| *a != algo) {
159 let alt_sum = Self::compute_checksum_with(data, alt);
160 if expected == alt_sum {
161 return Err(DatabaseError::new(
162 "ALGO_MISMATCH",
163 &format!(
164 "Checksum algorithm mismatch for block {}: stored algo {:?}, but data matches {:?}",
165 block_id, algo, alt
166 ),
167 ));
168 }
169 }
170 return Err(DatabaseError::new(
171 "CHECKSUM_MISMATCH",
172 &format!(
173 "Checksum mismatch for block {}: expected {}, got {}",
174 block_id, expected, actual
175 ),
176 ));
177 }
178 }
179 Ok(())
180 }
181
182 pub fn remove_checksum(&self, block_id: u64) {
184 lock_mutex!(self.checksums).remove(&block_id);
185 lock_mutex!(self.checksum_algos).remove(&block_id);
186 }
187
188 pub fn get_checksum(&self, block_id: u64) -> Option<u64> {
190 lock_mutex!(self.checksums).get(&block_id).copied()
191 }
192
193 pub fn get_algorithm(&self, block_id: u64) -> ChecksumAlgorithm {
195 lock_mutex!(self.checksum_algos)
196 .get(&block_id)
197 .copied()
198 .unwrap_or(self.checksum_algo_default)
199 }
200
201 pub fn replace_all(
203 &self,
204 new_checksums: HashMap<u64, u64>,
205 new_algos: HashMap<u64, ChecksumAlgorithm>,
206 ) {
207 *lock_mutex!(self.checksums) = new_checksums;
208 *lock_mutex!(self.checksum_algos) = new_algos;
209 }
210
211 pub fn checksums(&self) -> HashMap<u64, u64> {
213 lock_mutex!(self.checksums).clone()
214 }
215
216 pub fn algorithms(&self) -> HashMap<u64, ChecksumAlgorithm> {
218 lock_mutex!(self.checksum_algos).clone()
219 }
220
221 pub fn default_algorithm(&self) -> ChecksumAlgorithm {
223 self.checksum_algo_default
224 }
225
226 pub fn set_checksum_for_testing(&self, block_id: u64, checksum: u64) {
228 lock_mutex!(self.checksums).insert(block_id, checksum);
229 }
230
231 pub fn clear_checksums(&self) {
233 lock_mutex!(self.checksums).clear();
234 lock_mutex!(self.checksum_algos).clear();
235 }
236}