diff --git a/moli-indexeddb/src/sqlite/service/tests/connection_tests.rs b/moli-indexeddb/src/sqlite/service/tests/connection_tests.rs index 6136c0b23f2..e6d9519781c 100644 --- a/moli-indexeddb/src/sqlite/service/tests/connection_tests.rs +++ b/moli-indexeddb/src/sqlite/service/tests/connection_tests.rs @@ -518,6 +518,7 @@ fn panicked_worker_shutdown_rolls_back_and_retires_live_connections() { #[test] fn connection_registration_failure_does_not_publish_a_blocker_or_consume_metadata() { let service = Service::new(config()).unwrap(); + service.next_connection.store(1u64 << 53, Ordering::Relaxed); let client = open(&service, "registration-pressure", Location::Memory); let before = service.metadata_bytes(); let controls = client @@ -531,6 +532,7 @@ fn connection_registration_failure_does_not_publish_a_blocker_or_consume_metadat assert!(!client.has_open_connections()); drop(controls); let connection = client.open_connection(noop()).unwrap(); + assert_eq!(connection.handle().into_raw(), (1u64 << 53) + 1); let other_client = open(&service, "other-registration", Location::Memory); let other = other_client.open_connection(noop()).unwrap(); assert_ne!( diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/core.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/core.rs index 507bd4db00c..02bcd8d0514 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/core.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/core.rs @@ -1,9 +1,8 @@ use super::{ - CursorDirection, CursorSnapshotEntry, DatabaseHandle, INDEXED_DB_DATABASE_KEY_SLOT, - INDEXED_DB_REQUEST_ERROR_SLOT, INDEXED_DB_REQUEST_READY_STATE_SLOT, - INDEXED_DB_REQUEST_RESULT_SLOT, INDEXED_DB_TRANSACTION_ACTIVE_SLOT, - INDEXED_DB_TRANSACTION_FINISHED_SLOT, IdbKeyRangeQuery, IndexInfo, IndexedDbError, - IndexedDbExecutionOwner, IndexedDbExternalObject, IndexedDbManager, + CursorDirection, CursorSnapshotEntry, DatabaseHandle, INDEXED_DB_REQUEST_ERROR_SLOT, + INDEXED_DB_REQUEST_READY_STATE_SLOT, INDEXED_DB_REQUEST_RESULT_SLOT, + INDEXED_DB_TRANSACTION_ACTIVE_SLOT, INDEXED_DB_TRANSACTION_FINISHED_SLOT, IdbKeyRangeQuery, + IndexInfo, IndexedDbError, IndexedDbExecutionOwner, IndexedDbExternalObject, IndexedDbManager, IndexedDbObjectStoreMetadata, IndexedDbRuntimeArray, IndexedDbStorageScope, IndexedDbValue, IndexedDbWrapperKind, Key, KeyPath, MetadataNode, ObjectStoreInfo, ObjectStoreKey, PreparedObjectStoreKey, PreparedObjectStoreWrite, TransactionHandle, TransactionMode, @@ -11,16 +10,15 @@ use super::{ indexed_db_database_sql_client, indexed_db_database_store_metadata, indexed_db_object_store_metadata, indexed_db_runtime_array, indexed_db_typed_execution_owner, indexed_db_typed_storage_scope, new_null_prototype_object, object_bool_property, - object_string_property, push_unique_object_to_indexed_db_runtime_array, - register_indexed_db_cursor_lifecycle, register_indexed_db_database_lifecycle, - register_indexed_db_index_lifecycle, register_indexed_db_object_store_lifecycle, - register_indexed_db_request_lifecycle, register_indexed_db_transaction_lifecycle, - register_indexed_db_wrapper_with_owner, remove_indexed_db_database_index_metadata, - remove_indexed_db_database_store_metadata, replace_indexed_db_database_metadata, - replace_indexed_db_runtime_array, set_indexed_db_database_index_metadata, - set_indexed_db_database_store_metadata, set_indexed_db_internal_object_property, - set_indexed_db_object_store_metadata, set_indexed_db_request_surface_value, - set_indexed_db_slot_value, v8_string, v8str, + push_unique_object_to_indexed_db_runtime_array, register_indexed_db_cursor_lifecycle, + register_indexed_db_database_lifecycle, register_indexed_db_index_lifecycle, + register_indexed_db_object_store_lifecycle, register_indexed_db_request_lifecycle, + register_indexed_db_transaction_lifecycle, register_indexed_db_wrapper_with_owner, + remove_indexed_db_database_index_metadata, remove_indexed_db_database_store_metadata, + replace_indexed_db_database_metadata, replace_indexed_db_runtime_array, + set_indexed_db_database_index_metadata, set_indexed_db_database_store_metadata, + set_indexed_db_internal_object_property, set_indexed_db_object_store_metadata, + set_indexed_db_request_surface_value, set_indexed_db_slot_value, v8_string, v8str, }; use std::collections::BTreeSet; use v8::{ValueDeserializerHelper, ValueSerializerHelper}; diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/core/objects/creation/database.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/core/objects/creation/database.rs index 15ecb0d100d..7e80c896a2f 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/core/objects/creation/database.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/core/objects/creation/database.rs @@ -72,7 +72,6 @@ pub(in crate::context_bootstrap::indexed_db) fn create_database_object<'s>( version: u64, client: moli_indexeddb::sqlite::service::DatabaseClient, ) -> Result, IndexedDbError> { - let database_key = database_registry_key(storage_scope.storage_key(), name); let database = IdbDatabaseObjectDeclaration::new(name.to_owned(), version as f64) .bind(scope) .map_err(|error| IndexedDbError::InvalidState(error.to_string()))?; @@ -83,14 +82,7 @@ pub(in crate::context_bootstrap::indexed_db) fn create_database_object<'s>( owner, Some(storage_scope.clone()), ); - register_indexed_db_database_lifecycle( - scope, - database, - handle, - database_key, - storage_scope, - client, - ); + register_indexed_db_database_lifecycle(scope, database, handle, storage_scope, client); if let Err(error) = refresh_database_surface(scope, database) { crate::context_bootstrap::indexed_db::discard_indexed_db_database_lifecycle( scope, database, diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/core/objects/creation/transaction.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/core/objects/creation/transaction.rs index 748b7929a4e..b59438badda 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/core/objects/creation/transaction.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/core/objects/creation/transaction.rs @@ -63,9 +63,7 @@ pub(in crate::context_bootstrap::indexed_db) fn create_transaction_object<'s>( mode: TransactionMode, store_names: &[String], ) -> Option> { - let handle_raw = handle.map(|handle| handle.into_raw() as f64); let mode_label: &'static str = mode.into(); - let db_key = object_string_property(scope, db, INDEXED_DB_DATABASE_KEY_SLOT); let object_store_names = new_idb_name_list(scope, store_names); let tx = IdbTransactionObjectDeclaration::new(db, mode_label, object_store_names) .bind(scope) @@ -80,14 +78,6 @@ pub(in crate::context_bootstrap::indexed_db) fn create_transaction_object<'s>( owner, storage_scope, ); - register_indexed_db_transaction_lifecycle( - scope, - tx, - db, - handle, - mode, - handle_raw.is_some(), - db_key, - ); + register_indexed_db_transaction_lifecycle(scope, tx, db, handle, mode, handle.is_some()); Some(tx) } diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/core/objects/surface/database.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/core/objects/surface/database.rs index befbfd21567..ad6e6cfd78e 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/core/objects/surface/database.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/core/objects/surface/database.rs @@ -5,11 +5,11 @@ pub(in crate::context_bootstrap::indexed_db) fn refresh_database_surface<'s>( scope: &mut v8::PinScope<'s, '_>, database: v8::Local<'s, v8::Object>, ) -> std::result::Result<(), IndexedDbError> { - let Some(client) = + let client = crate::context_bootstrap::indexed_db::indexed_db_database_sql_client(scope, database) - else { - return Ok(()); - }; + .ok_or_else(|| { + IndexedDbError::InvalidState("SQL database client is unavailable".into()) + })?; let metadata = client.committed().ok_or_else(|| { IndexedDbError::InvalidState("SQL database metadata is unavailable".into()) })?; diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/core/registry.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/core/registry.rs index 87477b918e9..6329c9e6a56 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/core/registry.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/core/registry.rs @@ -1,10 +1,7 @@ use super::*; -mod connections; mod transactions; -pub(in crate::context_bootstrap::indexed_db) use self::connections::database_registry_key; - pub(in crate::context_bootstrap::indexed_db) use self::transactions::{ register_regular_transaction, unregister_regular_transaction, }; diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/core/registry/connections.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/core/registry/connections.rs deleted file mode 100644 index 154fcc52aaa..00000000000 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/core/registry/connections.rs +++ /dev/null @@ -1,6 +0,0 @@ -pub(in crate::context_bootstrap::indexed_db) fn database_registry_key( - origin: &str, - name: &str, -) -> String { - format!("{origin}\u{0}{name}") -} diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/mod.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/mod.rs index a5f1d0ef9d3..8ad613cf9a1 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/mod.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/mod.rs @@ -46,23 +46,26 @@ pub(crate) fn deserialize_indexed_db_value_for_test<'s>( #[cfg(test)] pub(crate) fn create_sql_database_for_test<'s>( scope: &mut v8::PinScope<'s, '_>, - client: moli_indexeddb::sqlite::service::DatabaseClient, - handle: moli_indexeddb::DatabaseHandle, + connection: moli_indexeddb::sqlite::service::DatabaseConnection, ) -> Option> { + let client = connection.client().clone(); let factory = indexed_db_runtime_factory(scope)?; let owner = indexed_db_typed_execution_owner(scope, factory)?; let storage_scope = indexed_db_factory_storage_scope(scope, factory)?; let metadata = client.committed()?; - create_database_object( + let database = create_database_object( scope, storage_scope, owner, - handle, + connection.handle(), &metadata.name, metadata.version, client, ) - .ok() + .ok()?; + attach_indexed_db_sql_connection(scope, database, connection) + .expect("fixture logical connection matches its SQL database"); + Some(database) } #[cfg(test)] pub(crate) fn create_sql_upgrade_for_test<'s>( diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/slots.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/slots.rs index e9c2e5bf48f..89837db455e 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/slots.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/slots.rs @@ -16,7 +16,6 @@ pub(super) const INDEXED_DB_DATABASE_HANDLE_SLOT: &str = "moli.IndexedDb.databas pub(super) const INDEXED_DB_DATABASE_METADATA_SLOT: &str = "moli.IndexedDb.databaseMetadata"; pub(super) const INDEXED_DB_DATABASE_UPGRADE_TRANSACTION_SLOT: &str = "moli.IndexedDb.databaseUpgradeTransaction"; -pub(super) const INDEXED_DB_DATABASE_KEY_SLOT: &str = "moli.IndexedDb.databaseKey"; pub(super) const INDEXED_DB_DATABASE_STORAGE_KEY_SLOT: &str = "moli.IndexedDb.databaseStorageKey"; pub(super) const INDEXED_DB_DATABASE_CLOSED_SLOT: &str = "moli.IndexedDb.databaseClosed"; pub(super) const INDEXED_DB_TRANSACTION_HANDLE_SLOT: &str = "moli.IndexedDb.transactionHandle"; @@ -28,7 +27,6 @@ pub(super) const INDEXED_DB_TRANSACTION_ABORTED_SLOT: &str = "moli.IndexedDb.tra pub(super) const INDEXED_DB_TRANSACTION_STARTED_SLOT: &str = "moli.IndexedDb.transactionStarted"; pub(super) const INDEXED_DB_TRANSACTION_START_SCHEDULED_SLOT: &str = "moli.IndexedDb.transactionStartScheduled"; -pub(super) const INDEXED_DB_TRANSACTION_DB_KEY_SLOT: &str = "moli.IndexedDb.transactionDbKey"; pub(super) const INDEXED_DB_TRANSACTION_PENDING_SLOT: &str = "moli.IndexedDb.transactionPending"; pub(super) const INDEXED_DB_TRANSACTION_COMMIT_SCHEDULED_SLOT: &str = "moli.IndexedDb.transactionCommitScheduled"; diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/storage_bucket.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/storage_bucket.rs index 12614adf4f8..1397f0c2a1b 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/storage_bucket.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/storage_bucket.rs @@ -42,12 +42,9 @@ pub(in crate::context_bootstrap::indexed_db) fn sql_quota_owner<'s>( } let database = indexed_db_transaction_database(scope, transaction) .ok_or_else(|| IndexedDbError::InvalidState("SQL transaction lost its database".into()))?; - // Raw SQL fixtures predate real IDBFactory connections; production must - // always have a logical connection and cannot bypass bucket accounting. - #[cfg(test)] - if super::indexed_db_database_sql_connection(scope, database).is_none() { - return Ok(None); - } + super::indexed_db_database_sql_connection(scope, database).ok_or_else(|| { + IndexedDbError::InvalidState("SQL database lost its logical connection".into()) + })?; let storage_scope = indexed_db_typed_storage_scope(scope, database).ok_or_else(|| { IndexedDbError::InvalidState("SQL database lost its storage owner".into()) })?; diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state.rs index f1462346782..248598c7107 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state.rs @@ -335,7 +335,6 @@ struct IndexedDbTransactionLifecycleState { deactivation_scheduled: bool, operation_in_flight: bool, operations: std::collections::VecDeque, - db_key: Option, } impl IndexedDbTransactionLifecycleState { @@ -344,7 +343,6 @@ impl IndexedDbTransactionLifecycleState { handle: Option, mode: TransactionMode, started: bool, - db_key: Option, ) -> Self { Self { mode, @@ -368,7 +366,6 @@ impl IndexedDbTransactionLifecycleState { deactivation_scheduled: false, operation_in_flight: false, operations: Default::default(), - db_key, } } } @@ -394,7 +391,6 @@ struct IndexedDbDatabaseLifecycleState { backend: IndexedDbDatabaseBackend, forced_close_scheduled: bool, handle: DatabaseHandle, - database_key: String, storage_scope: IndexedDbStorageScope, closed: bool, mirror: std::rc::Weak>, @@ -415,7 +411,6 @@ impl IndexedDbDatabaseLifecycleState { wrapper: v8::Local<'_, v8::Object>, backend: IndexedDbDatabaseBackend, handle: DatabaseHandle, - database_key: String, storage_scope: IndexedDbStorageScope, ) -> Self { Self { @@ -423,7 +418,6 @@ impl IndexedDbDatabaseLifecycleState { backend, forced_close_scheduled: false, handle, - database_key, storage_scope, closed: false, mirror: std::rc::Weak::new(), @@ -787,7 +781,6 @@ pub(super) fn register_indexed_db_transaction_lifecycle<'s>( handle: Option, mode: TransactionMode, started: bool, - db_key: Option, ) { let Some(id) = indexed_db_typed_state_id(scope, transaction) else { return; @@ -797,7 +790,6 @@ pub(super) fn register_indexed_db_transaction_lifecycle<'s>( handle, mode, started, - db_key, ); let table = indexed_db_runtime_state_table_for_object(scope, transaction); table.borrow_mut().transactions.insert(id, state); @@ -1233,7 +1225,6 @@ pub(super) fn register_indexed_db_database_lifecycle<'s>( scope: &mut v8::PinScope<'s, '_>, database: v8::Local<'s, v8::Object>, handle: DatabaseHandle, - database_key: String, storage_scope: IndexedDbStorageScope, client: moli_indexeddb::sqlite::service::DatabaseClient, ) { @@ -1246,14 +1237,8 @@ pub(super) fn register_indexed_db_database_lifecycle<'s>( connection: None, forced_close: None, }; - let mut state = IndexedDbDatabaseLifecycleState::new( - scope, - database, - backend, - handle, - database_key, - storage_scope, - ); + let mut state = + IndexedDbDatabaseLifecycleState::new(scope, database, backend, handle, storage_scope); let table = indexed_db_runtime_state_table_for_object(scope, database); let mirror = Rc::new(RefCell::new(IndexedDbDatabaseMirror::default())); state.mirror = Rc::downgrade(&mirror); @@ -2241,11 +2226,6 @@ fn indexed_db_typed_transaction_slot_value<'s>( INDEXED_DB_TRANSACTION_COMMIT_SCHEDULED_SLOT => { Some(v8::Boolean::new(scope, transaction.commit_scheduled).into()) } - INDEXED_DB_TRANSACTION_DB_KEY_SLOT => transaction - .db_key - .as_ref() - .and_then(|value| v8_string(scope, value)) - .map(Into::into), _ => None, } } @@ -2299,16 +2279,6 @@ fn set_indexed_db_typed_transaction_slot_value( transaction.commit_scheduled = value.boolean_value(scope); true } - INDEXED_DB_TRANSACTION_DB_KEY_SLOT => { - transaction.db_key = if value.is_null_or_undefined() { - None - } else { - value - .to_string(scope) - .map(|value| value.to_rust_string_lossy(scope)) - }; - true - } _ => false, } } @@ -2341,7 +2311,6 @@ fn indexed_db_typed_database_slot_value<'s>( INDEXED_DB_DATABASE_HANDLE_SLOT => { Some(v8::Number::new(scope, database.handle.into_raw() as f64).into()) } - INDEXED_DB_DATABASE_KEY_SLOT => v8_string(scope, &database.database_key).map(Into::into), INDEXED_DB_DATABASE_STORAGE_KEY_SLOT => { v8_string(scope, database.storage_scope.storage_key()).map(Into::into) } @@ -2371,13 +2340,6 @@ fn set_indexed_db_typed_database_slot_value( DatabaseHandle::from_raw(value.number_value(scope).unwrap_or(0.0) as u64); true } - INDEXED_DB_DATABASE_KEY_SLOT => { - database.database_key = value - .to_string(scope) - .map(|value| value.to_rust_string_lossy(scope)) - .unwrap_or_default(); - true - } INDEXED_DB_DATABASE_STORAGE_KEY_SLOT => { database.storage_scope.storage_key = value .to_string(scope) diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state/sql/tests.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state/sql/tests.rs index ed38e10f7ef..0109562aff2 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state/sql/tests.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state/sql/tests.rs @@ -6,18 +6,27 @@ use crate::context_bootstrap::indexed_db::{ }; use crate::util::get_private_value; use moli_indexeddb::sqlite::{ - DatabaseIdentity, IndexKeys, - service::{CommandResult, Location, Service, ServiceConfig, TaskKind}, + IndexKeys, + service::{CommandResult, DatabaseConnection, Service, ServiceClient, ServiceConfig, TaskKind}, }; use moli_indexeddb::{IndexOptions, KeyPath}; -use std::collections::BTreeSet; use std::{cell::Cell, sync::mpsc, time::Duration}; const TX: TransactionHandle = TransactionHandle::from_raw(19); struct Backend { client: DatabaseClient, - _service: Service, + _service: ServiceClient, + connection: DatabaseConnection, + buckets: moli_storage_service::SharedStorageBucketStore, + manager: Arc>, + storage_scope: IndexedDbStorageScope, +} + +impl Drop for Backend { + fn drop(&mut self) { + self.manager.lock().shutdown_sqlite().unwrap(); + } } impl Backend { @@ -34,35 +43,72 @@ impl Backend { } fn with_store(options: ObjectStoreOptions, indexes: Vec) -> Self { + Self::with_store_quota(options, indexes, None) + } + + fn with_store_quota( + options: ObjectStoreOptions, + indexes: Vec, + quota: Option, + ) -> Self { let mut config = ServiceConfig::default(); config.executor.workers = 1; let service = Service::new(config).unwrap(); + let service_client = service.client(); + let manager = Arc::new(parking_lot::Mutex::new( + moli_indexeddb::IndexedDbManager::with_sqlite_service(service), + )); + let buckets = + moli_storage_service::new_shared_storage_bucket_store_with_indexed_db_manager(&manager); + let storage_scope = if let Some(quota) = quota { + let identity = buckets + .lock() + .open_bucket_with_options( + storage_scope().storage_key(), + "limited", + None, + None, + Some(quota), + None, + ) + .unwrap(); + IndexedDbStorageScope::new( + identity.indexed_db_storage_key(), + "test-browser", + "test-partition", + ) + .with_bucket_identity(identity) + } else { + storage_scope() + }; let (sender, receiver) = mpsc::channel(); - let client = service - .open( - DatabaseIdentity { - owner_key: b"test-partition/storage-key/default-bucket".to_vec(), - name: "sql-routing".into(), - generation: [5; 16], - }, - Location::Memory, + let client = service_client + .resolve( + storage_scope.storage_key().as_bytes().to_vec(), + "sql-routing".into(), move |reply| { let _ = sender.send(reply); }, ) .unwrap(); - assert!(receive(&receiver).result.is_ok()); + receive(&receiver).result.unwrap(); + let connection = client.open_connection(Arc::new(|| {})).unwrap(); let backend = Self { client, - _service: service, + _service: service_client, + connection, + buckets, + manager, + storage_scope, }; - backend.execute(Command::Begin { - transaction: TX, - mode: TransactionMode::VersionChange, - stores: BTreeSet::new(), - version: Some(1), - admission: None, - }); + let (sender, receiver) = mpsc::channel(); + backend + .connection + .begin_upgrade(TX, 1, move |reply| { + let _ = sender.send(reply); + }) + .unwrap(); + receive(&receiver).result.unwrap(); backend.execute(Command::CreateStore { transaction: TX, name: "records".into(), @@ -101,13 +147,8 @@ impl Backend { fn begin(&self, transaction: TransactionHandle) { let stores = vec!["records".to_owned()]; let admission = self - .client - .queue_transaction_start( - moli_indexeddb::DatabaseHandle::from_raw(1), - &stores, - TransactionMode::ReadWrite, - Arc::new(|| {}), - ) + .connection + .queue_transaction_start(&stores, TransactionMode::ReadWrite, Arc::new(|| {})) .unwrap(); assert!(admission.handle().is_ready()); self.execute(Command::Begin { @@ -191,7 +232,9 @@ fn receive(receiver: &mpsc::Receiver) -> Completion { .expect("bounded SQL worker completion") } -fn runtime(scope: &mut v8::PinScope<'_, '_>) { +struct SqlWake(RefCell>>); + +fn runtime(scope: &mut v8::PinScope<'_, '_>, backend: &Backend) { // These transport tests need an internal queue, without materializing the // Window/Worker Web API prototypes in a bare V8 context. let state = v8::Object::new(scope); @@ -211,6 +254,14 @@ fn runtime(scope: &mut v8::PinScope<'_, '_>) { true, ); assert!(indexed_db_runtime_array(scope, IndexedDbRuntimeArray::TaskQueue).is_some()); + let context = scope.get_current_context(); + let (wake, receiver) = tokio::sync::mpsc::unbounded_channel(); + set_worker_indexed_db_task_wake_for_context(context, wake); + context.set_slot(Rc::new(SqlWake(RefCell::new(Some(receiver))))); + crate::context_bootstrap::storage_buckets::set_storage_bucket_store_for_context( + context, + Some(backend.buckets.clone()), + ); } fn source<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Object> { @@ -221,16 +272,30 @@ fn source<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Object> { fn transaction<'s>( scope: &mut v8::PinScope<'s, '_>, - client: &DatabaseClient, + backend: &Backend, started: bool, ) -> (v8::Local<'s, v8::Object>, v8::Local<'s, v8::Object>) { let database = v8::Object::new(scope); + register_indexed_db_wrapper( + scope, + database, + IndexedDbWrapperKind::Database, + Some(backend.storage_scope.clone()), + ); + register_indexed_db_database_lifecycle( + scope, + database, + backend.connection.handle(), + backend.storage_scope.clone(), + backend.client.clone(), + ); + attach_indexed_db_sql_connection(scope, database, backend.connection.clone()).unwrap(); let transaction = v8::Object::new(scope); register_indexed_db_wrapper( scope, transaction, IndexedDbWrapperKind::Transaction, - Some(storage_scope()), + Some(backend.storage_scope.clone()), ); register_indexed_db_transaction_lifecycle( scope, @@ -239,7 +304,6 @@ fn transaction<'s>( Some(TX), TransactionMode::ReadWrite, started, - None, ); let id = indexed_db_typed_state_id(scope, transaction).unwrap(); let table = indexed_db_runtime_state_table_for_object(scope, transaction); @@ -248,7 +312,7 @@ fn transaction<'s>( .transactions .get_mut(&id) .unwrap() - .sql_client = Some(client.clone()); + .sql_client = Some(backend.client.clone()); (database, transaction) } @@ -257,28 +321,21 @@ fn request_for_store<'s>( transaction: v8::Local<'s, v8::Object>, store: v8::Local<'s, v8::Object>, ) -> v8::Local<'s, v8::Object> { + let storage_scope = indexed_db_typed_storage_scope(scope, transaction); let request = v8::Object::new(scope); - register_indexed_db_wrapper( - scope, - request, - IndexedDbWrapperKind::Request, - Some(storage_scope()), - ); + register_indexed_db_wrapper(scope, request, IndexedDbWrapperKind::Request, storage_scope); register_indexed_db_request_lifecycle(scope, request, store.into(), transaction.into(), false); request } -fn request<'s>( - scope: &mut v8::PinScope<'s, '_>, - client: &DatabaseClient, -) -> v8::Local<'s, v8::Object> { - let (_, transaction) = transaction(scope, client, true); +fn request<'s>(scope: &mut v8::PinScope<'s, '_>, backend: &Backend) -> v8::Local<'s, v8::Object> { + let (_, transaction) = transaction(scope, backend, true); let store = v8::Object::new(scope); register_indexed_db_wrapper( scope, store, IndexedDbWrapperKind::ObjectStore, - Some(storage_scope()), + Some(backend.storage_scope.clone()), ); let database = indexed_db_transaction_database(scope, transaction).unwrap(); register_indexed_db_object_store_lifecycle( @@ -287,9 +344,9 @@ fn request<'s>( transaction, database, IndexedDbObjectStoreMetadata::try_from_sql( - client, + &backend.client, "records", - &client.committed().unwrap().stores["records"], + &backend.client.committed().unwrap().stores["records"], ) .unwrap(), ); @@ -301,13 +358,13 @@ fn write_store<'s>( backend: &Backend, started: bool, ) -> (v8::Local<'s, v8::Object>, v8::Local<'s, v8::Object>) { - let (database, transaction) = transaction(scope, &backend.client, started); + let (database, transaction) = transaction(scope, backend, started); let store = v8::Object::new(scope); register_indexed_db_wrapper( scope, store, IndexedDbWrapperKind::ObjectStore, - Some(storage_scope()), + Some(backend.storage_scope.clone()), ); register_indexed_db_object_store_lifecycle( scope, @@ -351,13 +408,47 @@ fn prepare_write<'s>( fn drain_sql(scope: &mut v8::PinScope<'_, '_>, backend: &Backend) -> usize { let table = ensure_indexed_db_runtime_state_table(scope); + let wake = scope.get_current_context().get_slot::().unwrap(); + let mut receiver = wake.0.borrow_mut().take().unwrap(); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap(); let mut completions = 0; loop { let id = table.borrow().sql_tasks.keys().next().copied(); let Some(id) = id else { + wake.0.borrow_mut().replace(receiver); return completions; }; - backend.barrier(); + if !backend.client.is_retired() { + backend.barrier(); + } + runtime.block_on(async { + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let ready = { + let table = table.borrow(); + table + .sql_tasks + .get(&id) + .unwrap() + .completion + .lock() + .is_some() + }; + if ready { + break; + } + receiver + .recv() + .await + .expect("SQL/quota completion wakes its owner"); + } + }) + .await + .expect("bounded SQL/quota completion"); + }); assert!(flush_indexed_db_task_by_id(scope, id)); completions += 1; assert!( @@ -368,7 +459,114 @@ fn drain_sql(scope: &mut v8::PinScope<'_, '_>, backend: &Backend) -> usize { } fn storage_scope() -> IndexedDbStorageScope { - IndexedDbStorageScope::new("https://sql.example", "test-browser", "test-partition") + let storage_key = moli_storage_key::MoliStorageKey::first_party_from_url( + &url::Url::parse("https://sql.example").unwrap(), + None, + ) + .serialized_storage_key(); + IndexedDbStorageScope::new(storage_key, "test-browser", "test-partition") +} + +#[test] +fn metadata_refresh_rejects_a_database_without_a_sql_client() { + crate::ensure_v8_for_test(); + let mut isolate = v8::Isolate::new(v8::CreateParams::default()); + let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate)); + let scope = &mut scope.init(); + let context = v8::Context::new(scope, Default::default()); + let scope = &mut v8::ContextScope::new(scope, context); + let database = v8::Object::new(scope); + assert!(matches!( + crate::context_bootstrap::indexed_db::refresh_database_surface(scope, database), + Err(IndexedDbError::InvalidState(_)) + )); +} + +#[test] +fn quota_requires_a_logical_connection_in_the_transport_fixture() { + crate::ensure_v8_for_test(); + let backend = Backend::new(); + let mut isolate = v8::Isolate::new(v8::CreateParams::default()); + let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate)); + let scope = &mut scope.init(); + let context = v8::Context::new(scope, Default::default()); + let scope = &mut v8::ContextScope::new(scope, context); + runtime(scope, &backend); + let (database, transaction) = transaction(scope, &backend, true); + let id = indexed_db_typed_state_id(scope, database).unwrap(); + let table = ensure_indexed_db_runtime_state_table(scope); + let connection = table + .borrow_mut() + .databases + .get_mut(&id) + .unwrap() + .backend + .connection + .take() + .unwrap(); + assert!(matches!( + crate::context_bootstrap::indexed_db::storage_bucket::sql_quota_owner(scope, transaction), + Err(IndexedDbError::InvalidState(_)) + )); + attach_indexed_db_sql_connection(scope, database, connection).unwrap(); + assert!( + crate::context_bootstrap::indexed_db::storage_bucket::sql_quota_owner(scope, transaction) + .unwrap() + .is_some() + ); +} + +#[test] +fn transport_writes_enforce_real_bucket_quota_and_restore_generated_keys() { + crate::ensure_v8_for_test(); + let backend = Backend::with_store_quota( + ObjectStoreOptions { + auto_increment: true, + ..Default::default() + }, + Vec::new(), + Some(1024), + ); + let mut isolate = v8::Isolate::new(v8::CreateParams::default()); + let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate)); + let scope = &mut scope.init(); + let context = v8::Context::new(scope, Default::default()); + let scope = &mut v8::ContextScope::new(scope, context); + runtime(scope, &backend); + let (transaction, store) = write_store(scope, &backend, true); + let mut requests = Vec::new(); + for bytes in [4096, 8] { + let request = request_for_store(scope, transaction, store); + schedule( + scope, + request, + IndexedDbTransactionOperation::ObjectStoreWrite { + prepared: crate::context_bootstrap::indexed_db::PreparedObjectStoreWrite { + key: crate::context_bootstrap::indexed_db::PreparedObjectStoreKey::Generate, + value: vec![1; bytes].into(), + }, + add_only: false, + }, + ); + requests.push(request); + } + assert_eq!(drain_sql(scope, &backend), 2); + let error = object_hidden_value(scope, requests[0], INDEXED_DB_PENDING_ERROR_SLOT) + .unwrap() + .to_object(scope) + .unwrap(); + // Bare transport contexts do not install DOMException's JS prototype. + // The clone helper checks the native QuotaExceededError brand and fields. + let (_, quota, requested) = + crate::context_bootstrap::quota_exceeded_error_clone_fields(scope, error) + .expect("the request contains a branded quota error"); + assert_eq!(quota, Some(1024.0)); + assert!(requested.is_some_and(|requested| requested > 1024.0)); + assert_eq!(result(scope, requests[1]).number_value(scope), Some(1.0)); + assert!(matches!( + backend.execute(backend.count()), + CommandResult::Count(1) + )); } #[test] @@ -381,8 +579,8 @@ fn rejected_deferred_commit_waits_for_rollback_with_a_full_control_lane() { let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); - let (_, transaction) = transaction(scope, &backend.client, true); + runtime(scope, &backend); + let (_, transaction) = transaction(scope, &backend, true); let table = ensure_indexed_db_runtime_state_table(scope); let transaction_id = indexed_db_typed_state_id(scope, transaction).unwrap(); table @@ -470,8 +668,8 @@ fn rejected_sql_request_after_native_close_settles_request_before_transaction_ab let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); - let request = request(scope, &backend.client); + runtime(scope, &backend); + let request = request(scope, &backend); let transaction = source_transaction(scope, request).unwrap(); ensure_sql_transaction_rollback(scope, request).unwrap(); backend.execute(Command::Close); @@ -517,7 +715,7 @@ fn inline_write_closed_after_prepare_settles_abort_after_request_error() { let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); + runtime(scope, &backend); let (transaction, store) = write_store(scope, &backend, true); let request = request_for_store(scope, transaction, store); let value = eval(scope, "({saved:true})"); @@ -531,6 +729,7 @@ fn inline_write_closed_after_prepare_settles_abort_after_request_error() { backend.execute(Command::Close); assert!(backend.client.is_retired()); assert!(flush_indexed_db_task_by_id(scope, task)); + drain_sql(scope, &backend); let id = indexed_db_typed_state_id(scope, transaction).unwrap(); assert!(table.borrow().transactions[&id].finished); assert!(table.borrow().transactions[&id].aborted); @@ -600,7 +799,7 @@ fn sql_read_results_materialize_without_a_legacy_manager_or_record_scan() { let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); + runtime(scope, &backend); let poison = v8str( scope, "Object.defineProperty(Array.prototype, '0', {set() {throw new Error('internal queue invoked author setter')}, configurable: true})", @@ -611,7 +810,7 @@ fn sql_read_results_materialize_without_a_legacy_manager_or_record_scan() { backend.put(serialize_js_value(scope, value.into()).unwrap()); let query = IdbKeyRangeQuery::default(); - let get = request(scope, &backend.client); + let get = request(scope, &backend); schedule( scope, get, @@ -630,7 +829,7 @@ fn sql_read_results_materialize_without_a_legacy_manager_or_record_scan() { Some("pending") ); - let get_key = request(scope, &backend.client); + let get_key = request(scope, &backend); schedule( scope, get_key, @@ -644,7 +843,7 @@ fn sql_read_results_materialize_without_a_legacy_manager_or_record_scan() { "primary" ); - let count = request(scope, &backend.client); + let count = request(scope, &backend); schedule( scope, count, @@ -654,7 +853,7 @@ fn sql_read_results_materialize_without_a_legacy_manager_or_record_scan() { assert_eq!(result(scope, count).number_value(scope), Some(1.0)); for kind in [CollectionKind::Value, CollectionKind::Key] { - let get_all = request(scope, &backend.client); + let get_all = request(scope, &backend); schedule( scope, get_all, @@ -681,7 +880,7 @@ fn sql_read_results_materialize_without_a_legacy_manager_or_record_scan() { expected ); } - let index_key = request(scope, &backend.client); + let index_key = request(scope, &backend); let store = object_hidden_value(scope, index_key, INDEXED_DB_REQUEST_SOURCE_SLOT) .unwrap() .to_object(scope) @@ -691,7 +890,7 @@ fn sql_read_results_materialize_without_a_legacy_manager_or_record_scan() { scope, index, IndexedDbWrapperKind::Index, - Some(storage_scope()), + Some(backend.storage_scope.clone()), ); register_indexed_db_index_lifecycle( scope, @@ -739,7 +938,7 @@ fn waiting_sql_tasks_do_not_spin_or_block_ready_owner_tasks() { let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); + runtime(scope, &backend); let (wake, mut wakes) = tokio::sync::mpsc::unbounded_channel(); set_worker_indexed_db_task_wake_for_context(context, wake); let gate = backend.block(); @@ -795,13 +994,13 @@ fn sql_completion_returns_to_the_accepting_realm() { let second = v8::Context::new(scope, Default::default()); let source = { let scope = &mut v8::ContextScope::new(scope, first); - runtime(scope); + runtime(scope, &backend); source(scope) }; let completed = Rc::new(Cell::new(false)); { let scope = &mut v8::ContextScope::new(scope, second); - runtime(scope); + runtime(scope, &backend); let observed = completed.clone(); submit_indexed_db_sql_task( scope, @@ -845,7 +1044,7 @@ fn discarding_sql_tasks_releases_ready_and_late_result_permits() { let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); + runtime(scope, &backend); let gate = (!ready).then(|| backend.block()); let source = source(scope); submit_indexed_db_sql_task( @@ -891,8 +1090,8 @@ fn malformed_sql_wire_is_a_request_error_instead_of_successful_undefined() { let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); - let get_key = request(scope, &backend.client); + runtime(scope, &backend); + let get_key = request(scope, &backend); schedule( scope, get_key, @@ -905,7 +1104,7 @@ fn malformed_sql_wire_is_a_request_error_instead_of_successful_undefined() { result(scope, get_key).to_rust_string_lossy(scope), "primary" ); - let request = request(scope, &backend.client); + let request = request(scope, &backend); schedule( scope, request, @@ -928,7 +1127,7 @@ fn sql_delete_commands_use_the_same_dispatcher_and_return_undefined() { let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); + runtime(scope, &backend); for kind in [ IndexedDbTransactionOperation::CursorDelete { key: Key::from("primary"), @@ -943,7 +1142,7 @@ fn sql_delete_commands_use_the_same_dispatcher_and_return_undefined() { IndexedDbTransactionOperation::ObjectStoreClear, ] { backend.put(vec![1, 2, 3].into()); - let request = request(scope, &backend.client); + let request = request(scope, &backend); schedule(scope, request, kind); finish_sql(scope, &backend); assert!(result(scope, request).is_undefined()); @@ -988,7 +1187,7 @@ fn inline_sql_writes_keep_their_round_trips_in_fifo_and_index_the_snapshot() { let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); + runtime(scope, &backend); let (transaction, store) = write_store(scope, &backend, true); let gate = backend.block(); let first = request_for_store(scope, transaction, store); @@ -1071,7 +1270,7 @@ fn sql_unique_failure_and_owner_decode_failure_roll_back_generated_keys_before_n let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); + runtime(scope, &backend); let (transaction, store) = write_store(scope, &backend, true); let mut requests = Vec::new(); for value in [ @@ -1122,7 +1321,7 @@ fn index_free_sql_writes_use_one_command_and_reuse_the_prepared_bytes() { let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); + runtime(scope, &backend); let (transaction, store) = write_store(scope, &backend, true); let mut requests = Vec::new(); for key in [ @@ -1165,7 +1364,7 @@ fn sql_operations_wait_for_start_and_hold_their_snapshot_budget() { let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); + runtime(scope, &backend); let (transaction, store) = write_store(scope, &backend, false); let write = request_for_store(scope, transaction, store); let value = eval(scope, "'snapshot'.repeat(8192)"); @@ -1228,7 +1427,7 @@ fn sql_inline_cancellation_and_finish_progress_with_all_data_tickets_reserved() let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); + runtime(scope, &backend); let (transaction, store) = write_store(scope, &backend, true); let invalid = request_for_store(scope, transaction, store); schedule( @@ -1282,7 +1481,7 @@ fn discarded_inline_prepare_aborts_native_transaction_with_a_full_data_lane() { let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); + runtime(scope, &backend); let (transaction, store) = write_store(scope, &backend, true); for _ in 0..2 { let request = request_for_store(scope, transaction, store); @@ -1346,8 +1545,8 @@ fn discarded_schema_admission_error_releases_its_sql_owner_with_a_full_data_lane let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); - let (_, transaction) = transaction(scope, &backend.client, true); + runtime(scope, &backend); + let (_, transaction) = transaction(scope, &backend, true); ensure_sql_transaction_rollback(scope, transaction).unwrap(); // Temporary task-slot pressure now waits. A genuine allocation failure // requires exhausting snapshot bytes, while retaining cleanup capacity. @@ -1389,6 +1588,7 @@ fn discarded_schema_admission_error_releases_its_sql_owner_with_a_full_data_lane }), CommandResult::Count(0) )); + // The live logical connection does not occupy an execution slot. assert_eq!(backend._service.queue_usage().control_tasks, 0); } @@ -1406,7 +1606,7 @@ fn schema_admission_error_waits_for_the_whole_preceding_inline_write() { let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); + runtime(scope, &backend); let (transaction, store) = write_store(scope, &backend, true); let request = request_for_store(scope, transaction, store); let value = eval(scope, "({saved: true})"); @@ -1481,7 +1681,7 @@ fn index_budget_failure_cancels_the_inline_request_and_preserves_the_generator() let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); + runtime(scope, &backend); let (transaction, store) = write_store(scope, &backend, true); let large = request_for_store(scope, transaction, store); let value = eval( @@ -1547,7 +1747,7 @@ fn terminated_index_extraction_aborts_sql_and_does_not_start_the_next_operation( let scope = &mut scope.init(); let context = v8::Context::new(scope, Default::default()); let scope = &mut v8::ContextScope::new(scope, context); - runtime(scope); + runtime(scope, &backend); let (transaction, store) = write_store(scope, &backend, true); for value in ["({tags: new Array(1)})", "({tags: []})"] { let request = request_for_store(scope, transaction, store); diff --git a/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle.rs b/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle.rs index 4f8f30efce9..31b0751a114 100644 --- a/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle.rs +++ b/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle.rs @@ -1,10 +1,10 @@ use super::*; -use moli_indexeddb::sqlite::{ - DatabaseIdentity, - service::{Command, CommandResult, DatabaseClient, Location, Service, ServiceConfig, TaskKind}, +use moli_indexeddb::sqlite::service::{ + Command, CommandResult, DatabaseClient, DatabaseConnection, Service, ServiceClient, + ServiceConfig, TaskKind, WeakDatabaseConnection, }; -use moli_indexeddb::{DatabaseHandle, IndexOptions, KeyPath, ObjectStoreOptions, TransactionMode}; -use std::{collections::BTreeSet, sync::mpsc, time::Duration}; +use moli_indexeddb::{IndexOptions, KeyPath, ObjectStoreOptions, TransactionMode}; +use std::{cell::RefCell, collections::BTreeSet, sync::mpsc, time::Duration}; mod admission_tests; mod blob_tests; @@ -14,9 +14,20 @@ mod fatal_tests; mod metadata_tests; mod sharing_tests; +// Execution slots count runnable/undelivered work. A live logical connection +// alone does not occupy one; its teardown runs independently of ordinary slots. struct SqlBackend { client: DatabaseClient, - _service: Service, + _service: ServiceClient, + manager: crate::SharedIndexedDbManager, + buckets: moli_storage_service::SharedStorageBucketStore, + connection: RefCell>, +} + +impl Drop for SqlBackend { + fn drop(&mut self) { + self.manager.lock().shutdown_sqlite().unwrap(); + } } impl SqlBackend { @@ -54,22 +65,23 @@ impl SqlBackend { }) .unwrap(); } - fn new() -> Self { - Self::with_config(ServiceConfig::default()) + fn new(vm: &mut ScriptVm) -> Self { + Self::with_config(ServiceConfig::default(), vm) } - fn with_config(mut config: ServiceConfig) -> Self { + fn with_config(mut config: ServiceConfig, vm: &mut ScriptVm) -> Self { config.executor.workers = 1; let service = Service::new(config).unwrap(); let (sender, receiver) = mpsc::channel(); let client = service - .open( - DatabaseIdentity { - owner_key: b"sql-web-lifecycle-test".to_vec(), - name: "sql-web-lifecycle".into(), - generation: [43; 16], - }, - Location::Memory, + .resolve( + vm._context_host + .borrow_mut() + .top_document_storage_context() + .storage_key() + .serialized_storage_key() + .into_bytes(), + "sql-web-lifecycle".into(), move |reply| { sender.send(reply).unwrap(); }, @@ -82,9 +94,17 @@ impl SqlBackend { .result .is_ok() ); + let service_client = service.client(); + let manager = std::sync::Arc::new(parking_lot::Mutex::new( + moli_indexeddb::IndexedDbManager::with_sqlite_service(service), + )); + let buckets = crate::new_shared_storage_bucket_store_with_indexed_db_manager(&manager); let backend = Self { client, - _service: service, + _service: service_client, + manager, + buckets, + connection: RefCell::new(None), }; let transaction = backend.client.allocate_transaction_handle().unwrap(); backend.execute(Command::Begin { @@ -146,15 +166,27 @@ impl SqlBackend { receiver.recv_timeout(Duration::from_secs(10)).unwrap(); } + fn connection(&self) -> DatabaseConnection { + self.connection + .borrow() + .as_ref() + .and_then(WeakDatabaseConnection::upgrade) + .expect("fixture's Web database owns a live logical connection") + } + fn bind(&self, vm: &mut ScriptVm) { + vm.set_indexed_db_manager(Some(crate::downgrade_indexed_db_manager(&self.manager))); + vm.set_storage_bucket_store(self.buckets.clone()); + let connection = self + .client + .open_connection(std::sync::Arc::new(|| {})) + .unwrap(); + self.connection.borrow_mut().replace(connection.downgrade()); let context_ptr = &vm.page_default_runtime.context as *const _; vm.with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| { - let database = crate::context_bootstrap::create_sql_database_for_test( - scope, - self.client.clone(), - DatabaseHandle::from_raw((1u64 << 53) + 1), - ) - .expect("real SQL IDBDatabase wrapper"); + let database = + crate::context_bootstrap::create_sql_database_for_test(scope, connection) + .expect("real SQL IDBDatabase wrapper"); let global = scope.get_current_context().global(scope); assert_eq!( global.set( @@ -183,7 +215,13 @@ impl SqlBackend { .await .unwrap() { - return; + if vm.has_in_flight_indexed_db_tasks_for_test().unwrap() { + wait_for_one_selected_page_task_executor_test_turn(vm, loader) + .await + .unwrap(); + } else { + return; + } } } panic!( @@ -203,7 +241,7 @@ fn fixture() -> ( "https://idb-sql-lifecycle.test/", &loader, ); - let backend = SqlBackend::new(); + let backend = SqlBackend::new(&mut vm); backend.bind(&mut vm); (vm, loader, backend) } @@ -598,7 +636,7 @@ async fn idb_sqlite_schema_backfill_recycles_budget_instead_of_accumulating_reco ); let mut config = ServiceConfig::default(); config.executor.data.bytes = 48 * 1024; - let backend = SqlBackend::with_config(config); + let backend = SqlBackend::with_config(config, &mut vm); backend.bind(&mut vm); for index in 0..20 { vm.eval(&format!("db.transaction('records','readwrite').objectStore('records').put({{group:'g{index}',payload:'x'.repeat(16384)}})")).unwrap(); @@ -631,9 +669,8 @@ async fn idb_sqlite_schema_corrupt_wire_aborts_backfill_instead_of_skipping_a_ro let (mut vm, loader, backend) = fixture(); let handle = backend.client.allocate_transaction_handle().unwrap(); let admission = backend - .client + .connection() .queue_transaction_start( - DatabaseHandle::from_raw((1u64 << 53) + 1), &["records".into()], TransactionMode::ReadWrite, std::sync::Arc::new(|| {}), diff --git a/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/admission_tests.rs b/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/admission_tests.rs index 0ddaf3ee3df..b342ea0da3f 100644 --- a/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/admission_tests.rs +++ b/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/admission_tests.rs @@ -59,7 +59,21 @@ async fn schema_admission_failure(task_capacity: bool) { if task_capacity { // A full execution lane waits without converting accepted schema // work into an error. Releasing slots must finish the same upgrade. - backend.drain(&mut vm, &loader).await; + // Run ready turns without waiting for the slot held by this test. + for turn in 0..200 { + backend.barrier(); + if !vm + .run_one_oldest_ready_page_task_executor_turn(&loader) + .await + .unwrap() + { + break; + } + assert!(turn < 199, "ready schema turns must remain bounded"); + } + assert!(vm.has_in_flight_indexed_db_tasks_for_test().unwrap()); + assert_eq!(backend._service.queue_usage().data_tasks, held.len()); + assert_eq!(backend.client.committed().unwrap().version, 1); assert_eq!( vm.eval("JSON.stringify(events)").unwrap(), r#"["returned"]"# diff --git a/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/blob_tests.rs b/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/blob_tests.rs index b415789f869..8b72f559eea 100644 --- a/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/blob_tests.rs +++ b/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/blob_tests.rs @@ -217,7 +217,7 @@ fn bounded_fixture() -> ( ); let mut config = ServiceConfig::default(); config.executor.data.bytes = 48 * 1024; - let backend = SqlBackend::with_config(config); + let backend = SqlBackend::with_config(config, &mut vm); backend.bind(&mut vm); (vm, loader, backend) } @@ -229,9 +229,8 @@ fn seed_large_blob(vm: &mut ScriptVm, backend: &SqlBackend) { fn seed_blobs(vm: &mut ScriptVm, backend: &SqlBackend, bytes: usize, count: usize) { let transaction = backend.client.allocate_transaction_handle().unwrap(); let admission = backend - .client + .connection() .queue_transaction_start( - DatabaseHandle::from_raw(7), &["records".into()], TransactionMode::ReadWrite, std::sync::Arc::new(|| {}), diff --git a/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/cursor_tests.rs b/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/cursor_tests.rs index af2a2e6957b..c050e6aebb5 100644 --- a/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/cursor_tests.rs +++ b/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/cursor_tests.rs @@ -200,7 +200,7 @@ async fn idb_sqlite_cursor_iterates_more_data_than_the_queue_budget_without_snap ); let mut config = ServiceConfig::default(); config.executor.data.bytes = 64 * 1024; - let backend = SqlBackend::with_config(config); + let backend = SqlBackend::with_config(config, &mut vm); backend.bind(&mut vm); for id in 1..=16 { vm.eval(&format!("db.transaction('records','readwrite').objectStore('records').put({{id:{id},group:'g{id}',payload:'x'.repeat(8192)}})")).unwrap(); @@ -268,9 +268,8 @@ async fn idb_sqlite_key_cursor_never_decodes_wire_and_value_cursor_propagates_de let (mut vm, loader, backend) = fixture(); let handle = backend.client.allocate_transaction_handle().unwrap(); let admission = backend - .client + .connection() .queue_transaction_start( - DatabaseHandle::from_raw((1u64 << 53) + 1), &["records".into()], TransactionMode::ReadWrite, std::sync::Arc::new(|| {}), @@ -370,13 +369,14 @@ async fn idb_sqlite_cursor_listener_termination_rolls_back_only_automatic_commit }})()"# )) .unwrap(); + let ready = std::sync::Arc::new(tokio::sync::Notify::new()); + let notify = ready.clone(); let admission = backend - .client + .connection() .queue_transaction_start( - DatabaseHandle::from_raw((1u64 << 53) + 1), &["records".into()], TransactionMode::ReadOnly, - std::sync::Arc::new(|| {}), + std::sync::Arc::new(move || notify.notify_one()), ) .unwrap(); for _ in 0..30 { @@ -389,7 +389,16 @@ async fn idb_sqlite_cursor_listener_termination_rolls_back_only_automatic_commit .await { Ok(true) => {} - Ok(false) => panic!("terminated transaction stranded native admission"), + Ok(false) => { + if !admission.handle().is_ready() { + tokio::time::timeout(Duration::from_secs(2), async { + tokio::select! { + _ = ready.notified() => {}, + arrived = vm.wait_for_task_executor_work_arrival() => assert!(arrived), + } + }).await.expect("native admission or quota completion wakes the fixture"); + } + } Err(error) => { let message = format!("{error:#}").to_lowercase(); assert!( diff --git a/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/derived_budget_tests.rs b/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/derived_budget_tests.rs index 18d1880a810..5f2f2877f2c 100644 --- a/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/derived_budget_tests.rs +++ b/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/derived_budget_tests.rs @@ -12,7 +12,7 @@ fn bounded_fixture() -> ( ); let mut config = ServiceConfig::default(); config.executor.data.bytes = 32 * 1024; - let backend = SqlBackend::with_config(config); + let backend = SqlBackend::with_config(config, &mut vm); backend.bind(&mut vm); (vm, loader, backend) } @@ -115,7 +115,7 @@ async fn idb_sqlite_small_write_shares_schema_larger_than_its_data_capacity() { ); let mut config = ServiceConfig::default(); config.executor.data.bytes = 32 * 1024; - let backend = SqlBackend::with_config(config); + let backend = SqlBackend::with_config(config, &mut vm); let transaction = backend.client.allocate_transaction_handle().unwrap(); backend.execute(Command::Begin { transaction, diff --git a/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/metadata_tests.rs b/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/metadata_tests.rs index 2bd4e468127..4ccc10978bb 100644 --- a/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/metadata_tests.rs +++ b/moli-renderer-v8/src/script_vm/tests/idb_sqlite_lifecycle/metadata_tests.rs @@ -58,7 +58,7 @@ async fn idb_sqlite_metadata_budget_commit_failure_restores_schema_and_records() metadata_bytes: 64 * 1024, ..Default::default() }; - let backend = SqlBackend::with_config(settings); + let backend = SqlBackend::with_config(settings, &mut vm); backend.bind(&mut vm); backend.upgrade(&mut vm); let control = install_metadata_control(&mut vm, &backend, settings.metadata_bytes); @@ -136,23 +136,34 @@ async fn idb_sqlite_mirror_budget_schema_methods_return_then_abort_in_fifo_order ] { let (mut vm, loader, backend) = fixture(); backend.upgrade(&mut vm); + // Exhausting metadata also rejects the quota job's bounded error DTO. + // The schema abort cancels that pending write; its AbortError must be + // delivered before the transaction abort event. let held = backend .client .try_reserve_metadata( ServiceConfig::default().metadata_bytes - backend.client.metadata_bytes(), ) .unwrap(); - assert_eq!(vm.eval(&format!(r#"(() => {{ + assert_eq!( + vm.eval(&format!( + r#"(() => {{ globalThis.events = []; const store = upgrade.objectStore('records'); - store.put({{group:'before'}}).onsuccess = event => events.push('written:' + event.target.result); + const pendingWrite = store.put({{group:'before'}}); + pendingWrite.onsuccess = event => events.push('written:' + event.target.result); + pendingWrite.onerror = event => events.push('write-error:' + event.target.error.name); const result = (() => {{ {operation} }})(); events.push('returned'); upgrade.onabort = () => events.push('abort:' + upgrade.error.name); upgrade.oncomplete = () => events.push('bad-complete'); upgrade.commit(); return result + ',' + String(upgrade.error); - }})()"#)).unwrap(), format!("{expected},null")); + }})()"# + )) + .unwrap(), + format!("{expected},null") + ); if expected != "deleted" { assert_eq!( vm.eval("(() => { try { failed.get(1); } catch(error) { return error.name; } })()") @@ -167,7 +178,7 @@ async fn idb_sqlite_mirror_budget_schema_methods_return_then_abort_in_fifo_order backend.drain(&mut vm, &loader).await; assert_eq!( vm.eval("JSON.stringify(events)").unwrap(), - r#"["returned","written:1","abort:UnknownError"]"# + r#"["returned","write-error:AbortError","abort:UnknownError"]"# ); assert_eq!( vm.eval("[db.version,Array.from(db.objectStoreNames)].join('|')") @@ -180,6 +191,9 @@ async fn idb_sqlite_mirror_budget_schema_methods_return_then_abort_in_fifo_order assert!(metadata.stores["records"].indexes.contains_key("unique")); assert!(backend.client.metadata_bytes() <= ServiceConfig::default().metadata_bytes); drop(held); + vm.eval("globalThis.savedCount = -1; db.transaction('records').objectStore('records').count().onsuccess = event => savedCount = event.target.result").unwrap(); + backend.drain(&mut vm, &loader).await; + assert_eq!(vm.eval("String(savedCount)").unwrap(), "0"); assert_eq!(backend._service.queue_usage().data_tasks, 0); assert_eq!(backend._service.queue_usage().control_tasks, 0); } @@ -243,11 +257,24 @@ async fn idb_sqlite_committed_upgrade_promotes_mirror_with_metadata_capacity_exh break; } assert!(step < 199); - assert!( - vm.run_one_oldest_ready_page_task_executor_turn(&loader) + if !vm + .run_one_oldest_ready_page_task_executor_turn(&loader) + .await + .unwrap() + { + // Quota authorization may still be running outside the SQL worker. + // Only await its wake here: executing the next turn could consume + // the COMMIT receipt before we exhaust the mirror budget below. + assert!(vm.has_in_flight_indexed_db_tasks_for_test().unwrap()); + assert!( + tokio::time::timeout( + Duration::from_secs(2), + vm.wait_for_task_executor_work_arrival(), + ) .await - .unwrap() - ); + .expect("quota/SQL completion wakes the fixture") + ); + } } assert_eq!(backend.client.committed().unwrap().version, 2); assert_eq!(vm.eval("JSON.stringify(events)").unwrap(), "[]"); @@ -298,7 +325,7 @@ async fn idb_sqlite_failed_database_mirror_admission_refunds_partial_nodes_and_c "https://idb-sql-mirror-open-budget.test/", &loader, ); - let backend = SqlBackend::new(); + let backend = SqlBackend::new(&mut vm); let transaction = backend.client.allocate_transaction_handle().unwrap(); backend.execute(Command::Begin { transaction, @@ -329,14 +356,17 @@ async fn idb_sqlite_failed_database_mirror_admission_refunds_partial_nodes_and_c assert!( crate::context_bootstrap::create_sql_database_for_test( scope, - backend.client.clone(), - DatabaseHandle::from_raw(99), + backend + .client + .open_connection(std::sync::Arc::new(|| {})) + .unwrap(), ) .is_none() ); Ok(()) }) .unwrap(); + backend.barrier(); // The small 'records' definition was constructed before 'zzz' exceeded the // allowance. No partial mirror or lifecycle registration can retain it. assert_eq!(backend.client.metadata_bytes(), before);