absurder-sql 0.1.27

High-performance SQLite for browsers (IndexedDB or Hybrid OPFS), native apps, and mobile, with export/import and multi-tab coordination
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
#[cfg(target_arch = "wasm32")]
use super::BlockStorage;
#[cfg(target_arch = "wasm32")]
use super::StorageBackend;
#[cfg(target_arch = "wasm32")]
use super::vfs_sync;
#[cfg(target_arch = "wasm32")]
use crate::types::DatabaseError;

/// Register a BlockStorage instance for VFS sync callbacks
/// NOTE: This function is deprecated. Use indexeddb_vfs::STORAGE_REGISTRY directly.
#[cfg(target_arch = "wasm32")]
pub fn register_storage_for_vfs_sync(
    _db_name: &str,
    _storage: std::rc::Weak<std::cell::RefCell<BlockStorage>>,
) {
    // This function is no longer used - registration happens in indexeddb_vfs::open_or_create
    // Kept as no-op for backwards compatibility during refactoring
}

/// Trigger a sync for a specific database from VFS
#[cfg(target_arch = "wasm32")]
pub fn vfs_sync_database(db_name: &str) -> Result<(), DatabaseError> {
    // DEBUG: Log where this is being called from
    // web_sys::console::log_1(&"vfs_sync_database() CALLED - THIS SHOULD BE RARE!".into());

    // Advance the commit marker to make writes visible
    let _next_commit = vfs_sync::with_global_commit_marker(|cm| {
        let current = cm.borrow().get(db_name).copied().unwrap_or(0);
        let new_marker = current + 1;
        cm.borrow_mut().insert(db_name.to_string(), new_marker);
        web_sys::console::log_1(
            &format!(
                "VFS sync: Advanced commit marker for {} from {} to {}",
                db_name, current, new_marker
            )
            .into(),
        );
        new_marker
    });

    // Trigger immediate IndexedDB persistence for the committed data
    let db_name_clone = db_name.to_string();

    // CRITICAL: Collect blocks BEFORE spawning async task to avoid timing issues
    let (blocks_to_persist, metadata_to_persist) = vfs_sync::with_global_storage(|storage| {
        let storage_map = storage;

        // DEBUG: Log all keys in GLOBAL_STORAGE
        //web_sys::console::log_1(&format!("VFS sync: GLOBAL_STORAGE keys: {:?}", storage_map.keys().collect::<Vec<_>>()).into());
        //web_sys::console::log_1(&format!("VFS sync: Looking for key: {}", db_name_clone).into());

        let blocks = if let Some(db_storage) = storage_map.borrow().get(&db_name_clone) {
            //web_sys::console::log_1(&format!("VFS sync: Found {} blocks for {}", db_storage.len(), db_name_clone).into());
            db_storage
                .iter()
                .map(|(&id, data)| (id, data.clone()))
                .collect::<Vec<_>>()
        } else {
            web_sys::console::log_1(
                &format!("VFS sync: No storage found for key: {}", db_name_clone).into(),
            );
            Vec::new()
        };

        // Also collect metadata
        let metadata = vfs_sync::with_global_metadata(|meta| {
            if let Some(db_meta) = meta.borrow().get(&db_name_clone) {
                db_meta
                    .iter()
                    .map(|(&id, metadata)| (id, metadata.clone()))
                    .collect::<Vec<_>>()
            } else {
                Vec::new()
            }
        });

        (blocks, metadata)
    });

    if !blocks_to_persist.is_empty() {
        let backend = crate::vfs::indexeddb_vfs::get_storage_with_fallback(&db_name_clone)
            .map(|storage| storage.storage_backend())
            .unwrap_or(StorageBackend::IndexedDb);

        wasm_bindgen_futures::spawn_local(async move {
            let next_commit = vfs_sync::with_global_commit_marker(|cm| {
                cm.borrow().get(&db_name_clone).copied().unwrap_or(0)
            });

            web_sys::console::log_1(
                &format!(
                    "VFS sync: Persisting {} blocks using backend {} with commit marker {}",
                    blocks_to_persist.len(),
                    backend.as_str(),
                    next_commit
                )
                .into(),
            );

            let persist_result = match backend {
                StorageBackend::IndexedDb => {
                    super::wasm_indexeddb::persist_to_indexeddb_event_based(
                        &db_name_clone,
                        blocks_to_persist,
                        metadata_to_persist,
                        next_commit,
                        #[cfg(feature = "telemetry")]
                        None,
                        #[cfg(feature = "telemetry")]
                        None,
                    )
                    .await
                }
                StorageBackend::Opfs | StorageBackend::Hybrid => {
                    if let Err(error) = super::hybrid_store::hybrid_persist(
                        &db_name_clone,
                        blocks_to_persist,
                        metadata_to_persist,
                        next_commit,
                        #[cfg(feature = "telemetry")]
                        None,
                        #[cfg(feature = "telemetry")]
                        None,
                    )
                    .await
                    {
                        web_sys::console::log_1(
                            &format!(
                                "VFS sync: Failed to persist {} to OPFS: {:?}",
                                db_name_clone, error
                            )
                            .into(),
                        );
                        Err(error)
                    } else {
                        Ok(())
                    }
                }
            };

            match persist_result {
                Ok(_) => {
                    web_sys::console::log_1(
                        &format!(
                            "VFS sync: Successfully persisted {} using backend {}",
                            db_name_clone,
                            backend.as_str()
                        )
                        .into(),
                    );
                }
                Err(e) => {
                    web_sys::console::log_1(
                        &format!(
                            "VFS sync: Failed to persist {} to IndexedDB: {:?}",
                            db_name_clone, e
                        )
                        .into(),
                    );
                }
            }
        });
    } else {
        web_sys::console::log_1(
            &format!("VFS sync: No blocks to persist for {}", db_name_clone).into(),
        );
    }

    Ok(())
}

