absurder-sql 0.1.23

AbsurderSQL - SQLite + IndexedDB that's absurdly better than absurd-sql
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! Constructor functions for BlockStorage
//! This module contains platform-specific constructor implementations

#[cfg(target_arch = "wasm32")]
use super::block_storage::{BlockStorage, DEFAULT_CACHE_CAPACITY, RecoveryReport};
#[cfg(target_arch = "wasm32")]
use super::metadata::{ChecksumAlgorithm, ChecksumManager};
#[cfg(target_arch = "wasm32")]
use super::vfs_sync;
#[cfg(target_arch = "wasm32")]
use crate::types::DatabaseError;
#[cfg(target_arch = "wasm32")]
use std::cell::RefCell;
#[cfg(target_arch = "wasm32")]
use std::collections::{HashMap, HashSet, VecDeque};
#[cfg(target_arch = "wasm32")]
use std::sync::Arc;

// On-disk JSON schema for fs_persist
#[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
#[derive(serde::Serialize, serde::Deserialize, Default)]
#[allow(dead_code)]
struct FsAlloc {
    allocated: Vec<u64>,
}

#[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
#[derive(serde::Serialize, serde::Deserialize, Default)]
#[allow(dead_code)]
struct FsDealloc {
    tombstones: Vec<u64>,
}

