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
// Checksum algorithm selection, persistence, and cleanup tests

#![cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]

use absurder_sql::storage::{BLOCK_SIZE, BlockStorage};
use serial_test::serial;
#[path = "common/mod.rs"]
mod common;
use tempfile::TempDir;
// removed unused tokio::time imports
use std::{
    collections::hash_map::DefaultHasher,
    fs,
    hash::{Hash, Hasher},
    path::PathBuf,
};

#[cfg(feature = "fs_persist")]
#[derive(serde::Deserialize)]
struct TestMetaEntry {
    checksum: u64,
    last_modified_ms: u64,
    version: u32,
    algo: String,
}

#[cfg(feature = "fs_persist")]
#[derive(serde::Deserialize)]
struct TestFsMeta {
    entries: Vec<(u64, TestMetaEntry)>,
}

// Helper to compute DefaultHasher checksum like current implementation
fn default_hasher_checksum(data: &[u8]) -> u64 {
    let mut h = DefaultHasher::new();
    data.hash(&mut h);
    h.finish()
}

#[tokio::test(flavor = "current_thread")]
#[serial]
#[cfg(feature = "fs_persist")]
async fn test_default_algo_is_fasthash_and_persisted() {
    let tmp = TempDir::new().expect("tempdir");
    common::set_var("ABSURDERSQL_FS_BASE", tmp.path());

    // Ensure no checksum algorithm is set in environment to test default behavior
    {
        let _g = common::ENV_LOCK.lock().expect("env lock poisoned");
        unsafe { std::env::remove_var("DATASYNC_CHECKSUM_ALGO") }
        drop(_g);
    }
    let db = "test_default_algo_persist";
    let mut s = BlockStorage::new_with_capacity(db, 4)
        .await
        .expect("create storage");

    let payload = vec![0xABu8; BLOCK_SIZE];
    s.write_block(1, payload).await.expect("write");
    s.sync().await.expect("sync");

    // metadata.json should include algo FastHash
    let mut meta_path = PathBuf::from(tmp.path());
    meta_path.push(db);
    meta_path.push("metadata.json");
    let text = fs::read_to_string(&meta_path).expect("read metadata.json");
    let parsed: TestFsMeta = serde_json::from_str(&text).expect("parse FsMeta");
    let entry = &parsed
        .entries
        .iter()
        .find(|(bid, _)| *bid == 1)
        .expect("entry for block 1")
        .1;
    assert_eq!(
        entry.algo.as_str(),
        "FastHash",
        "default algo should be FastHash"
    );
    assert!(entry.checksum > 0);
    // Mark unused fields as read to satisfy -D warnings while keeping schema intact
    let _ = entry.last_modified_ms;
    let _ = entry.version;
}

#[tokio::test(flavor = "current_thread")]
#[serial]
#[cfg(feature = "fs_persist")]
async fn test_crc32_algo_selection_persisted_and_used_across_instances() {
    let tmp = TempDir::new().expect("tempdir");
    common::set_var("ABSURDERSQL_FS_BASE", tmp.path());
    common::set_var("DATASYNC_CHECKSUM_ALGO", "CRC32");

    let db = "test_crc32_algo_persist_and_recover";

    // Instance A: write with CRC32 selected
    {
        let mut a = BlockStorage::new_with_capacity(db, 4)
            .await
            .expect("create A");
        let mut data = vec![0u8; BLOCK_SIZE];
        data[0] = 1;
        data[1] = 2;
        data[2] = 3;
        data[3] = 4;
        a.write_block(1, data.clone()).await.expect("write block 1");
        a.sync().await.expect("sync A");

        // Verify metadata shows algo CRC32 and checksum differs from DefaultHasher
        let mut meta_path = PathBuf::from(tmp.path());
        meta_path.push(db);
        meta_path.push("metadata.json");
        let text = fs::read_to_string(&meta_path).expect("read metadata.json");
        let parsed: TestFsMeta = serde_json::from_str(&text).expect("parse FsMeta");
        let entry = &parsed
            .entries
            .iter()
            .find(|(bid, _)| *bid == 1)
            .expect("entry for block 1")
            .1;
        assert_eq!(
            entry.algo.as_str(),
            "CRC32",
            "algo should be CRC32 when selected via env"
        );
        let dh = default_hasher_checksum(&data);
        assert_ne!(
            entry.checksum, dh,
            "CRC32 checksum should differ from DefaultHasher for known data"
        );
        let _ = entry.last_modified_ms;
        let _ = entry.version;
    }

    // Clear env so instance B must rely on persisted algorithm (synchronized)
    {
        let _g = common::ENV_LOCK.lock().expect("env lock poisoned");
        unsafe { std::env::remove_var("DATASYNC_CHECKSUM_ALGO") }
        drop(_g);
    }

    // Instance B: read and verify should succeed using persisted algorithm from metadata
    {
        let b = BlockStorage::new_with_capacity(db, 4)
            .await
            .expect("create B");
        // A simple read triggers verification in read path
        let bytes = b.read_block(1).await.expect("read block 1 in B");
        assert_eq!(bytes.len(), BLOCK_SIZE);
    }
}