/// Blocking version of VFS sync that waits for IndexedDB persistence to complete
#[cfg(target_arch = "wasm32")]
pub fn vfs_sync_database_blocking(db_name: &str) -> Result<(), DatabaseError> {
    // Advance the commit marker to make writes visible
    let next_commit = vfs_sync::with_global_commit_marker(|cm| {
        let current = cm.borrow().get(db_name).copied().unwrap_or(0);
        let new_marker = current + 1;
        cm.borrow_mut().insert(db_name.to_string(), new_marker);
        web_sys::console::log_1(
            &format!(
                "VFS sync: Advanced commit marker for {} from {} to {}",
                db_name, current, new_marker
            )
            .into(),
        );
        new_marker
    });

    // Collect all data from global storage for this database
    let (blocks_to_persist, metadata_to_persist) = vfs_sync::with_global_storage(|storage| {
        let storage_map = storage;
        let blocks = if let Some(db_storage) = storage_map.borrow().get(db_name) {
            db_storage
                .iter()
                .map(|(&id, data)| (id, data.clone()))
                .collect::<Vec<_>>()
        } else {
            Vec::new()
        };

        // Also collect metadata
        let metadata = vfs_sync::with_global_metadata(|meta| {
            if let Some(db_meta) = meta.borrow().get(db_name) {
                db_meta
                    .iter()
                    .map(|(&id, metadata)| (id, metadata.clone()))
                    .collect::<Vec<_>>()
            } else {
                Vec::new()
            }
        });

        (blocks, metadata)
    });

    if blocks_to_persist.is_empty() {
        web_sys::console::log_1(&format!("VFS sync: No blocks to persist for {}", db_name).into());
        return Ok(());
    }

    // Use wasm-bindgen-futures to block on the async operation
    let db_name_string = db_name.to_string();
    let backend = crate::vfs::indexeddb_vfs::get_storage_with_fallback(db_name)
        .map(|storage| storage.storage_backend())
        .unwrap_or(StorageBackend::IndexedDb);
    let fut = async move {
        // Create a temporary storage instance just for persistence
        match BlockStorage::new(&db_name_string).await {
            Ok(_storage) => {
                let persist_result = match backend {
                    StorageBackend::IndexedDb => {
                        super::wasm_indexeddb::persist_to_indexeddb_event_based(
                            &db_name_string,
                            blocks_to_persist,
                            metadata_to_persist,
                            next_commit,
                            #[cfg(feature = "telemetry")]
                            None,
                            #[cfg(feature = "telemetry")]
                            None,
                        )
                        .await
                    }
                    StorageBackend::Opfs | StorageBackend::Hybrid => {
                        if let Err(error) = super::hybrid_store::hybrid_persist(
                            &db_name_string,
                            blocks_to_persist,
                            metadata_to_persist,
                            next_commit,
                            #[cfg(feature = "telemetry")]
                            None,
                            #[cfg(feature = "telemetry")]
                            None,
                        )
                        .await
                        {
                            Err(error)
                        } else {
                            Ok(())
                        }
                    }
                };

                match persist_result {
                    Ok(_) => {
                        web_sys::console::log_1(
                            &format!(
                                "VFS sync: Successfully persisted {} using backend {}",
                                db_name_string,
                                backend.as_str()
                            )
                            .into(),
                        );

                        // CRITICAL FIX: Also persist the commit marker to IndexedDB
                        if let Err(e) =
                            persist_commit_marker_to_indexeddb(&db_name_string, next_commit).await
                        {
                            web_sys::console::log_1(
                                &format!(
                                    "VFS sync: Failed to persist commit marker for {}: {:?}",
                                    db_name_string, e
                                )
                                .into(),
                            );
                        } else {
                            web_sys::console::log_1(
                                &format!(
                                    "VFS sync: Successfully persisted commit marker {} for {}",
                                    next_commit, db_name_string
                                )
                                .into(),
                            );
                        }
                    }
                    Err(e) => {
                        web_sys::console::log_1(
                            &format!(
                                "VFS sync: Failed to persist {} using backend {}: {:?}",
                                db_name_string,
                                backend.as_str(),
                                e
                            )
                            .into(),
                        );
                    }
                }
            }
            Err(e) => {
                web_sys::console::log_1(
                    &format!(
                        "VFS sync: Failed to create storage instance for {}: {:?}",
                        db_name_string, e
                    )
                    .into(),
                );
            }
        }
    };

    // We can't actually block in WASM, so just spawn the async task
    // The commit marker advancement above is sufficient for immediate visibility
    wasm_bindgen_futures::spawn_local(fut);

    Ok(())
}

