Skip to main content

absurder_sql/
lib.rs

1#[cfg(target_arch = "wasm32")]
2use std::rc::Rc;
3#[cfg(target_arch = "wasm32")]
4use wasm_bindgen::prelude::*;
5
6// Conditional rusqlite import: same crate, different features
7// Make this public so child crates can use it
8// When encryption is enabled, rusqlite uses bundled-sqlcipher-vendored-openssl feature
9// When bundled-sqlite is enabled, rusqlite uses bundled feature
10#[cfg(all(
11    not(target_arch = "wasm32"),
12    any(
13        feature = "bundled-sqlite",
14        feature = "encryption",
15        feature = "encryption-commoncrypto",
16        feature = "encryption-ios"
17    )
18))]
19pub extern crate rusqlite;
20
21// Enable better panic messages and memory allocation
22#[cfg(feature = "console_error_panic_hook")]
23pub use console_error_panic_hook::set_once as set_panic_hook;
24
25#[cfg(feature = "wee_alloc")]
26#[global_allocator]
27static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
28
29// Initialize logging infrastructure for WASM
30#[cfg(all(target_arch = "wasm32", feature = "console_log"))]
31#[wasm_bindgen(start)]
32pub fn init_logger() {
33    // Initialize console_log for browser logging
34    // Use Info level for production, Debug for development
35    #[cfg(debug_assertions)]
36    let log_level = log::Level::Debug;
37    #[cfg(not(debug_assertions))]
38    let log_level = log::Level::Info;
39
40    console_log::init_with_level(log_level).expect("Failed to initialize console_log");
41
42    log::info!("AbsurderSQL logging initialized at level: {:?}", log_level);
43}
44
45// Use centralized normalize_db_name from utils - SINGLE SOURCE OF TRUTH
46// See utils.rs for documentation and rationale
47#[cfg(target_arch = "wasm32")]
48use crate::utils::normalize_db_name;
49
50// Module declarations
51mod cleanup;
52#[cfg(target_arch = "wasm32")]
53pub mod connection_pool;
54#[cfg(not(target_arch = "wasm32"))]
55pub mod database;
56pub mod storage;
57pub mod types;
58pub mod vfs;
59#[cfg(not(target_arch = "wasm32"))]
60pub use database::PreparedStatement;
61pub mod utils;
62#[cfg(target_arch = "wasm32")]
63mod wasm_statement;
64
65#[cfg(feature = "telemetry")]
66pub mod telemetry;
67
68// Re-export main public API
69#[cfg(not(target_arch = "wasm32"))]
70pub use database::SqliteIndexedDB;
71
72// WASM: Track databases currently being opened to serialize SQLite connection initialization
73#[cfg(target_arch = "wasm32")]
74thread_local! {
75    static DB_OPEN_IN_PROGRESS: std::cell::RefCell<std::collections::HashSet<String>> =
76        std::cell::RefCell::new(std::collections::HashSet::new());
77}
78
79// Type alias for native platforms
80#[cfg(not(target_arch = "wasm32"))]
81pub type Database = SqliteIndexedDB;
82
83pub use types::DatabaseConfig;
84pub use types::{ColumnValue, DatabaseError, QueryResult, Row, TransactionOptions};
85
86// Re-export VFS
87pub use vfs::indexeddb_vfs::IndexedDBVFS;
88
89/// DRY macro for async storage operations with interior mutability
90#[cfg(target_arch = "wasm32")]
91macro_rules! with_storage_async {
92    ($storage:expr, $operation:expr, |$s:ident| $body:expr) => {{
93        // BlockStorage uses RefCell for interior mutability, no outer borrow needed
94        let $s = &*$storage;
95        Some($body.await)
96    }};
97}
98
99// WASM Database implementation using sqlite-wasm-rs
100#[cfg(target_arch = "wasm32")]
101#[wasm_bindgen]
102pub struct Database {
103    connection_state: Rc<crate::connection_pool::ConnectionState>,
104    #[allow(dead_code)]
105    name: String,
106    on_data_change_callback: Option<js_sys::Function>,
107    allow_non_leader_writes: bool,
108    optimistic_updates_manager:
109        std::cell::RefCell<crate::storage::optimistic_updates::OptimisticUpdatesManager>,
110    coordination_metrics_manager:
111        std::cell::RefCell<crate::storage::coordination_metrics::CoordinationMetricsManager>,
112    #[cfg(feature = "telemetry")]
113    metrics: Option<crate::telemetry::Metrics>,
114    #[cfg(feature = "telemetry")]
115    span_recorder: Option<crate::telemetry::SpanRecorder>,
116    #[cfg(feature = "telemetry")]
117    span_context: Option<crate::telemetry::SpanContext>,
118    max_export_size_bytes: Option<u64>,
119}
120
121#[cfg(target_arch = "wasm32")]
122struct PendingConnection(Option<Rc<crate::connection_pool::ConnectionState>>);
123
124#[cfg(target_arch = "wasm32")]
125impl Drop for PendingConnection {
126    fn drop(&mut self) {
127        if let Some(state) = &self.0 {
128            crate::connection_pool::release_connection_state(state);
129        }
130    }
131}
132
133#[cfg(target_arch = "wasm32")]
134impl Database {
135    fn query_error(error: DatabaseError) -> JsValue {
136        let context = if matches!(error.code.as_str(), "NOT_LEADER" | "LEADER_ELECTION_ERROR") {
137            "Write permission denied"
138        } else {
139            "Query execution failed"
140        };
141        JsValue::from_str(&format!("{context}: {error}"))
142    }
143
144    /// Check if a SQL statement is a write operation
145    fn is_write_operation(&self, sql: &str) -> Result<bool, DatabaseError> {
146        let statement =
147            crate::wasm_statement::Statement::prepare(self.connection_state.db.get(), sql)?;
148        Ok(statement.is_data_write())
149    }
150
151    /// Get metrics for observability
152    ///
153    /// Returns a reference to the Metrics instance for tracking queries, errors, and performance
154    #[cfg(feature = "telemetry")]
155    pub fn metrics(&self) -> Option<&crate::telemetry::Metrics> {
156        self.metrics.as_ref()
157    }
158
159    /// Check write permission - only leader can write (unless override enabled)
160    async fn check_write_permission(&mut self, sql: &str) -> Result<(), DatabaseError> {
161        if !self.is_write_operation(sql)? {
162            // Not a write operation, allow it
163            return Ok(());
164        }
165
166        // Check if non-leader writes are allowed
167        if self.allow_non_leader_writes {
168            log::info!("WRITE_ALLOWED: Non-leader writes enabled for {}", self.name);
169            return Ok(());
170        }
171
172        // Check if this instance is the leader
173        use crate::vfs::indexeddb_vfs::get_storage_with_fallback;
174
175        let db_name = &self.name;
176        let storage_rc = get_storage_with_fallback(db_name);
177
178        if let Some(storage) = storage_rc {
179            let is_leader = with_storage_async!(storage, "check_write_permission", |s| s
180                .is_leader())
181            .ok_or_else(|| {
182                DatabaseError::new("BORROW_CONFLICT", "Failed to check leader status")
183            })?;
184
185            if !is_leader {
186                log::error!("WRITE_DENIED: Instance is not leader for {}", db_name);
187                return Err(DatabaseError::new(
188                    "WRITE_PERMISSION_DENIED",
189                    "Only the leader tab can write to this database. Use db.isLeader() to check status or call db.allowNonLeaderWrites(true) for single-tab mode.",
190                ));
191            }
192
193            log::info!("WRITE_ALLOWED: Instance is leader for {}", db_name);
194            Ok(())
195        } else {
196            // No storage found - allow by default (single-instance mode)
197            log::info!(
198                "WRITE_ALLOWED: No storage found for {} (single-instance mode)",
199                db_name
200            );
201            Ok(())
202        }
203    }
204
205    fn default_wasm_config(name: String) -> DatabaseConfig {
206        DatabaseConfig {
207            name,
208            version: Some(1),
209            cache_size: Some(10_000),
210            page_size: Some(4096),
211            auto_vacuum: Some(true),
212            journal_mode: Some("WAL".to_string()),
213            max_export_size_bytes: Some(2 * 1024 * 1024 * 1024),
214        }
215    }
216
217    async fn new_with_storage_backend(
218        config: DatabaseConfig,
219        backend: crate::storage::StorageBackend,
220    ) -> Result<Self, DatabaseError> {
221        let normalized_name = normalize_db_name(&config.name);
222        crate::vfs::indexeddb_vfs::ensure_storage_registered_with_backend(
223            &normalized_name,
224            backend,
225        )
226        .await?;
227        Self::new(config).await
228    }
229
230    pub async fn new(config: DatabaseConfig) -> Result<Self, DatabaseError> {
231        use std::ffi::{CStr, CString};
232
233        log::info!("Database::new called for {}", config.name);
234
235        // CRITICAL: Use DRY helper to normalize name WITH .db extension
236        // This ensures Database.name, GLOBAL_STORAGE keys, and IndexedDB keys all match
237        let normalized_name = normalize_db_name(&config.name);
238
239        // Use a unique VFS name per database to avoid interference
240        let vfs_name = format!("vfs_{}", normalized_name.trim_end_matches(".db"));
241        let vfs_name_cstr = CString::new(vfs_name.as_str())
242            .map_err(|_| DatabaseError::new("INVALID_VFS_NAME", "Invalid VFS name"))?;
243        let vfs_exists = unsafe {
244            let existing_vfs = sqlite_wasm_rs::sqlite3_vfs_find(vfs_name_cstr.as_ptr());
245            !existing_vfs.is_null()
246        };
247
248        if !vfs_exists {
249            // Create and register VFS only if it doesn't exist
250            log::debug!("Creating IndexedDBVFS for: {}", normalized_name);
251            let vfs = crate::vfs::IndexedDBVFS::new(&normalized_name).await?;
252            log::debug!("Registering VFS as '{}'", vfs_name);
253            vfs.register(&vfs_name)?;
254            log::info!("VFS registered successfully");
255        } else {
256            log::info!("VFS '{}' already registered, reusing existing", vfs_name);
257            // Ensure BlockStorage exists for this database in the registry
258            // The existing VFS will find it via STORAGE_REGISTRY
259            let _vfs = crate::vfs::IndexedDBVFS::new(&normalized_name).await?;
260            log::info!("BlockStorage ensured for {}", normalized_name);
261        }
262
263        // CRITICAL: Synchronize SQLite connection opening to prevent WAL initialization conflicts
264        // Wait if another task is currently opening a connection to this database
265        let _open_reservation = {
266            struct Reservation(String);
267            impl Drop for Reservation {
268                fn drop(&mut self) {
269                    DB_OPEN_IN_PROGRESS.with(|opens| {
270                        opens.borrow_mut().remove(&self.0);
271                    });
272                }
273            }
274            const MAX_OPEN_WAIT_MS: u32 = 1000; // Reduced from 5000 - 1s is sufficient
275            const OPEN_POLL_MS: u32 = 10;
276            let max_open_attempts = MAX_OPEN_WAIT_MS / OPEN_POLL_MS;
277
278            let mut reservation = None;
279            for attempt in 0..max_open_attempts {
280                let can_open = DB_OPEN_IN_PROGRESS.with(|opens| {
281                    let mut set = opens.borrow_mut();
282                    if set.contains(&normalized_name) {
283                        false // Someone else is opening
284                    } else {
285                        set.insert(normalized_name.clone());
286                        true // We got it
287                    }
288                });
289
290                if can_open {
291                    reservation = Some(Reservation(normalized_name.clone()));
292                    web_sys::console::log_1(
293                        &format!("[DB] {} - ACQUIRED sqlite open lock", config.name).into(),
294                    );
295                    break;
296                } else {
297                    web_sys::console::log_1(
298                        &format!(
299                            "[DB] {} - Waiting for sqlite open (attempt {})",
300                            config.name, attempt
301                        )
302                        .into(),
303                    );
304                    crate::storage::export_import_lock::sleep(OPEN_POLL_MS)
305                        .await
306                        .map_err(|error| {
307                            DatabaseError::new("OPEN_WAIT_ERROR", &format!("{error:?}"))
308                        })?;
309                    continue;
310                }
311            }
312            reservation.ok_or_else(|| {
313                DatabaseError::new("OPEN_TIMEOUT", "SQLite open reservation timed out")
314            })?
315        };
316
317        // Use connection pooling to share connections between instances
318        let (connection_state, db) = {
319            let vfs_name_str = vfs_name.clone(); // Capture the VFS name to use in closure
320            let filename_copy = normalized_name.clone(); // Capture filename for logging
321            let pool_key = normalized_name.trim_end_matches(".db").to_string(); // Pool uses name without .db
322            let state = crate::connection_pool::get_or_create_connection(&pool_key, || {
323                let mut db = std::ptr::null_mut();
324                let db_name = CString::new(normalized_name.clone())
325                    .map_err(|_| "Invalid database name".to_string())?;
326                let vfs_cstr = CString::new(vfs_name_str.as_str())
327                    .map_err(|_| "Invalid VFS name".to_string())?;
328
329                log::info!(
330                    "Opening database: {} with VFS: {}",
331                    filename_copy,
332                    vfs_name_str
333                );
334
335                #[cfg(target_arch = "wasm32")]
336                web_sys::console::log_1(
337                    &"[OPEN] About to call sqlite3_open_v2...".to_string().into(),
338                );
339
340                let ret = unsafe {
341                    sqlite_wasm_rs::sqlite3_open_v2(
342                        db_name.as_ptr(),
343                        &mut db as *mut _,
344                        sqlite_wasm_rs::SQLITE_OPEN_READWRITE | sqlite_wasm_rs::SQLITE_OPEN_CREATE,
345                        vfs_cstr.as_ptr(),
346                    )
347                };
348
349                #[cfg(target_arch = "wasm32")]
350                web_sys::console::log_1(
351                    &format!("[OPEN] sqlite3_open_v2 returned: {}", ret).into(),
352                );
353
354                log::info!(
355                    "sqlite3_open_v2 returned: {} for database: {}",
356                    ret,
357                    filename_copy
358                );
359
360                if ret != sqlite_wasm_rs::SQLITE_OK {
361                    let err_msg = unsafe {
362                        let msg_ptr = sqlite_wasm_rs::sqlite3_errmsg(db);
363                        if !msg_ptr.is_null() {
364                            CStr::from_ptr(msg_ptr).to_string_lossy().into_owned()
365                        } else {
366                            "Unknown error".to_string()
367                        }
368                    };
369
370                    #[cfg(target_arch = "wasm32")]
371                    web_sys::console::log_1(
372                        &format!(
373                            "[OPEN] ERROR - sqlite3_open_v2 FAILED: ret={}, err={}",
374                            ret, err_msg
375                        )
376                        .into(),
377                    );
378
379                    if !db.is_null() {
380                        let close_result = unsafe { sqlite_wasm_rs::sqlite3_close(db) };
381                        if close_result != sqlite_wasm_rs::SQLITE_OK {
382                            log::error!(
383                                "Failed to close rejected SQLite connection: {}",
384                                close_result
385                            );
386                        }
387                    }
388                    return Err(format!(
389                        "Failed to open database with IndexedDB VFS: {}",
390                        err_msg
391                    ));
392                }
393
394                log::info!("Database opened successfully with IndexedDB VFS");
395                Ok(db)
396            })
397            .map_err(|e| DatabaseError::new("CONNECTION_POOL_ERROR", &e))?;
398            let db_ptr = state.db.get();
399            (state, db_ptr)
400        };
401        let mut pending_connection = PendingConnection(Some(connection_state.clone()));
402
403        // Apply configuration options via PRAGMA statements
404        let exec_sql = |db: *mut sqlite_wasm_rs::sqlite3, sql: &str| -> Result<(), DatabaseError> {
405            let c_sql = CString::new(sql)
406                .map_err(|_| DatabaseError::new("INVALID_SQL", "Invalid SQL statement"))?;
407
408            let ret = unsafe {
409                sqlite_wasm_rs::sqlite3_exec(
410                    db,
411                    c_sql.as_ptr(),
412                    None,
413                    std::ptr::null_mut(),
414                    std::ptr::null_mut(),
415                )
416            };
417
418            if ret != sqlite_wasm_rs::SQLITE_OK {
419                let err_msg = unsafe {
420                    let msg_ptr = sqlite_wasm_rs::sqlite3_errmsg(db);
421                    if !msg_ptr.is_null() {
422                        CStr::from_ptr(msg_ptr).to_string_lossy().into_owned()
423                    } else {
424                        "Unknown error".to_string()
425                    }
426                };
427                log::warn!("Failed to execute SQL '{}': {}", sql, err_msg);
428                return Err(DatabaseError::new(
429                    "SQLITE_ERROR",
430                    &format!("Failed to execute: {}", err_msg),
431                ));
432            }
433            Ok(())
434        };
435
436        // CRITICAL: Set busy_timeout FIRST to handle concurrent access
437        // This makes SQLite wait and retry for up to 10 seconds when the database is locked
438        // instead of immediately returning SQLITE_BUSY errors during parallel operations
439        log::debug!("Setting busy_timeout to 10000ms for concurrent access handling");
440        exec_sql(db, "PRAGMA busy_timeout = 10000")?;
441
442        // Apply page_size (must be set before any tables are created)
443        if let Some(page_size) = config.page_size {
444            log::debug!("Setting page_size to {}", page_size);
445            exec_sql(db, &format!("PRAGMA page_size = {}", page_size))?;
446        }
447
448        // Apply cache_size
449        if let Some(cache_size) = config.cache_size {
450            log::debug!("Setting cache_size to {}", cache_size);
451            exec_sql(db, &format!("PRAGMA cache_size = {}", cache_size))?;
452        }
453
454        // Apply journal_mode
455        // WAL mode is now fully supported via shared memory (xShm*) implementation
456        if let Some(ref journal_mode) = config.journal_mode {
457            log::debug!("Setting journal_mode to {}", journal_mode);
458
459            let pragma_sql = format!("PRAGMA journal_mode = {}", journal_mode);
460            let c_sql = CString::new(pragma_sql.as_str())
461                .map_err(|_| DatabaseError::new("INVALID_SQL", "Invalid SQL statement"))?;
462
463            let mut stmt: *mut sqlite_wasm_rs::sqlite3_stmt = std::ptr::null_mut();
464            let ret = unsafe {
465                sqlite_wasm_rs::sqlite3_prepare_v2(
466                    db,
467                    c_sql.as_ptr(),
468                    -1,
469                    &mut stmt as *mut _,
470                    std::ptr::null_mut(),
471                )
472            };
473
474            if ret == sqlite_wasm_rs::SQLITE_OK && !stmt.is_null() {
475                let step_ret = unsafe { sqlite_wasm_rs::sqlite3_step(stmt) };
476                if step_ret == sqlite_wasm_rs::SQLITE_ROW {
477                    let result_ptr = unsafe { sqlite_wasm_rs::sqlite3_column_text(stmt, 0) };
478                    if !result_ptr.is_null() {
479                        let result_mode = unsafe {
480                            std::ffi::CStr::from_ptr(result_ptr as *const i8)
481                                .to_string_lossy()
482                                .to_uppercase()
483                        };
484
485                        if result_mode != journal_mode.to_uppercase() {
486                            log::warn!(
487                                "journal_mode {} requested but SQLite set {}",
488                                journal_mode,
489                                result_mode
490                            );
491                        } else {
492                            log::info!("journal_mode successfully set to {}", result_mode);
493                        }
494                    }
495                }
496                unsafe { sqlite_wasm_rs::sqlite3_finalize(stmt) };
497            } else {
498                log::warn!("Failed to prepare journal_mode PRAGMA");
499            }
500        }
501
502        // Apply auto_vacuum (must be set before any tables are created)
503        if let Some(auto_vacuum) = config.auto_vacuum {
504            let vacuum_mode = if auto_vacuum { 1 } else { 0 }; // 0=none, 1=full, 2=incremental
505            log::debug!("Setting auto_vacuum to {}", vacuum_mode);
506            exec_sql(db, &format!("PRAGMA auto_vacuum = {}", vacuum_mode))?;
507        }
508
509        log::info!("Database configuration applied successfully");
510
511        // Initialize metrics for telemetry
512        #[cfg(feature = "telemetry")]
513        let metrics = crate::telemetry::Metrics::new().map_err(|e| {
514            DatabaseError::new(
515                "METRICS_ERROR",
516                &format!("Failed to initialize metrics: {}", e),
517            )
518        })?;
519
520        let database = Database {
521            connection_state,
522            name: normalized_name.clone(), // CRITICAL: Use normalized name WITH .db to match registry
523            on_data_change_callback: None,
524            allow_non_leader_writes: false,
525            optimistic_updates_manager: std::cell::RefCell::new(
526                crate::storage::optimistic_updates::OptimisticUpdatesManager::new(),
527            ),
528            coordination_metrics_manager: std::cell::RefCell::new(
529                crate::storage::coordination_metrics::CoordinationMetricsManager::new(),
530            ),
531            #[cfg(feature = "telemetry")]
532            metrics: Some(metrics),
533            #[cfg(feature = "telemetry")]
534            span_recorder: None,
535            #[cfg(feature = "telemetry")]
536            span_context: Some(crate::telemetry::SpanContext::new()),
537            max_export_size_bytes: config.max_export_size_bytes,
538        };
539
540        pending_connection.0 = None;
541        Ok(database)
542    }
543
544    /// Open a database with a specific VFS using connection pooling
545    pub async fn open_with_vfs(filename: &str, vfs_name: &str) -> Result<Self, DatabaseError> {
546        use std::ffi::CString;
547
548        log::info!("Opening database {} with VFS {}", filename, vfs_name);
549
550        // Normalize the database name WITH .db extension
551        let normalized_name = normalize_db_name(filename);
552        let pool_key = normalized_name.trim_end_matches(".db").to_string();
553
554        // Use connection pooling with custom VFS
555        let connection_state = crate::connection_pool::get_or_create_connection(&pool_key, || {
556            let mut db: *mut sqlite_wasm_rs::sqlite3 = std::ptr::null_mut();
557            let db_name = CString::new(normalized_name.clone())
558                .map_err(|_| "Invalid database name".to_string())?;
559            let vfs_cstr = CString::new(vfs_name).map_err(|_| "Invalid VFS name".to_string())?;
560
561            let ret = unsafe {
562                sqlite_wasm_rs::sqlite3_open_v2(
563                    db_name.as_ptr(),
564                    &mut db as *mut _,
565                    sqlite_wasm_rs::SQLITE_OPEN_READWRITE | sqlite_wasm_rs::SQLITE_OPEN_CREATE,
566                    vfs_cstr.as_ptr(),
567                )
568            };
569
570            if ret != sqlite_wasm_rs::SQLITE_OK {
571                let err_msg = if !db.is_null() {
572                    unsafe {
573                        let msg_ptr = sqlite_wasm_rs::sqlite3_errmsg(db);
574                        if !msg_ptr.is_null() {
575                            std::ffi::CStr::from_ptr(msg_ptr)
576                                .to_string_lossy()
577                                .into_owned()
578                        } else {
579                            "Unknown error".to_string()
580                        }
581                    }
582                } else {
583                    "Failed to open database".to_string()
584                };
585                return Err(format!("SQLITE_ERROR: {}", err_msg));
586            }
587
588            Ok(db)
589        })
590        .map_err(|e| DatabaseError::new("OPEN_ERROR", &e))?;
591
592        log::info!(
593            "Successfully opened database {} with VFS {}",
594            normalized_name,
595            vfs_name
596        );
597
598        // Initialize metrics for telemetry
599        #[cfg(feature = "telemetry")]
600        let metrics = crate::telemetry::Metrics::new().map_err(|e| {
601            DatabaseError::new(
602                "METRICS_ERROR",
603                &format!("Failed to initialize metrics: {}", e),
604            )
605        })?;
606
607        Ok(Database {
608            connection_state,
609            name: normalized_name, // CRITICAL: Store normalized name WITH .db
610            on_data_change_callback: None,
611            allow_non_leader_writes: false,
612            optimistic_updates_manager: std::cell::RefCell::new(
613                crate::storage::optimistic_updates::OptimisticUpdatesManager::new(),
614            ),
615            coordination_metrics_manager: std::cell::RefCell::new(
616                crate::storage::coordination_metrics::CoordinationMetricsManager::new(),
617            ),
618            #[cfg(feature = "telemetry")]
619            metrics: Some(metrics),
620            #[cfg(feature = "telemetry")]
621            span_recorder: None,
622            #[cfg(feature = "telemetry")]
623            span_context: Some(crate::telemetry::SpanContext::new()),
624            max_export_size_bytes: Some(2 * 1024 * 1024 * 1024), // Default 2GB limit
625        })
626    }
627
628    pub async fn execute_internal(&mut self, sql: &str) -> Result<QueryResult, DatabaseError> {
629        self.execute_with_params_internal(sql, &[]).await
630    }
631
632    pub async fn execute_with_params_internal(
633        &mut self,
634        sql: &str,
635        params: &[ColumnValue],
636    ) -> Result<QueryResult, DatabaseError> {
637        self.execute_query(sql, params, false).await
638    }
639
640    async fn execute_query(
641        &mut self,
642        sql: &str,
643        params: &[ColumnValue],
644        enforce_write_permission: bool,
645    ) -> Result<QueryResult, DatabaseError> {
646        let start_time = js_sys::Date::now();
647
648        #[cfg(feature = "telemetry")]
649        self.ensure_metrics_propagated();
650        #[cfg(feature = "telemetry")]
651        let span = if self.span_recorder.is_some() {
652            let query_type = sql
653                .split_whitespace()
654                .next()
655                .unwrap_or("UNKNOWN")
656                .to_uppercase();
657            let mut builder = crate::telemetry::SpanBuilder::new("execute_query".to_string())
658                .with_attribute("query_type", query_type)
659                .with_attribute("sql", sql.to_string());
660            if let Some(context) = &self.span_context {
661                builder = builder.with_baggage_from_context(context);
662            }
663            let span = builder.build();
664            if let Some(context) = &self.span_context {
665                context.enter_span(span.span_id.clone());
666            }
667            Some(span)
668        } else {
669            None
670        };
671        #[cfg(feature = "telemetry")]
672        if let Some(metrics) = &self.metrics {
673            metrics.queries_total().inc();
674        }
675
676        let permission = if enforce_write_permission {
677            self.check_write_permission(sql).await
678        } else {
679            Ok(())
680        };
681        let mut result = permission
682            .and_then(|()| {
683                crate::wasm_statement::Statement::prepare(self.connection_state.db.get(), sql)
684            })
685            .and_then(|statement| statement.execute(params))
686            .map_err(|error| error.with_sql(sql));
687        let duration = js_sys::Date::now() - start_time;
688        if let Ok(query) = &mut result {
689            query.execution_time_ms = duration;
690        }
691
692        #[cfg(feature = "telemetry")]
693        if let Some(metrics) = &self.metrics {
694            metrics.query_duration().observe(duration);
695            if result.is_err() {
696                metrics.errors_total().inc();
697            }
698        }
699        #[cfg(feature = "telemetry")]
700        if let Some(mut span) = span {
701            span.end_time_ms = Some(js_sys::Date::now());
702            span.attributes
703                .insert("duration_ms".to_string(), duration.to_string());
704            match &result {
705                Ok(query) => {
706                    span.status = crate::telemetry::SpanStatus::Ok;
707                    span.attributes
708                        .insert("row_count".to_string(), query.rows.len().to_string());
709                    span.attributes
710                        .insert("affected_rows".to_string(), query.affected_rows.to_string());
711                }
712                Err(error) => span.status = crate::telemetry::SpanStatus::Error(error.to_string()),
713            }
714            if let Some(recorder) = &self.span_recorder {
715                recorder.record_span(span);
716            }
717            if let Some(context) = &self.span_context {
718                context.exit_span();
719            }
720        }
721        result
722    }
723
724    /// Set telemetry metrics for this database instance
725    #[cfg(feature = "telemetry")]
726    pub fn set_metrics(&mut self, metrics: Option<crate::telemetry::Metrics>) {
727        self.metrics = metrics.clone();
728        self.ensure_metrics_propagated();
729    }
730
731    /// Set span recorder for distributed tracing
732    #[cfg(feature = "telemetry")]
733    pub fn set_span_recorder(&mut self, recorder: Option<crate::telemetry::SpanRecorder>) {
734        self.span_recorder = recorder;
735    }
736
737    /// Get span context for distributed tracing
738    #[cfg(feature = "telemetry")]
739    pub fn get_span_context(&self) -> Option<&crate::telemetry::SpanContext> {
740        self.span_context.as_ref()
741    }
742
743    /// Get span recorder for distributed tracing
744    #[cfg(feature = "telemetry")]
745    pub fn get_span_recorder(&self) -> Option<&crate::telemetry::SpanRecorder> {
746        self.span_recorder.as_ref()
747    }
748    /// Ensure metrics are propagated to BlockStorage
749    #[cfg(feature = "telemetry")]
750    fn ensure_metrics_propagated(&self) {
751        // Propagate metrics to BlockStorage via STORAGE_REGISTRY
752        #[cfg(target_arch = "wasm32")]
753        {
754            use crate::vfs::indexeddb_vfs::get_storage_with_fallback;
755
756            if self.metrics.is_none() {
757                return;
758            }
759
760            let db_name = &self.name;
761
762            if let Some(storage_rc) = get_storage_with_fallback(db_name) {
763                storage_rc.set_metrics(self.metrics.clone());
764            }
765        }
766    }
767
768    pub async fn close_internal(&mut self) -> Result<(), DatabaseError> {
769        log::info!("CLOSE_INTERNAL STARTED for: {}", self.name);
770
771        // Check if connection is already null (e.g., after import force-close)
772        if self.connection_state.db.get().is_null() {
773            log::info!(
774                "Connection already null for {}, skipping close operations",
775                self.name
776            );
777            return Ok(());
778        }
779
780        // Checkpoint WAL data before close using PASSIVE mode (non-blocking)
781        log::info!("Checkpointing WAL before close: {}", self.name);
782        let _ = self
783            .execute_internal("PRAGMA wal_checkpoint(PASSIVE)")
784            .await;
785        log::info!("WAL checkpoint completed for: {}", self.name);
786
787        // Sync to IndexedDB before closing to ensure data persists
788        log::info!("Syncing database before close: {}", self.name);
789        self.sync_internal().await?;
790        log::info!("Sync completed for: {}", self.name);
791
792        web_sys::console::log_1(
793            &format!("CLOSE: About to stop leader election for {}", self.name).into(),
794        );
795
796        // Stop leader election before closing
797        #[cfg(target_arch = "wasm32")]
798        {
799            use crate::vfs::indexeddb_vfs::get_storage_with_fallback;
800
801            let db_name = &self.name;
802            web_sys::console::log_1(
803                &format!("STOP_ELECTION: Getting storage for {}", db_name).into(),
804            );
805            log::info!("STOP_ELECTION: Getting storage for {}", db_name);
806            let storage_rc = get_storage_with_fallback(db_name);
807
808            if let Some(storage_rc) = storage_rc {
809                log::info!("STOP_ELECTION: Found storage for {}, calling stop", db_name);
810                match with_storage_async!(storage_rc, "stop_leader_election", |storage| storage
811                    .stop_leader_election())
812                {
813                    Some(Ok(())) => {
814                        log::info!("STOP_ELECTION: Successfully stopped for {}", db_name);
815                    }
816                    Some(Err(e)) => {
817                        log::warn!("STOP_ELECTION: Failed for {}: {:?}", db_name, e);
818                    }
819                    None => {
820                        log::warn!("STOP_ELECTION: Borrow failed for {}", db_name);
821                    }
822                }
823            } else {
824                log::warn!("STOP_ELECTION: No storage found for {}", db_name);
825            }
826            log::info!("STOP_ELECTION: Completed section for {}", db_name);
827        }
828
829        // NOTE: Do NOT call release_connection here
830        // The Drop impl will handle releasing the connection when the Database instance is dropped
831        // Calling it here would cause a double-release when both close() and Drop are called
832
833        log::info!(
834            "Closed database: {} (connection will be released on Drop)",
835            self.name
836        );
837        Ok(())
838    }
839
840    /// Query database and return rows (alias for execute that returns rows)
841    pub async fn query(&mut self, sql: &str) -> Result<Vec<Row>, DatabaseError> {
842        let result = self.execute_internal(sql).await?;
843        Ok(result.rows)
844    }
845
846    pub async fn sync_internal(&mut self) -> Result<(), DatabaseError> {
847        // Start timing for telemetry
848        #[cfg(all(target_arch = "wasm32", feature = "telemetry"))]
849        let start_time = js_sys::Date::now();
850
851        // Create span for VFS sync operation with automatic context linking
852        #[cfg(feature = "telemetry")]
853        let span = if self.span_recorder.is_some() {
854            let mut builder = crate::telemetry::SpanBuilder::new("vfs_sync".to_string())
855                .with_attribute("operation", "sync");
856
857            // Automatically link to parent span via context and copy baggage
858            if let Some(ref context) = self.span_context {
859                builder = builder
860                    .with_context(context)
861                    .with_baggage_from_context(context);
862            }
863
864            let span = builder.build();
865
866            // Enter this span's context
867            if let Some(ref context) = self.span_context {
868                context.enter_span(span.span_id.clone());
869            }
870
871            Some(span)
872        } else {
873            None
874        };
875
876        // Track sync operation start
877        #[cfg(feature = "telemetry")]
878        if let Some(ref metrics) = self.metrics {
879            metrics.sync_operations_total().inc();
880        }
881
882        // Track blocks persisted for span attributes
883        #[cfg(feature = "telemetry")]
884        let mut blocks_count = 0;
885
886        // Trigger VFS sync to persist all blocks to IndexedDB
887        #[cfg(target_arch = "wasm32")]
888        {
889            use crate::storage::vfs_sync;
890
891            // CRITICAL: Checkpoint WAL and flush page cache to ensure all data is in GLOBAL_STORAGE
892            let db_ptr = self.connection_state.db.get();
893            if !db_ptr.is_null() {
894                // Step 1: Checkpoint WAL to write all WAL data to main database
895                // TRUNCATE mode ensures WAL is cleared after checkpoint
896                let checkpoint_sql =
897                    std::ffi::CString::new("PRAGMA wal_checkpoint(TRUNCATE)").expect("valid SQL");
898                let mut stmt: *mut sqlite_wasm_rs::sqlite3_stmt = std::ptr::null_mut();
899                let prepare_result = unsafe {
900                    sqlite_wasm_rs::sqlite3_prepare_v2(
901                        db_ptr,
902                        checkpoint_sql.as_ptr(),
903                        -1,
904                        &mut stmt,
905                        std::ptr::null_mut(),
906                    )
907                };
908                if prepare_result == sqlite_wasm_rs::SQLITE_OK && !stmt.is_null() {
909                    unsafe {
910                        sqlite_wasm_rs::sqlite3_step(stmt);
911                        sqlite_wasm_rs::sqlite3_finalize(stmt);
912                    }
913                    log::debug!("WAL checkpoint completed");
914                }
915
916                // Step 2: Flush page cache to VFS
917                let flush_result = unsafe { sqlite_wasm_rs::sqlite3_db_cacheflush(db_ptr) };
918                if flush_result != sqlite_wasm_rs::SQLITE_OK {
919                    log::warn!("sqlite3_db_cacheflush returned {}", flush_result);
920                }
921            }
922
923            // Collect blocks from GLOBAL_STORAGE (where VFS writes them)
924            // CRITICAL: Use self.name WITH .db - matches main branch behavior
925            // Database.name already normalized by normalize_db_name() in Database::new()
926            let storage_name = &self.name;
927
928            // Advance commit marker
929            let next_commit = vfs_sync::with_global_commit_marker(|cm| {
930                #[cfg(target_arch = "wasm32")]
931                let mut cm_ref = cm.borrow_mut();
932                #[cfg(not(target_arch = "wasm32"))]
933                let mut cm_ref = cm.lock();
934
935                let current = cm_ref.get(storage_name).copied().unwrap_or(0);
936                let new_marker = current + 1;
937                cm_ref.insert(storage_name.to_string(), new_marker);
938                log::debug!(
939                    "Advanced commit marker for {} from {} to {}",
940                    storage_name,
941                    current,
942                    new_marker
943                );
944                new_marker
945            });
946
947            web_sys::console::log_1(
948                &format!(
949                    "[SYNC] Collecting blocks from GLOBAL_STORAGE for: {}",
950                    storage_name
951                )
952                .into(),
953            );
954            let (blocks_to_persist, metadata_to_persist) =
955                vfs_sync::with_global_storage(|storage| {
956                    #[cfg(target_arch = "wasm32")]
957                    let storage_map = storage.borrow();
958                    #[cfg(not(target_arch = "wasm32"))]
959                    let storage_map = storage.lock();
960
961                    let blocks = if let Some(db_storage) = storage_map.get(storage_name) {
962                        let count = db_storage.len();
963                        web_sys::console::log_1(
964                            &format!("[SYNC] Found {} blocks in GLOBAL_STORAGE", count).into(),
965                        );
966                        db_storage
967                            .iter()
968                            .map(|(&id, data)| (id, data.clone()))
969                            .collect::<Vec<_>>()
970                    } else {
971                        web_sys::console::log_1(
972                            &format!(
973                                "[SYNC] No blocks found in GLOBAL_STORAGE for {}",
974                                storage_name
975                            )
976                            .into(),
977                        );
978                        Vec::new()
979                    };
980
981                    let metadata = vfs_sync::with_global_metadata(|meta| {
982                        #[cfg(target_arch = "wasm32")]
983                        let meta_map = meta.borrow();
984                        #[cfg(not(target_arch = "wasm32"))]
985                        let meta_map = meta.lock();
986                        if let Some(db_meta) = meta_map.get(storage_name) {
987                            let count = db_meta.len();
988                            web_sys::console::log_1(
989                                &format!("[SYNC] Found {} metadata entries", count).into(),
990                            );
991                            db_meta
992                                .iter()
993                                .map(|(&id, metadata)| (id, metadata.clone()))
994                                .collect::<Vec<_>>()
995                        } else {
996                            web_sys::console::log_1(&"[SYNC] No metadata found".to_string().into());
997                            Vec::new()
998                        }
999                    });
1000
1001                    (blocks, metadata)
1002                });
1003
1004            let backend = crate::vfs::indexeddb_vfs::get_storage_with_fallback(storage_name)
1005                .map(|storage| storage.storage_backend())
1006                .unwrap_or(crate::storage::StorageBackend::IndexedDb);
1007
1008            web_sys::console::log_1(
1009                &format!(
1010                    "[SYNC] Preparing to persist {} blocks using backend {}",
1011                    blocks_to_persist.len(),
1012                    backend.as_str()
1013                )
1014                .into(),
1015            );
1016
1017            if !blocks_to_persist.is_empty() {
1018                #[cfg(feature = "telemetry")]
1019                {
1020                    blocks_count = blocks_to_persist.len();
1021                }
1022                match backend {
1023                    crate::storage::StorageBackend::IndexedDb => {
1024                        web_sys::console::log_1(
1025                            &format!(
1026                                "[SYNC] Persisting {} blocks to IndexedDB",
1027                                blocks_to_persist.len()
1028                            )
1029                            .into(),
1030                        );
1031                        crate::storage::wasm_indexeddb::persist_to_indexeddb_event_based(
1032                            storage_name,
1033                            blocks_to_persist,
1034                            metadata_to_persist,
1035                            next_commit,
1036                            #[cfg(feature = "telemetry")]
1037                            self.span_recorder.clone(),
1038                            #[cfg(feature = "telemetry")]
1039                            span.as_ref().map(|s| s.span_id.clone()),
1040                        )
1041                        .await?;
1042                        web_sys::console::log_1(
1043                            &"[SYNC] Successfully persisted to IndexedDB"
1044                                .to_string()
1045                                .into(),
1046                        );
1047                    }
1048                    crate::storage::StorageBackend::Opfs
1049                    | crate::storage::StorageBackend::Hybrid => {
1050                        web_sys::console::log_1(
1051                            &format!(
1052                                "[SYNC] Persisting {} blocks to OPFS and mirroring to IndexedDB",
1053                                blocks_to_persist.len()
1054                            )
1055                            .into(),
1056                        );
1057                        crate::storage::hybrid_store::hybrid_persist(
1058                            storage_name,
1059                            blocks_to_persist,
1060                            metadata_to_persist,
1061                            next_commit,
1062                            #[cfg(feature = "telemetry")]
1063                            self.span_recorder.clone(),
1064                            #[cfg(feature = "telemetry")]
1065                            span.as_ref().map(|s| s.span_id.clone()),
1066                        )
1067                        .await?;
1068                        web_sys::console::log_1(
1069                            &"[SYNC] Successfully persisted to OPFS and IndexedDB"
1070                                .to_string()
1071                                .into(),
1072                        );
1073                    }
1074                }
1075            } else {
1076                web_sys::console::log_1(
1077                    &"[SYNC] WARNING: No blocks to persist - GLOBAL_STORAGE is empty!"
1078                        .to_string()
1079                        .into(),
1080                );
1081            }
1082
1083            // Send notification after successful sync
1084            use crate::storage::broadcast_notifications::{
1085                BroadcastNotification, send_change_notification,
1086            };
1087
1088            let notification = BroadcastNotification::DataChanged {
1089                db_name: self.name.clone(),
1090                timestamp: js_sys::Date::now() as u64,
1091            };
1092
1093            log::debug!("Sending DataChanged notification for {}", self.name);
1094
1095            if let Err(e) = send_change_notification(&notification) {
1096                log::warn!("Failed to send change notification: {}", e);
1097                // Don't fail the sync if notification fails
1098            }
1099        }
1100
1101        // Record sync duration
1102        #[cfg(all(target_arch = "wasm32", feature = "telemetry"))]
1103        if let Some(ref metrics) = self.metrics {
1104            let duration_ms = js_sys::Date::now() - start_time;
1105            metrics.sync_duration().observe(duration_ms);
1106        }
1107
1108        // Finish span successfully
1109        #[cfg(feature = "telemetry")]
1110        if let Some(mut s) = span {
1111            s.status = crate::telemetry::SpanStatus::Ok;
1112            #[cfg(target_arch = "wasm32")]
1113            {
1114                s.end_time_ms = Some(js_sys::Date::now());
1115                let duration_ms = s.end_time_ms.unwrap() - s.start_time_ms;
1116                s.attributes
1117                    .insert("duration_ms".to_string(), duration_ms.to_string());
1118            }
1119            #[cfg(not(target_arch = "wasm32"))]
1120            {
1121                let now = std::time::SystemTime::now()
1122                    .duration_since(std::time::UNIX_EPOCH)
1123                    .unwrap()
1124                    .as_millis() as f64;
1125                s.end_time_ms = Some(now);
1126                let duration_ms = s.end_time_ms.unwrap() - s.start_time_ms;
1127                s.attributes
1128                    .insert("duration_ms".to_string(), duration_ms.to_string());
1129            }
1130            s.attributes
1131                .insert("blocks_persisted".to_string(), blocks_count.to_string());
1132            if let Some(recorder) = &self.span_recorder {
1133                recorder.record_span(s);
1134            }
1135
1136            // Exit span context
1137            if let Some(ref context) = self.span_context {
1138                context.exit_span();
1139            }
1140        }
1141
1142        Ok(())
1143    }
1144}
1145
1146#[cfg(target_arch = "wasm32")]
1147impl Drop for Database {
1148    fn drop(&mut self) {
1149        web_sys::console::log_1(&format!("DROP: Releasing connection for {}", self.name).into());
1150
1151        // Release the connection back to the pool
1152        // The pool will close it if this was the last reference
1153        if !crate::connection_pool::release_connection_state(&self.connection_state) {
1154            return;
1155        }
1156
1157        web_sys::console::log_1(&format!("DROP: Connection released for {}", self.name).into());
1158
1159        // CRITICAL: Stop heartbeat interval synchronously to prevent leaks
1160        use crate::vfs::indexeddb_vfs::get_storage_with_fallback;
1161        if let Some(storage_rc) = get_storage_with_fallback(&self.name) {
1162            // No outer borrow needed - BlockStorage uses RefCell for interior mutability
1163            let storage = &*storage_rc;
1164            // Try to borrow manager - if it fails, skip (already being cleaned)
1165            if let Ok(mut manager_ref) = storage.leader_election.try_borrow_mut() {
1166                if let Some(ref mut manager) = *manager_ref {
1167                    // Clear interval if it exists (idempotent)
1168                    if let Some(interval_id) = manager.heartbeat_interval.take() {
1169                        if let Some(window) = web_sys::window() {
1170                            window.clear_interval_with_handle(interval_id);
1171                            web_sys::console::log_1(
1172                                &format!(
1173                                    "DROP: Cleared heartbeat interval {} for {}",
1174                                    interval_id, self.name
1175                                )
1176                                .into(),
1177                            );
1178                        }
1179                    }
1180                    // Note: heartbeat closure is intentionally leaked (via forget())
1181                    // and becomes a no-op when heartbeat_valid is set to false
1182                }
1183            } else {
1184                // Manager already borrowed - skip (first DB is cleaning up)
1185                web_sys::console::log_1(
1186                    &format!(
1187                        "[DROP] Skipping {} (heartbeat already stopped by shared DB)",
1188                        self.name
1189                    )
1190                    .into(),
1191                );
1192            }
1193        }
1194
1195        // Keep BlockStorage in STORAGE_REGISTRY so multiple Database instances
1196        // with the same name share the same BlockStorage and leader election state
1197        // Blocks persist in GLOBAL_STORAGE across Database instances
1198        log::debug!(
1199            "Closed database: {} (BlockStorage remains in registry)",
1200            self.name
1201        );
1202    }
1203}
1204
1205// Add wasm_bindgen exports for the main Database struct
1206#[cfg(target_arch = "wasm32")]
1207#[wasm_bindgen]
1208impl Database {
1209    #[wasm_bindgen(js_name = "newDatabase")]
1210    pub async fn new_wasm(name: String) -> Result<Database, JsValue> {
1211        // Normalize database name: ensure it has .db suffix
1212        let normalized_name = if name.ends_with(".db") {
1213            name.clone()
1214        } else {
1215            format!("{}.db", name)
1216        };
1217
1218        let config = Self::default_wasm_config(normalized_name.clone());
1219
1220        let db = Database::new(config)
1221            .await
1222            .map_err(|e| JsValue::from_str(&format!("Failed to create database: {}", e)))?;
1223
1224        // Start listening for write queue requests (leader will process them)
1225        Self::start_write_queue_listener(&normalized_name)?;
1226
1227        Ok(db)
1228    }
1229
1230    #[wasm_bindgen(js_name = "newDatabaseAuto")]
1231    pub async fn new_wasm_auto(name: String) -> Result<Database, JsValue> {
1232        let normalized_name = if name.ends_with(".db") {
1233            name.clone()
1234        } else {
1235            format!("{}.db", name)
1236        };
1237
1238        let config = Self::default_wasm_config(normalized_name.clone());
1239        let backend = crate::storage::backend_detect::detect_best_backend().await;
1240
1241        let db = Database::new_with_storage_backend(config, backend)
1242            .await
1243            .map_err(|e| JsValue::from_str(&format!("Failed to create database: {}", e)))?;
1244
1245        Self::start_write_queue_listener(&normalized_name)?;
1246
1247        Ok(db)
1248    }
1249
1250    #[wasm_bindgen(js_name = "newDatabaseWithBackend")]
1251    pub async fn new_wasm_with_backend(
1252        name: String,
1253        backend_name: String,
1254    ) -> Result<Database, JsValue> {
1255        let normalized_name = if name.ends_with(".db") {
1256            name.clone()
1257        } else {
1258            format!("{}.db", name)
1259        };
1260
1261        let backend = match backend_name.to_ascii_lowercase().as_str() {
1262            "indexeddb" | "indexed-db" | "indexed_db" | "idb" => {
1263                crate::storage::StorageBackend::IndexedDb
1264            }
1265            "opfs" => crate::storage::StorageBackend::Opfs,
1266            "hybrid" => crate::storage::StorageBackend::Hybrid,
1267            _ => {
1268                return Err(JsValue::from_str(&format!(
1269                    "Unsupported storage backend '{}'. Expected IndexedDB, OPFS, or Hybrid.",
1270                    backend_name
1271                )));
1272            }
1273        };
1274
1275        let config = Self::default_wasm_config(normalized_name.clone());
1276
1277        let db = Database::new_with_storage_backend(config, backend)
1278            .await
1279            .map_err(|e| JsValue::from_str(&format!("Failed to create database: {}", e)))?;
1280
1281        Self::start_write_queue_listener(&normalized_name)?;
1282
1283        Ok(db)
1284    }
1285
1286    /// Get the database name
1287    #[wasm_bindgen(getter)]
1288    pub fn name(&self) -> String {
1289        self.name.clone()
1290    }
1291
1292    #[wasm_bindgen(js_name = "getStorageBackend")]
1293    pub fn get_storage_backend(&self) -> Result<String, JsValue> {
1294        use crate::vfs::indexeddb_vfs::get_storage_with_fallback;
1295
1296        let storage = get_storage_with_fallback(&self.name).ok_or_else(|| {
1297            JsValue::from_str(&format!("No storage found for database: {}", self.name))
1298        })?;
1299
1300        Ok(storage.storage_backend().as_str().to_string())
1301    }
1302
1303    /// Get all database names stored in IndexedDB
1304    ///
1305    /// Returns an array of database names (sorted alphabetically)
1306    #[wasm_bindgen(js_name = "getAllDatabases")]
1307    pub async fn get_all_databases() -> Result<JsValue, JsValue> {
1308        use crate::storage::vfs_sync::with_global_storage;
1309        use crate::vfs::indexeddb_vfs::STORAGE_REGISTRY;
1310        use std::collections::HashSet;
1311
1312        log::info!("getAllDatabases called");
1313        let mut db_names = HashSet::new();
1314
1315        // Get databases from persistent list (localStorage)
1316        match Self::get_persistent_database_list() {
1317            Ok(persistent_list) => {
1318                log::info!("Persistent list has {} entries", persistent_list.len());
1319                for name in persistent_list {
1320                    log::info!("Found in persistent list: {}", name);
1321                    db_names.insert(name);
1322                }
1323            }
1324            Err(e) => {
1325                log::warn!("Failed to get persistent list: {:?}", e);
1326            }
1327        }
1328
1329        // Get databases from STORAGE_REGISTRY (currently open)
1330        // SAFETY: WASM is single-threaded, no concurrent access possible
1331        STORAGE_REGISTRY.with(|reg| unsafe {
1332            let registry = &*reg.get();
1333            log::info!("STORAGE_REGISTRY has {} entries", registry.len());
1334            for key in registry.keys() {
1335                log::info!("Found in STORAGE_REGISTRY: {}", key);
1336                db_names.insert(key.clone());
1337            }
1338        });
1339
1340        // Get databases from GLOBAL_STORAGE (in-memory persistent storage)
1341        with_global_storage(|storage| {
1342            let storage_borrow = storage.borrow();
1343            log::info!("GLOBAL_STORAGE has {} entries", storage_borrow.len());
1344            for key in storage_borrow.keys() {
1345                log::info!("Found in GLOBAL_STORAGE: {}", key);
1346                db_names.insert(key.clone());
1347            }
1348        });
1349
1350        log::info!("Total unique databases found: {}", db_names.len());
1351
1352        // Convert to sorted vector
1353        let mut result_vec: Vec<String> = db_names.into_iter().collect();
1354        result_vec.sort();
1355
1356        // Convert to JavaScript array
1357        let js_array = js_sys::Array::new();
1358        for name in &result_vec {
1359            log::info!("Returning database: {}", name);
1360            js_array.push(&JsValue::from_str(name));
1361        }
1362
1363        log::info!("getAllDatabases returning {} databases", result_vec.len());
1364
1365        Ok(js_array.into())
1366    }
1367
1368    /// Delete a database from storage
1369    ///
1370    /// Callers must first close the database in every runtime that uses it.
1371    /// Success means its persistent blocks and OPFS mirror have been removed.
1372    #[wasm_bindgen(js_name = "deleteDatabase")]
1373    pub async fn delete_database(name: String) -> Result<(), JsValue> {
1374        let normalized_name = crate::utils::normalize_db_name(&name);
1375        log::info!("Deleting database: {}", normalized_name);
1376
1377        crate::storage::export_import_lock::with_lock(&normalized_name, || async {
1378            // Do not erase the recovery copy or local state when OPFS is still locked.
1379            crate::storage::wasm_opfs::delete_all_from_opfs(&normalized_name)
1380                .await
1381                .map_err(|error| {
1382                    JsValue::from_str(&format!("{}: {}", error.code, error.message))
1383                })?;
1384            crate::storage::wasm_indexeddb::delete_all_database_blocks_from_indexeddb(
1385                &normalized_name,
1386            )
1387            .await
1388            .map_err(|error| JsValue::from_str(&format!("{}: {}", error.code, error.message)))?;
1389
1390            crate::storage::wasm_auto_sync::unregister_wasm_auto_sync(&normalized_name);
1391            crate::storage::import::clear_database_storage(&normalized_name)
1392                .await
1393                .map_err(|error| JsValue::from_str(&error.to_string()))?;
1394            Self::remove_database_from_persistent_list(&normalized_name)?;
1395            log::info!("Database deleted: {}", normalized_name);
1396            Ok(())
1397        })
1398        .await
1399    }
1400
1401    /// Add database name to persistent list in localStorage
1402    #[allow(dead_code)]
1403    fn persistent_list_storage() -> Result<Option<web_sys::Storage>, JsValue> {
1404        let Some(window) = web_sys::window() else {
1405            log::info!("Persistent database list unavailable without Window; skipping");
1406            return Ok(None);
1407        };
1408
1409        let Some(storage) = window.local_storage().map_err(|e| {
1410            log::error!("Failed to get localStorage: {:?}", e);
1411            JsValue::from_str("No localStorage")
1412        })?
1413        else {
1414            log::info!("Persistent database list unavailable without localStorage; skipping");
1415            return Ok(None);
1416        };
1417
1418        Ok(Some(storage))
1419    }
1420
1421    /// Add database name to persistent list in localStorage
1422    #[allow(dead_code)]
1423    fn add_database_to_persistent_list(db_name: &str) -> Result<(), JsValue> {
1424        log::info!("add_database_to_persistent_list called for: {}", db_name);
1425
1426        let Some(storage) = Self::persistent_list_storage()? else {
1427            return Ok(());
1428        };
1429
1430        let key = "absurder_db_list";
1431        let existing = storage.get_item(key).map_err(|e| {
1432            log::error!("Failed to read localStorage key {}: {:?}", key, e);
1433            JsValue::from_str("Failed to read localStorage")
1434        })?;
1435
1436        log::debug!("Existing localStorage value: {:?}", existing);
1437
1438        let mut db_list: Vec<String> = if let Some(json_str) = existing {
1439            match serde_json::from_str(&json_str) {
1440                Ok(list) => {
1441                    log::debug!("Parsed existing list: {:?}", list);
1442                    list
1443                }
1444                Err(e) => {
1445                    log::warn!("Failed to parse localStorage JSON: {}, starting fresh", e);
1446                    Vec::new()
1447                }
1448            }
1449        } else {
1450            log::debug!("No existing list, creating new");
1451            Vec::new()
1452        };
1453
1454        if !db_list.contains(&db_name.to_string()) {
1455            db_list.push(db_name.to_string());
1456            db_list.sort();
1457            log::debug!("Updated list: {:?}", db_list);
1458
1459            let json_str = serde_json::to_string(&db_list).map_err(|e| {
1460                log::error!("Failed to serialize list: {}", e);
1461                JsValue::from_str("Failed to serialize")
1462            })?;
1463
1464            log::debug!("Writing to localStorage: {}", json_str);
1465
1466            storage.set_item(key, &json_str).map_err(|e| {
1467                log::error!("Failed to write to localStorage: {:?}", e);
1468                JsValue::from_str("Failed to write localStorage")
1469            })?;
1470
1471            log::info!("Successfully added {} to persistent database list", db_name);
1472        } else {
1473            log::info!("{} already in persistent list", db_name);
1474        }
1475
1476        Ok(())
1477    }
1478
1479    /// Remove database name from persistent list in localStorage
1480    fn remove_database_from_persistent_list(db_name: &str) -> Result<(), JsValue> {
1481        let Some(storage) = Self::persistent_list_storage()? else {
1482            return Ok(());
1483        };
1484
1485        let key = "absurder_db_list";
1486        let existing = storage
1487            .get_item(key)
1488            .map_err(|_| JsValue::from_str("Failed to read localStorage"))?;
1489
1490        if let Some(json_str) = existing {
1491            let mut db_list: Vec<String> =
1492                serde_json::from_str(&json_str).unwrap_or_else(|_| Vec::new());
1493            db_list.retain(|name| name != db_name);
1494            let json_str = serde_json::to_string(&db_list)
1495                .map_err(|_| JsValue::from_str("Failed to serialize"))?;
1496            storage
1497                .set_item(key, &json_str)
1498                .map_err(|_| JsValue::from_str("Failed to write localStorage"))?;
1499            log::info!("Removed {} from persistent database list", db_name);
1500        }
1501
1502        Ok(())
1503    }
1504
1505    /// Get database names from persistent list in localStorage
1506    fn get_persistent_database_list() -> Result<Vec<String>, JsValue> {
1507        log::info!("get_persistent_database_list called");
1508
1509        let Some(storage) = Self::persistent_list_storage()? else {
1510            return Ok(Vec::new());
1511        };
1512
1513        let key = "absurder_db_list";
1514        let existing = storage.get_item(key).map_err(|e| {
1515            log::error!("Failed to read localStorage key {}: {:?}", key, e);
1516            JsValue::from_str("Failed to read localStorage")
1517        })?;
1518
1519        log::debug!("Read from localStorage: {:?}", existing);
1520
1521        if let Some(json_str) = existing {
1522            match serde_json::from_str::<Vec<String>>(&json_str) {
1523                Ok(db_list) => {
1524                    log::info!(
1525                        "Successfully parsed {} databases from localStorage",
1526                        db_list.len()
1527                    );
1528                    log::debug!("Database list: {:?}", db_list);
1529                    Ok(db_list)
1530                }
1531                Err(e) => {
1532                    log::error!("Failed to parse localStorage JSON: {}", e);
1533                    Ok(Vec::new())
1534                }
1535            }
1536        } else {
1537            log::info!("No persistent database list in localStorage");
1538            Ok(Vec::new())
1539        }
1540    }
1541
1542    /// Start listening for write queue requests (leader processes these)
1543    fn start_write_queue_listener(db_name: &str) -> Result<(), JsValue> {
1544        use crate::storage::write_queue::{
1545            WriteQueueMessage, WriteResponse, register_write_queue_listener,
1546        };
1547        use crate::vfs::indexeddb_vfs::get_storage_with_fallback;
1548
1549        let db_name_clone = db_name.to_string();
1550
1551        let callback = Closure::wrap(Box::new(move |msg: JsValue| {
1552            let db_name_inner = db_name_clone.clone();
1553
1554            // Parse the message
1555            if let Ok(json_str) = js_sys::JSON::stringify(&msg) {
1556                if let Some(json_str) = json_str.as_string() {
1557                    if let Ok(WriteQueueMessage::WriteRequest(request)) =
1558                        serde_json::from_str::<WriteQueueMessage>(&json_str)
1559                    {
1560                        log::debug!("Leader received write request: {}", request.request_id);
1561
1562                        // Check if we're the leader
1563                        let storage_rc = get_storage_with_fallback(&db_name_inner);
1564
1565                        if let Some(storage) = storage_rc {
1566                            // Spawn async task to process the write
1567                            wasm_bindgen_futures::spawn_local(async move {
1568                                let is_leader =
1569                                    with_storage_async!(storage, "write_queue_is_leader", |s| s
1570                                        .is_leader());
1571                                if is_leader.is_none() {
1572                                    log::error!("Failed to check leader status");
1573                                    return;
1574                                }
1575                                let is_leader = is_leader.unwrap();
1576
1577                                if !is_leader {
1578                                    log::error!("Not leader, ignoring write request");
1579                                    return;
1580                                }
1581
1582                                log::debug!("Processing write request as leader");
1583
1584                                // Create a temporary database instance to execute the SQL
1585                                match Database::new_wasm(db_name_inner.clone()).await {
1586                                    Ok(mut db) => {
1587                                        // Execute the SQL
1588                                        match db.execute_internal(&request.sql).await {
1589                                            Ok(result) => {
1590                                                // Send success response
1591                                                let response = WriteResponse::Success {
1592                                                    request_id: request.request_id.clone(),
1593                                                    affected_rows: result.affected_rows as usize,
1594                                                };
1595
1596                                                use crate::storage::write_queue::send_write_response;
1597                                                if let Err(e) =
1598                                                    send_write_response(&db_name_inner, response)
1599                                                {
1600                                                    log::error!("Failed to send response: {}", e);
1601                                                } else {
1602                                                    log::info!("Write response sent successfully");
1603                                                }
1604                                            }
1605                                            Err(e) => {
1606                                                // Send error response
1607                                                let response = WriteResponse::Error {
1608                                                    request_id: request.request_id.clone(),
1609                                                    error_message: e.to_string(),
1610                                                };
1611
1612                                                use crate::storage::write_queue::send_write_response;
1613                                                if let Err(e) =
1614                                                    send_write_response(&db_name_inner, response)
1615                                                {
1616                                                    log::error!(
1617                                                        "Failed to send error response: {}",
1618                                                        e
1619                                                    );
1620                                                }
1621                                            }
1622                                        }
1623                                    }
1624                                    Err(e) => {
1625                                        log::error!(
1626                                            "Failed to create db for write processing: {:?}",
1627                                            e
1628                                        );
1629                                    }
1630                                }
1631                            });
1632                        }
1633                    }
1634                }
1635            }
1636        }) as Box<dyn FnMut(JsValue)>);
1637
1638        let callback_fn = callback.as_ref().unchecked_ref();
1639        register_write_queue_listener(db_name, callback_fn).map_err(|e| {
1640            JsValue::from_str(&format!("Failed to register write queue listener: {}", e))
1641        })?;
1642
1643        callback.forget();
1644
1645        Ok(())
1646    }
1647
1648    #[wasm_bindgen]
1649    pub async fn execute(&mut self, sql: &str) -> Result<JsValue, JsValue> {
1650        let result = self
1651            .execute_query(sql, &[], true)
1652            .await
1653            .map_err(Self::query_error)?;
1654        serde_wasm_bindgen::to_value(&result).map_err(|e| JsValue::from_str(&e.to_string()))
1655    }
1656
1657    #[wasm_bindgen(js_name = "executeWithParams")]
1658    pub async fn execute_with_params(
1659        &mut self,
1660        sql: &str,
1661        params: JsValue,
1662    ) -> Result<JsValue, JsValue> {
1663        let params: Vec<ColumnValue> = serde_wasm_bindgen::from_value(params)
1664            .map_err(|e| JsValue::from_str(&format!("Invalid parameters: {}", e)))?;
1665
1666        let result = self
1667            .execute_query(sql, &params, true)
1668            .await
1669            .map_err(Self::query_error)?;
1670        serde_wasm_bindgen::to_value(&result).map_err(|e| JsValue::from_str(&e.to_string()))
1671    }
1672
1673    #[wasm_bindgen]
1674    pub async fn close(&mut self) -> Result<(), JsValue> {
1675        self.close_internal()
1676            .await
1677            .map_err(|e| JsValue::from_str(&format!("Failed to close database: {}", e)))
1678    }
1679
1680    /// Force close connection and remove from pool (for test cleanup)
1681    #[wasm_bindgen(js_name = "forceCloseConnection")]
1682    pub async fn force_close_connection(&mut self) -> Result<(), JsValue> {
1683        // First do normal close to cleanup
1684        let _ = self.close_internal().await;
1685
1686        // Then force-remove from connection pool
1687        // Pool uses name without .db, so strip it
1688        let pool_key = self.name.trim_end_matches(".db");
1689        crate::connection_pool::force_close_connection(pool_key);
1690
1691        // CRITICAL: Single source of truth for ALL cleanup
1692        #[cfg(target_arch = "wasm32")]
1693        {
1694            crate::cleanup::cleanup_all_state(pool_key)
1695                .await
1696                .map_err(|e| JsValue::from_str(&format!("Cleanup failed: {}", e)))?;
1697        }
1698        log::info!("Force closed and removed connection for: {}", self.name);
1699        Ok(())
1700    }
1701
1702    #[wasm_bindgen]
1703    pub async fn sync(&mut self) -> Result<(), JsValue> {
1704        self.sync_internal()
1705            .await
1706            .map_err(|e| JsValue::from_str(&format!("Failed to sync database: {}", e)))
1707    }
1708
1709    /// Allow non-leader writes (for single-tab apps or testing)
1710    #[wasm_bindgen(js_name = "allowNonLeaderWrites")]
1711    pub async fn allow_non_leader_writes(&mut self, allow: bool) -> Result<(), JsValue> {
1712        log::debug!("Setting allowNonLeaderWrites = {} for {}", allow, self.name);
1713        self.allow_non_leader_writes = allow;
1714        Ok(())
1715    }
1716
1717    /// Export database to SQLite .db file format
1718    ///
1719    /// Returns the complete database as a Uint8Array that can be downloaded
1720    /// or saved as a standard SQLite .db file.
1721    ///
1722    /// # Example
1723    /// ```javascript
1724    /// const dbBytes = await db.exportToFile();
1725    /// const blob = new Blob([dbBytes], { type: 'application/x-sqlite3' });
1726    /// const url = URL.createObjectURL(blob);
1727    /// const a = document.createElement('a');
1728    /// a.href = url;
1729    /// a.download = 'database.db';
1730    /// a.click();
1731    /// ```
1732    #[wasm_bindgen(js_name = "exportToFile")]
1733    pub async fn export_to_file(&self) -> Result<js_sys::Uint8Array, JsValue> {
1734        let db_name = self.name.clone();
1735        let max_export_size = self.max_export_size_bytes;
1736
1737        crate::storage::export_import_lock::with_lock(&db_name, || async {
1738            log::info!("[EXPORT] ===== Step 1: Lock acquired");
1739
1740            // Get storage and sync AFTER lock - this ensures only one export syncs at a time
1741            use crate::vfs::indexeddb_vfs::get_storage_with_fallback;
1742            log::info!("[EXPORT] ===== Step 2: Getting storage");
1743            let storage_rc = get_storage_with_fallback(&db_name).ok_or_else(|| {
1744                JsValue::from_str(&format!("Storage not found for database: {}", db_name))
1745            })?;
1746            log::info!("[EXPORT] ===== Step 3: Got storage");
1747
1748            // CRITICAL: Checkpoint WAL to flush SQLite data to VFS blocks before export
1749            // Without this, data stays in SQLite's WAL buffer and doesn't appear in exported bytes
1750            log::info!("[EXPORT] ===== Step 4: Checkpointing WAL");
1751            let db = self.connection_state.db.get();
1752            if db.is_null() {
1753                return Err(JsValue::from_str(
1754                    "Export checkpoint failed: database connection is closed",
1755                ));
1756            }
1757            let mut wal_frames = -1;
1758            let mut checkpointed_frames = -1;
1759            let rc = unsafe {
1760                sqlite_wasm_rs::sqlite3_wal_checkpoint_v2(
1761                    db,
1762                    c"main".as_ptr(),
1763                    sqlite_wasm_rs::SQLITE_CHECKPOINT_PASSIVE,
1764                    &mut wal_frames,
1765                    &mut checkpointed_frames,
1766                )
1767            };
1768            if rc != sqlite_wasm_rs::SQLITE_OK {
1769                let message =
1770                    unsafe { std::ffi::CStr::from_ptr(sqlite_wasm_rs::sqlite3_errmsg(db)) }
1771                        .to_string_lossy();
1772                let error = format!("Export checkpoint failed (SQLite {rc}): {message}");
1773                log::error!("{error}");
1774                return Err(JsValue::from_str(&error));
1775            }
1776            if wal_frames != checkpointed_frames {
1777                let error = format!(
1778                    "Export checkpoint incomplete: {checkpointed_frames} of {wal_frames} WAL frames"
1779                );
1780                log::error!("{error}");
1781                return Err(JsValue::from_str(&error));
1782            }
1783
1784            // Reload after checkpoint so the awaited sync/export path sees the canonical
1785            // post-checkpoint block state instead of any stale pre-checkpoint cache.
1786            #[cfg(target_arch = "wasm32")]
1787            {
1788                log::info!("[EXPORT] ===== Step 4b: Reloading cache after checkpoint");
1789                storage_rc.reload_cache_from_global_storage();
1790            }
1791
1792            log::info!("[EXPORT] ===== Step 5: Starting sync");
1793            storage_rc
1794                .sync()
1795                .await
1796                .map_err(|e| JsValue::from_str(&format!("Sync failed: {}", e)))?;
1797            log::info!("[EXPORT] ===== Step 6: Sync complete");
1798
1799            log::info!("[EXPORT] Calling export_database_to_bytes");
1800            let mut db_bytes = {
1801                let storage = &*storage_rc;
1802                crate::storage::export::export_database_to_bytes(storage, max_export_size)
1803                    .await
1804                    .map_err(|e| {
1805                        log::error!("[EXPORT] Export failed: {}", e);
1806                        JsValue::from_str(&format!("Export failed: {}", e))
1807                    })?
1808            };
1809
1810            let format_versions = db_bytes.get_mut(18..20).ok_or_else(|| {
1811                JsValue::from_str("Export failed: SQLite snapshot header is incomplete")
1812            })?;
1813            if !format_versions
1814                .iter()
1815                .all(|version| matches!(version, 1 | 2))
1816            {
1817                return Err(JsValue::from_str(
1818                    "Export failed: unsupported SQLite snapshot file format",
1819                ));
1820            }
1821            // A fully checkpointed standalone snapshot has no WAL/SHM sidecars.
1822            // Normalize only this copy; the live database remains in WAL mode.
1823            format_versions.fill(1);
1824            log::info!("[EXPORT] Export complete: {} bytes", db_bytes.len());
1825
1826            let uint8_array = js_sys::Uint8Array::new_with_length(db_bytes.len() as u32);
1827            uint8_array.copy_from(&db_bytes);
1828
1829            Ok(uint8_array)
1830        })
1831        .await
1832    }
1833
1834    /// Test method for concurrent locking - simple increment counter
1835    #[wasm_bindgen(js_name = "testLock")]
1836    pub async fn test_lock(&self, value: u32) -> Result<u32, JsValue> {
1837        let lock_name = format!("{}.lock_test", self.name);
1838
1839        log::info!(
1840            "[LOCK-TEST] Acquiring lock: {} with value: {}",
1841            lock_name,
1842            value
1843        );
1844        let _guard = weblocks::acquire(&lock_name, weblocks::AcquireOptions::exclusive()).await?;
1845        log::info!("[LOCK-TEST] Lock acquired, processing value: {}", value);
1846
1847        // Simulate some work
1848        let result = value + 1;
1849
1850        // Small delay to test serialization
1851        let delay_promise = js_sys::Promise::new(&mut |resolve, _reject| {
1852            let window = web_sys::window().unwrap();
1853            let _ = window
1854                .set_timeout_with_callback_and_timeout_and_arguments_0(resolve.unchecked_ref(), 10);
1855        });
1856        wasm_bindgen_futures::JsFuture::from(delay_promise).await?;
1857
1858        log::info!(
1859            "[LOCK-TEST] Lock releasing for: {} with result: {}",
1860            lock_name,
1861            result
1862        );
1863        Ok(result)
1864    }
1865
1866    /// Import SQLite database from .db file bytes
1867    ///
1868    /// Replaces the current database contents with the imported data.
1869    /// This will close the current database connection and clear all existing data.
1870    ///
1871    /// # Arguments
1872    /// * `file_data` - SQLite .db file as Uint8Array
1873    ///
1874    /// # Returns
1875    /// * `Ok(())` - Import successful
1876    /// * `Err(JsValue)` - Import failed (invalid file, validation error, etc.)
1877    ///
1878    /// # Example
1879    /// ```javascript
1880    /// // From file input
1881    /// const fileInput = document.getElementById('dbFile');
1882    /// const file = fileInput.files[0];
1883    /// const arrayBuffer = await file.arrayBuffer();
1884    /// const uint8Array = new Uint8Array(arrayBuffer);
1885    ///
1886    /// await db.importFromFile(uint8Array);
1887    ///
1888    /// // Database is immediately usable after import (no reopen needed)
1889    /// const result = await db.execute('SELECT * FROM imported_table');
1890    /// ```
1891    ///
1892    /// # Warning
1893    /// This operation is destructive and will replace all existing database data.
1894    #[wasm_bindgen(js_name = "importFromFile")]
1895    pub async fn import_from_file(&mut self, file_data: js_sys::Uint8Array) -> Result<(), JsValue> {
1896        log::info!("[IMPORT] Starting import with lock for: {}", self.name);
1897        let db_name = self.name.clone();
1898        let data = file_data.to_vec();
1899
1900        crate::storage::export_import_lock::with_lock(&db_name, || async {
1901            log::info!("[IMPORT] Lock acquired for: {}", db_name);
1902            log::debug!("Import data size: {} bytes", data.len());
1903
1904            let storage_backend = crate::vfs::indexeddb_vfs::get_storage_with_fallback(&db_name)
1905                .map(|storage| storage.storage_backend())
1906                .unwrap_or(crate::storage::StorageBackend::IndexedDb);
1907
1908            log::debug!("Force-closing database connection before import");
1909
1910            self.close_internal()
1911                .await
1912                .map_err(|e| JsValue::from_str(&format!("Failed to close before import: {}", e)))?;
1913
1914            let pool_key = self.name.trim_end_matches(".db");
1915            crate::connection_pool::force_close_connection(pool_key);
1916            self.connection_state.db.set(std::ptr::null_mut());
1917            log::debug!("Removed connection from pool for import");
1918
1919            crate::storage::import::import_database_from_bytes_with_backend(
1920                &db_name,
1921                data,
1922                storage_backend,
1923            )
1924            .await
1925            .map_err(|e| {
1926                log::error!("Import failed for {}: {}", db_name, e);
1927                JsValue::from_str(&format!("Import failed: {}", e))
1928            })?;
1929
1930            log::info!("[IMPORT] Import complete for: {}", db_name);
1931            log::info!("[IMPORT] Reopening connection for: {}", db_name);
1932
1933            use std::ffi::CString;
1934
1935            let vfs_name = format!("vfs_{}", db_name.trim_end_matches(".db"));
1936            let pool_key = db_name.trim_end_matches(".db").to_string();
1937            let db_name_for_closure = db_name.clone();
1938            let vfs_name_for_closure = vfs_name.clone();
1939
1940            let new_state = crate::connection_pool::get_or_create_connection(&pool_key, || {
1941                let mut db = std::ptr::null_mut();
1942                let db_name_cstr = CString::new(db_name_for_closure.clone())
1943                    .map_err(|_| "Invalid database name".to_string())?;
1944                let vfs_cstr = CString::new(vfs_name_for_closure.as_str())
1945                    .map_err(|_| "Invalid VFS name".to_string())?;
1946
1947                log::info!(
1948                    "[IMPORT] Reopening database: {} with VFS: {}",
1949                    db_name_for_closure,
1950                    vfs_name_for_closure
1951                );
1952
1953                let ret = unsafe {
1954                    sqlite_wasm_rs::sqlite3_open_v2(
1955                        db_name_cstr.as_ptr(),
1956                        &mut db as *mut _,
1957                        sqlite_wasm_rs::SQLITE_OPEN_READWRITE | sqlite_wasm_rs::SQLITE_OPEN_CREATE,
1958                        vfs_cstr.as_ptr(),
1959                    )
1960                };
1961
1962                if ret != sqlite_wasm_rs::SQLITE_OK {
1963                    let err_msg = unsafe {
1964                        let msg_ptr = sqlite_wasm_rs::sqlite3_errmsg(db);
1965                        if !msg_ptr.is_null() {
1966                            std::ffi::CStr::from_ptr(msg_ptr)
1967                                .to_string_lossy()
1968                                .into_owned()
1969                        } else {
1970                            "Unknown error".to_string()
1971                        }
1972                    };
1973                    return Err(format!(
1974                        "Failed to reopen database after import: {}",
1975                        err_msg
1976                    ));
1977                }
1978
1979                log::info!("[IMPORT] Database reopened successfully");
1980                Ok(db)
1981            })
1982            .map_err(|e| {
1983                JsValue::from_str(&format!("Failed to reopen connection after import: {}", e))
1984            })?;
1985
1986            self.connection_state = new_state;
1987            log::info!("[IMPORT] Connection state updated for: {}", db_name);
1988
1989            Ok(())
1990        })
1991        .await
1992    }
1993
1994    /// Wait for this instance to become leader
1995    #[wasm_bindgen(js_name = "waitForLeadership")]
1996    pub async fn wait_for_leadership(&mut self) -> Result<(), JsValue> {
1997        use crate::vfs::indexeddb_vfs::get_storage_with_fallback;
1998
1999        // Track leader election attempt
2000        #[cfg(feature = "telemetry")]
2001        if let Some(ref metrics) = self.metrics {
2002            metrics.leader_elections_total().inc();
2003        }
2004
2005        let db_name = &self.name;
2006        let start_time = js_sys::Date::now();
2007
2008        let timeout_ms = 5000.0; // 5 second timeout
2009
2010        loop {
2011            let storage_rc = get_storage_with_fallback(db_name);
2012
2013            if let Some(storage) = storage_rc {
2014                let is_leader =
2015                    match with_storage_async!(storage, "wait_for_leadership", |s| s.is_leader()) {
2016                        Some(v) => v,
2017                        None => continue,
2018                    };
2019
2020                if is_leader {
2021                    log::info!("Became leader for {}", db_name);
2022
2023                    // Record telemetry on successful leadership acquisition
2024                    #[cfg(feature = "telemetry")]
2025                    if let Some(ref metrics) = self.metrics {
2026                        let duration_ms = js_sys::Date::now() - start_time;
2027                        metrics.leader_election_duration().observe(duration_ms);
2028                        metrics.is_leader().set(1.0);
2029                        metrics.leadership_changes_total().inc();
2030                    }
2031
2032                    return Ok(());
2033                }
2034            }
2035
2036            // Check timeout
2037            if js_sys::Date::now() - start_time > timeout_ms {
2038                // Record telemetry on timeout
2039                #[cfg(feature = "telemetry")]
2040                if let Some(ref metrics) = self.metrics {
2041                    let duration_ms = js_sys::Date::now() - start_time;
2042                    metrics.leader_election_duration().observe(duration_ms);
2043                }
2044
2045                return Err(JsValue::from_str("Timeout waiting for leadership"));
2046            }
2047
2048            // Wait a bit before checking again
2049            let promise = js_sys::Promise::new(&mut |resolve, _| {
2050                let window = web_sys::window().expect("should have window");
2051                let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, 100);
2052            });
2053            let _ = wasm_bindgen_futures::JsFuture::from(promise).await;
2054        }
2055    }
2056
2057    /// Request leadership (triggers re-election check)
2058    #[wasm_bindgen(js_name = "requestLeadership")]
2059    pub async fn request_leadership(&mut self) -> Result<(), JsValue> {
2060        use crate::vfs::indexeddb_vfs::get_storage_with_fallback;
2061
2062        let db_name = &self.name;
2063        log::debug!("Requesting leadership for {}", db_name);
2064
2065        // Record telemetry data before the request
2066        #[cfg(feature = "telemetry")]
2067        let telemetry_data = if self.metrics.is_some() {
2068            let start_time = js_sys::Date::now();
2069            let was_leader = self
2070                .is_leader_wasm()
2071                .await
2072                .ok()
2073                .and_then(|v| v.as_bool())
2074                .unwrap_or(false);
2075
2076            if let Some(ref metrics) = self.metrics {
2077                metrics.leader_elections_total().inc();
2078            }
2079
2080            Some((start_time, was_leader))
2081        } else {
2082            None
2083        };
2084
2085        let storage_rc = get_storage_with_fallback(db_name);
2086
2087        if let Some(storage) = storage_rc {
2088            {
2089                // Trigger leader election
2090                let result = with_storage_async!(storage, "request_leadership", |s| s
2091                    .start_leader_election())
2092                .ok_or_else(|| {
2093                    JsValue::from_str("Failed to acquire storage lock for leadership request")
2094                })?;
2095                result.map_err(|e| {
2096                    JsValue::from_str(&format!("Failed to request leadership: {}", e))
2097                })?;
2098
2099                log::debug!("Re-election triggered for {}", db_name);
2100            } // Drop the borrow here
2101
2102            // Record telemetry after election (after dropping borrow)
2103            #[cfg(feature = "telemetry")]
2104            if let Some((start_time, was_leader)) = telemetry_data {
2105                if let Some(ref metrics) = self.metrics {
2106                    // Record election duration
2107                    let duration_ms = js_sys::Date::now() - start_time;
2108                    metrics.leader_election_duration().observe(duration_ms);
2109
2110                    // Check if leadership status changed
2111                    let is_leader_now = self
2112                        .is_leader_wasm()
2113                        .await
2114                        .ok()
2115                        .and_then(|v| v.as_bool())
2116                        .unwrap_or(false);
2117
2118                    // Update is_leader gauge
2119                    metrics
2120                        .is_leader()
2121                        .set(if is_leader_now { 1.0 } else { 0.0 });
2122
2123                    // Track leadership changes
2124                    if was_leader != is_leader_now {
2125                        metrics.leadership_changes_total().inc();
2126                    }
2127                }
2128            }
2129
2130            Ok(())
2131        } else {
2132            Err(JsValue::from_str(&format!(
2133                "No storage found for database: {}",
2134                db_name
2135            )))
2136        }
2137    }
2138
2139    /// Get leader information
2140    #[wasm_bindgen(js_name = "getLeaderInfo")]
2141    pub async fn get_leader_info(&mut self) -> Result<JsValue, JsValue> {
2142        use crate::vfs::indexeddb_vfs::get_storage_with_fallback;
2143
2144        let db_name = &self.name;
2145
2146        let storage_rc = get_storage_with_fallback(db_name);
2147
2148        if let Some(storage) = storage_rc {
2149            let is_leader = with_storage_async!(storage, "get_leader_info", |s| s.is_leader())
2150                .ok_or_else(|| {
2151                    JsValue::from_str(&format!(
2152                        "Failed to access storage for database: {}",
2153                        db_name
2154                    ))
2155                })?;
2156
2157            // Get leader info - we'll use simpler data for now
2158            // Real implementation would need public getters on BlockStorage
2159            let leader_id_str = if is_leader {
2160                format!("leader_{}", db_name)
2161            } else {
2162                "unknown".to_string()
2163            };
2164
2165            // Create JavaScript object
2166            let obj = js_sys::Object::new();
2167            js_sys::Reflect::set(&obj, &"isLeader".into(), &JsValue::from_bool(is_leader))?;
2168            js_sys::Reflect::set(&obj, &"leaderId".into(), &JsValue::from_str(&leader_id_str))?;
2169            js_sys::Reflect::set(
2170                &obj,
2171                &"leaseExpiry".into(),
2172                &JsValue::from_f64(js_sys::Date::now()),
2173            )?;
2174
2175            Ok(obj.into())
2176        } else {
2177            Err(JsValue::from_str(&format!(
2178                "No storage found for database: {}",
2179                db_name
2180            )))
2181        }
2182    }
2183
2184    /// Queue a write operation to be executed by the leader
2185    ///
2186    /// Non-leader tabs can use this to request writes from the leader.
2187    /// The write is forwarded via BroadcastChannel and executed by the leader.
2188    ///
2189    /// # Arguments
2190    /// * `sql` - SQL statement to execute (must be a write operation)
2191    ///
2192    /// # Returns
2193    /// Result indicating success or failure
2194    #[wasm_bindgen(js_name = "queueWrite")]
2195    pub async fn queue_write(&mut self, sql: String) -> Result<(), JsValue> {
2196        self.queue_write_with_timeout(sql, 5000).await
2197    }
2198
2199    /// Queue a write operation with a specific timeout
2200    ///
2201    /// # Arguments
2202    /// * `sql` - SQL statement to execute
2203    /// * `timeout_ms` - Timeout in milliseconds
2204    #[wasm_bindgen(js_name = "queueWriteWithTimeout")]
2205    pub async fn queue_write_with_timeout(
2206        &mut self,
2207        sql: String,
2208        timeout_ms: u32,
2209    ) -> Result<(), JsValue> {
2210        use crate::storage::write_queue::{WriteQueueMessage, WriteResponse, send_write_request};
2211        use std::cell::RefCell;
2212        use std::rc::Rc;
2213
2214        log::debug!("Queuing write: {}", sql);
2215
2216        // Check if we're the leader - if so, just execute directly
2217        use crate::vfs::indexeddb_vfs::get_storage_with_fallback;
2218        let is_leader = {
2219            let storage_rc = get_storage_with_fallback(&self.name);
2220
2221            if let Some(storage) = storage_rc {
2222                with_storage_async!(storage, "queue_write_is_leader", |s| s.is_leader())
2223                    .unwrap_or(false)
2224            } else {
2225                false
2226            }
2227        };
2228
2229        if is_leader {
2230            log::debug!("We are leader, executing directly");
2231            return self
2232                .execute_internal(&sql)
2233                .await
2234                .map(|_| ())
2235                .map_err(|e| JsValue::from_str(&format!("Execute failed: {}", e)));
2236        }
2237
2238        // Send write request to leader
2239        let request_id = send_write_request(&self.name, &sql)
2240            .map_err(|e| JsValue::from_str(&format!("Failed to send write request: {}", e)))?;
2241
2242        log::debug!("Write request sent with ID: {}", request_id);
2243
2244        // Wait for response with timeout
2245        let response_received = Rc::new(RefCell::new(false));
2246        let response_error = Rc::new(RefCell::new(None::<String>));
2247
2248        let response_received_clone = response_received.clone();
2249        let response_error_clone = response_error.clone();
2250        let request_id_clone = request_id.clone();
2251
2252        // Set up listener for response
2253        let callback = Closure::wrap(Box::new(move |msg: JsValue| {
2254            // Parse the message
2255            if let Ok(json_str) = js_sys::JSON::stringify(&msg) {
2256                if let Some(json_str) = json_str.as_string() {
2257                    if let Ok(WriteQueueMessage::WriteResponse(response)) =
2258                        serde_json::from_str::<WriteQueueMessage>(&json_str)
2259                    {
2260                        match response {
2261                            WriteResponse::Success { request_id, .. } => {
2262                                if request_id == request_id_clone {
2263                                    *response_received_clone.borrow_mut() = true;
2264                                    log::debug!("Write response received: Success");
2265                                }
2266                            }
2267                            WriteResponse::Error {
2268                                request_id,
2269                                error_message,
2270                            } => {
2271                                if request_id == request_id_clone {
2272                                    *response_received_clone.borrow_mut() = true;
2273                                    *response_error_clone.borrow_mut() = Some(error_message);
2274                                    log::debug!("Write response received: Error");
2275                                }
2276                            }
2277                        }
2278                    }
2279                }
2280            }
2281        }) as Box<dyn FnMut(JsValue)>);
2282
2283        // Register listener
2284        use crate::storage::write_queue::register_write_queue_listener;
2285        let callback_fn = callback.as_ref().unchecked_ref();
2286        register_write_queue_listener(&self.name, callback_fn)
2287            .map_err(|e| JsValue::from_str(&format!("Failed to register listener: {}", e)))?;
2288
2289        // Keep callback alive
2290        callback.forget();
2291
2292        // Wait for response with polling (timeout_ms)
2293        let start_time = js_sys::Date::now();
2294        let timeout_f64 = timeout_ms as f64;
2295
2296        loop {
2297            // Check if response received
2298            if *response_received.borrow() {
2299                if let Some(error_msg) = response_error.borrow().as_ref() {
2300                    return Err(JsValue::from_str(&format!("Write failed: {}", error_msg)));
2301                }
2302                log::info!("Write completed successfully");
2303                return Ok(());
2304            }
2305
2306            // Check timeout
2307            let elapsed = js_sys::Date::now() - start_time;
2308            if elapsed > timeout_f64 {
2309                return Err(JsValue::from_str("Write request timed out"));
2310            }
2311
2312            // Wait a bit before checking again
2313            wasm_bindgen_futures::JsFuture::from(js_sys::Promise::new(&mut |resolve, _reject| {
2314                if let Some(window) = web_sys::window() {
2315                    let _ =
2316                        window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, 100);
2317                } else {
2318                    log::error!("Window unavailable in timeout handler");
2319                }
2320            }))
2321            .await
2322            .ok();
2323        }
2324    }
2325
2326    #[wasm_bindgen(js_name = "isLeader")]
2327    pub async fn is_leader_wasm(&self) -> Result<JsValue, JsValue> {
2328        // Get the storage from STORAGE_REGISTRY
2329        use crate::vfs::indexeddb_vfs::get_storage_with_fallback;
2330
2331        let db_name = &self.name;
2332        log::debug!("isLeader() called for database: {} (self.name)", db_name);
2333
2334        let storage_rc = get_storage_with_fallback(db_name);
2335
2336        if let Some(storage) = storage_rc {
2337            log::debug!("Found storage for {}, calling is_leader()", db_name);
2338            let is_leader = with_storage_async!(storage, "is_leader_wasm", |s| s.is_leader())
2339                .ok_or_else(|| {
2340                    JsValue::from_str(&format!(
2341                        "Failed to access storage for database: {}",
2342                        db_name
2343                    ))
2344                })?;
2345            log::debug!("is_leader() = {} for {}", is_leader, db_name);
2346
2347            // Return as JsValue boolean
2348            Ok(JsValue::from_bool(is_leader))
2349        } else {
2350            log::error!("ERROR: No storage found for database: {}", db_name);
2351            Err(JsValue::from_str(&format!(
2352                "No storage found for database: {}",
2353                db_name
2354            )))
2355        }
2356    }
2357
2358    /// Check if this instance is the leader (non-wasm version for internal use/tests)
2359    pub async fn is_leader(&self) -> Result<bool, JsValue> {
2360        let result = self.is_leader_wasm().await?;
2361        Ok(result.as_bool().unwrap_or(false))
2362    }
2363
2364    #[wasm_bindgen(js_name = "onDataChange")]
2365    pub fn on_data_change_wasm(&mut self, callback: &js_sys::Function) -> Result<(), JsValue> {
2366        log::debug!("Registering onDataChange callback for {}", self.name);
2367
2368        // Store the callback
2369        self.on_data_change_callback = Some(callback.clone());
2370
2371        // Register listener for BroadcastChannel notifications from other tabs
2372        use crate::storage::broadcast_notifications::register_change_listener;
2373
2374        let db_name = &self.name;
2375        register_change_listener(db_name, callback).map_err(|e| {
2376            JsValue::from_str(&format!("Failed to register change listener: {}", e))
2377        })?;
2378
2379        log::debug!("onDataChange callback registered for {}", self.name);
2380        Ok(())
2381    }
2382
2383    /// Reload data from IndexedDB into memory
2384    /// Call this when another tab has written data and you need to see the changes
2385    /// This closes and reopens the SQLite connection to invalidate its page cache
2386    #[wasm_bindgen(js_name = "reloadFromIndexedDB")]
2387    pub async fn reload_from_indexed_db(&mut self) -> Result<(), JsValue> {
2388        log::info!("Reloading data from IndexedDB for {}", self.name);
2389
2390        let db_name = self.name.clone();
2391
2392        // Step 1: Close the SQLite connection to invalidate page cache
2393        let pool_key = db_name.trim_end_matches(".db");
2394        crate::connection_pool::force_close_connection(pool_key);
2395        self.connection_state.db.set(std::ptr::null_mut());
2396        log::info!("[RELOAD] Closed SQLite connection for {}", db_name);
2397
2398        // Step 2: Restore from IndexedDB into global storage (force reload)
2399        crate::storage::wasm_indexeddb::restore_from_indexeddb_force(&db_name)
2400            .await
2401            .map_err(|e| JsValue::from_str(&format!("Failed to restore from IndexedDB: {}", e)))?;
2402        log::info!("[RELOAD] Restored from IndexedDB for {}", db_name);
2403
2404        // Step 3: Reload BlockStorage cache from global storage
2405        use crate::vfs::indexeddb_vfs::STORAGE_REGISTRY;
2406        STORAGE_REGISTRY.with(|reg| unsafe {
2407            let registry = &*reg.get();
2408            if let Some(storage_rc) = registry.get(&db_name) {
2409                storage_rc.reload_cache_from_global_storage();
2410                log::info!("[RELOAD] Reloaded BlockStorage cache for {}", db_name);
2411            }
2412        });
2413
2414        // Step 4: Reopen the SQLite connection
2415        use std::ffi::CString;
2416
2417        let vfs_name = format!("vfs_{}", db_name.trim_end_matches(".db"));
2418        let pool_key = db_name.trim_end_matches(".db").to_string();
2419        let db_name_for_closure = db_name.clone();
2420        let vfs_name_for_closure = vfs_name.clone();
2421
2422        let new_state = crate::connection_pool::get_or_create_connection(&pool_key, || {
2423            let mut db = std::ptr::null_mut();
2424            let db_name_cstr = CString::new(db_name_for_closure.clone())
2425                .map_err(|_| "Invalid database name".to_string())?;
2426            let vfs_cstr = CString::new(vfs_name_for_closure.as_str())
2427                .map_err(|_| "Invalid VFS name".to_string())?;
2428
2429            log::info!(
2430                "[RELOAD] Reopening database: {} with VFS: {}",
2431                db_name_for_closure,
2432                vfs_name_for_closure
2433            );
2434
2435            let ret = unsafe {
2436                sqlite_wasm_rs::sqlite3_open_v2(
2437                    db_name_cstr.as_ptr(),
2438                    &mut db as *mut _,
2439                    sqlite_wasm_rs::SQLITE_OPEN_READWRITE | sqlite_wasm_rs::SQLITE_OPEN_CREATE,
2440                    vfs_cstr.as_ptr(),
2441                )
2442            };
2443
2444            if ret != sqlite_wasm_rs::SQLITE_OK {
2445                let err_msg = unsafe {
2446                    let msg_ptr = sqlite_wasm_rs::sqlite3_errmsg(db);
2447                    if !msg_ptr.is_null() {
2448                        std::ffi::CStr::from_ptr(msg_ptr)
2449                            .to_string_lossy()
2450                            .into_owned()
2451                    } else {
2452                        "Unknown error".to_string()
2453                    }
2454                };
2455                return Err(format!("Failed to reopen database: {}", err_msg));
2456            }
2457
2458            log::info!("[RELOAD] Database reopened successfully");
2459            Ok(db)
2460        })
2461        .map_err(|e| JsValue::from_str(&format!("Failed to reopen connection: {}", e)))?;
2462
2463        self.connection_state = new_state;
2464        log::info!("[RELOAD] Connection state updated for {}", db_name);
2465
2466        Ok(())
2467    }
2468
2469    /// Enable or disable optimistic updates mode
2470    #[wasm_bindgen(js_name = "enableOptimisticUpdates")]
2471    pub async fn enable_optimistic_updates(&mut self, enabled: bool) -> Result<(), JsValue> {
2472        self.optimistic_updates_manager
2473            .borrow_mut()
2474            .set_enabled(enabled);
2475        log::debug!(
2476            "Optimistic updates {}",
2477            if enabled { "enabled" } else { "disabled" }
2478        );
2479        Ok(())
2480    }
2481
2482    /// Check if optimistic mode is enabled
2483    #[wasm_bindgen(js_name = "isOptimisticMode")]
2484    pub async fn is_optimistic_mode(&self) -> bool {
2485        self.optimistic_updates_manager.borrow().is_enabled()
2486    }
2487
2488    /// Track an optimistic write
2489    #[wasm_bindgen(js_name = "trackOptimisticWrite")]
2490    pub async fn track_optimistic_write(&mut self, sql: String) -> Result<String, JsValue> {
2491        let id = self
2492            .optimistic_updates_manager
2493            .borrow_mut()
2494            .track_write(sql);
2495        Ok(id)
2496    }
2497
2498    /// Get count of pending writes
2499    #[wasm_bindgen(js_name = "getPendingWritesCount")]
2500    pub async fn get_pending_writes_count(&self) -> usize {
2501        self.optimistic_updates_manager.borrow().get_pending_count()
2502    }
2503
2504    /// Clear all optimistic writes
2505    #[wasm_bindgen(js_name = "clearOptimisticWrites")]
2506    pub async fn clear_optimistic_writes(&mut self) -> Result<(), JsValue> {
2507        self.optimistic_updates_manager.borrow_mut().clear_all();
2508        Ok(())
2509    }
2510
2511    /// Enable or disable coordination metrics tracking
2512    #[wasm_bindgen(js_name = "enableCoordinationMetrics")]
2513    pub async fn enable_coordination_metrics(&mut self, enabled: bool) -> Result<(), JsValue> {
2514        self.coordination_metrics_manager
2515            .borrow_mut()
2516            .set_enabled(enabled);
2517        Ok(())
2518    }
2519
2520    /// Check if coordination metrics tracking is enabled
2521    #[wasm_bindgen(js_name = "isCoordinationMetricsEnabled")]
2522    pub async fn is_coordination_metrics_enabled(&self) -> bool {
2523        self.coordination_metrics_manager.borrow().is_enabled()
2524    }
2525
2526    /// Record a leadership change
2527    #[wasm_bindgen(js_name = "recordLeadershipChange")]
2528    pub async fn record_leadership_change(&mut self, became_leader: bool) -> Result<(), JsValue> {
2529        self.coordination_metrics_manager
2530            .borrow_mut()
2531            .record_leadership_change(became_leader);
2532        Ok(())
2533    }
2534
2535    /// Record a notification latency in milliseconds
2536    #[wasm_bindgen(js_name = "recordNotificationLatency")]
2537    pub async fn record_notification_latency(&mut self, latency_ms: f64) -> Result<(), JsValue> {
2538        self.coordination_metrics_manager
2539            .borrow_mut()
2540            .record_notification_latency(latency_ms);
2541        Ok(())
2542    }
2543
2544    /// Record a write conflict (non-leader write attempt)
2545    #[wasm_bindgen(js_name = "recordWriteConflict")]
2546    pub async fn record_write_conflict(&mut self) -> Result<(), JsValue> {
2547        self.coordination_metrics_manager
2548            .borrow_mut()
2549            .record_write_conflict();
2550        Ok(())
2551    }
2552
2553    /// Record a follower refresh
2554    #[wasm_bindgen(js_name = "recordFollowerRefresh")]
2555    pub async fn record_follower_refresh(&mut self) -> Result<(), JsValue> {
2556        self.coordination_metrics_manager
2557            .borrow_mut()
2558            .record_follower_refresh();
2559        Ok(())
2560    }
2561
2562    /// Get coordination metrics as JSON string
2563    #[wasm_bindgen(js_name = "getCoordinationMetrics")]
2564    pub async fn get_coordination_metrics(&self) -> Result<String, JsValue> {
2565        self.coordination_metrics_manager
2566            .borrow()
2567            .get_metrics_json()
2568            .map_err(|e| JsValue::from_str(&e))
2569    }
2570
2571    /// Reset all coordination metrics
2572    #[wasm_bindgen(js_name = "resetCoordinationMetrics")]
2573    pub async fn reset_coordination_metrics(&mut self) -> Result<(), JsValue> {
2574        self.coordination_metrics_manager.borrow_mut().reset();
2575        Ok(())
2576    }
2577}
2578
2579// Export WasmColumnValue for WASM
2580#[cfg(target_arch = "wasm32")]
2581#[wasm_bindgen]
2582pub struct WasmColumnValue {
2583    #[allow(dead_code)]
2584    inner: ColumnValue,
2585}
2586
2587#[cfg(target_arch = "wasm32")]
2588#[wasm_bindgen]
2589impl WasmColumnValue {
2590    #[wasm_bindgen(js_name = "createNull")]
2591    pub fn create_null() -> WasmColumnValue {
2592        WasmColumnValue {
2593            inner: ColumnValue::Null,
2594        }
2595    }
2596
2597    #[wasm_bindgen(js_name = "createInteger")]
2598    pub fn create_integer(value: i64) -> WasmColumnValue {
2599        WasmColumnValue {
2600            inner: ColumnValue::Integer(value),
2601        }
2602    }
2603
2604    #[wasm_bindgen(js_name = "createReal")]
2605    pub fn create_real(value: f64) -> WasmColumnValue {
2606        WasmColumnValue {
2607            inner: ColumnValue::Real(value),
2608        }
2609    }
2610
2611    #[wasm_bindgen(js_name = "createText")]
2612    pub fn create_text(value: String) -> WasmColumnValue {
2613        WasmColumnValue {
2614            inner: ColumnValue::Text(value),
2615        }
2616    }
2617
2618    #[wasm_bindgen(js_name = "createBlob")]
2619    pub fn create_blob(value: &[u8]) -> WasmColumnValue {
2620        WasmColumnValue {
2621            inner: ColumnValue::Blob(value.to_vec()),
2622        }
2623    }
2624
2625    #[wasm_bindgen(js_name = "createBigInt")]
2626    pub fn create_bigint(value: &str) -> WasmColumnValue {
2627        WasmColumnValue {
2628            inner: ColumnValue::BigInt(value.to_string()),
2629        }
2630    }
2631
2632    #[wasm_bindgen(js_name = "createDate")]
2633    pub fn create_date(timestamp: f64) -> WasmColumnValue {
2634        WasmColumnValue {
2635            inner: ColumnValue::Date(timestamp as i64),
2636        }
2637    }
2638
2639    #[wasm_bindgen(js_name = "fromJsValue")]
2640    pub fn from_js_value(value: &JsValue) -> WasmColumnValue {
2641        if value.is_null() || value.is_undefined() {
2642            WasmColumnValue {
2643                inner: ColumnValue::Null,
2644            }
2645        } else if let Some(s) = value.as_string() {
2646            // Check if it's a large number string
2647            if let Ok(parsed) = s.parse::<i64>() {
2648                WasmColumnValue {
2649                    inner: ColumnValue::Integer(parsed),
2650                }
2651            } else {
2652                WasmColumnValue {
2653                    inner: ColumnValue::Text(s),
2654                }
2655            }
2656        } else if let Some(n) = value.as_f64() {
2657            if n.fract() == 0.0 && n >= i64::MIN as f64 && n <= i64::MAX as f64 {
2658                WasmColumnValue {
2659                    inner: ColumnValue::Integer(n as i64),
2660                }
2661            } else {
2662                WasmColumnValue {
2663                    inner: ColumnValue::Real(n),
2664                }
2665            }
2666        } else if value.is_object() {
2667            // Check if it's a Date
2668            if js_sys::Date::new(value).get_time().is_finite() {
2669                let timestamp = js_sys::Date::new(value).get_time() as i64;
2670                WasmColumnValue {
2671                    inner: ColumnValue::Date(timestamp),
2672                }
2673            } else {
2674                // Convert to string for other objects
2675                WasmColumnValue {
2676                    inner: ColumnValue::Text(format!("{:?}", value)),
2677                }
2678            }
2679        } else {
2680            WasmColumnValue {
2681                inner: ColumnValue::Null,
2682            }
2683        }
2684    }
2685
2686    // --- Rust-friendly alias constructors used in wasm tests ---
2687    // These mirror the create* methods but with simpler names and
2688    // argument types matching test usage.
2689    pub fn null() -> WasmColumnValue {
2690        Self::create_null()
2691    }
2692
2693    // Tests call integer(42.0), so accept f64 and cast to i64.
2694    pub fn integer(value: f64) -> WasmColumnValue {
2695        Self::create_integer(value as i64)
2696    }
2697
2698    pub fn real(value: f64) -> WasmColumnValue {
2699        Self::create_real(value)
2700    }
2701
2702    pub fn text(value: String) -> WasmColumnValue {
2703        Self::create_text(value)
2704    }
2705
2706    pub fn blob(value: Vec<u8>) -> WasmColumnValue {
2707        Self::create_blob(&value)
2708    }
2709
2710    pub fn big_int(value: String) -> WasmColumnValue {
2711        Self::create_bigint(&value)
2712    }
2713
2714    pub fn date(timestamp_ms: f64) -> WasmColumnValue {
2715        Self::create_date(timestamp_ms)
2716    }
2717}