fix(indexeddb): derive durability options and preserve transaction hints

This commit is contained in:
ldm0
2026-11-03 18:08:20 +08:00
parent 6a802bcc03
commit f7e775c653
12 changed files with 605 additions and 8 deletions
@@ -0,0 +1,167 @@
globalThis.durabilityChecks = [];
async function durabilityProbe(prefix = 'durability') {
const checks = durabilityChecks;
const check = (label, pass, actual = '') => checks.push({label, pass, actual: String(actual)});
const same = (label, actual, expected) => check(label, JSON.stringify(actual) === JSON.stringify(expected), JSON.stringify(actual));
const completed = tx => new Promise((resolve, reject) => {
tx.addEventListener('complete', resolve);
tx.addEventListener('abort', () => reject(tx.error || new Error('unexpected abort')));
});
const requestResult = request => new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
const exercise = async (label, Realm, MethodRealm) => {
const checkHere = (name, pass, actual) => check(label + ': ' + name, pass, actual);
const sameHere = (name, actual, expected) => same(label + ': ' + name, actual, expected);
const method = MethodRealm.IDBDatabase.prototype.transaction;
const descriptor = Object.getOwnPropertyDescriptor(MethodRealm.IDBTransaction.prototype, 'durability');
const get = receiver => typeof descriptor?.get === 'function' ? descriptor.get.call(receiver) : undefined;
const throws = (name, action, prototype = MethodRealm.TypeError.prototype, exceptionName = 'TypeError') => {
let caught, unexpected;
try { unexpected = action(); } catch (error) { caught = error; }
if (unexpected?.abort) { try { unexpected.abort(); } catch {} }
checkHere(name, caught !== undefined && Object.getPrototypeOf(caught) === prototype && caught.name === exceptionName, caught?.name);
};
checkHere('readonly prototype descriptor', typeof descriptor?.get === 'function' && descriptor.set === undefined && descriptor.enumerable && descriptor.configurable);
checkHere('getter metadata', descriptor?.get?.name === 'get durability' && descriptor.get.length === 0);
checkHere('transaction arity', method.length === 1, method.length);
const name = prefix + '-' + label;
const opening = Realm.indexedDB.open(name, 1);
let upgrade;
opening.onupgradeneeded = () => {
upgrade = opening.transaction;
opening.result.createObjectStore('records');
checkHere('upgrade default hint', get(upgrade) === 'default', get(upgrade));
const marker = {};
let caught;
try { method.call(opening.result, 'records', 'readonly', {get durability() { throw marker; }}); } catch (error) { caught = error; }
checkHere('options conversion precedes upgrade validation', caught === marker);
};
const db = await requestResult(opening);
checkHere('completed upgrade retains hint', get(upgrade) === 'default', get(upgrade));
const cases = [
[undefined, 'default'], [null, 'default'], [{}, 'default'], [{durability: undefined}, 'default'],
[{durability: 'default'}, 'default'], [{durability: 'relaxed'}, 'relaxed'], [{durability: 'strict'}, 'strict'],
[Object.create({durability: 'strict'}), 'strict'], [{durability: {toString() { return 'relaxed'; }}}, 'relaxed'],
];
for (let i = 0; i < cases.length; ++i) {
const [options, expected] = cases[i];
const tx = method.call(db, 'records', 'readwrite', options);
checkHere('created transaction realm ' + i, Object.getPrototypeOf(tx) === Realm.IDBTransaction.prototype);
checkHere('hint ' + i, tx.durability === expected, tx.durability);
checkHere('inherited hint ' + i, !Object.hasOwn(tx, 'durability'));
checkHere('readonly hint ' + i, Reflect.set(tx, 'durability', 'invalid') === false);
const done = completed(tx);
tx.objectStore('records').put(i, i);
await done;
checkHere('completed hint ' + i, get(tx) === expected, get(tx));
}
for (const value of [1, true, 'strict', Symbol(), 1n]) {
throws('reject primitive options ' + String(value), () => method.call(db, 'records', 'readwrite', value));
}
for (const value of [null, '', 'STRICT', 'invalid', 1, true, Symbol(), 1n]) {
throws('reject invalid hint ' + String(value), () => method.call(db, 'records', 'readonly', {durability: value}));
}
const order = [];
const tx = method.call(db, {
[Symbol.iterator]() { order.push('stores'); return ['records'][Symbol.iterator](); }
}, {toString() { order.push('mode'); return 'readonly'; }}, new Proxy({}, {
get(_target, key) { order.push(key); return {toString() { order.push('hint'); return 'strict'; }}; }
}));
const convertedDone = completed(tx);
sameHere('conversion order', order, ['stores', 'mode', 'durability', 'hint']);
checkHere('converted hint', get(tx) === 'strict', get(tx));
await convertedDone;
const marker = {};
let reads = 0;
const throwingOptions = {get durability() { ++reads; throw marker; }};
for (const [stores, mode] of [['records', 'readonly'], [[], 'readonly'], ['missing', 'readonly'], ['records', 'versionchange']]) {
let caught;
try { method.call(db, stores, mode, throwingOptions); } catch (error) { caught = error; }
checkHere('options exception precedes semantic validation ' + stores + '/' + mode, caught === marker);
}
checkHere('options read exactly once per conversion', reads === 4, reads);
reads = 0;
throws('invalid mode precedes options', () => method.call(db, 'records', 'invalid', throwingOptions));
checkHere('invalid mode skips options', reads === 0, reads);
const typeMarker = {};
let caught;
try { method.call(db, 'records', 'readonly', {durability: {toString() { throw typeMarker; }}}); } catch (error) { caught = error; }
checkHere('hint conversion exception identity', caught === typeMarker);
const revoked = Proxy.revocable(tx, {}); revoked.revoke();
let traps = 0;
const proxy = new Proxy(tx, {get() { ++traps; }, getPrototypeOf() { ++traps; }});
for (const value of [null, undefined, 1, {}, Realm.IDBTransaction.prototype, Object.create(tx), new Proxy(tx, {}), revoked.proxy, proxy, db]) {
throws('getter receiver', () => get(value));
}
checkHere('getter skips Proxy traps', traps === 0, traps);
for (const value of [{}, Object.create(db), new Proxy(db, {})]) {
reads = 0;
throws('method receiver precedes options', () => method.call(value, 'records', 'readonly', throwingOptions));
checkHere('invalid receiver skips options', reads === 0, reads);
}
Object.setPrototypeOf(tx, null);
checkHere('native identity survives prototype removal', get(tx) === 'strict', get(tx));
Object.setPrototypeOf(tx, Realm.IDBTransaction.prototype);
const first = method.call(db, 'records', 'readwrite', {durability: 'strict'});
const firstDone = completed(first);
first.objectStore('records').put('first', 'queued');
const queued = method.call(db, 'records', 'readwrite', {durability: 'relaxed'});
checkHere('queued hint', get(queued) === 'relaxed', get(queued));
Object.defineProperty(queued, 'durability', {configurable: true, get() { throw new Error('author shadow'); }});
const queuedDone = completed(queued);
queued.objectStore('records').put('second', 'queued');
await Promise.all([firstDone, queuedDone]);
checkHere('author shadow cannot change commit hint', get(queued) === 'relaxed', get(queued));
delete queued.durability;
checkHere('restored completed hint', queued.durability === 'relaxed', queued.durability);
const read = method.call(db, 'records', 'readonly', {durability: 'strict'});
const readDone = completed(read);
const result = read.objectStore('records').get('queued');
await readDone;
checkHere('queued writes commit in order', result.result === 'second', result.result);
checkHere('readonly hint retained', get(read) === 'strict', get(read));
const outer = method.call(db, 'records', 'readwrite', {durability: 'strict'});
const reentered = new Promise((resolve, reject) => {
outer.onabort = () => reject(outer.error);
outer.oncomplete = () => {
try {
const inner = method.call(db, 'records', 'readwrite', {durability: 'relaxed'});
const done = completed(inner);
inner.objectStore('records').put('callback', 'reentry');
done.then(() => resolve(get(inner)), reject);
} catch (error) { reject(error); }
};
});
outer.objectStore('records').put('outer', 'reentry');
checkHere('complete callback can commit another write', await reentered === 'relaxed');
const aborted = method.call(db, 'records', 'readwrite', {durability: 'strict'});
const abortedDone = new Promise(resolve => aborted.onabort = resolve);
aborted.abort(); await abortedDone;
checkHere('abort retains hint', get(aborted) === 'strict', get(aborted));
const failed = method.call(db, 'records', 'readwrite', {durability: 'relaxed'});
const failedDone = new Promise(resolve => failed.onabort = resolve);
failed.objectStore('records').add('duplicate', 'queued'); await failedDone;
checkHere('failed request retains hint', get(failed) === 'relaxed', get(failed));
checkHere('failed request abort reason', failed.error?.name === 'ConstraintError', failed.error?.name);
db.close();
caught = undefined;
try { method.call(db, 'records', 'readonly', throwingOptions); } catch (error) { caught = error; }
checkHere('options conversion precedes closed validation', caught === marker);
throws('valid hint on closed database', () => method.call(db, 'records', 'readonly', {durability: 'strict'}), MethodRealm.DOMException.prototype, 'InvalidStateError');
await requestResult(Realm.indexedDB.deleteDatabase(name));
};
await exercise('local', globalThis, globalThis);
if (typeof document !== 'undefined') {
const frame = document.createElement('iframe');
const loaded = new Promise(resolve => frame.onload = resolve);
frame.srcdoc = '<!doctype html>'; document.documentElement.appendChild(frame); await loaded;
try {
await exercise('foreign-method', globalThis, frame.contentWindow);
await exercise('foreign-receiver', frame.contentWindow, globalThis);
} finally { frame.remove(); }
}
return {state: checks.every(check => check.pass) ? 'pass' : 'fail', checks};
}
@@ -790,3 +790,24 @@ async fn indexed_db_index_names_follow_upgrade_commit_abort_and_utf16_identity()
server.shutdown().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn indexed_db_transaction_durability_preserves_options_realms_and_lifecycle() -> Result<()> {
let server = FixtureServer::spawn().await?;
let browser = Browser::new(AppConfig::default())?;
let fixture = include_str!("fixtures/indexeddb-durability.js");
for target in ["window", "child", "worker"] {
let source = format!(
"{fixture}\ndurabilityProbe('durability-{target}').then(finish, error => finish({{state: 'error', error: String(error), checks: durabilityChecks}}));"
);
let result = run_probe(&browser, &server, target, &source).await?;
assert_eq!(result["state"], "pass", "{target}: {result}");
assert_eq!(
result["checks"].as_array().unwrap().len(),
if target == "worker" { 103 } else { 309 },
"{target}: {result}"
);
}
server.shutdown().await;
Ok(())
}
@@ -92,6 +92,7 @@ pub(crate) use indexed_db::{
indexed_db_has_in_flight_sql_tasks_for_test, indexed_db_has_queued_task_kind_for_test,
indexed_db_metadata_sharing_probe_for_test, indexed_db_native_cursor_count_for_test,
indexed_db_transaction_resources_for_test, serialize_indexed_db_value_for_test,
sql_transaction_durability_for_test,
sql_transaction_handle_for_test, sql_transaction_started_for_test,
};
mod form_navigation;
@@ -5,7 +5,8 @@ use crate::context_bootstrap::indexed_db::{
object_store_info_from_database_metadata,
};
use crate::context_bootstrap::indexed_db::{
indexed_db_database_sql_client, set_indexed_db_transaction_start_request,
IdbTransactionDurability, indexed_db_database_sql_client, resolve_transaction_durability,
set_indexed_db_transaction_durability, set_indexed_db_transaction_start_request,
};
use crate::webidl;
use moli_indexeddb::{DatabaseHandle, IndexedDbError};
@@ -25,6 +26,15 @@ struct IdbDatabaseTransactionArgs {
store_names: names::TransactionStoreNames,
#[webidl(converter = "enum", default = TransactionModeWebIdl::Readonly)]
mode: TransactionModeWebIdl,
#[webidl(index = 2, dictionary)]
options: IdbTransactionOptions,
}
#[derive(Default, webidl::WebIdlDictionary)]
#[webidl(prefix = "IDBTransactionOptions")]
struct IdbTransactionOptions {
#[webidl(converter = "enum", default = IdbTransactionDurability::Default)]
durability: IdbTransactionDurability,
}
pub(in crate::context_bootstrap::indexed_db) fn idb_database_transaction_callback<'s>(
@@ -35,7 +45,8 @@ pub(in crate::context_bootstrap::indexed_db) fn idb_database_transaction_callbac
let Some(parsed) = webidl::parse_args::<IdbDatabaseTransactionArgs>(scope, &args) else {
return;
};
let database = args.this();
let database = moli_webapi_declare::web_api_object_target(scope, args.this())
.expect("database receiver was validated");
let Some(handle) = database_handle_from_value(scope, database.into()) else {
rv.set_undefined();
return;
@@ -103,12 +114,29 @@ pub(in crate::context_bootstrap::indexed_db) fn idb_database_transaction_callbac
return;
}
};
let durability =
match resolve_transaction_durability(scope, database, parsed.options.durability) {
Ok(durability) => durability,
Err(error) => {
let error = request_error_object(scope, &error);
scope.throw_exception(error);
return;
}
};
let Some(context) = database.get_creation_context(scope) else {
return;
};
let result = {
let scope = &mut v8::ContextScope::new(scope, context);
create_regular_transaction(scope, database, handle, &store_names, mode)
create_regular_transaction(
scope,
database,
handle,
&store_names,
mode,
parsed.options.durability,
durability,
)
};
match result {
Ok(Some(transaction)) => rv.set(transaction.into()),
@@ -126,6 +154,8 @@ fn create_regular_transaction<'s>(
handle: DatabaseHandle,
store_names: &[moli_indexeddb::IndexedDbName],
mode: TransactionMode,
durability_hint: IdbTransactionDurability,
durability: moli_indexeddb::TransactionDurability,
) -> Result<Option<v8::Local<'s, v8::Object>>, IndexedDbError> {
// Objects and task queues belong to the connection's realm even when the
// operation was borrowed from another Window. Conversion and exceptions
@@ -150,6 +180,7 @@ fn create_regular_transaction<'s>(
else {
return Ok(None);
};
set_indexed_db_transaction_durability(scope, transaction, durability_hint, durability);
crate::context_bootstrap::indexed_db::typed_state::sql::configure_sql_transaction(
scope,
transaction,
@@ -0,0 +1,174 @@
use super::*;
use crate::context_bootstrap::storage_buckets::with_storage_bucket_store_entry;
use crate::webidl;
use moli_indexeddb::TransactionDurability;
use moli_storage_service::{StorageBucketDurability, StorageBucketStore};
#[derive(Clone, Copy, Default, webidl::WebIdlEnum)]
#[webidl(name = "IDBTransactionDurability")]
pub(super) enum IdbTransactionDurability {
#[default]
Default,
Strict,
Relaxed,
}
impl IdbTransactionDurability {
fn label(self) -> &'static str {
match self {
Self::Default => "default",
Self::Strict => "strict",
Self::Relaxed => "relaxed",
}
}
}
pub(super) fn idb_transaction_durability_getter<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
let receiver = moli_webapi_declare::web_api_object_target(scope, args.this())
.expect("transaction receiver was validated");
let hint = indexed_db_transaction_durability(scope, receiver)
.expect("branded transaction retains its durability hint");
rv.set(v8str(scope, hint.label()).into());
}
pub(super) fn resolve_transaction_durability<'s>(
scope: &mut v8::PinScope<'s, '_>,
database: v8::Local<'s, v8::Object>,
hint: IdbTransactionDurability,
) -> Result<TransactionDurability, IndexedDbError> {
match hint {
IdbTransactionDurability::Strict => Ok(TransactionDurability::Strict),
IdbTransactionDurability::Relaxed => Ok(TransactionDurability::Relaxed),
IdbTransactionDurability::Default => {
let storage_scope = indexed_db_typed_storage_scope(scope, database)
.expect("database has its native storage scope");
// Resolve before native admission, as Chromium's CreateTransaction
// does. A waiting writer must not reread bucket policy at COMMIT.
with_storage_bucket_store_entry(scope, |store| {
bucket_transaction_durability(store, &storage_scope)
})
.unwrap_or_else(|| {
if storage_scope.bucket_identity().is_none() {
Ok(TransactionDurability::Relaxed)
} else {
Err(missing_bucket_policy())
}
})
}
}
}
fn bucket_transaction_durability(
store: &StorageBucketStore,
storage_scope: &IndexedDbStorageScope,
) -> Result<TransactionDurability, IndexedDbError> {
let policy = if let Some(identity) = storage_scope.bucket_identity() {
store
.bucket_durability_for_identity(identity)
.ok_or_else(missing_bucket_policy)?
} else {
// A bucket named "default" is independent of the implicit default.
store
.bucket_durability(
storage_scope.storage_key(),
moli_storage_service::IMPLICIT_DEFAULT_BUCKET_INTERNAL_NAME,
)
.unwrap_or(StorageBucketDurability::Relaxed)
};
Ok(match policy {
StorageBucketDurability::Strict => TransactionDurability::Strict,
StorageBucketDurability::Relaxed => TransactionDurability::Relaxed,
})
}
fn missing_bucket_policy() -> IndexedDbError {
IndexedDbError::InvalidState("StorageBucket durability policy is unavailable".into())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn idb_durability_bucket_defaults_use_exact_bucket_identity() {
let shared = moli_storage_service::new_shared_storage_bucket_store();
let mut store = shared.lock();
let implicit = IndexedDbStorageScope::new("https://durability.test", "context", "profile");
let named = store
.open_bucket_with_options(
implicit.storage_key(),
"default",
None,
Some(StorageBucketDurability::Strict),
None,
None,
)
.unwrap();
let named_scope = implicit.clone().with_bucket_identity(named.clone());
assert_eq!(
bucket_transaction_durability(&store, &implicit).unwrap(),
TransactionDurability::Relaxed
);
assert_eq!(
bucket_transaction_durability(&store, &named_scope).unwrap(),
TransactionDurability::Strict
);
store
.open_bucket_with_options(
implicit.storage_key(),
moli_storage_service::IMPLICIT_DEFAULT_BUCKET_INTERNAL_NAME,
None,
Some(StorageBucketDurability::Strict),
None,
None,
)
.unwrap();
store
.open_bucket_with_options(
implicit.storage_key(),
"default",
None,
Some(StorageBucketDurability::Relaxed),
None,
None,
)
.unwrap();
assert_eq!(
bucket_transaction_durability(&store, &implicit).unwrap(),
TransactionDurability::Strict
);
assert_eq!(
bucket_transaction_durability(&store, &named_scope).unwrap(),
TransactionDurability::Relaxed
);
store
.delete_bucket(implicit.storage_key(), "default")
.unwrap();
// This registry-only fixture has no backend resources to retire.
store.finish_bucket_deletion(&named).unwrap();
let recreated = store
.open_bucket_with_options(
implicit.storage_key(),
"default",
None,
Some(StorageBucketDurability::Strict),
None,
None,
)
.unwrap();
assert_ne!(named, recreated);
assert!(matches!(
bucket_transaction_durability(&store, &named_scope),
Err(IndexedDbError::InvalidState(_))
));
assert_eq!(
bucket_transaction_durability(&store, &implicit.with_bucket_identity(recreated))
.unwrap(),
TransactionDurability::Strict
);
}
}
@@ -1,8 +1,8 @@
use super::*;
use crate::context_bootstrap::indexed_db::{
idb_database_name_getter, idb_database_object_store_names_getter, idb_database_version_getter,
idb_transaction_db_getter, idb_transaction_error_getter, idb_transaction_mode_getter,
idb_transaction_object_store_names_getter,
idb_transaction_db_getter, idb_transaction_durability_getter, idb_transaction_error_getter,
idb_transaction_mode_getter, idb_transaction_object_store_names_getter,
};
use crate::web_api_interfaces;
use moli_webapi_declare::WebApiFunctionTemplate;
@@ -33,6 +33,8 @@ struct IdbTransactionPrototypeDeclaration {
db: (),
#[webapi(accessor_property, getter = idb_transaction_mode_getter, receiver = web_api_interfaces::IDBTransaction::is_instance)]
mode: (),
#[webapi(accessor_property, getter = idb_transaction_durability_getter, receiver = web_api_interfaces::IDBTransaction::is_instance)]
durability: (),
#[webapi(accessor_property, getter = idb_transaction_error_getter, receiver = web_api_interfaces::IDBTransaction::is_instance)]
error: (),
#[webapi(accessor_property, getter = idb_transaction_object_store_names_getter, receiver = web_api_interfaces::IDBTransaction::is_instance)]
@@ -11,6 +11,7 @@ mod backend;
mod core;
mod cursor;
mod database;
mod durability;
mod event_target;
mod install;
mod operation_state;
@@ -106,6 +107,14 @@ pub(crate) fn sql_transaction_handle_for_test(
indexed_db_native_transaction_handle(scope, transaction)
}
#[cfg(test)]
pub(crate) fn sql_transaction_durability_for_test(
scope: &mut v8::PinScope<'_, '_>,
transaction: v8::Local<'_, v8::Object>,
) -> Option<moli_indexeddb::TransactionDurability> {
indexed_db_transaction_sql_durability(scope, transaction)
}
#[cfg(test)]
pub(crate) fn sql_transaction_started_for_test(
scope: &mut v8::PinScope<'_, '_>,
@@ -118,6 +127,7 @@ use self::backend::*;
use self::core::*;
use self::cursor::*;
use self::database::*;
use self::durability::*;
pub(crate) use self::event_target::dispatch_indexed_db_event_callback;
use self::event_target::*;
use self::operation_state::*;
@@ -1,6 +1,6 @@
use super::*;
use crate::context_bootstrap::indexed_db::{
indexed_db_transaction_mode,
indexed_db_transaction_mode, indexed_db_transaction_sql_durability,
typed_state::sql::{
ensure_sql_transaction_rollback, indexed_db_request_sql_client, submit_indexed_db_sql_task,
},
@@ -56,10 +56,12 @@ pub(in crate::context_bootstrap::indexed_db) fn flush_transaction_start_task<'s>
let Some(mode) = indexed_db_transaction_mode(scope, transaction) else {
return;
};
let durability = indexed_db_transaction_sql_durability(scope, transaction)
.expect("transaction has its resolved native durability");
let command = Command::Begin {
transaction: handle,
mode,
durability: moli_indexeddb::TransactionDurability::Relaxed,
durability,
stores: request.store_names().into_iter().collect(),
version: None,
admission: Some(request),
@@ -322,6 +322,8 @@ struct IndexedDbRequestLifecycleState {
struct IndexedDbTransactionLifecycleState {
mode: TransactionMode,
durability: IdbTransactionDurability,
sql_durability: moli_indexeddb::TransactionDurability,
store_names: BTreeSet<IndexedDbName>,
database: Option<RealmValueHandle>,
upgrade_open_request: Option<RealmValueHandle>,
@@ -362,6 +364,12 @@ impl IndexedDbTransactionLifecycleState {
) -> Self {
Self {
mode,
durability: IdbTransactionDurability::Default,
sql_durability: if mode == TransactionMode::VersionChange {
moli_indexeddb::TransactionDurability::Strict
} else {
moli_indexeddb::TransactionDurability::Relaxed
},
store_names: store_names.iter().cloned().collect(),
database: Some(database),
upgrade_open_request: None,
@@ -915,6 +923,50 @@ pub(super) fn indexed_db_transaction_mode<'s>(
table.borrow().transactions.get(&id).map(|state| state.mode)
}
pub(super) fn set_indexed_db_transaction_durability(
scope: &mut v8::PinScope<'_, '_>,
transaction: v8::Local<'_, v8::Object>,
hint: IdbTransactionDurability,
policy: moli_indexeddb::TransactionDurability,
) {
let id =
indexed_db_typed_state_id(scope, transaction).expect("new transaction native identity");
let table = indexed_db_runtime_state_table_for_object(scope, transaction);
let mut table = table.borrow_mut();
let state = table
.transactions
.get_mut(&id)
.expect("new transaction lifecycle");
state.durability = hint;
state.sql_durability = policy;
}
pub(super) fn indexed_db_transaction_durability(
scope: &mut v8::PinScope<'_, '_>,
transaction: v8::Local<'_, v8::Object>,
) -> Option<IdbTransactionDurability> {
let id = indexed_db_typed_state_id(scope, transaction)?;
let table = indexed_db_runtime_state_table_for_object(scope, transaction);
table
.borrow()
.transactions
.get(&id)
.map(|state| state.durability)
}
pub(super) fn indexed_db_transaction_sql_durability(
scope: &mut v8::PinScope<'_, '_>,
transaction: v8::Local<'_, v8::Object>,
) -> Option<moli_indexeddb::TransactionDurability> {
let id = indexed_db_typed_state_id(scope, transaction)?;
let table = indexed_db_runtime_state_table_for_object(scope, transaction);
table
.borrow()
.transactions
.get(&id)
.map(|state| state.sql_durability)
}
pub(super) fn indexed_db_transaction_is_committing<'s>(
scope: &mut v8::PinScope<'s, '_>,
transaction: v8::Local<'s, v8::Object>,
@@ -9,6 +9,7 @@ use std::{cell::RefCell, collections::BTreeSet, sync::mpsc, time::Duration};
mod admission_tests;
mod blob_tests;
mod cursor_tests;
mod durability_tests;
mod fatal_tests;
mod index_tests;
mod metadata_tests;
@@ -0,0 +1,136 @@
use super::*;
use moli_indexeddb::TransactionDurability;
use moli_storage_service::{IMPLICIT_DEFAULT_BUCKET_INTERNAL_NAME, StorageBucketDurability};
fn policy(vm: &mut ScriptVm, name: &'static str) -> TransactionDurability {
let mut found = None;
vm.with_default_context_scope(|scope, _| {
let global = scope.get_current_context().global(scope);
let value = global
.get(scope, crate::util::v8str(scope, name).into())
.unwrap();
let transaction = v8::Local::<v8::Object>::try_from(value).unwrap();
found = crate::context_bootstrap::sql_transaction_durability_for_test(scope, transaction);
Ok(())
})
.unwrap();
found.expect("real transaction has a resolved native policy")
}
#[tokio::test]
async fn idb_sqlite_durability_snapshots_bucket_policy_before_admission_and_preserves_native_receivers()
{
let (mut vm, loader, backend) = fixture();
let storage_key = String::from_utf8(backend.client.identity().owner_key.clone()).unwrap();
backend
.buckets
.lock()
.open_bucket_with_options(
&storage_key,
"default",
None,
Some(StorageBucketDurability::Strict),
None,
None,
)
.unwrap();
vm.with_default_context_scope(|scope, _| {
let global = scope.get_current_context().global(scope);
let function = v8::Function::new(scope, super::rename_tests::registered_proxy).unwrap();
assert_eq!(
global.set(
scope,
crate::util::v8str(scope, "nativeProxy").into(),
function.into()
),
Some(true)
);
Ok(())
})
.unwrap();
vm.eval(r#"
globalThis.events=[];
globalThis.first=db.transaction('records','readwrite');
first.objectStore('records').put({group:'first'});
first.oncomplete=()=>events.push('first:'+first.durability);
globalThis.nativeFirst=nativeProxy(first);
globalThis.nativeDb=nativeProxy(db);
const getter=Object.getOwnPropertyDescriptor(IDBTransaction.prototype,'durability').get;
globalThis.nativeHint=getter.call(nativeFirst);
globalThis.rejected=false;
try {getter.call(new Proxy(nativeFirst,{}));} catch(error) {rejected=error instanceof TypeError;}
'queued'
"#).unwrap();
assert_eq!(policy(&mut vm, "first"), TransactionDurability::Relaxed);
assert_eq!(
vm.eval("[nativeHint,rejected].join(',')").unwrap(),
"default,true"
);
// The first writer has not reached its SQL BEGIN yet. Updating the actual
// implicit bucket now must only affect transactions created afterwards.
backend
.buckets
.lock()
.open_bucket_with_options(
&storage_key,
IMPLICIT_DEFAULT_BUCKET_INTERNAL_NAME,
None,
Some(StorageBucketDurability::Strict),
None,
None,
)
.unwrap();
vm.eval(r#"
globalThis.second=IDBDatabase.prototype.transaction.call(nativeDb,'records','readwrite');
second.objectStore('records').put({group:'second'});
second.oncomplete=()=>events.push('second:'+second.durability);
Object.defineProperty(second,'durability',{configurable:true,get(){throw Error('author shadow');}});
globalThis.relaxed=db.transaction('records','readwrite',{durability:'relaxed'});
relaxed.objectStore('records').put({group:'relaxed'});
relaxed.oncomplete=()=>events.push('relaxed:'+relaxed.durability);
'queued'
"#).unwrap();
assert_eq!(policy(&mut vm, "first"), TransactionDurability::Relaxed);
assert_eq!(policy(&mut vm, "second"), TransactionDurability::Strict);
assert_eq!(policy(&mut vm, "relaxed"), TransactionDurability::Relaxed);
backend
.buckets
.lock()
.open_bucket_with_options(
&storage_key,
IMPLICIT_DEFAULT_BUCKET_INTERNAL_NAME,
None,
Some(StorageBucketDurability::Relaxed),
None,
None,
)
.unwrap();
vm.eval(
r#"
delete second.durability;
globalThis.strict=db.transaction('records','readwrite',{durability:'strict'});
strict.objectStore('records').put({group:'strict'});
strict.oncomplete=()=>events.push('strict:'+strict.durability);
'queued'
"#,
)
.unwrap();
assert_eq!(policy(&mut vm, "second"), TransactionDurability::Strict);
assert_eq!(policy(&mut vm, "strict"), TransactionDurability::Strict);
backend.drain(&mut vm, &loader).await;
assert_eq!(
vm.eval("JSON.stringify(events)").unwrap(),
r#"["first:default","second:default","relaxed:relaxed","strict:strict"]"#
);
for (name, expected) in [
("first", TransactionDurability::Relaxed),
("second", TransactionDurability::Strict),
("relaxed", TransactionDurability::Relaxed),
("strict", TransactionDurability::Strict),
] {
assert_eq!(policy(&mut vm, name), expected);
}
vm.eval("globalThis.count=-1;db.transaction('records').objectStore('records').count().onsuccess=e=>count=e.target.result").unwrap();
backend.drain(&mut vm, &loader).await;
assert_eq!(vm.eval("String(count)").unwrap(), "4");
}
@@ -116,7 +116,7 @@ async fn idb_sqlite_rename_abort_restores_existing_identity_and_keeps_created_na
assert_eq!(vm.eval("String(saved)").unwrap(), "0");
}
fn registered_proxy<'s>(
pub(super) fn registered_proxy<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,