#[tokio::test(flavor = "current_thread")]
#[serial]
#[cfg(feature = "fs_persist")]
async fn test_tempdir_based_fs_base_is_cleaned_up_after_drop() {
    let base_path: PathBuf;
    {
        let tmp = TempDir::new().expect("tempdir");
        base_path = tmp.path().to_path_buf();
        common::set_var("ABSURDERSQL_FS_BASE", &base_path);
        let db = "test_cleanup_tempdir";
        let mut s = BlockStorage::new_with_capacity(db, 4)
            .await
            .expect("create storage");
        s.write_block(1, vec![7u8; BLOCK_SIZE])
            .await
            .expect("write");
        s.sync().await.expect("sync");
        // tmp dropped here when going out of scope
    }
    // After TempDir drop, the directory should not exist
    assert!(
        !base_path.exists(),
        "TempDir-based ABSURDERSQL_FS_BASE should be removed after drop"
    );
}

#[tokio::test(flavor = "current_thread")]
#[serial]
#[cfg(feature = "fs_persist")]
async fn test_algo_removed_on_deallocate_and_reuse_picks_new_default() {
    let tmp = TempDir::new().expect("tempdir");
    common::set_var("ABSURDERSQL_FS_BASE", tmp.path());
    common::set_var("DATASYNC_CHECKSUM_ALGO", "CRC32");
    let db = "test_algo_reuse_new_default";

    // Instance A: CRC32 default, write then deallocate block 3
    {
        let mut a = BlockStorage::new_with_capacity(db, 4)
            .await
            .expect("create A");
        // Explicitly allocate block 3 before writing/deallocating to match allocation semantics
        let _ = a.allocate_block().await.expect("alloc 1");
        let _ = a.allocate_block().await.expect("alloc 2");
        let id3 = a.allocate_block().await.expect("alloc 3");
        assert_eq!(id3, 3, "expected third allocation to be block 3");
        let data = vec![0x11u8; BLOCK_SIZE];
        a.write_block(3, data).await.expect("write A");
        a.sync().await.expect("sync A");
        a.deallocate_block(3).await.expect("dealloc 3");
        a.sync().await.expect("sync A2");
    }

    // Switch default to FastHash for new instance reuse
    {
        let _g = common::ENV_LOCK.lock().expect("env lock");
        unsafe { std::env::set_var("DATASYNC_CHECKSUM_ALGO", "FastHash") }
        drop(_g);
    }

    // Instance B: reuse block 3; metadata algo should now be FastHash
    {
        let mut b = BlockStorage::new_with_capacity(db, 4)
            .await
            .expect("create B");
        let data2 = vec![0x22u8; BLOCK_SIZE];
        b.write_block(3, data2).await.expect("write B");
        b.sync().await.expect("sync B");

        let mut meta_path = PathBuf::from(tmp.path());
        meta_path.push(db);
        meta_path.push("metadata.json");
        let text = fs::read_to_string(&meta_path).expect("read metadata.json");
        let parsed: TestFsMeta = serde_json::from_str(&text).expect("parse FsMeta");
        let entry = &parsed
            .entries
            .iter()
            .find(|(bid, _)| *bid == 3)
            .expect("entry for block 3")
            .1;
        assert_eq!(
            entry.algo.as_str(),
            "FastHash",
            "reused block should use current default algo after deallocation"
        );
    }
}

