absurder_sql/storage/
allocation.rs1#[cfg(target_arch = "wasm32")]
6macro_rules! lock_mutex {
7 ($mutex:expr) => {
8 $mutex
9 .try_borrow_mut()
10 .expect("RefCell borrow failed - reentrancy detected in allocation.rs")
11 };
12}
13
14#[cfg(not(target_arch = "wasm32"))]
15macro_rules! lock_mutex {
16 ($mutex:expr) => {
17 $mutex.lock()
18 };
19}
20
21use super::block_storage::BlockStorage;
22use crate::types::DatabaseError;
23#[cfg(any(
24 target_arch = "wasm32",
25 all(not(target_arch = "wasm32"), not(feature = "fs_persist"))
26))]
27use std::collections::HashSet;
28use std::sync::atomic::Ordering;
29
30#[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
31use std::{
32 fs,
33 io::{Read, Write},
34 path::PathBuf,
35};
36
37#[cfg(any(
38 target_arch = "wasm32",
39 all(not(target_arch = "wasm32"), not(feature = "fs_persist"))
40))]
41use super::vfs_sync;
42
43#[cfg(all(not(target_arch = "wasm32"), not(feature = "fs_persist")))]
44use super::block_storage::GLOBAL_METADATA_TEST;
45
46#[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
48#[derive(serde::Serialize, serde::Deserialize, Default)]
49#[allow(dead_code)]
50struct FsAlloc {
51 allocated: Vec<u64>,
52}
53
54#[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
55#[derive(serde::Serialize, serde::Deserialize, Default)]
56#[allow(dead_code)]
57struct FsDealloc {
58 tombstones: Vec<u64>,
59}
60
61pub async fn allocate_block_impl(storage: &mut BlockStorage) -> Result<u64, DatabaseError> {
63 let block_id = storage.next_block_id.fetch_add(1, Ordering::SeqCst);
65
66 lock_mutex!(storage.allocated_blocks).insert(block_id);
68
69 #[cfg(target_arch = "wasm32")]
71 {
72 vfs_sync::with_global_allocation_map(|allocation_map| {
73 let mut map = allocation_map.borrow_mut();
74 let db_allocations = map
75 .entry(storage.db_name.clone())
76 .or_insert_with(HashSet::new);
77 db_allocations.insert(block_id);
78 });
79 }
80
81 #[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
83 {
84 let base: PathBuf = storage.base_dir.clone();
85 let mut db_dir = base.clone();
86 db_dir.push(&storage.db_name);
87 let _ = fs::create_dir_all(&db_dir);
88 let mut blocks_dir = db_dir.clone();
90 blocks_dir.push("blocks");
91 let _ = fs::create_dir_all(&blocks_dir);
92 let mut alloc_path = db_dir.clone();
93 alloc_path.push("allocations.json");
94 let mut alloc = FsAlloc::default();
96 if let Ok(mut f) = fs::File::open(&alloc_path) {
97 let mut s = String::new();
98 if f.read_to_string(&mut s).is_ok() {
99 let _ = serde_json::from_str::<FsAlloc>(&s).map(|a| {
100 alloc = a;
101 });
102 }
103 }
104 if !alloc.allocated.contains(&block_id) {
105 alloc.allocated.push(block_id);
106 }
107 if let Ok(mut f) = fs::File::create(&alloc_path) {
108 let _ = f.write_all(
109 serde_json::to_string(&alloc)
110 .unwrap_or_else(|_| "{}".into())
111 .as_bytes(),
112 );
113 }
114
115 let mut dealloc_path = db_dir.clone();
117 dealloc_path.push("deallocated.json");
118 lock_mutex!(storage.deallocated_blocks).remove(&block_id);
119 let mut dealloc = FsDealloc::default();
120 if let Ok(mut f) = fs::File::open(&dealloc_path) {
122 let mut s = String::new();
123 if f.read_to_string(&mut s).is_ok() {
124 let _ = serde_json::from_str::<FsDealloc>(&s).map(|d| {
125 dealloc = d;
126 });
127 }
128 }
129 dealloc.tombstones = lock_mutex!(storage.deallocated_blocks)
130 .iter()
131 .cloned()
132 .collect();
133 dealloc.tombstones.sort_unstable();
134 if let Ok(mut f) = fs::File::create(&dealloc_path) {
135 let _ = f.write_all(
136 serde_json::to_string(&dealloc)
137 .unwrap_or_else(|_| "{}".into())
138 .as_bytes(),
139 );
140 }
141 }
142
143 #[cfg(all(not(target_arch = "wasm32"), not(feature = "fs_persist")))]
145 {
146 vfs_sync::with_global_allocation_map(|allocation_map| {
147 let mut map = allocation_map.borrow_mut();
148 let db_allocations = map
149 .entry(storage.db_name.clone())
150 .or_insert_with(HashSet::new);
151 db_allocations.insert(block_id);
152 });
153 }
154
155 #[cfg(feature = "telemetry")]
157 if let Some(ref metrics) = storage.metrics {
158 metrics.blocks_allocated_total().inc();
159 let total_memory = (lock_mutex!(storage.allocated_blocks).len() as f64)
161 * (super::block_storage::BLOCK_SIZE as f64);
162 metrics.memory_bytes().set(total_memory);
163 }
164
165 log::info!(
166 "Allocated block: {} (total allocated: {})",
167 block_id,
168 lock_mutex!(storage.allocated_blocks).len()
169 );
170 Ok(block_id)
171}
172
173pub async fn deallocate_block_impl(
175 storage: &mut BlockStorage,
176 block_id: u64,
177) -> Result<(), DatabaseError> {
178 if !lock_mutex!(storage.allocated_blocks).contains(&block_id) {
180 return Err(DatabaseError::new(
181 "BLOCK_NOT_ALLOCATED",
182 &format!("Block {} is not allocated", block_id),
183 ));
184 }
185
186 lock_mutex!(storage.allocated_blocks).remove(&block_id);
188
189 lock_mutex!(storage.cache).remove(&block_id);
191 lock_mutex!(storage.dirty_blocks).remove(&block_id);
192 storage.checksum_manager.remove_checksum(block_id);
194
195 #[cfg(target_arch = "wasm32")]
197 {
198 vfs_sync::with_global_storage(|storage_map| {
199 if let Some(db_storage) = storage_map.borrow_mut().get_mut(&storage.db_name) {
200 db_storage.remove(&block_id);
201 }
202 });
203
204 vfs_sync::with_global_allocation_map(|allocation_map| {
205 if let Some(db_allocations) = allocation_map.borrow_mut().get_mut(&storage.db_name) {
206 db_allocations.remove(&block_id);
207 }
208 });
209
210 vfs_sync::with_global_metadata(|meta_map| {
212 if let Some(db_meta) = meta_map.borrow_mut().get_mut(&storage.db_name) {
213 db_meta.remove(&block_id);
214 }
215 });
216 }
217
218 #[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
220 {
221 let base: PathBuf = storage.base_dir.clone();
222 let mut db_dir = base.clone();
223 db_dir.push(&storage.db_name);
224 let mut blocks_dir = db_dir.clone();
225 blocks_dir.push("blocks");
226 let mut block_path = blocks_dir.clone();
227 block_path.push(format!("block_{}.bin", block_id));
228 let _ = fs::remove_file(&block_path);
229
230 let mut alloc_path = db_dir.clone();
232 alloc_path.push("allocations.json");
233 let mut alloc = FsAlloc::default();
234 if let Ok(mut f) = fs::File::open(&alloc_path) {
235 let mut s = String::new();
236 if f.read_to_string(&mut s).is_ok() {
237 let _ = serde_json::from_str::<FsAlloc>(&s).map(|a| {
238 alloc = a;
239 });
240 }
241 }
242 alloc.allocated.retain(|&id| id != block_id);
243 if let Ok(mut f) = fs::File::create(&alloc_path) {
244 let _ = f.write_all(
245 serde_json::to_string(&alloc)
246 .unwrap_or_else(|_| "{}".into())
247 .as_bytes(),
248 );
249 }
250
251 let mut meta_path = db_dir.clone();
253 meta_path.push("metadata.json");
254 let mut meta_val: serde_json::Value = serde_json::json!({"entries": []});
256 if let Ok(mut f) = fs::File::open(&meta_path) {
257 let mut s = String::new();
258 if f.read_to_string(&mut s).is_ok() {
259 if let Ok(v) = serde_json::from_str::<serde_json::Value>(&s) {
260 meta_val = v;
261 }
262 }
263 }
264 if !meta_val.is_object() {
265 meta_val = serde_json::json!({"entries": []});
266 }
267 if let Some(entries) = meta_val.get_mut("entries").and_then(|v| v.as_array_mut()) {
268 entries.retain(|ent| {
269 ent.as_array()
270 .and_then(|arr| arr.first())
271 .and_then(|v| v.as_u64())
272 .map(|bid| bid != block_id)
273 .unwrap_or(true)
274 });
275 }
276 let meta_string = serde_json::to_string(&meta_val).unwrap_or_else(|_| "{}".into());
277 if let Ok(mut f) = fs::File::create(&meta_path) {
278 let _ = f.write_all(meta_string.as_bytes());
279 }
280
281 let mut dealloc_path = db_dir.clone();
283 dealloc_path.push("deallocated.json");
284 lock_mutex!(storage.deallocated_blocks).insert(block_id);
285 let mut dealloc = FsDealloc::default();
286 if let Ok(mut f) = fs::File::open(&dealloc_path) {
287 let mut s = String::new();
288 if f.read_to_string(&mut s).is_ok() {
289 let _ = serde_json::from_str::<FsDealloc>(&s).map(|d| {
290 dealloc = d;
291 });
292 }
293 }
294 dealloc.tombstones = lock_mutex!(storage.deallocated_blocks)
295 .iter()
296 .cloned()
297 .collect();
298 dealloc.tombstones.sort_unstable();
299 if let Ok(mut f) = fs::File::create(&dealloc_path) {
300 let _ = f.write_all(
301 serde_json::to_string(&dealloc)
302 .unwrap_or_else(|_| "{}".into())
303 .as_bytes(),
304 );
305 }
306 }
307
308 #[cfg(all(not(target_arch = "wasm32"), not(feature = "fs_persist")))]
310 {
311 vfs_sync::with_global_storage(|gs| {
312 let mut storage_map = gs.borrow_mut();
313 if let Some(db_storage) = storage_map.get_mut(&storage.db_name) {
314 db_storage.remove(&block_id);
315 }
316 });
317
318 vfs_sync::with_global_allocation_map(|allocation_map| {
319 if let Some(db_allocations) = allocation_map.borrow_mut().get_mut(&storage.db_name) {
320 db_allocations.remove(&block_id);
321 }
322 });
323
324 GLOBAL_METADATA_TEST.with(|meta| {
325 let mut meta_map = meta.lock();
326 if let Some(db_meta) = meta_map.get_mut(&storage.db_name) {
327 db_meta.remove(&block_id);
328 }
329 });
330 }
331
332 let current = storage.next_block_id.load(Ordering::SeqCst);
334 if block_id < current {
335 storage.next_block_id.store(block_id, Ordering::SeqCst);
336 }
337
338 #[cfg(feature = "telemetry")]
340 if let Some(ref metrics) = storage.metrics {
341 metrics.blocks_deallocated_total().inc();
342 let total_memory = (lock_mutex!(storage.allocated_blocks).len() as f64)
344 * (super::block_storage::BLOCK_SIZE as f64);
345 metrics.memory_bytes().set(total_memory);
346 }
347
348 log::info!(
349 "Deallocated block: {} (total allocated: {})",
350 block_id,
351 lock_mutex!(storage.allocated_blocks).len()
352 );
353 Ok(())
354}