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
//! Sync operations for BlockStorage
//! This module contains the core sync implementation logic

// Reentrancy-safe lock macros
#[cfg(target_arch = "wasm32")]
macro_rules! lock_mutex {
    ($mutex:expr) => {
        $mutex
            .try_borrow_mut()
            .expect("RefCell borrow failed - reentrancy detected in sync_operations.rs")
    };
}

#[cfg(not(target_arch = "wasm32"))]
macro_rules! lock_mutex {
    ($mutex:expr) => {
        $mutex.lock()
    };
}

#[allow(unused_macros)]
#[cfg(target_arch = "wasm32")]
macro_rules! try_lock_mutex {
    ($mutex:expr) => {
        $mutex
    };
}

#[allow(unused_macros)]
#[cfg(not(target_arch = "wasm32"))]
macro_rules! try_lock_mutex {
    ($mutex:expr) => {
        $mutex.lock()
    };
}

use super::block_storage::BlockStorage;
use crate::types::DatabaseError;

#[cfg(all(
    not(target_arch = "wasm32"),
    any(test, debug_assertions),
    not(feature = "fs_persist")
))]
use std::collections::HashMap;
#[cfg(all(not(target_arch = "wasm32"), not(feature = "fs_persist")))]
use std::sync::atomic::Ordering;

#[cfg(all(
    not(target_arch = "wasm32"),
    any(test, debug_assertions),
    not(feature = "fs_persist")
))]
use super::metadata::BlockMetadataPersist;
#[cfg(any(
    target_arch = "wasm32",
    all(
        not(target_arch = "wasm32"),
        any(test, debug_assertions),
        not(feature = "fs_persist")
    )
))]
use super::vfs_sync;

#[cfg(target_arch = "wasm32")]
use super::metadata::BlockMetadataPersist;
#[cfg(target_arch = "wasm32")]
use std::collections::HashMap;

#[cfg(all(
    not(target_arch = "wasm32"),
    any(test, debug_assertions),
    not(feature = "fs_persist")
))]
use super::block_storage::GLOBAL_METADATA_TEST;