#[tokio::test(flavor = "current_thread")]
#[serial]
#[cfg(feature = "fs_persist")]
async fn test_missing_algo_field_fallbacks_to_default_on_next_write() {
    let tmp = TempDir::new().expect("tempdir");
    common::set_var("ABSURDERSQL_FS_BASE", tmp.path());
    let db = "test_missing_algo_fallback";

    // Instance A: write with default FastHash
    {
        let mut a = BlockStorage::new_with_capacity(db, 4)
            .await
            .expect("create A");
        a.write_block(1, vec![0x33u8; BLOCK_SIZE])
            .await
            .expect("write A");
        a.sync().await.expect("sync A");
    }

    // Corrupt metadata: remove 'algo' for block 1
    let mut meta_path = PathBuf::from(tmp.path());
    meta_path.push(db);
    meta_path.push("metadata.json");
    let text = fs::read_to_string(&meta_path).expect("read meta");
    let mut v: serde_json::Value = serde_json::from_str(&text).expect("json");
    if let Some(entries) = v.get_mut("entries").and_then(|e| e.as_array_mut()) {
        for ent in entries.iter_mut() {
            if let Some(arr) = ent.as_array_mut() {
                if let (Some(id), Some(obj)) = (
                    arr.first().and_then(|x| x.as_u64()),
                    arr.get_mut(1).and_then(|x| x.as_object_mut()),
                ) {
                    if id == 1 {
                        obj.remove("algo");
                    }
                }
            }
        }
    }
    fs::write(&meta_path, serde_json::to_string(&v).unwrap()).expect("write meta");

    // Instance B: can read, then rewrite and metadata should regain default algo
    {
        let mut b = BlockStorage::new_with_capacity(db, 4)
            .await
            .expect("create B");
        let bytes = b.read_block(1).await.expect("read B");
        // rewrite same contents to persist fresh metadata with default algo
        b.write_block(1, bytes).await.expect("rewrite B");
        b.sync().await.expect("sync B");

        let text2 = fs::read_to_string(&meta_path).expect("read meta2");
        let parsed: TestFsMeta = serde_json::from_str(&text2).expect("parse FsMeta after");
        let entry = &parsed
            .entries
            .iter()
            .find(|(bid, _)| *bid == 1)
            .expect("entry for block 1")
            .1;
        assert_eq!(
            entry.algo.as_str(),
            "FastHash",
            "missing algo should fall back to default on next write"
        );
    }
}

