fix(indexeddb): prepare write snapshots before request admission

Queued put/add calls now validate and serialize their values and keys at the API boundary. Only a successfully prepared native snapshot can create a request or enter the deferred queue. Started and queued transactions share one storage executor; failed synchronous calls allocate no request lifecycle state and cannot consume autoIncrement keys.

Serialize with the transaction inactive, propagate the original getter exception, and derive inline keys from the clone's own properties. Validate key injection before admission, generate keys only in storage execution, and remove the compensating discard_unreturned_request path. Unsupported explicit keys report DataError. Regressions exercise started/queued writes, snapshots, generated keys, getter reentrancy and exception identity, native request-state counts, and same-origin child realms; correct the earlier getter-error expectation.

Validation: cargo fmt --all; strict all-feature workspace Clippy;
cargo nextest run --no-fail-fast (20719 tests run: 20719 passed (9 slow), 19 skipped).
This commit is contained in:
ldm0
2026-10-28 22:52:34 +08:00
committed by Donough Liu
parent 70da688622
commit 050c8fadfb
26 changed files with 636 additions and 532 deletions
+1 -1
View File
@@ -342,7 +342,7 @@ pub(crate) use self::indexed_db::{
#[cfg(test)]
pub(crate) use self::indexed_db::{
indexed_db_manager_context_slot_present_for_test,
indexed_db_manager_isolate_slot_present_for_test,
indexed_db_manager_isolate_slot_present_for_test, indexed_db_request_state_entries_for_test,
};
pub(in crate::context_bootstrap) use self::indexed_db::{
indexed_db_usage_bytes_for_storage_key, scoped_storage_bucket_indexed_db_factory,
@@ -1,12 +1,13 @@
use super::{
CursorDirection, CursorSnapshotEntry, DatabaseHandle, DatabaseInfo,
CursorDirection, CursorSnapshotEntry, DatabaseHandle, DatabaseInfo, ExtractedObjectStoreKey,
INDEXED_DB_DATABASE_CLOSED_SLOT, INDEXED_DB_DATABASE_HANDLE_SLOT, INDEXED_DB_DATABASE_KEY_SLOT,
INDEXED_DB_REQUEST_ERROR_SLOT, INDEXED_DB_REQUEST_READY_STATE_SLOT,
INDEXED_DB_REQUEST_RESULT_SLOT, INDEXED_DB_TRANSACTION_HANDLE_SLOT, IdbKeyRangeQuery,
INDEXED_DB_REQUEST_RESULT_SLOT, INDEXED_DB_TRANSACTION_ACTIVE_SLOT,
INDEXED_DB_TRANSACTION_FINISHED_SLOT, INDEXED_DB_TRANSACTION_HANDLE_SLOT, IdbKeyRangeQuery,
IndexEntry, IndexInfo, IndexedDbError, IndexedDbExecutionOwner, IndexedDbExternalObject,
IndexedDbManager, IndexedDbObjectStoreMetadata, IndexedDbRuntimeArray, IndexedDbStorageScope,
IndexedDbValue, IndexedDbWrapperKind, Key, KeyPath, ObjectStoreInfo, PreparedObjectStoreWrite,
PreparedObjectStoreWriteError, TransactionHandle, TransactionMode,
IndexedDbValue, IndexedDbWrapperKind, Key, KeyPath, ObjectStoreInfo, PreparedObjectStoreKey,
PreparedObjectStoreWrite, TransactionHandle, TransactionMode,
context_host_ptr_from_global_bridge, global_constructor_prototype,
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,
@@ -19,7 +20,8 @@ use super::{
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, v8_string, v8str,
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};
@@ -352,14 +352,11 @@ pub(in crate::context_bootstrap::indexed_db) fn serialize_js_value(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> Option<IndexedDbValue> {
let mut should_throw_data_clone_error = false;
let external_objects = Rc::new(RefCell::new(Vec::new()));
let serialized = {
let try_catch = std::pin::pin!(v8::TryCatch::new(scope));
let scope = try_catch.init();
let context = scope.get_current_context();
let serializer = v8::ValueSerializer::new(
&scope,
scope,
Box::new(IndexedDbStructuredCloneSerializer {
external_objects: Rc::clone(&external_objects),
}),
@@ -367,28 +364,57 @@ pub(in crate::context_bootstrap::indexed_db) fn serialize_js_value(
serializer.write_header();
match serializer.write_value(context, value) {
Some(true) => Some(serializer.release()),
_ => {
should_throw_data_clone_error =
scope.has_caught() && scope.can_continue() && !scope.has_terminated();
None
}
_ => None,
}
};
if let Some(wire_bytes) = serialized {
let external_objects = external_objects.borrow().clone();
return Some(IndexedDbValue::new(wire_bytes, external_objects));
}
if should_throw_data_clone_error {
let exception = dom_exception_value(
scope,
"The value could not be cloned for IndexedDB storage.",
"DataCloneError",
);
scope.throw_exception(exception);
}
None
}
/// Serialization invokes getters while the transaction cannot accept requests.
/// Restore its state before propagating the original exception, including throws
/// of null or undefined. An explicit abort during serialization stays finished.
pub(in crate::context_bootstrap::indexed_db) fn serialize_js_value_for_transaction<'s>(
scope: &mut v8::PinScope<'s, '_>,
transaction: v8::Local<'s, v8::Object>,
value: v8::Local<'s, v8::Value>,
) -> Option<IndexedDbValue> {
let inactive = v8::Boolean::new(scope, false).into();
set_indexed_db_slot_value(
scope,
transaction,
INDEXED_DB_TRANSACTION_ACTIVE_SLOT,
inactive,
);
v8::tc_scope!(let scope, scope);
let serialized = serialize_js_value(scope, value);
if scope.can_continue() {
let exception = scope.exception();
scope.reset();
if !object_bool_property(scope, transaction, INDEXED_DB_TRANSACTION_FINISHED_SLOT)
.unwrap_or(false)
{
let active = v8::Boolean::new(scope, true).into();
set_indexed_db_slot_value(
scope,
transaction,
INDEXED_DB_TRANSACTION_ACTIVE_SLOT,
active,
);
}
if let Some(exception) = exception {
scope.throw_exception(exception);
}
}
if scope.has_caught() {
scope.rethrow();
}
serialized
}
pub(in crate::context_bootstrap::indexed_db) fn deserialize_js_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
value: &IndexedDbValue,
@@ -43,23 +43,3 @@ pub(in crate::context_bootstrap::indexed_db) fn key_path_to_js_value<'s>(
KeyPath::Sequence(values) => values.as_slice().to_v8_value(scope),
}
}
pub(in crate::context_bootstrap::indexed_db) fn key_path_from_js_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
value: v8::Local<'s, v8::Value>,
) -> Option<KeyPath> {
if value.is_null_or_undefined() {
return None;
}
if let Ok(array) = v8::Local::<v8::Array>::try_from(value) {
let mut key_path = Vec::with_capacity(array.length() as usize);
for index in 0..array.length() {
let value = array.get_index(scope, index)?;
key_path.push(value.to_string(scope)?.to_rust_string_lossy(scope));
}
return Some(KeyPath::Sequence(key_path));
}
value
.to_string(scope)
.map(|value| KeyPath::String(value.to_rust_string_lossy(scope)))
}
@@ -1,14 +1,13 @@
use super::*;
mod clone;
mod extraction;
mod injection;
mod prepare;
use self::clone::clone_js_value;
use self::injection::inject_key_path_into_value;
use self::injection::can_inject_key_path_into_value;
pub(in crate::context_bootstrap::indexed_db) use self::injection::inject_key_path_into_value;
pub(in crate::context_bootstrap::indexed_db) use self::extraction::{
derive_object_store_key_from_value, extract_index_keys_from_value,
extract_index_keys_from_value, extract_object_store_key_from_value,
};
pub(in crate::context_bootstrap::indexed_db) use self::prepare::prepare_object_store_write;
@@ -1,9 +0,0 @@
use super::*;
pub(super) fn clone_js_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
value: v8::Local<'s, v8::Value>,
) -> Option<v8::Local<'s, v8::Value>> {
let bytes = serialize_js_value(scope, value)?;
deserialize_js_value(scope, &bytes)
}
@@ -78,29 +78,66 @@ fn value_at_string_key_path<'s>(
}
let mut current = value;
for segment in key_path.split('.') {
if current.is_string() && segment == "length" {
let text = v8::Local::<v8::String>::try_from(current).ok()?;
current = v8::Number::new(scope, text.length() as f64).into();
continue;
}
let Ok(object) = v8::Local::<v8::Object>::try_from(current) else {
return None;
};
let next = object.get(
scope,
v8_string(scope, segment)
.unwrap_or_else(|| v8::String::empty(scope))
.into(),
)?;
let property = v8_string(scope, segment).unwrap_or_else(|| v8::String::empty(scope));
// Ordinary key paths only inspect the clone's own data properties.
// The specification also exposes these intrinsic Blob/File attributes.
let host_attribute = matches!(
(
moli_webapi_declare::web_api_object_type(scope, object).map(|kind| kind.name()),
segment
),
(Some("Blob" | "File"), "size" | "type") | (Some("File"), "name" | "lastModified")
);
if !host_attribute && object.has_own_property(scope, property.into()) != Some(true) {
return None;
}
let next = object.get(scope, property.into())?;
if next.is_undefined() {
return None;
}
current = next;
}
Some(current)
}
pub(in crate::context_bootstrap::indexed_db) fn derive_object_store_key_from_value<'s>(
pub(in crate::context_bootstrap::indexed_db) fn extract_object_store_key_from_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
store: v8::Local<'s, v8::Object>,
value: v8::Local<'s, v8::Value>,
) -> Option<Key> {
let key_path = store
.get(scope, v8str(scope, "keyPath").into())
.and_then(|value| key_path_from_js_value(scope, value))?;
extract_index_keys_from_value(scope, value, &key_path, false)
.into_iter()
.next()
key_path: &KeyPath,
) -> ExtractedObjectStoreKey {
if let KeyPath::Sequence(paths) = key_path {
let mut keys = Vec::with_capacity(paths.len());
for path in paths {
match extract_object_store_key_from_value(scope, value, &KeyPath::String(path.clone()))
{
ExtractedObjectStoreKey::Key(key) => keys.push(key),
other => return other,
}
}
let key = Key::Array(keys);
return if key.validate_depth().is_ok() {
ExtractedObjectStoreKey::Key(key)
} else {
ExtractedObjectStoreKey::Invalid
};
}
let KeyPath::String(path) = key_path else {
return ExtractedObjectStoreKey::Missing;
};
let Some(value) = value_at_string_key_path(scope, value, path) else {
return ExtractedObjectStoreKey::Missing;
};
match parse_idb_key(scope, value) {
Ok(Some(key)) => ExtractedObjectStoreKey::Key(key),
Ok(None) => ExtractedObjectStoreKey::Missing,
Err(_) => ExtractedObjectStoreKey::Invalid,
}
}
@@ -1,76 +1,60 @@
use super::*;
use moli_webapi_declare::ObjectLiteralDeclaration;
pub(super) fn inject_key_path_into_value<'s>(
pub(super) fn can_inject_key_path_into_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
mut value: v8::Local<'s, v8::Value>,
key_path: &str,
) -> bool {
let mut segments = key_path.split('.').peekable();
while let Some(segment) = segments.next() {
let Ok(object) = v8::Local::<v8::Object>::try_from(value) else {
return false;
};
if segments.peek().is_none() {
return true;
}
let property = v8_string(scope, segment).unwrap_or_else(|| v8::String::empty(scope));
match object.has_own_property(scope, property.into()) {
Some(false) => return true,
Some(true) => {
let Some(next) = object.get(scope, property.into()) else {
return false;
};
value = next;
}
None => return false,
}
}
false
}
/// The caller already cloned the value and checked injection before admission.
/// Use data properties so prototype setters never run during storage execution.
pub(in crate::context_bootstrap::indexed_db) fn inject_key_path_into_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
value: v8::Local<'s, v8::Value>,
key_path: &str,
key: &Key,
) -> Result<v8::Local<'s, v8::Value>, PreparedObjectStoreWriteError> {
let cloned =
clone_js_value(scope, value).ok_or(PreparedObjectStoreWriteError::DomException {
message: "Failed to clone the value before assigning the generated key.",
name: "DataCloneError",
})?;
let mut current = v8::Local::<v8::Object>::try_from(cloned).map_err(|_| {
PreparedObjectStoreWriteError::DomException {
message: "Failed to execute the operation: the value cannot accept an inline key.",
name: "DataError",
}
})?;
) -> Option<()> {
let mut current = v8::Local::<v8::Object>::try_from(value).ok()?;
let mut segments = key_path.split('.').peekable();
while let Some(segment) = segments.next() {
let property = v8_string(scope, segment).unwrap_or_else(|| v8::String::empty(scope));
if segments.peek().is_none() {
let key_value = key_to_js_value(scope, key);
let _ = current.set(scope, property.into(), key_value);
return Ok(cloned);
let key = key_to_js_value(scope, key);
return (current.create_data_property(scope, property.into(), key) == Some(true))
.then_some(());
}
let next = current.get(scope, property.into());
let next_object = match next {
Some(next) if next.is_undefined() => {
let nested = generated_key_path_suffix_object(scope, &mut segments, key);
let _ = current.set(scope, property.into(), nested.into());
return Ok(cloned);
if current.has_own_property(scope, property.into())? {
current =
v8::Local::<v8::Object>::try_from(current.get(scope, property.into())?).ok()?;
} else {
let nested = v8::Object::new(scope);
if current.create_data_property(scope, property.into(), nested.into()) != Some(true) {
return None;
}
Some(next) => v8::Local::<v8::Object>::try_from(next).map_err(|_| {
PreparedObjectStoreWriteError::DomException {
message:
"Failed to execute the operation: the value cannot accept an inline key.",
name: "DataError",
}
})?,
None => {
return Err(PreparedObjectStoreWriteError::DomException {
message:
"Failed to execute the operation: the value cannot accept an inline key.",
name: "DataError",
});
}
};
current = next_object;
current = nested;
}
}
Err(PreparedObjectStoreWriteError::DomException {
message: "Failed to execute the operation: keyPath is empty.",
name: "DataError",
})
}
fn generated_key_path_suffix_object<'s>(
scope: &mut v8::PinScope<'s, '_>,
segments: &mut std::iter::Peekable<std::str::Split<'_, char>>,
key: &Key,
) -> v8::Local<'s, v8::Object> {
let segment = segments
.next()
.expect("generated key path suffix should include a segment");
let property = v8_string(scope, segment).unwrap_or_else(|| v8::String::empty(scope));
let value = if segments.peek().is_none() {
key_to_js_value(scope, key)
} else {
generated_key_path_suffix_object(scope, segments, key).into()
};
let object = ObjectLiteralDeclaration::bind(scope);
object.set_value_property(scope, property.into(), value);
object.into_object()
None
}
@@ -3,70 +3,74 @@ use super::*;
pub(in crate::context_bootstrap::indexed_db) fn prepare_object_store_write<'s>(
scope: &mut v8::PinScope<'s, '_>,
store: v8::Local<'s, v8::Object>,
handle: TransactionHandle,
store_name: &str,
transaction: v8::Local<'s, v8::Object>,
value: v8::Local<'s, v8::Value>,
explicit_key: Option<Key>,
) -> Result<PreparedObjectStoreWrite<'s>, PreparedObjectStoreWriteError> {
let key_path = store
.get(scope, v8str(scope, "keyPath").into())
.and_then(|value| key_path_from_js_value(scope, value));
let auto_increment = object_bool_property(scope, store, "autoIncrement").unwrap_or(false);
if key_path.is_some() && explicit_key.is_some() {
return Err(PreparedObjectStoreWriteError::DomException {
message: "Failed to execute the operation: the store uses in-line keys and does not accept a key argument.",
name: "DataError",
});
}
match key_path {
) -> Option<PreparedObjectStoreWrite> {
let metadata = indexed_db_object_store_metadata(scope, store)?;
let info = metadata.info();
let serialized = serialize_js_value_for_transaction(scope, transaction, value)?;
let key = match &info.key_path {
Some(key_path) => {
if let Some(key) = derive_object_store_key_from_value(scope, store, value) {
return Ok(PreparedObjectStoreWrite {
key: Some(key),
value,
});
if explicit_key.is_some() {
return invalid_write(
scope,
"The store uses in-line keys and does not accept a key argument.",
);
}
if !auto_increment {
return Err(PreparedObjectStoreWriteError::DomException {
message: "Failed to execute the operation: the value does not contain the object store keyPath.",
name: "DataError",
});
let clone = deserialize_js_value(scope, &serialized)?;
match extract_object_store_key_from_value(scope, clone, key_path) {
ExtractedObjectStoreKey::Key(key) => PreparedObjectStoreKey::Explicit(key),
ExtractedObjectStoreKey::Invalid => {
return invalid_write(
scope,
"The value at the object store keyPath is not a valid key.",
);
}
ExtractedObjectStoreKey::Missing => {
if !info.auto_increment {
return invalid_write(
scope,
"The value does not contain the object store keyPath.",
);
}
let KeyPath::String(key_path) = key_path else {
return invalid_write(
scope,
"A compound keyPath cannot accept generated keys.",
);
};
if !can_inject_key_path_into_value(scope, clone, key_path) {
return invalid_write(
scope,
"The value cannot accept a generated inline key.",
);
}
PreparedObjectStoreKey::GenerateInline {
key_path: key_path.clone(),
}
}
}
let generated_key =
with_indexed_db_manager(scope, |manager| manager.generate_key(handle, store_name))
.map_err(PreparedObjectStoreWriteError::Backend)?;
let KeyPath::String(key_path) = key_path else {
return Err(PreparedObjectStoreWriteError::DomException {
message: "Failed to execute the operation: compound keyPath stores cannot accept generated inline keys.",
name: "InvalidAccessError",
});
};
let value = inject_key_path_into_value(scope, value, &key_path, &generated_key)?;
Ok(PreparedObjectStoreWrite {
key: Some(generated_key),
value,
})
}
None => {
if explicit_key.is_none() && !auto_increment {
return Err(PreparedObjectStoreWriteError::DomException {
message: "Failed to execute the operation: a key is required for stores without autoIncrement.",
name: "DataError",
});
None => match explicit_key {
Some(key) => PreparedObjectStoreKey::Explicit(key),
None if info.auto_increment => PreparedObjectStoreKey::Generate,
None => {
return invalid_write(scope, "A key is required for stores without autoIncrement.");
}
let key = if let Some(key) = explicit_key {
Some(key)
} else if auto_increment {
Some(
with_indexed_db_manager(scope, |manager| {
manager.generate_key(handle, store_name)
})
.map_err(PreparedObjectStoreWriteError::Backend)?,
)
} else {
None
};
Ok(PreparedObjectStoreWrite { key, value })
}
}
},
};
Some(PreparedObjectStoreWrite {
key,
value: serialized,
})
}
fn invalid_write(
scope: &mut v8::PinScope<'_, '_>,
message: &str,
) -> Option<PreparedObjectStoreWrite> {
let error = dom_exception_value(scope, message, "DataError");
scope.throw_exception(error);
None
}
@@ -56,6 +56,8 @@ pub(crate) use self::tasks::{
};
pub(crate) use self::typed_state::IndexedDbTaskId;
pub(crate) use self::typed_state::deactivate_indexed_db_transaction_after_microtask_checkpoint;
#[cfg(test)]
pub(crate) use self::typed_state::indexed_db_request_state_entries_for_test;
pub(crate) use self::typed_state::retain_indexed_db_state_in_retired_realm;
pub(in crate::context_bootstrap::indexed_db) use self::typed_state::schedule_indexed_db_transaction_deactivation_after_microtask_checkpoint;
@@ -1,5 +1,5 @@
use super::stores::collection::CollectionRequest;
use super::{CursorDirection, IdbKeyRangeQuery, IndexInfo};
use super::{CursorDirection, IdbKeyRangeQuery, IndexInfo, PreparedObjectStoreWrite};
use crate::native_bridge::OwnerDispatchScope;
pub(super) enum IndexedDbCursorSource {
@@ -56,8 +56,7 @@ pub(super) enum IndexedDbTransactionOperation {
},
OpenCursor(IndexedDbCursorOpenOperation),
ObjectStoreWrite {
value: v8::Global<v8::Value>,
key: v8::Global<v8::Value>,
prepared: PreparedObjectStoreWrite,
add_only: bool,
},
ObjectStoreDelete {
@@ -77,7 +76,7 @@ pub(super) enum IndexedDbTransactionOperation {
}
// Query arguments are converted at the API boundary and retained as native snapshots.
// Write requests retain their existing deferred value/key conversion behavior.
// Write values and keys are also prepared synchronously, before request admission.
pub(super) struct IndexedDbPendingTransactionOperation {
owner: OwnerDispatchScope,
source: v8::Global<v8::Object>,
@@ -2,20 +2,20 @@ use super::{
CursorDirection, CursorSnapshotEntry, INDEXED_DB_TRANSACTION_ACTIVE_SLOT,
INDEXED_DB_TRANSACTION_STARTED_SLOT, IdbKeyRangeQuery, IndexInfo, IndexOptions,
IndexedDbCursorOpenOperation, IndexedDbError, IndexedDbTransactionOperation, KeyPath,
PreparedObjectStoreWriteError, TransactionHandle, apply_cursor_direction, compare_idb_keys,
create_index_object, create_key_range_object, create_request_object, deserialize_js_value,
discard_unreturned_request, dom_exception_value, enforce_object_store_unique_constraints,
TransactionHandle, apply_cursor_direction, compare_idb_keys, create_index_object,
create_key_range_object, create_request_object, deserialize_js_value, dom_exception_value,
enqueue_transaction_operation, execute_object_store_clear_request,
execute_object_store_delete_request, index_info_from_store_metadata, indexed_db_index_info,
indexed_db_index_object_store, indexed_db_object_store_database, indexed_db_object_store_name,
execute_object_store_delete_request, execute_object_store_write_request,
index_info_from_store_metadata, indexed_db_index_info, indexed_db_index_object_store,
indexed_db_object_store_database, indexed_db_object_store_name,
indexed_db_object_store_transaction, key_in_range, key_to_js_value, object_bool_property,
object_string_property, parse_cursor_direction, parse_cursor_direction_with_context,
parse_idb_key, parse_idb_key_path, parse_key_or_range, parse_key_range_from_value,
parse_optional_count, prepare_object_store_write, queue_transaction_request,
remove_database_index_metadata, request_error_object, scan_index_entries,
scan_object_store_entries, serialize_js_value, set_database_index_metadata,
storage_bucket_quota_check_for_object_store, store_request_error, store_request_success,
submit_cursor_open_operation, transaction_handle_from_value, with_indexed_db_manager,
scan_object_store_entries, set_database_index_metadata, store_request_error,
store_request_success, submit_cursor_open_operation, transaction_handle_from_value,
with_indexed_db_manager,
};
use crate::webidl;
@@ -2,9 +2,6 @@ use super::*;
use crate::context_bootstrap::indexed_db::indexed_db_transaction_mode;
use moli_indexeddb::TransactionMode;
mod enqueue;
mod execute;
pub(super) fn object_store_write_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
@@ -14,68 +11,82 @@ pub(super) fn object_store_write_callback<'s>(
add_only: bool,
) {
let store = args.this();
let Some((request, transaction)) = create_store_request(scope, store) else {
let Some(transaction) = object_store_active_transaction(scope, store) else {
return;
};
if indexed_db_transaction_mode(scope, transaction) == Some(TransactionMode::ReadOnly) {
discard_unreturned_request(scope, request);
let error = dom_exception_value(scope, "The transaction is readonly.", "ReadOnlyError");
scope.throw_exception(error);
return;
}
let Some(store_name) = indexed_db_object_store_name(scope, store) else {
rv.set(request.into());
return;
let explicit_key = {
v8::tc_scope!(let scope, scope);
match parse_idb_key(scope, key) {
Ok(key) => key,
Err(error) => {
error.throw(scope);
scope.rethrow();
return;
}
}
};
if !object_bool_property(scope, transaction, INDEXED_DB_TRANSACTION_STARTED_SLOT)
// Key conversion can invoke getters too, including one that aborts the transaction.
if !object_bool_property(scope, transaction, INDEXED_DB_TRANSACTION_ACTIVE_SLOT)
.unwrap_or(false)
{
enqueue::enqueue_deferred_object_store_write(
throw_inactive(scope);
return;
}
let Some(prepared) = prepare_object_store_write(scope, store, transaction, value, explicit_key)
else {
return;
};
let Some(store_name) = indexed_db_object_store_name(scope, store) else {
return;
};
let handle = if object_bool_property(scope, transaction, INDEXED_DB_TRANSACTION_STARTED_SLOT)
.unwrap_or(false)
{
let Some(handle) = transaction_handle_from_value(scope, transaction.into()) else {
throw_inactive(scope);
return;
};
Some(handle)
} else {
None
};
let Some((request, _)) = create_store_request(scope, store) else {
throw_inactive(scope);
return;
};
if let Some(handle) = handle {
execute_object_store_write_request(
scope,
store,
request,
handle,
&store_name,
&prepared,
add_only,
);
} else {
enqueue_transaction_operation(
scope,
transaction,
store,
request,
&store_name,
value,
key,
add_only,
IndexedDbTransactionOperation::ObjectStoreWrite { prepared, add_only },
);
rv.set(request.into());
return;
}
let Some(handle) = transaction_handle_from_value(scope, transaction.into()) else {
discard_unreturned_request(scope, request);
let error = dom_exception_value(
scope,
"The transaction is not active.",
"TransactionInactiveError",
);
scope.throw_exception(error);
return;
};
v8::tc_scope!(let scope, scope);
if execute::execute_started_object_store_write(
scope,
store,
request,
handle,
&store_name,
value,
key,
add_only,
) {
rv.set(request.into());
} else if scope.can_continue() {
// Preserve the original exception while removing the request which
// create_store_request admitted before synchronous validation.
let exception = scope.exception();
scope.reset();
discard_unreturned_request(scope, request);
if let Some(exception) = exception {
scope.throw_exception(exception);
}
}
if scope.has_caught() {
scope.rethrow();
}
rv.set(request.into());
}
fn throw_inactive(scope: &mut v8::PinScope<'_, '_>) {
let error = dom_exception_value(
scope,
"The transaction is not active.",
"TransactionInactiveError",
);
scope.throw_exception(error);
}
@@ -1,27 +0,0 @@
use super::*;
pub(super) fn enqueue_deferred_object_store_write<'s>(
scope: &mut v8::PinScope<'s, '_>,
transaction: v8::Local<'s, v8::Object>,
store: v8::Local<'s, v8::Object>,
request: v8::Local<'s, v8::Object>,
store_name: &str,
value: v8::Local<'s, v8::Value>,
key: v8::Local<'s, v8::Value>,
add_only: bool,
) {
let value = v8::Global::new(scope, value);
let key = v8::Global::new(scope, key);
enqueue_transaction_operation(
scope,
transaction,
store,
request,
store_name,
IndexedDbTransactionOperation::ObjectStoreWrite {
value,
key,
add_only,
},
);
}
@@ -1,107 +0,0 @@
use super::*;
pub(super) fn execute_started_object_store_write<'s>(
scope: &mut v8::PinScope<'s, '_>,
store: v8::Local<'s, v8::Object>,
request: v8::Local<'s, v8::Object>,
handle: TransactionHandle,
store_name: &str,
value: v8::Local<'s, v8::Value>,
key_value: v8::Local<'s, v8::Value>,
add_only: bool,
) -> bool {
let explicit_key = match parse_idb_key(scope, key_value) {
Ok(key) => key,
Err(error) => {
error.throw(scope);
return false;
}
};
let prepared =
match prepare_object_store_write(scope, store, handle, store_name, value, explicit_key) {
Ok(prepared) => prepared,
Err(PreparedObjectStoreWriteError::DomException { message, name }) => {
let error = dom_exception_value(scope, message, name);
scope.throw_exception(error);
return false;
}
Err(PreparedObjectStoreWriteError::Backend(error)) => {
let error = request_error_object(scope, &error);
store_request_error(scope, request, error);
return true;
}
};
let Some(value_bytes) = serialize_js_value(scope, prepared.value) else {
return false;
};
let Some(primary_key) = prepared.key.clone() else {
let error = dom_exception_value(
scope,
"Failed to execute the operation: a key is required for stores without autoIncrement.",
"DataError",
);
scope.throw_exception(error);
return false;
};
if let Err(error) = enforce_object_store_unique_constraints(
scope,
store,
handle,
store_name,
&primary_key,
prepared.value,
) {
let error = request_error_object(scope, &error);
store_request_error(scope, request, error);
return true;
}
let quota_check = match storage_bucket_quota_check_for_object_store(scope, store) {
Some(Ok(quota)) => Some(quota),
Some(Err(error)) => {
let error = request_error_object(scope, &error);
store_request_error(scope, request, error);
return true;
}
None => None,
};
let result = if add_only {
with_indexed_db_manager(scope, |manager| {
if let Some(quota) = quota_check {
manager.add_with_quota(
handle,
store_name,
prepared.key.clone(),
value_bytes,
quota.quota_check,
)
} else {
manager.add(handle, store_name, prepared.key.clone(), value_bytes)
}
})
} else {
with_indexed_db_manager(scope, |manager| {
if let Some(quota) = quota_check {
manager.put_with_quota(
handle,
store_name,
prepared.key.clone(),
value_bytes,
quota.quota_check,
)
} else {
manager.put(handle, store_name, prepared.key.clone(), value_bytes)
}
})
};
match result {
Ok(key) => {
let key_value = key_to_js_value(scope, &key);
store_request_success(scope, request, key_value);
}
Err(error) => {
let error = request_error_object(scope, &error);
store_request_error(scope, request, error);
}
}
true
}
@@ -11,32 +11,32 @@ use super::{
INDEXED_DB_TRANSACTION_START_SCHEDULED_SLOT, INDEXED_DB_TRANSACTION_STARTED_SLOT,
IdbKeyRangeQuery, IndexInfo, IndexedDbCursorOpenOperation, IndexedDbCursorSource,
IndexedDbError, IndexedDbPendingTransactionOperation, IndexedDbRuntimeArray,
IndexedDbStorageScope, IndexedDbTransactionOperation, OpenOptions,
PreparedObjectStoreWriteError, TransactionHandle, TransactionMode,
apply_index_collection_direction, apply_object_store_collection_direction,
close_indexed_db_database_connection, create_database_object, create_transaction_object,
database_registry_key, define_non_enumerable_value_property, deserialize_js_value,
dispatch_idb_named_event, dispatch_version_change_event, dom_exception_value,
enforce_object_store_unique_constraints, enqueue_version_change_to_open_connections,
flush_databases_settle_task, has_open_database_connections_for_key, index_cursor_snapshot,
indexed_db_blocked_task_payload, indexed_db_index_info, indexed_db_object_task_target,
indexed_db_open_task_payload, indexed_db_request_dispatch_task_request,
indexed_db_request_transaction_object, indexed_db_runtime_array,
indexed_db_runtime_array_contains_object, indexed_db_typed_execution_owner,
indexed_db_typed_owner_scope, indexed_db_typed_task_execution_context,
indexed_db_typed_task_execution_owner, indexed_db_typed_task_id, indexed_db_typed_task_kind,
indexed_db_typed_task_owner_scope, indexed_db_typed_task_storage_scope, key_in_range,
key_to_js_value, materialize_cursor_result_in_request_realm, object_bool_property,
object_hidden_value, object_number_property, object_store_cursor_snapshot,
object_string_property, parse_idb_key, pop_first_indexed_db_task, prepare_object_store_write,
push_indexed_db_operation_waiting_for_start, push_object_to_indexed_db_runtime_array,
push_unique_object_to_indexed_db_runtime_array, refresh_cursor_surface,
refresh_database_surface, register_blocked_database_context, replace_indexed_db_runtime_array,
request_error_object, scan_index_entries, scan_object_store_entries, serialize_js_value,
set_indexed_db_request_surface_value, set_indexed_db_slot_value,
signal_worker_indexed_db_task_wake, storage_bucket_quota_check_for_object_store,
storage_bucket_quota_check_for_transaction, take_indexed_db_operations_waiting_for_start,
take_indexed_db_task_by_id, transaction_handle_from_value, unregister_blocked_database_context,
IndexedDbStorageScope, IndexedDbTransactionOperation, Key, OpenOptions, PreparedObjectStoreKey,
PreparedObjectStoreWrite, TransactionHandle, TransactionMode, apply_index_collection_direction,
apply_object_store_collection_direction, close_indexed_db_database_connection,
create_database_object, create_transaction_object, database_registry_key,
define_non_enumerable_value_property, deserialize_js_value, dispatch_idb_named_event,
dispatch_version_change_event, dom_exception_value, enforce_object_store_unique_constraints,
enqueue_version_change_to_open_connections, flush_databases_settle_task,
has_open_database_connections_for_key, index_cursor_snapshot, indexed_db_blocked_task_payload,
indexed_db_index_info, indexed_db_object_task_target, indexed_db_open_task_payload,
indexed_db_request_dispatch_task_request, indexed_db_request_transaction_object,
indexed_db_runtime_array, indexed_db_runtime_array_contains_object,
indexed_db_typed_execution_owner, indexed_db_typed_owner_scope,
indexed_db_typed_task_execution_context, indexed_db_typed_task_execution_owner,
indexed_db_typed_task_id, indexed_db_typed_task_kind, indexed_db_typed_task_owner_scope,
indexed_db_typed_task_storage_scope, inject_key_path_into_value, key_in_range, key_to_js_value,
materialize_cursor_result_in_request_realm, object_bool_property, object_hidden_value,
object_number_property, object_store_cursor_snapshot, object_string_property,
pop_first_indexed_db_task, push_indexed_db_operation_waiting_for_start,
push_object_to_indexed_db_runtime_array, push_unique_object_to_indexed_db_runtime_array,
refresh_cursor_surface, refresh_database_surface, register_blocked_database_context,
replace_indexed_db_runtime_array, request_error_object, scan_index_entries,
scan_object_store_entries, serialize_js_value, set_indexed_db_request_surface_value,
set_indexed_db_slot_value, signal_worker_indexed_db_task_wake,
storage_bucket_quota_check_for_object_store, storage_bucket_quota_check_for_transaction,
take_indexed_db_operations_waiting_for_start, take_indexed_db_task_by_id,
transaction_handle_from_value, unregister_blocked_database_context,
unregister_regular_transaction, v8str, validate_storage_bucket_scope, with_indexed_db_manager,
};
use crate::util::enqueue_host_microtask;
@@ -6,5 +6,4 @@ mod finish;
mod success;
pub(in crate::context_bootstrap::indexed_db) use self::error::flush_request_error_task;
pub(in crate::context_bootstrap::indexed_db) use self::finish::discard_unreturned_request;
pub(in crate::context_bootstrap::indexed_db) use self::success::flush_request_success_task;
@@ -12,16 +12,6 @@ fn release_request_dispatch_refs<'s>(
release_indexed_db_request_dispatch_refs(scope, request);
}
/// A synchronous rejection never returns or dispatches this request.
/// Release its admission count and native roots without creating an event.
pub(in crate::context_bootstrap::indexed_db) fn discard_unreturned_request<'s>(
scope: &mut v8::PinScope<'s, '_>,
request: v8::Local<'s, v8::Object>,
) {
request_finished(scope, request);
release_indexed_db_request_dispatch_refs(scope, request);
}
pub(super) fn finish_request_dispatch<'s>(
scope: &mut v8::PinScope<'s, '_>,
request: v8::Local<'s, v8::Object>,
@@ -5,21 +5,14 @@ pub(super) fn try_dispatch_object_store_write_operation<'s>(
operation: &operation::QueuedTransactionOperation<'s>,
) -> bool {
match &operation.kind {
IndexedDbTransactionOperation::ObjectStoreWrite {
value,
key,
add_only,
} => {
let value = v8::Local::new(scope, value);
let key = v8::Local::new(scope, key);
IndexedDbTransactionOperation::ObjectStoreWrite { prepared, add_only } => {
execute_object_store_write_request(
scope,
operation.source,
operation.request,
operation.handle,
&operation.store_name,
value,
key,
prepared,
*add_only,
);
}
@@ -6,102 +6,81 @@ pub(in crate::context_bootstrap::indexed_db) fn execute_object_store_write_reque
request: v8::Local<'s, v8::Object>,
handle: TransactionHandle,
store_name: &str,
value: v8::Local<'s, v8::Value>,
key_value: v8::Local<'s, v8::Value>,
prepared: &PreparedObjectStoreWrite,
add_only: bool,
) {
let explicit_key = match parse_idb_key(scope, key_value) {
Ok(key) => key,
Err(error) => {
let error = error.into_value(scope);
) -> bool {
v8::tc_scope!(let scope, scope);
let result = execute_prepared_write(scope, store, handle, store_name, prepared, add_only);
if scope.has_caught() {
if scope.can_continue()
&& let Some(error) = scope.exception()
{
scope.reset();
store_request_error(scope, request, error);
return;
}
};
let prepared =
match prepare_object_store_write(scope, store, handle, store_name, value, explicit_key) {
Ok(prepared) => prepared,
Err(PreparedObjectStoreWriteError::DomException { message, name }) => {
let error = dom_exception_value(scope, message, name);
store_request_error(scope, request, error);
return;
}
Err(PreparedObjectStoreWriteError::Backend(error)) => {
let error = request_error_object(scope, &error);
store_request_error(scope, request, error);
return;
}
};
let Some(value_bytes) = serialize_js_value(scope, prepared.value) else {
return;
};
let Some(primary_key) = prepared.key.clone() else {
let error = dom_exception_value(
scope,
"Failed to execute the operation: a key is required for stores without autoIncrement.",
"DataError",
);
store_request_error(scope, request, error);
return;
};
if let Err(error) = enforce_object_store_unique_constraints(
scope,
store,
handle,
store_name,
&primary_key,
prepared.value,
) {
let error = request_error_object(scope, &error);
store_request_error(scope, request, error);
return;
return false;
}
let quota_check = match storage_bucket_quota_check_for_object_store(scope, store) {
Some(Ok(quota)) => Some(quota),
Some(Err(error)) => {
let error = request_error_object(scope, &error);
store_request_error(scope, request, error);
return;
}
None => None,
};
let result = if add_only {
with_indexed_db_manager(scope, |manager| {
if let Some(quota) = quota_check {
manager.add_with_quota(
handle,
store_name,
prepared.key.clone(),
value_bytes,
quota.quota_check,
)
} else {
manager.add(handle, store_name, prepared.key.clone(), value_bytes)
}
})
} else {
with_indexed_db_manager(scope, |manager| {
if let Some(quota) = quota_check {
manager.put_with_quota(
handle,
store_name,
prepared.key.clone(),
value_bytes,
quota.quota_check,
)
} else {
manager.put(handle, store_name, prepared.key.clone(), value_bytes)
}
})
};
match result {
Ok(key) => {
let js_key = key_to_js_value(scope, &key);
store_request_success(scope, request, js_key);
let key = key_to_js_value(scope, &key);
store_request_success(scope, request, key);
true
}
Err(error) => {
let error = request_error_object(scope, &error);
store_request_error(scope, request, error);
false
}
}
}
fn execute_prepared_write<'s>(
scope: &mut v8::PinScope<'s, '_>,
store: v8::Local<'s, v8::Object>,
handle: TransactionHandle,
store_name: &str,
prepared: &PreparedObjectStoreWrite,
add_only: bool,
) -> Result<Key, IndexedDbError> {
let value = deserialize_js_value(scope, &prepared.value).ok_or_else(|| {
IndexedDbError::Serialization("Failed to read a prepared IndexedDB value.".into())
})?;
// Only storage execution can consume the generator; synchronous rejection
// and waiting for another transaction cannot change its state.
let key = match &prepared.key {
PreparedObjectStoreKey::Explicit(key) => key.clone(),
PreparedObjectStoreKey::Generate | PreparedObjectStoreKey::GenerateInline { .. } => {
with_indexed_db_manager(scope, |manager| manager.generate_key(handle, store_name))?
}
};
let value_bytes = if let PreparedObjectStoreKey::GenerateInline { key_path } = &prepared.key {
inject_key_path_into_value(scope, value, key_path, &key).ok_or_else(|| {
IndexedDbError::Serialization("Failed to inject a prepared inline key.".into())
})?;
serialize_js_value(scope, value).ok_or_else(|| {
IndexedDbError::Serialization("Failed to store a prepared IndexedDB value.".into())
})?
} else {
prepared.value.clone()
};
enforce_object_store_unique_constraints(scope, store, handle, store_name, &key, value)?;
let quota = storage_bucket_quota_check_for_object_store(scope, store).transpose()?;
with_indexed_db_manager(scope, |manager| match (add_only, quota) {
(true, Some(quota)) => manager.add_with_quota(
handle,
store_name,
Some(key),
value_bytes,
quota.quota_check,
),
(false, Some(quota)) => manager.put_with_quota(
handle,
store_name,
Some(key),
value_bytes,
quota.quota_check,
),
(true, None) => manager.add(handle, store_name, Some(key), value_bytes),
(false, None) => manager.put(handle, store_name, Some(key), value_bytes),
})
}
@@ -767,6 +767,21 @@ pub(super) fn release_indexed_db_request_dispatch_refs<'s>(
clear_pending_request_values(scope, request);
}
#[cfg(test)]
pub(crate) fn indexed_db_request_state_entries_for_test(
scope: &mut v8::PinScope<'_, '_>,
source: v8::Local<'_, v8::Object>,
) -> usize {
let table = indexed_db_runtime_state_table_for_object(scope, source);
let table = table.borrow();
table.requests.len()
+ table
.wrappers
.values()
.filter(|state| matches!(state.kind, IndexedDbWrapperKind::Request))
.count()
}
pub(super) fn register_indexed_db_transaction_lifecycle<'s>(
scope: &mut v8::PinScope<'s, '_>,
transaction: v8::Local<'s, v8::Object>,
@@ -1,4 +1,4 @@
use super::{IndexedDbError, IndexedDbValue, Key};
use super::{IndexedDbValue, Key};
#[derive(Debug, Clone)]
pub(super) struct IdbKeyRangeQuery {
@@ -22,15 +22,19 @@ pub(super) struct CursorSnapshotEntry {
pub(super) value: Option<IndexedDbValue>,
}
pub(super) struct PreparedObjectStoreWrite<'s> {
pub(super) key: Option<Key>,
pub(super) value: v8::Local<'s, v8::Value>,
pub(super) struct PreparedObjectStoreWrite {
pub(super) key: PreparedObjectStoreKey,
pub(super) value: IndexedDbValue,
}
pub(super) enum PreparedObjectStoreWriteError {
Backend(IndexedDbError),
DomException {
message: &'static str,
name: &'static str,
},
pub(super) enum PreparedObjectStoreKey {
Explicit(Key),
Generate,
GenerateInline { key_path: String },
}
pub(super) enum ExtractedObjectStoreKey {
Key(Key),
Missing,
Invalid,
}
@@ -26,12 +26,13 @@ globalThis.__idbRejectedRequestRun = (async () => {
tx.addEventListener('complete', () => completions++);
tx.addEventListener('error', () => requestErrors++);
const done = finished(tx);
const marker = new realm.Error('clone getter');
for (const method of ['put','add']) {
for (const [j, value] of [function(){}, new realm.Event('not-cloneable'),
{get payload(){getterReads++; throw new realm.Error('clone getter');}}].entries()) {
{get payload(){getterReads++; throw marker;}}].entries()) {
let error;
try {store[method](value, `${method}-rejected-${j}`);} catch (e) {error=e;}
check(`${i}: ${method} rejection ${j}`, error instanceof realm.DOMException && error.name === 'DataCloneError');
check(`${i}: ${method} rejection ${j}`, j === 2 ? error === marker : error instanceof realm.DOMException && error.name === 'DataCloneError');
}
}
store.put('accepted', 'safe'); await done;
@@ -0,0 +1,144 @@
async function(realm, scenario, realmIndex, requestStateEntries) {
const assert = (value, message) => {
if (!value) throw new Error(`${scenario}/${realmIndex}: ${message}`);
};
const throws = (callback, expected) => {
let caught = false;
try { callback(); } catch (error) {
caught = true;
assert(typeof expected === 'string' ? error.name === expected : error === expected,
`wrong exception: ${String(error)}`);
}
assert(caught, 'expected synchronous exception');
};
const result = request => new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
const complete = tx => new Promise((resolve, reject) => {
tx.oncomplete = resolve;
tx.onabort = () => reject(tx.error);
});
const open = realm.indexedDB.open(`write-preparation-${scenario}-${realmIndex}`, 1);
open.onupgradeneeded = () => {
open.result.createObjectStore('plain');
open.result.createObjectStore('inline', {keyPath: 'id', autoIncrement: true});
open.result.createObjectStore('nested', {keyPath: 'meta.id', autoIncrement: true});
open.result.createObjectStore('generated', {autoIncrement: true});
};
const db = await result(open);
try {
if (scenario === 'queued') {
const first = db.transaction('plain', 'readwrite');
const firstDone = complete(first);
first.objectStore('plain').put('first', 'first');
const tx = db.transaction('plain', 'readwrite');
const done = complete(tx), store = tx.objectStore('plain');
for (const method of ['put', 'add']) {
throws(() => store[method](() => {}, 'bad'), 'DataCloneError');
const marker = new realm.Error(`${method} getter`);
throws(() => store[method]({get payload() {throw marker;}}, 'bad-getter'), marker);
throws(() => store[method]('bad-key', {}), 'DataError');
}
const value = {payload: {text: 'snapshot'}};
let keyReads = 0;
const key = [Object.defineProperty([], '0', {enumerable: true, configurable: true,
get() {keyReads++; return 'snapshot-key';}})];
const write = result(store.put(value, key));
value.payload.text = 'changed';
Object.defineProperty(key[0], '0', {value: 'changed-key'});
await firstDone;
assert(JSON.stringify(await write) === '[["snapshot-key"]]', 'queued key was not snapshotted');
assert(keyReads === 1, `queued key converted ${keyReads} times`);
await done;
const read = db.transaction('plain'), readDone = complete(read);
const saved = await result(read.objectStore('plain').get([['snapshot-key']]));
assert(saved.payload.text === 'snapshot', 'queued value was not snapshotted');
await readDone;
} else if (scenario === 'generated-keys') {
const tx = db.transaction(['inline', 'generated', 'nested'], 'readwrite');
const done = complete(tx), requests = [];
for (const name of ['inline', 'generated', 'nested']) {
const store = tx.objectStore(name);
for (const method of ['put', 'add']) {
throws(() => store[method]({payload: () => {}}), 'DataCloneError');
if (name !== 'generated') {
throws(() => store[method](0), 'DataError');
}
if (name === 'nested') {
throws(() => store[method]({meta: 0}), 'DataError');
}
const value = {payload: `${name}-${method}`};
requests.push(result(store[method](value)));
assert(!Object.hasOwn(value, 'id') && !Object.hasOwn(value, 'meta'), 'mutated original value');
}
}
const keys = await Promise.all(requests);
assert(JSON.stringify(keys) === '[1,2,1,2,1,2]', `failed writes consumed generated keys: ${keys}`);
await done;
const read = db.transaction(['inline', 'nested']), readDone = complete(read);
const inline = result(read.objectStore('inline').get(1));
const nested = result(read.objectStore('nested').get(2));
assert((await inline).id === 1 && (await nested).meta.id === 2, 'generated key was not stored inline');
await readDone;
} else if (scenario === 'getters') {
const tx = db.transaction('inline', 'readwrite'), store = tx.objectStore('inline');
const done = complete(tx);
for (const marker of [new realm.Error('original'), {}, null, undefined]) {
throws(() => store.put({get payload() {throw marker;}}), marker);
}
let inheritedReads = 0, inheritedWrite;
const prototype = realm.Object.prototype;
const originalId = Object.getOwnPropertyDescriptor(prototype, 'id');
try {
Object.defineProperty(prototype, 'id', {configurable: true, get() {
inheritedReads++;
throw new Error('inherited key getter');
}});
inheritedWrite = result(store.put({payload: 'own-only'}));
} finally {
if (originalId) Object.defineProperty(prototype, 'id', originalId);
else delete prototype.id;
}
assert(inheritedReads === 0, 'key extraction invoked a prototype getter');
let keyReads = 0, payloadReads = 0;
const value = {
get id() {keyReads++; return 7;},
get payload() {
payloadReads++;
throws(() => store.get(7), 'TransactionInactiveError');
throws(() => store.add({id: 99}), 'TransactionInactiveError');
return 'snapshot';
}
};
const key = await result(store.put(value));
assert(await inheritedWrite === 1, 'missing own key did not use the key generator');
assert(keyReads === 1 && payloadReads === 1, `getters ran ${keyReads}/${payloadReads} times`);
assert(key === 7, 'key came from the wrong snapshot');
await done;
const read = db.transaction('inline'), readDone = complete(read);
const saved = await result(read.objectStore('inline').get(7));
assert(saved.id === 7 && saved.payload === 'snapshot', 'stored value and primary key disagree');
await readDone;
} else if (scenario === 'native-state') {
const first = db.transaction('plain', 'readwrite'), firstDone = complete(first);
const queued = db.transaction('plain', 'readwrite'), queuedDone = complete(queued);
for (const tx of [first, queued]) {
const store = tx.objectStore('plain');
const before = requestStateEntries(store);
for (let index = 0; index < 100; index++) {
throws(() => store.put(() => {}, 'bad'), 'DataCloneError');
throws(() => store.add(() => {}, 'bad'), 'DataCloneError');
}
assert(requestStateEntries(store) === before, 'rejected write retained native request state');
store.put('accepted', 'valid');
}
await firstDone;
await queuedDone;
} else {
throw new Error(`unknown scenario: ${scenario}`);
}
} finally {
db.close();
}
}
@@ -0,0 +1,77 @@
use super::*;
fn request_state_entries<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s>,
) {
let source = v8::Local::<v8::Object>::try_from(args.get(0)).unwrap();
let count = crate::context_bootstrap::indexed_db_request_state_entries_for_test(scope, source);
rv.set(v8::Number::new(scope, count as f64).into());
}
async fn assert_write_preparation(case: &str) {
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
let mut vm = new_storage_page_task_executor_test_vm_with_loader(
"https://idb-write-preparation.test/",
&loader,
);
vm.eval("document.body.innerHTML = '<iframe id=child></iframe>'")
.unwrap();
vm.with_default_context_scope(|scope, _| {
let count = v8::Function::new(scope, request_state_entries).unwrap();
let name = v8::String::new(scope, "__idbRequestStateEntries").unwrap();
let global = scope.get_current_context().global(scope);
global.set(scope, name.into(), count.into()).unwrap();
Ok(())
})
.unwrap();
let fixture = include_str!("idb_write_preparation.js");
vm.eval(&format!(
r#"
globalThis.__idbWritePreparation = {{done: false}};
(async () => {{
for (const [index, realm] of [window, document.getElementById('child').contentWindow].entries()) {{
await ({fixture})(realm, {case:?}, index, __idbRequestStateEntries);
}}
}})().then(
() => globalThis.__idbWritePreparation = {{done: true, result: 'ok'}},
error => globalThis.__idbWritePreparation = {{done: true, result: String(error), stack: error?.stack}}
);
"#
))
.unwrap();
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(__idbWritePreparation.done)",
"true",
case,
)
.await;
assert_eq!(
vm.eval("JSON.stringify(__idbWritePreparation)").unwrap(),
r#"{"done":true,"result":"ok"}"#,
"{case}"
);
}
#[tokio::test]
async fn queued_writes_validate_and_snapshot_before_transaction_start() {
assert_write_preparation("queued").await;
}
#[tokio::test]
async fn rejected_writes_do_not_consume_generated_keys() {
assert_write_preparation("generated-keys").await;
}
#[tokio::test]
async fn write_getters_run_once_and_propagate_exceptions_without_reentrancy() {
assert_write_preparation("getters").await;
}
#[tokio::test]
async fn rejected_writes_allocate_no_native_request_state() {
assert_write_preparation("native-state").await;
}
@@ -2255,6 +2255,7 @@ mod data_transfer_native_receivers;
mod frame_owner_origin_access;
mod hyperlink_null_url_protocol;
mod idb_rejected_request;
mod idb_write_preparation;
mod import_meta;
mod indexed_db;
mod indexed_db_gc;