/// Internal sync implementation shared by sync() and sync_now()
pub fn sync_implementation_impl(storage: &mut BlockStorage) -> Result<(), DatabaseError> {
    #[cfg(all(
        not(target_arch = "wasm32"),
        any(test, debug_assertions),
        not(feature = "fs_persist")
    ))]
    let start = std::time::Instant::now();

    // Record sync start for observability
    let dirty_count = lock_mutex!(storage.dirty_blocks).len();
    let dirty_bytes = dirty_count * super::block_storage::BLOCK_SIZE;
    storage
        .observability
        .record_sync_start(dirty_count, dirty_bytes);

    // Invoke sync start callback if set
    #[cfg(not(target_arch = "wasm32"))]
    if let Some(ref callback) = storage.observability.sync_start_callback {
        callback(dirty_count, dirty_bytes);
    }

    // Early return for native release builds without fs_persist
    #[cfg(all(
        not(target_arch = "wasm32"),
        not(any(test, debug_assertions)),
        not(feature = "fs_persist")
    ))]
    {
        // In release mode without fs_persist, just clear dirty blocks
        lock_mutex!(storage.dirty_blocks).clear();
        storage.sync_count.fetch_add(1, Ordering::SeqCst);
        return Ok(());
    }

    // Call the existing fs_persist implementation for native builds
    #[cfg(all(not(target_arch = "wasm32"), feature = "fs_persist"))]
    {
        storage.fs_persist_sync()
    }

    // For native non-fs_persist builds (test/debug only), use simple in-memory sync with commit marker handling
    #[cfg(all(
        not(target_arch = "wasm32"),
        any(test, debug_assertions),
        not(feature = "fs_persist")
    ))]
    {
        let current_dirty = lock_mutex!(storage.dirty_blocks).len();
        log::info!(
            "Syncing {} dirty blocks (native non-fs_persist)",
            current_dirty
        );

        let to_persist: Vec<(u64, Vec<u8>)> = {
            let dirty = lock_mutex!(storage.dirty_blocks);
            dirty.iter().map(|(k, v)| (*k, v.clone())).collect()
        };
        let ids: Vec<u64> = to_persist.iter().map(|(k, _)| *k).collect();
        let blocks_synced = ids.len(); // Capture length before moving ids

        // Determine next commit version for native test path
        let next_commit: u64 = vfs_sync::with_global_commit_marker(|cm| {
            #[cfg(target_arch = "wasm32")]
            let cm = cm;
            #[cfg(not(target_arch = "wasm32"))]
            let cm = cm.borrow();
            let current = cm.get(&storage.db_name).copied().unwrap_or(0);
            current + 1
        });

        // Store blocks in global test storage with versioning
        vfs_sync::with_global_storage(|gs| {
            #[cfg(target_arch = "wasm32")]
            let storage_map = gs;
            #[cfg(not(target_arch = "wasm32"))]
            let mut storage_map = gs.borrow_mut();
            let db_storage = storage_map
                .entry(storage.db_name.clone())
                .or_insert_with(HashMap::new);
            for (block_id, data) in to_persist {
                db_storage.insert(block_id, data);
            }
        });

        // Store metadata with per-commit versioning
        GLOBAL_METADATA_TEST.with(|meta| {
            #[cfg(target_arch = "wasm32")]
            let mut meta_map = meta.borrow_mut();
            #[cfg(not(target_arch = "wasm32"))]
            let mut meta_map = meta.lock();
            let db_meta = meta_map
                .entry(storage.db_name.clone())
                .or_insert_with(HashMap::new);
            for block_id in ids {
                if let Some(checksum) = storage.checksum_manager.get_checksum(block_id) {
                    // Use the per-commit version so entries remain invisible until the commit marker advances
                    let version = next_commit as u32;
                    db_meta.insert(
                        block_id,
                        BlockMetadataPersist {
                            checksum,
                            last_modified_ms: std::time::SystemTime::now()
                                .duration_since(std::time::UNIX_EPOCH)
                                .unwrap_or_default()
                                .as_millis() as u64,
                            version,
                            algo: storage.checksum_manager.get_algorithm(block_id),
                        },
                    );
                }
            }
        });

        // Atomically advance the commit marker after all data and metadata are persisted
        vfs_sync::with_global_commit_marker(|cm| {
            #[cfg(target_arch = "wasm32")]
            let cm_map = cm;
            #[cfg(not(target_arch = "wasm32"))]
            let mut cm_map = cm.borrow_mut();
            cm_map.insert(storage.db_name.clone(), next_commit);
        });

        // Clear dirty blocks
        {
            let mut dirty = lock_mutex!(storage.dirty_blocks);
            dirty.clear();
        }

        // Update sync metrics
        storage.sync_count.fetch_add(1, Ordering::SeqCst);
        let elapsed = start.elapsed();
        let ms = elapsed.as_millis() as u64;
        let ms = if ms == 0 { 1 } else { ms };
        storage.last_sync_duration_ms.store(ms, Ordering::SeqCst);

        // Record sync success for observability
        storage.observability.record_sync_success(ms, blocks_synced);

        // Invoke sync success callback if set
        if let Some(ref callback) = storage.observability.sync_success_callback {
            callback(ms, blocks_synced);
        }

        storage.evict_if_needed();
        return Ok(());
    }

    #[cfg(target_arch = "wasm32")]
    {
        // WASM implementation
        let current_dirty = lock_mutex!(storage.dirty_blocks).len();
        log::info!("Syncing {} dirty blocks (WASM)", current_dirty);

        // For WASM, persist dirty blocks to global storage
        let to_persist: Vec<(u64, Vec<u8>)> = {
            let dirty = lock_mutex!(storage.dirty_blocks);
            dirty.iter().map(|(k, v)| (*k, v.clone())).collect()
        };
        let ids: Vec<u64> = to_persist.iter().map(|(k, _)| *k).collect();
        // Determine next commit version so that all metadata written in this sync share the same version
        let next_commit: u64 = vfs_sync::with_global_commit_marker(|cm| {
            let cm = cm;
            let current = cm.borrow().get(&storage.db_name).copied().unwrap_or(0);
            current + 1
        });
        vfs_sync::with_global_storage(|gs| {
            let mut storage_map = gs.borrow_mut();
            let db_storage = storage_map
                .entry(storage.db_name.clone())
                .or_insert_with(HashMap::new);
            for (block_id, data) in &to_persist {
                // Check if block already exists in global storage with committed data
                let should_update = if let Some(existing) = db_storage.get(block_id) {
                    if existing != data {
                        // Check if existing data has committed metadata (version > 0)
                        let has_committed_metadata = vfs_sync::with_global_metadata(|meta| {
                            if let Some(db_meta) = meta.borrow().get(&storage.db_name) {
                                if let Some(metadata) = db_meta.get(block_id) {
                                    metadata.version > 0
                                } else {
                                    false
                                }
                            } else {
                                false
                            }
                        });

                        if has_committed_metadata {
                            // CRITICAL FIX: Never overwrite committed data to prevent corruption
                            false // Never overwrite committed data
                        } else {
                            true // Update uncommitted data
                        }
                    } else {
                        true // Same data, safe to update
                    }
                } else {
                    true // No existing data, safe to insert
                };

                if should_update {
                    db_storage.insert(*block_id, data.clone());
                }
            }
        });
        // Persist corresponding metadata entries
        vfs_sync::with_global_metadata(|meta| {
            let mut meta_guard = meta.borrow_mut();
            let db_meta = meta_guard
                .entry(storage.db_name.clone())
                .or_insert_with(HashMap::new);
            for block_id in ids {
                if let Some(checksum) = storage.checksum_manager.get_checksum(block_id) {
                    // Use the per-commit version so entries remain invisible until the commit marker advances
                    let version = next_commit as u32;
                    db_meta.insert(
                        block_id,
                        BlockMetadataPersist {
                            checksum,
                            last_modified_ms: BlockStorage::now_millis(),
                            version,
                            algo: storage.checksum_manager.get_algorithm(block_id),
                        },
                    );
                }
            }
        });
        // Atomically advance the commit marker after all data and metadata are persisted
        vfs_sync::with_global_commit_marker(|cm| {
            let cm_map = cm;
            cm_map
                .borrow_mut()
                .insert(storage.db_name.clone(), next_commit);
        });

        // Spawn async IndexedDB persistence (fire and forget for sync compatibility)
        let db_name = storage.db_name.clone();
        wasm_bindgen_futures::spawn_local(async move {
            use wasm_bindgen::JsCast;

            // Get IndexedDB factory (works in both Window and Worker contexts)
            let global = js_sys::global();
            let indexed_db_value = match js_sys::Reflect::get(
                &global,
                &wasm_bindgen::JsValue::from_str("indexedDB"),
            ) {
                Ok(val) => val,
                Err(_) => {
                    log::error!("IndexedDB property access failed - cannot persist");
                    return;
                }
            };

            if indexed_db_value.is_null() || indexed_db_value.is_undefined() {
                log::warn!(
                    "IndexedDB unavailable for sync (private browsing?) - data not persisted to IndexedDB"
                );
                return;
            }

            let idb_factory = match indexed_db_value.dyn_into::<web_sys::IdbFactory>() {
                Ok(factory) => factory,
                Err(_) => {
                    log::error!("IndexedDB property is not an IdbFactory - cannot persist");
                    return;
                }
            };

            let open_req = match idb_factory.open_with_u32("block_storage", 2) {
                Ok(req) => req,
                Err(e) => {
                    log::error!("Failed to open IndexedDB for sync: {:?}", e);
                    return;
                }
            };

            // Set up upgrade handler to create object stores if needed
            let upgrade_handler = js_sys::Function::new_no_args(&format!(
                "
                    const db = event.target.result;
                    if (!db.objectStoreNames.contains('blocks')) {{
                        db.createObjectStore('blocks');
                    }}
                    if (!db.objectStoreNames.contains('metadata')) {{
                        db.createObjectStore('metadata');
                    }}
                    "
            ));
            open_req.set_onupgradeneeded(Some(&upgrade_handler));

            // Use event-based approach for opening database
            let (tx, rx) = futures::channel::oneshot::channel();
            let tx = std::rc::Rc::new(std::cell::RefCell::new(Some(tx)));

            let success_tx = tx.clone();
            let success_callback =
                wasm_bindgen::closure::Closure::wrap(Box::new(move |event: web_sys::Event| {
                    if let Some(tx) = success_tx.borrow_mut().take() {
                        let target = event.target().unwrap();
                        let request: web_sys::IdbOpenDbRequest = target.unchecked_into();
                        let result = request.result().unwrap();
                        let _ = tx.send(Ok(result));
                    }
                }) as Box<dyn FnMut(_)>);

            let error_tx = tx.clone();
            let error_callback =
                wasm_bindgen::closure::Closure::wrap(Box::new(move |event: web_sys::Event| {
                    if let Some(tx) = error_tx.borrow_mut().take() {
                        let _ = tx.send(Err(format!("IndexedDB open failed: {:?}", event)));
                    }
                }) as Box<dyn FnMut(_)>);

            open_req.set_onsuccess(Some(success_callback.as_ref().unchecked_ref()));
            open_req.set_onerror(Some(error_callback.as_ref().unchecked_ref()));

            let db_result = rx.await;

            // Keep closures alive
            success_callback.forget();
            error_callback.forget();

            match db_result {
                Ok(Ok(db_value)) => {
                    if let Ok(db) = db_value.dyn_into::<web_sys::IdbDatabase>() {
                        // Start transaction for both blocks and metadata
                        let store_names = js_sys::Array::new();
                        store_names.push(&wasm_bindgen::JsValue::from_str("blocks"));
                        store_names.push(&wasm_bindgen::JsValue::from_str("metadata"));

                        let transaction = db
                            .transaction_with_str_sequence_and_mode(
                                &store_names,
                                web_sys::IdbTransactionMode::Readwrite,
                            )
                            .unwrap();

                        let blocks_store = transaction.object_store("blocks").unwrap();
                        let metadata_store = transaction.object_store("metadata").unwrap();

                        // Persist all blocks
                        for (block_id, data) in &to_persist {
                            let key = wasm_bindgen::JsValue::from_str(&format!(
                                "{}_{}",
                                db_name, block_id
                            ));
                            let value = js_sys::Uint8Array::from(&data[..]);
                            blocks_store.put_with_key(&value, &key).unwrap();
                        }

                        // Persist commit marker
                        let commit_key =
                            wasm_bindgen::JsValue::from_str(&format!("{}_commit_marker", db_name));
                        let commit_value = wasm_bindgen::JsValue::from_f64(next_commit as f64);
                        metadata_store
                            .put_with_key(&commit_value, &commit_key)
                            .unwrap();

                        // Use event-based approach for transaction completion
                        let (tx_tx, tx_rx) = futures::channel::oneshot::channel();
                        let tx_tx = std::rc::Rc::new(std::cell::RefCell::new(Some(tx_tx)));

                        let tx_complete_tx = tx_tx.clone();
                        let tx_complete_callback = wasm_bindgen::closure::Closure::wrap(Box::new(
                            move |_event: web_sys::Event| {
                                if let Some(tx) = tx_complete_tx.borrow_mut().take() {
                                    let _ = tx.send(Ok(()));
                                }
                            },
                        )
                            as Box<dyn FnMut(_)>);

                        let tx_error_tx = tx_tx.clone();
                        let tx_error_callback = wasm_bindgen::closure::Closure::wrap(Box::new(
                            move |event: web_sys::Event| {
                                if let Some(tx) = tx_error_tx.borrow_mut().take() {
                                    let _ =
                                        tx.send(Err(format!("Transaction failed: {:?}", event)));
                                }
                            },
                        )
                            as Box<dyn FnMut(_)>);

                        transaction
                            .set_oncomplete(Some(tx_complete_callback.as_ref().unchecked_ref()));
                        transaction.set_onerror(Some(tx_error_callback.as_ref().unchecked_ref()));

                        let _ = tx_rx.await;

                        // Keep closures alive
                        tx_complete_callback.forget();
                        tx_error_callback.forget();
                    }
                }
                _ => {} // Silently ignore errors in background persistence
            }
        });
        // Clear dirty blocks after successful persistence
        {
            let mut dirty = lock_mutex!(storage.dirty_blocks);
            dirty.clear();
        }

        // Record sync success for observability (WASM)
        // For WASM, we don't have precise timing, so use a default duration
        storage.observability.record_sync_success(1, current_dirty);

        // Invoke WASM sync success callback if set
        #[cfg(target_arch = "wasm32")]
        if let Some(ref callback) = storage.observability.wasm_sync_success_callback {
            callback(1, current_dirty);
        }

        storage.evict_if_needed();
        Ok(())
    }
}