#[tokio::test(flavor = "current_thread")]
#[serial]
#[cfg(feature = "fs_persist")]
async fn test_invalid_algo_string_tolerant_restore_and_fallback_per_entry() {
    let tmp = TempDir::new().expect("tempdir");
    common::set_var("ABSURDERSQL_FS_BASE", tmp.path());
    let db = "test_invalid_algo_tolerant";

    // Instance A: write two blocks with default FastHash
    {
        let mut a = BlockStorage::new_with_capacity(db, 4)
            .await
            .expect("create A");
        a.write_block(10, vec![0x44u8; BLOCK_SIZE])
            .await
            .expect("w10");
        a.write_block(11, vec![0x55u8; BLOCK_SIZE])
            .await
            .expect("w11");
        a.sync().await.expect("sync A");
    }

    // Corrupt metadata: set block 10 algo to invalid string, keep block 11 valid
    let mut meta_path = PathBuf::from(tmp.path());
    meta_path.push(db);
    meta_path.push("metadata.json");
    let text = fs::read_to_string(&meta_path).expect("read meta");
    let mut v: serde_json::Value = serde_json::from_str(&text).expect("json");
    if let Some(entries) = v.get_mut("entries").and_then(|e| e.as_array_mut()) {
        for ent in entries.iter_mut() {
            if let Some(arr) = ent.as_array_mut() {
                if let (Some(id), Some(obj)) = (
                    arr.first().and_then(|x| x.as_u64()),
                    arr.get_mut(1).and_then(|x| x.as_object_mut()),
                ) {
                    if id == 10 {
                        obj.insert("algo".into(), serde_json::Value::String("BAD".into()));
                    }
                }
            }
        }
    }
    fs::write(&meta_path, serde_json::to_string(&v).unwrap()).expect("write meta");

    // Instance B: tolerant restore should retain checksums, fall back algo for id 10 only.
    {
        let mut b = BlockStorage::new_with_capacity(db, 4)
            .await
            .expect("create B");
        // Ensure other entries restored unaffected
        assert!(
            b.get_block_checksum(11).is_some(),
            "valid entries should still restore"
        );
        // Verify id 10 is readable and verifiable (fallback to default algorithm)
        b.verify_block_checksum(10)
            .await
            .expect("verify id10 with fallback algo");
        // Sync to rewrite normalized metadata for id 10
        b.sync().await.expect("sync B");
        let text2 = fs::read_to_string(&meta_path).expect("read meta2");
        let parsed: TestFsMeta = serde_json::from_str(&text2).expect("parse FsMeta after");
        let entry10 = &parsed
            .entries
            .iter()
            .find(|(bid, _)| *bid == 10)
            .expect("entry for block 10")
            .1;
        assert_eq!(
            entry10.algo.as_str(),
            "FastHash",
            "invalid algo should be normalized to default after sync"
        );
    }
}

#[tokio::test(flavor = "current_thread")]
#[serial]
#[cfg(feature = "fs_persist")]
async fn test_algo_mismatch_triggers_verification_error() {
    let tmp = TempDir::new().expect("tempdir");
    common::set_var("ABSURDERSQL_FS_BASE", tmp.path());
    let db = "test_algo_mismatch_error";

    // Instance A: write with default FastHash
    {
        let mut a = BlockStorage::new_with_capacity(db, 4)
            .await
            .expect("create A");
        a.write_block(5, vec![0x66u8; BLOCK_SIZE])
            .await
            .expect("write A");
        a.sync().await.expect("sync A");
    }

    // Tamper metadata: switch algo to CRC32 but keep checksum (from FastHash)
    let mut meta_path = PathBuf::from(tmp.path());
    meta_path.push(db);
    meta_path.push("metadata.json");
    let text = fs::read_to_string(&meta_path).expect("read meta");
    let mut v: serde_json::Value = serde_json::from_str(&text).expect("json");
    if let Some(entries) = v.get_mut("entries").and_then(|e| e.as_array_mut()) {
        for ent in entries.iter_mut() {
            if let Some(arr) = ent.as_array_mut() {
                if let (Some(id), Some(obj)) = (
                    arr.first().and_then(|x| x.as_u64()),
                    arr.get_mut(1).and_then(|x| x.as_object_mut()),
                ) {
                    if id == 5 {
                        obj.insert("algo".into(), serde_json::Value::String("CRC32".into()));
                    }
                }
            }
        }
    }
    fs::write(&meta_path, serde_json::to_string(&v).unwrap()).expect("write meta");

    // Instance B: read should now fail checksum verification due to algo mismatch
    {
        let b = BlockStorage::new_with_capacity(db, 4)
            .await
            .expect("create B");
        let res = b.read_block(5).await;
        assert!(
            res.is_err(),
            "expected checksum verification error after algo tamper"
        );
    }
}