/// Persist commit marker to IndexedDB for cross-instance visibility
#[cfg(target_arch = "wasm32")]
pub async fn persist_commit_marker_to_indexeddb(
    db_name: &str,
    commit_marker: u64,
) -> Result<(), DatabaseError> {
    use futures::channel::oneshot;
    use wasm_bindgen::JsCast;
    use wasm_bindgen::prelude::*;

    let db_name_string = db_name.to_string();

    // Get IndexedDB factory (works in both Window and Worker contexts)
    let global = js_sys::global();
    let indexed_db_value =
        js_sys::Reflect::get(&global, &wasm_bindgen::JsValue::from_str("indexedDB")).map_err(
            |_| DatabaseError::new("INDEXEDDB_ERROR", "Failed to access indexedDB property"),
        )?;

    if indexed_db_value.is_null() || indexed_db_value.is_undefined() {
        return Err(DatabaseError::new(
            "INDEXEDDB_ERROR",
            "IndexedDB is not available",
        ));
    }

    let indexed_db = indexed_db_value
        .dyn_into::<web_sys::IdbFactory>()
        .map_err(|_| DatabaseError::new("INDEXEDDB_ERROR", "indexedDB is not an IdbFactory"))?;

    let (tx, rx) = oneshot::channel();
    let tx = std::rc::Rc::new(std::cell::RefCell::new(Some(tx)));

    let open_request = indexed_db
        .open_with_u32("block_storage", 2)
        .map_err(|_| DatabaseError::new("INDEXEDDB_ERROR", "Failed to open IndexedDB"))?;

    // Handle database upgrade
    let upgrade_closure = Closure::wrap(Box::new(move |event: web_sys::Event| {
        let target = event.target().unwrap();
        let db: web_sys::IdbDatabase = target.dyn_into().unwrap();

        // Create metadata store if it doesn't exist
        if !db.object_store_names().contains("metadata") {
            let _store = db.create_object_store("metadata").unwrap();
        }
    }) as Box<dyn FnMut(_)>);
    open_request.set_onupgradeneeded(Some(upgrade_closure.as_ref().unchecked_ref()));
    upgrade_closure.forget();

    // Handle success
    let tx_clone = tx.clone();
    let success_closure = Closure::wrap(Box::new(move |event: web_sys::Event| {
        let target = event.target().expect("event target");
        let request: web_sys::IdbOpenDbRequest =
            target.dyn_into().expect("cast to IdbOpenDbRequest");
        let result = request.result().expect("get result");
        let db: web_sys::IdbDatabase = result.dyn_into().expect("cast to IdbDatabase");

        let transaction = db
            .transaction_with_str_and_mode("metadata", web_sys::IdbTransactionMode::Readwrite)
            .expect("create transaction");
        let store = transaction.object_store("metadata").expect("get store");

        // Store commit marker with key "<db_name>:commit_marker" (matches restore format)
        let key = format!("{}:commit_marker", db_name_string);
        let value = js_sys::Number::from(commit_marker as f64);
        let _request = store
            .put_with_key(&value, &JsValue::from_str(&key))
            .expect("put commit marker");

        if let Some(sender) = tx_clone.borrow_mut().take() {
            let _ = sender.send(Ok(()));
        }
    }) as Box<dyn FnMut(_)>);
    open_request.set_onsuccess(Some(success_closure.as_ref().unchecked_ref()));
    success_closure.forget();

    // Handle error
    let error_closure = Closure::wrap(Box::new(move |_event: web_sys::Event| {
        if let Some(sender) = tx.borrow_mut().take() {
            let _ = sender.send(Err(DatabaseError::new(
                "INDEXEDDB_ERROR",
                "Failed to persist commit marker",
            )));
        }
    }) as Box<dyn FnMut(_)>);
    open_request.set_onerror(Some(error_closure.as_ref().unchecked_ref()));
    error_closure.forget();

    rx.await
        .map_err(|_| DatabaseError::new("ASYNC_ERROR", "Channel error"))?
        .map_err(|e| e)
}

/// Sync blocks to global storage without advancing commit marker
/// Used by VFS x_sync callback to persist blocks but maintain commit marker lag
#[cfg(target_arch = "wasm32")]
pub fn sync_blocks_only(storage: &BlockStorage) -> Result<(), DatabaseError> {
    let _db_name = &storage.db_name;
    // web_sys::console::log_1(&format!("DEBUG: sync_blocks_only called for {}", _db_name).into());

    // Simply persist blocks to cache without advancing commit marker
    // The blocks are already in the local cache and will be visible to other instances
    // through the global storage registry, but the commit marker won't advance
    // web_sys::console::log_1(&format!("DEBUG: sync_blocks_only completed for {} (commit marker unchanged)", db_name).into());

    Ok(())
}