/// Create a new BlockStorage instance for WASM platform
#[cfg(target_arch = "wasm32")]
pub async fn new_wasm(db_name: &str) -> Result<BlockStorage, DatabaseError> {
    log::info!("Creating BlockStorage for database: {}", db_name);

    // Perform IndexedDB recovery scan first
    let recovery_performed = super::wasm_indexeddb::perform_indexeddb_recovery_scan(db_name)
        .await
        .unwrap_or(false);
    if recovery_performed {
        log::info!("IndexedDB recovery scan completed for: {}", db_name);
    }

    // Try to restore from IndexedDB
    match super::wasm_indexeddb::restore_from_indexeddb(db_name).await {
        Ok(_) => log::info!(
            "Successfully restored BlockStorage from IndexedDB for: {}",
            db_name
        ),
        Err(e) => log::warn!(
            "IndexedDB restoration failed for {}: {}",
            db_name,
            e.message
        ),
    }

    // Debug: Log what's in global storage after restoration
    vfs_sync::with_global_storage(|storage_map| {
        if let Some(db_storage) = storage_map.borrow().get(db_name) {
            #[cfg(target_arch = "wasm32")]
            web_sys::console::log_1(
                &format!(
                    "DEBUG: After restoration, database {} has {} blocks in global storage",
                    db_name,
                    db_storage.len()
                )
                .into(),
            );
            for (block_id, data) in db_storage.iter() {
                let preview = if data.len() >= 16 {
                    format!(
                        "{:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x}",
                        data[0],
                        data[1],
                        data[2],
                        data[3],
                        data[4],
                        data[5],
                        data[6],
                        data[7],
                        data[8],
                        data[9],
                        data[10],
                        data[11],
                        data[12],
                        data[13],
                        data[14],
                        data[15]
                    )
                } else {
                    "short".to_string()
                };
                #[cfg(target_arch = "wasm32")]
                web_sys::console::log_1(
                    &format!(
                        "DEBUG: Block {} preview after restoration: {}",
                        block_id, preview
                    )
                    .into(),
                );

                // CRITICAL: Check SQLite magic bytes on block 0
                if *block_id == 0 {
                    let is_valid = data.len() >= 16 && &data[0..16] == b"SQLite format 3\0";
                    #[cfg(target_arch = "wasm32")]
                    web_sys::console::log_1(
                        &format!("DEBUG: Block 0 SQLite header valid: {}", is_valid).into(),
                    );
                }
            }

            #[cfg(target_arch = "wasm32")]
            web_sys::console::log_1(
                &format!(
                    "DEBUG: Found {} blocks in global storage for pre-population",
                    db_storage.len()
                )
                .into(),
            );
        } else {
            #[cfg(target_arch = "wasm32")]
            web_sys::console::log_1(
                &format!(
                    "DEBUG: After restoration, no blocks found for database {}",
                    db_name
                )
                .into(),
            );
        }
    });

    // In fs_persist mode, proactively ensure the on-disk structure exists for this DB
    // so tests that inspect the filesystem right after first sync can find the blocks dir.
    #[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
    {
        let mut db_dir = fs_base_dir.clone();
        db_dir.push(db_name);
        let _ = fs::create_dir_all(&db_dir);
        let mut blocks_dir = db_dir.clone();
        blocks_dir.push("blocks");
        let _ = fs::create_dir_all(&blocks_dir);
        println!(
            "[fs] init base_dir={:?}, db_dir={:?}, blocks_dir={:?}",
            fs_base_dir, db_dir, blocks_dir
        );
        // Ensure metadata.json exists
        let mut meta_path = db_dir.clone();
        meta_path.push("metadata.json");
        if fs::metadata(&meta_path).is_err() {
            if let Ok(mut f) = fs::File::create(&meta_path) {
                let _ = f.write_all(br#"{"entries":[]}"#);
            }
        }
        // Ensure allocations.json exists
        let mut alloc_path = db_dir.clone();
        alloc_path.push("allocations.json");
        if fs::metadata(&alloc_path).is_err() {
            if let Ok(mut f) = fs::File::create(&alloc_path) {
                let _ = f.write_all(br#"{"allocated":[]}"#);
            }
        }
        // Ensure deallocated.json exists
        let mut dealloc_path = db_dir.clone();
        dealloc_path.push("deallocated.json");
        if fs::metadata(&dealloc_path).is_err() {
            if let Ok(mut f) = fs::File::create(&dealloc_path) {
                let _ = f.write_all(br#"{"tombstones":[]}"#);
            }
        }
    }

    // Initialize allocation tracking
    let (allocated_blocks, next_block_id) = {
        // WASM: restore allocation state from global storage
        #[cfg(target_arch = "wasm32")]
        {
            let mut allocated_blocks = HashSet::new();
            let mut next_block_id: u64 = 1;

            vfs_sync::with_global_allocation_map(|allocation_map| {
                if let Some(existing_allocations) = allocation_map.borrow().get(db_name) {
                    allocated_blocks = existing_allocations.clone();
                    next_block_id = allocated_blocks.iter().max().copied().unwrap_or(0) + 1;
                    log::info!(
                        "Restored {} allocated blocks for database: {}",
                        allocated_blocks.len(),
                        db_name
                    );
                }
            });

            (allocated_blocks, next_block_id)
        }

        // fs_persist (native): restore allocation from filesystem
        #[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
        {
            let mut path = fs_base_dir.clone();
            path.push(db_name);
            let mut alloc_path = path.clone();
            alloc_path.push("allocations.json");
            let (mut allocated_blocks, mut next_block_id) = (HashSet::new(), 1u64);
            if let Ok(mut f) = fs::File::open(&alloc_path) {
                let mut s = String::new();
                if f.read_to_string(&mut s).is_ok() {
                    if let Ok(parsed) = serde_json::from_str::<FsAlloc>(&s) {
                        for id in parsed.allocated {
                            allocated_blocks.insert(id);
                        }
                        next_block_id = allocated_blocks.iter().max().copied().unwrap_or(0) + 1;
                        log::info!(
                            "[fs] Restored {} allocated blocks for database: {}",
                            allocated_blocks.len(),
                            db_name
                        );
                    }
                }
            }
            (allocated_blocks, next_block_id)
        }

        // Native tests: restore allocation from test-global (when fs_persist is disabled)
        #[cfg(all(
            not(target_arch = "wasm32"),
            any(test, debug_assertions),
            not(feature = "fs_persist")
        ))]
        {
            let mut allocated_blocks = HashSet::new();
            let mut next_block_id: u64 = 1;

            vfs_sync::with_global_allocation_map(|allocation_map| {
                if let Some(existing_allocations) = allocation_map.get(db_name) {
                    allocated_blocks = existing_allocations.clone();
                    next_block_id = allocated_blocks.iter().max().copied().unwrap_or(0) + 1;
                    log::info!(
                        "[test] Restored {} allocated blocks for database: {}",
                        allocated_blocks.len(),
                        db_name
                    );
                }
            });

            (allocated_blocks, next_block_id)
        }

        // Native defaults
        #[cfg(all(not(target_arch = "wasm32"), not(any(test, debug_assertions))))]
        {
            (HashSet::new(), 1u64)
        }
    };

    // Initialize checksum map, restoring persisted metadata in WASM builds
    #[cfg(target_arch = "wasm32")]
    let checksums_init: HashMap<u64, u64> = {
        let mut map = HashMap::new();
        let committed = vfs_sync::with_global_commit_marker(|cm| {
            cm.borrow().get(db_name).copied().unwrap_or(0)
        });
        vfs_sync::with_global_metadata(|meta_map| {
            if let Some(db_meta) = meta_map.borrow().get(db_name) {
                for (bid, m) in db_meta.iter() {
                    if (m.version as u64) <= committed {
                        map.insert(*bid, m.checksum);
                    }
                }
                log::info!(
                    "Restored {} checksum entries for database: {}",
                    map.len(),
                    db_name
                );
            }
        });
        map
    };

    // fs_persist: restore from metadata.json
    #[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
    let checksums_init: HashMap<u64, u64> = {
        let mut map = HashMap::new();
        let mut path = fs_base_dir.clone();
        path.push(db_name);
        let mut meta_path = path.clone();
        meta_path.push("metadata.json");
        if let Ok(mut f) = fs::File::open(&meta_path) {
            let mut s = String::new();
            if f.read_to_string(&mut s).is_ok() {
                if let Ok(val) = serde_json::from_str::<serde_json::Value>(&s) {
                    if let Some(entries) = val.get("entries").and_then(|v| v.as_array()) {
                        for entry in entries.iter() {
                            if let Some(arr) = entry.as_array() {
                                if arr.len() == 2 {
                                    let id_opt = arr.get(0).and_then(|v| v.as_u64());
                                    let meta_opt = arr.get(1).and_then(|v| v.as_object());
                                    if let (Some(bid), Some(meta)) = (id_opt, meta_opt) {
                                        if let Some(csum) =
                                            meta.get("checksum").and_then(|v| v.as_u64())
                                        {
                                            map.insert(bid, csum);
                                        }
                                    }
                                }
                            }
                        }
                        log::info!("[fs] Restored checksum metadata for database: {}", db_name);
                    }
                }
            }
        }
        map
    };

    // fs_persist: restore per-block checksum algorithms from metadata.json
    #[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
    let checksum_algos_init: HashMap<u64, ChecksumAlgorithm> = {
        let mut map = HashMap::new();
        let mut path = fs_base_dir.clone();
        path.push(db_name);
        let mut meta_path = path.clone();
        meta_path.push("metadata.json");
        if let Ok(mut f) = fs::File::open(&meta_path) {
            let mut s = String::new();
            if f.read_to_string(&mut s).is_ok() {
                if let Ok(val) = serde_json::from_str::<serde_json::Value>(&s) {
                    if let Some(entries) = val.get("entries").and_then(|v| v.as_array()) {
                        for entry in entries.iter() {
                            if let Some(arr) = entry.as_array() {
                                if arr.len() == 2 {
                                    let id_opt = arr.get(0).and_then(|v| v.as_u64());
                                    let meta_opt = arr.get(1).and_then(|v| v.as_object());
                                    if let (Some(bid), Some(meta)) = (id_opt, meta_opt) {
                                        let algo_opt = meta.get("algo").and_then(|v| v.as_str());
                                        let algo = match algo_opt {
                                            Some("FastHash") => Some(ChecksumAlgorithm::FastHash),
                                            Some("CRC32") => Some(ChecksumAlgorithm::CRC32),
                                            _ => None, // tolerate invalid/missing by not inserting; will fallback to default later
                                        };
                                        if let Some(a) = algo {
                                            map.insert(bid, a);
                                        }
                                    }
                                }
                            }
                        }
                        log::info!(
                            "[fs] Restored checksum algorithms for database: {}",
                            db_name
                        );
                    }
                }
            }
        }
        map
    };

    // fs_persist: restore deallocation tombstones
    #[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
    let deallocated_init: HashSet<u64> = {
        let mut set = HashSet::new();
        let mut path = fs_base_dir.clone();
        path.push(db_name);
        let mut dealloc_path = path.clone();
        dealloc_path.push("deallocated.json");
        if let Ok(mut f) = fs::File::open(&dealloc_path) {
            let mut s = String::new();
            if f.read_to_string(&mut s).is_ok() {
                if let Ok(parsed) = serde_json::from_str::<FsDealloc>(&s) {
                    for id in parsed.tombstones {
                        set.insert(id);
                    }
                    log::info!(
                        "[fs] Restored {} deallocation tombstones for database: {}",
                        set.len(),
                        db_name
                    );
                }
            }
        }
        set
    };

    // Native tests: restore from test-global metadata (when fs_persist is disabled)
    #[cfg(all(
        not(target_arch = "wasm32"),
        any(test, debug_assertions),
        not(feature = "fs_persist")
    ))]
    let checksums_init: HashMap<u64, u64> = {
        let mut map = HashMap::new();
        let committed =
            vfs_sync::with_global_commit_marker(|cm| cm.get(db_name).copied().unwrap_or(0));
        GLOBAL_METADATA_TEST.with(|meta| {
            let meta_map = meta.borrow_mut();
            if let Some(db_meta) = meta_map.get(db_name) {
                for (bid, m) in db_meta.iter() {
                    if (m.version as u64) <= committed {
                        map.insert(*bid, m.checksum);
                    }
                }
                log::info!(
                    "[test] Restored {} checksum entries for database: {}",
                    db_meta.len(),
                    db_name
                );
            }
        });
        map
    };

    // Native tests: restore per-block algorithms (when fs_persist is disabled)
    #[cfg(all(
        not(target_arch = "wasm32"),
        any(test, debug_assertions),
        not(feature = "fs_persist")
    ))]
    let checksum_algos_init: HashMap<u64, ChecksumAlgorithm> = {
        let mut map = HashMap::new();
        let committed =
            vfs_sync::with_global_commit_marker(|cm| cm.get(db_name).copied().unwrap_or(0));
        GLOBAL_METADATA_TEST.with(|meta| {
            let meta_map = meta.borrow_mut();
            if let Some(db_meta) = meta_map.get(db_name) {
                for (bid, m) in db_meta.iter() {
                    if (m.version as u64) <= committed {
                        map.insert(*bid, m.algo);
                    }
                }
            }
        });
        map
    };

    // Native non-test: start empty
    #[cfg(all(not(target_arch = "wasm32"), not(any(test, debug_assertions))))]
    let checksums_init: HashMap<u64, u64> = HashMap::new();

    // Native non-test: start empty for algorithms
    #[cfg(all(not(target_arch = "wasm32"), not(any(test, debug_assertions))))]
    let checksum_algos_init: HashMap<u64, ChecksumAlgorithm> = HashMap::new();

    // WASM: restore per-block algorithms
    #[cfg(target_arch = "wasm32")]
    let checksum_algos_init: HashMap<u64, ChecksumAlgorithm> = {
        let mut map = HashMap::new();
        let committed = vfs_sync::with_global_commit_marker(|cm| {
            cm.borrow().get(db_name).copied().unwrap_or(0)
        });
        vfs_sync::with_global_metadata(|meta_map| {
            if let Some(db_meta) = meta_map.borrow().get(db_name) {
                for (bid, m) in db_meta.iter() {
                    if (m.version as u64) <= committed {
                        map.insert(*bid, m.algo);
                    }
                }
            }
        });
        map
    };

    // Determine default checksum algorithm from environment (fs_persist native), fallback to FastHash
    #[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
    let checksum_algo_default = match env::var("DATASYNC_CHECKSUM_ALGO").ok().as_deref() {
        Some("CRC32") => ChecksumAlgorithm::CRC32,
        _ => ChecksumAlgorithm::FastHash,
    };
    #[cfg(not(all(not(target_arch = "wasm32"), feature = "fs_persist")))]
    let checksum_algo_default = ChecksumAlgorithm::FastHash;

    Ok(BlockStorage {
        #[cfg(target_arch = "wasm32")]
        cache: RefCell::new(HashMap::new()),
        #[cfg(not(target_arch = "wasm32"))]
        cache: Mutex::new(HashMap::new()),

        #[cfg(target_arch = "wasm32")]
        dirty_blocks: Arc::new(RefCell::new(HashMap::new())),
        #[cfg(not(target_arch = "wasm32"))]
        dirty_blocks: Arc::new(Mutex::new(HashMap::new())),

        #[cfg(target_arch = "wasm32")]
        allocated_blocks: RefCell::new(allocated_blocks),
        #[cfg(not(target_arch = "wasm32"))]
        allocated_blocks: Mutex::new(allocated_blocks),

        next_block_id: std::sync::atomic::AtomicU64::new(next_block_id),
        capacity: DEFAULT_CACHE_CAPACITY,

        #[cfg(target_arch = "wasm32")]
        lru_order: RefCell::new(VecDeque::new()),
        #[cfg(not(target_arch = "wasm32"))]
        lru_order: Mutex::new(VecDeque::new()),
        checksum_manager: ChecksumManager::with_data(
            checksums_init,
            checksum_algos_init,
            checksum_algo_default,
        ),
        db_name: db_name.to_string(),
        #[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
        base_dir: fs_base_dir,

        #[cfg(all(target_arch = "wasm32", feature = "fs_persist"))]
        deallocated_blocks: RefCell::new(deallocated_init),
        #[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
        deallocated_blocks: Mutex::new(deallocated_init),
        #[cfg(all(target_arch = "wasm32", not(feature = "fs_persist")))]
        deallocated_blocks: RefCell::new(HashSet::new()),
        #[cfg(all(not(target_arch = "wasm32"), not(feature = "fs_persist")))]
        deallocated_blocks: Mutex::new(HashSet::new()),

        #[cfg(target_arch = "wasm32")]
        auto_sync_interval: RefCell::new(None),
        #[cfg(not(target_arch = "wasm32"))]
        auto_sync_interval: Mutex::new(None),

        #[cfg(not(target_arch = "wasm32"))]
        last_auto_sync: Instant::now(),

        #[cfg(target_arch = "wasm32")]
        policy: RefCell::new(None),
        #[cfg(not(target_arch = "wasm32"))]
        policy: Mutex::new(None),
        #[cfg(not(target_arch = "wasm32"))]
        auto_sync_stop: None,
        #[cfg(not(target_arch = "wasm32"))]
        auto_sync_thread: None,
        #[cfg(not(target_arch = "wasm32"))]
        debounce_thread: None,
        #[cfg(not(target_arch = "wasm32"))]
        tokio_timer_task: None,
        #[cfg(not(target_arch = "wasm32"))]
        tokio_debounce_task: None,
        #[cfg(not(target_arch = "wasm32"))]
        last_write_ms: Arc::new(AtomicU64::new(0)),
        #[cfg(not(target_arch = "wasm32"))]
        threshold_hit: Arc::new(AtomicBool::new(false)),
        #[cfg(not(target_arch = "wasm32"))]
        sync_count: Arc::new(AtomicU64::new(0)),
        #[cfg(not(target_arch = "wasm32"))]
        timer_sync_count: Arc::new(AtomicU64::new(0)),
        #[cfg(not(target_arch = "wasm32"))]
        debounce_sync_count: Arc::new(AtomicU64::new(0)),
        #[cfg(not(target_arch = "wasm32"))]
        last_sync_duration_ms: Arc::new(AtomicU64::new(0)),
        #[cfg(not(target_arch = "wasm32"))]
        sync_sender: None,
        #[cfg(not(target_arch = "wasm32"))]
        sync_receiver: None,
        recovery_report: RecoveryReport::default(),
        #[cfg(target_arch = "wasm32")]
        leader_election: std::cell::RefCell::new(None),
        observability: super::observability::ObservabilityManager::new(),
        #[cfg(feature = "telemetry")]
        metrics: None,
    })
}