Skip to main content

script/dom/indexeddb/
idbrequest.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::cell::Cell;
8
9use dom_struct::dom_struct;
10use js::context::JSContext;
11use js::conversions::ToJSValConvertible;
12use js::jsapi::Heap;
13use js::jsval::{DoubleValue, JSVal, ObjectValue, UndefinedValue};
14use js::rust::HandleValue;
15use profile_traits::generic_callback::GenericCallback;
16use script_bindings::reflector::{DomObject, reflect_dom_object_with_cx};
17use serde::{Deserialize, Serialize};
18use servo_base::generic_channel::{GenericSend, SendError};
19use storage_traits::indexeddb::{
20    AsyncOperation, AsyncReadOnlyOperation, BackendError, BackendResult, IndexedDBKeyType,
21    IndexedDBRecord, IndexedDBThreadMsg, IndexedDBTxnMode, PutItemResult, SyncOperation,
22};
23use stylo_atoms::Atom;
24
25use crate::dom::bindings::codegen::Bindings::IDBRequestBinding::{
26    IDBRequestMethods, IDBRequestReadyState,
27};
28use crate::dom::bindings::codegen::Bindings::IDBTransactionBinding::IDBTransactionMode;
29use crate::dom::bindings::error::{Error, Fallible, create_dom_exception};
30use crate::dom::bindings::inheritance::Castable;
31use crate::dom::bindings::refcounted::Trusted;
32use crate::dom::bindings::reflector::DomGlobal;
33use crate::dom::bindings::root::{DomRoot, MutNullableDom};
34use crate::dom::bindings::structuredclone;
35use crate::dom::domexception::DOMException;
36use crate::dom::event::{Event, EventBubbles, EventCancelable};
37use crate::dom::eventtarget::EventTarget;
38use crate::dom::globalscope::GlobalScope;
39use crate::dom::indexeddb::idbcursor::{IterationParam, iterate_cursor};
40use crate::dom::indexeddb::idbcursorwithvalue::IDBCursorWithValue;
41use crate::dom::indexeddb::idbobjectstore::IDBObjectStore;
42use crate::dom::indexeddb::idbtransaction::IDBTransaction;
43use crate::dom::indexeddb::key::key_type_to_jsval;
44use crate::realms::enter_auto_realm;
45
46#[derive(Clone)]
47struct RequestListener {
48    request: Trusted<IDBRequest>,
49    iteration_param: Option<IterationParam>,
50    request_id: u64,
51}
52
53pub enum IdbResult {
54    Key(IndexedDBKeyType),
55    Keys(Vec<IndexedDBKeyType>),
56    Value(Vec<u8>),
57    Values(Vec<Vec<u8>>),
58    Count(u64),
59    Iterate(Vec<IndexedDBRecord>),
60    Error(Error),
61    None,
62}
63
64impl From<IndexedDBKeyType> for IdbResult {
65    fn from(value: IndexedDBKeyType) -> Self {
66        IdbResult::Key(value)
67    }
68}
69
70impl From<Vec<IndexedDBKeyType>> for IdbResult {
71    fn from(value: Vec<IndexedDBKeyType>) -> Self {
72        IdbResult::Keys(value)
73    }
74}
75
76impl From<Vec<u8>> for IdbResult {
77    fn from(value: Vec<u8>) -> Self {
78        IdbResult::Value(value)
79    }
80}
81
82impl From<Vec<Vec<u8>>> for IdbResult {
83    fn from(value: Vec<Vec<u8>>) -> Self {
84        IdbResult::Values(value)
85    }
86}
87
88impl From<PutItemResult> for IdbResult {
89    fn from(value: PutItemResult) -> Self {
90        match value {
91            PutItemResult::Key(key) => Self::Key(key),
92            PutItemResult::CannotOverwrite => Self::Error(Error::Constraint(None)),
93        }
94    }
95}
96
97impl From<Vec<IndexedDBRecord>> for IdbResult {
98    fn from(value: Vec<IndexedDBRecord>) -> Self {
99        Self::Iterate(value)
100    }
101}
102
103impl From<()> for IdbResult {
104    fn from(_value: ()) -> Self {
105        Self::None
106    }
107}
108
109impl<T> From<Option<T>> for IdbResult
110where
111    T: Into<IdbResult>,
112{
113    fn from(value: Option<T>) -> Self {
114        match value {
115            Some(value) => value.into(),
116            None => IdbResult::None,
117        }
118    }
119}
120
121impl From<u64> for IdbResult {
122    fn from(value: u64) -> Self {
123        IdbResult::Count(value)
124    }
125}
126
127impl RequestListener {
128    fn send_request_handled(cx: &mut JSContext, transaction: &IDBTransaction, request_id: u64) {
129        let global = transaction.global();
130        // https://w3c.github.io/IndexedDB/#transaction-lifecycle
131        // A transaction is inactive after control returns to the event loop and
132        // when events are not being dispatched. We call this after dispatching
133        // the request event, so the backend can reevaluate commit eligibility.
134        let send_result = global.storage_threads().send(IndexedDBThreadMsg::Sync(
135            SyncOperation::RequestHandled {
136                origin: global.origin().immutable().clone(),
137                db_name: String::from(transaction.get_db_name()),
138                txn: transaction.get_serial_number(),
139                request_id,
140            },
141        ));
142        if send_result.is_err() {
143            error!("Failed to send SyncOperation::RequestHandled");
144        }
145        transaction.mark_request_handled(request_id);
146
147        // This request's result has been handled by script, the
148        // transaction might finally be ready to auto-commit.
149        transaction.maybe_commit(cx);
150    }
151
152    // https://www.w3.org/TR/IndexedDB-3/#async-execute-request
153    // Implements Step 5.4
154    fn handle_async_request_finished(&self, cx: &mut JSContext, result: BackendResult<IdbResult>) {
155        let request = self.request.root();
156        let global = request.global();
157
158        let transaction = request
159            .transaction
160            .get()
161            .expect("Request unexpectedly has no transaction");
162        // Substep 1: Set the result of request to result.
163        request.set_ready_state_done();
164
165        let mut realm = enter_auto_realm(cx, &*request);
166        let cx: &mut JSContext = &mut realm;
167        rooted!(&in(cx) let mut answer = UndefinedValue());
168
169        if let Ok(data) = result {
170            match data {
171                IdbResult::Key(key) => key_type_to_jsval(cx, &key, answer.handle_mut()),
172                IdbResult::Keys(keys) => {
173                    rooted!(&in(cx) let mut array = vec![JSVal::default(); keys.len()]);
174                    for (i, key) in keys.into_iter().enumerate() {
175                        key_type_to_jsval(cx, &key, array.handle_mut_at(i));
176                    }
177                    array.to_jsval(cx, answer.handle_mut());
178                },
179                IdbResult::Value(serialized_data) => {
180                    let result = postcard::from_bytes(&serialized_data)
181                        .map_err(|_| Error::Data(None))
182                        .and_then(|data| {
183                            structuredclone::read(cx, &global, data, answer.handle_mut())
184                        });
185                    if let Err(e) = result {
186                        warn!("Error reading structuredclone data");
187                        Self::handle_async_request_error(&global, cx, request, e, self.request_id);
188                        return;
189                    };
190                },
191                IdbResult::Values(serialized_values) => {
192                    rooted!(&in(cx) let mut values = vec![JSVal::default(); serialized_values.len()]);
193                    for (i, serialized_data) in serialized_values.into_iter().enumerate() {
194                        let result = postcard::from_bytes(&serialized_data)
195                            .map_err(|_| Error::Data(None))
196                            .and_then(|data| {
197                                structuredclone::read(cx, &global, data, values.handle_mut_at(i))
198                            });
199                        if let Err(e) = result {
200                            warn!("Error reading structuredclone data");
201                            Self::handle_async_request_error(
202                                &global,
203                                cx,
204                                request,
205                                e,
206                                self.request_id,
207                            );
208                            return;
209                        };
210                    }
211                    values.to_jsval(cx, answer.handle_mut());
212                },
213                IdbResult::Count(count) => {
214                    answer.handle_mut().set(DoubleValue(count as f64));
215                },
216                IdbResult::Iterate(records) => {
217                    let param = self.iteration_param.as_ref().expect(
218                        "iteration_param must be provided by IDBRequest::execute_async for Iterate",
219                    );
220                    let cursor = match iterate_cursor(&global, cx, param, records) {
221                        Ok(cursor) => cursor,
222                        Err(e) => {
223                            warn!("Error reading structuredclone data");
224                            Self::handle_async_request_error(
225                                &global,
226                                cx,
227                                request,
228                                e,
229                                self.request_id,
230                            );
231                            return;
232                        },
233                    };
234                    if let Some(cursor) = cursor {
235                        match cursor.downcast::<IDBCursorWithValue>() {
236                            Some(cursor_with_value) => {
237                                answer.handle_mut().set(ObjectValue(
238                                    *cursor_with_value.reflector().get_jsobject(),
239                                ));
240                            },
241                            None => {
242                                answer
243                                    .handle_mut()
244                                    .set(ObjectValue(*cursor.reflector().get_jsobject()));
245                            },
246                        }
247                    }
248                },
249                IdbResult::None => {
250                    // no-op
251                },
252                IdbResult::Error(error) => {
253                    // Substep 2
254                    Self::handle_async_request_error(&global, cx, request, error, self.request_id);
255                    return;
256                },
257            }
258
259            // Substep 3.1: Set the result of request to answer.
260            request.set_result(answer.handle());
261
262            // Substep 3.2: Set the error of request to undefined
263            request.set_error(cx, None);
264
265            // https://w3c.github.io/IndexedDB/#fire-success-event
266            // Step 1: Let event be the result of creating an event using Event.
267            // Step 2: Set event’s type attribute to "success".
268            // Step 3: Set event’s bubbles and cancelable attributes to false.
269            let event = Event::new(
270                cx,
271                &global,
272                Atom::from("success"),
273                EventBubbles::DoesNotBubble,
274                EventCancelable::NotCancelable,
275            );
276
277            // Step 5: Let legacyOutputDidListenersThrowFlag be initially false.
278            let did_listeners_throw = Cell::new(false);
279            // Step 6: If transaction’s state is inactive, then set transaction’s state to active.
280            if transaction.is_inactive() {
281                transaction.set_active_flag(true);
282            }
283            // Step 7: Dispatch event at request with legacyOutputDidListenersThrowFlag.
284            event
285                .upcast::<Event>()
286                .fire_with_legacy_output_did_listeners_throw(
287                    cx,
288                    request.upcast(),
289                    &did_listeners_throw,
290                );
291            // Step 8: If transaction’s state is active, then:
292            if transaction.is_active() {
293                // Step 8.1: Set transaction’s state to inactive.
294                transaction.set_active_flag(false);
295                // Step 8.2: If legacyOutputDidListenersThrowFlag is true, then run abort a
296                // transaction with transaction and a newly created "AbortError" DOMException.
297                if did_listeners_throw.get() {
298                    transaction.initiate_abort(cx, Error::Abort(None));
299                    transaction.request_backend_abort();
300                }
301            }
302            transaction.request_finished();
303
304            Self::send_request_handled(cx, &transaction, self.request_id);
305        } else {
306            // FIXME:(arihant2math) dispatch correct error
307            // Substep 2
308            Self::handle_async_request_error(
309                &global,
310                cx,
311                request,
312                Error::Data(None),
313                self.request_id,
314            );
315        }
316    }
317
318    // https://www.w3.org/TR/IndexedDB-3/#async-execute-request
319    // Implements Step 5.4.2
320    fn handle_async_request_error(
321        global: &GlobalScope,
322        cx: &mut JSContext,
323        request: DomRoot<IDBRequest>,
324        error: Error,
325        request_id: u64,
326    ) {
327        let transaction = request
328            .transaction
329            .get()
330            .expect("Request has no transaction");
331        // Substep 1: Set the result of request to undefined.
332        rooted!(&in(cx) let undefined = UndefinedValue());
333        request.set_result(undefined.handle());
334
335        // Substep 2: Set the error of request to result.
336        request.set_error(cx, Some(error.clone()));
337
338        // https://w3c.github.io/IndexedDB/#fire-error-event
339        // Step 1: Let event be the result of creating an event using Event.
340        // Step 2: Set event’s type attribute to "error".
341        // Step 3: Set event’s bubbles and cancelable attributes to true.
342        let event = Event::new(
343            cx,
344            global,
345            Atom::from("error"),
346            EventBubbles::Bubbles,
347            EventCancelable::Cancelable,
348        );
349
350        // If result is an error and transaction’s state is committing, then run abort a
351        // transaction with transaction and result, and terminate these steps.
352        if transaction.is_committing() {
353            transaction.initiate_abort(cx, error.clone());
354            transaction.request_backend_abort();
355        }
356        // Step 5: Let legacyOutputDidListenersThrowFlag be initially false.
357        let did_listeners_throw = Cell::new(false);
358        // Step 6: If transaction’s state is inactive, then set transaction’s state to active.
359        if transaction.is_inactive() {
360            transaction.set_active_flag(true);
361        }
362        // Step 7: Dispatch event at request with legacyOutputDidListenersThrowFlag.
363        let default_not_prevented = event
364            .upcast::<Event>()
365            .fire_with_legacy_output_did_listeners_throw(
366                cx,
367                request.upcast(),
368                &did_listeners_throw,
369            );
370        // Step 8: If transaction’s state is active, then:
371        if transaction.is_active() {
372            // Step 8.1: Set transaction’s state to inactive.
373            transaction.set_active_flag(false);
374            // Step 8.2: If legacyOutputDidListenersThrowFlag is true, then run abort a transaction
375            // with transaction and a newly created "AbortError" DOMException and terminate these steps.
376            // NOTE: This is done even if event’s canceled flag is false.
377            // NOTE: This means that if an error event is fired and any of the event handlers throw an
378            // exception, transaction’s error property is set to an AbortError rather than request’s
379            // error, even if preventDefault() is never called.
380            if did_listeners_throw.get() {
381                transaction.initiate_abort(cx, Error::Abort(None));
382                transaction.request_backend_abort();
383            } else if default_not_prevented {
384                // Step 8.3: If event’s canceled flag is false, then run abort a transaction
385                // using transaction and request’s error, and terminate these steps.
386                transaction.initiate_abort(cx, error);
387                transaction.request_backend_abort();
388            }
389        }
390        transaction.request_finished();
391        Self::send_request_handled(cx, &transaction, request_id);
392    }
393}
394
395#[dom_struct]
396pub struct IDBRequest {
397    eventtarget: EventTarget,
398    #[ignore_malloc_size_of = "mozjs"]
399    result: Heap<JSVal>,
400    error: MutNullableDom<DOMException>,
401    source: MutNullableDom<IDBObjectStore>,
402    transaction: MutNullableDom<IDBTransaction>,
403    ready_state: Cell<IDBRequestReadyState>,
404}
405
406impl IDBRequest {
407    pub fn new_inherited() -> IDBRequest {
408        IDBRequest {
409            eventtarget: EventTarget::new_inherited(),
410
411            result: Heap::default(),
412            error: Default::default(),
413            source: Default::default(),
414            transaction: Default::default(),
415            ready_state: Cell::new(IDBRequestReadyState::Pending),
416        }
417    }
418
419    pub fn new(cx: &mut JSContext, global: &GlobalScope) -> DomRoot<IDBRequest> {
420        reflect_dom_object_with_cx(Box::new(IDBRequest::new_inherited()), global, cx)
421    }
422
423    pub fn set_source(&self, source: Option<&IDBObjectStore>) {
424        self.source.set(source);
425    }
426
427    pub fn set_ready_state_done(&self) {
428        self.ready_state.set(IDBRequestReadyState::Done);
429    }
430
431    pub fn set_result(&self, result: HandleValue) {
432        self.result.set(result.get());
433    }
434
435    pub fn set_error(&self, cx: &mut JSContext, error: Option<Error>) {
436        if let Some(error) = error {
437            if let Ok(exception) = create_dom_exception(cx, &self.global(), error) {
438                self.error.set(Some(&exception));
439            }
440        } else {
441            self.error.set(None);
442        }
443    }
444
445    pub fn set_transaction(&self, transaction: &IDBTransaction) {
446        self.transaction.set(Some(transaction));
447    }
448
449    pub fn clear_transaction(&self) {
450        self.transaction.set(None);
451    }
452
453    fn is_done(&self) -> bool {
454        self.ready_state.get() == IDBRequestReadyState::Done
455    }
456
457    pub(crate) fn transaction(&self) -> Option<DomRoot<IDBTransaction>> {
458        self.transaction.get()
459    }
460
461    // https://www.w3.org/TR/IndexedDB-3/#asynchronously-execute-a-request
462    pub fn execute_async<T, F>(
463        cx: &mut JSContext,
464        source: &IDBObjectStore,
465        operation_fn: F,
466        request: Option<DomRoot<IDBRequest>>,
467        iteration_param: Option<IterationParam>,
468    ) -> Fallible<DomRoot<IDBRequest>>
469    where
470        T: Into<IdbResult> + for<'a> Deserialize<'a> + Serialize + Send + Sync + 'static,
471        F: FnOnce(GenericCallback<BackendResult<T>>) -> AsyncOperation,
472    {
473        // Step 1: Let transaction be the transaction associated with source.
474        let transaction = source.transaction();
475        let global = transaction.global();
476        // Step 2: Assert: transaction is active.
477        if !transaction.is_active() || !transaction.is_usable() {
478            return Err(Error::TransactionInactive(None));
479        }
480
481        let request_id = transaction.allocate_request_id();
482
483        // Step 3: If request was not given, let request be a new request with source as source.
484        let request = request.unwrap_or_else(|| {
485            let new_request = IDBRequest::new(cx, &global);
486            new_request.set_source(Some(source));
487            new_request.set_transaction(&transaction);
488            new_request
489        });
490
491        // Step 4: Add request to the end of transaction’s request list.
492        transaction.add_request(&request);
493
494        // Step 5: Run the operation, and queue a returning task in parallel
495        // the result will be put into `receiver`
496        let transaction_mode = match transaction.get_mode() {
497            IDBTransactionMode::Readonly => IndexedDBTxnMode::Readonly,
498            IDBTransactionMode::Readwrite => IndexedDBTxnMode::Readwrite,
499            IDBTransactionMode::Versionchange => IndexedDBTxnMode::Versionchange,
500        };
501
502        let response_listener = RequestListener {
503            request: Trusted::new(&request),
504            iteration_param: iteration_param.clone(),
505            request_id,
506        };
507
508        let task_source = global
509            .task_manager()
510            .database_access_task_source()
511            .to_sendable();
512
513        let closure = move |message: Result<BackendResult<T>, SendError>| {
514            let response_listener = response_listener.clone();
515            task_source.queue(task!(request_callback: move |cx| {
516                response_listener.handle_async_request_finished(
517                    cx,
518                    message.expect("Could not unwrap message").inspect_err(|e| {
519                        if let BackendError::DbErr(e) = e {
520                            error!("Error in IndexedDB operation: {}", e);
521                        }
522                    }).map(|t| t.into()),
523                );
524            }));
525        };
526        let callback = GenericCallback::new(closure).expect("Could not create callback");
527        let operation = operation_fn(callback);
528
529        if matches!(
530            operation,
531            AsyncOperation::ReadOnly(AsyncReadOnlyOperation::Iterate { .. })
532        ) {
533            assert!(
534                iteration_param.is_some(),
535                "iteration_param must be provided for Iterate"
536            );
537        } else {
538            assert!(
539                iteration_param.is_none(),
540                "iteration_param should not be provided for operation other than Iterate"
541            );
542        }
543
544        // Start is a backend database task (spec). Script does not model it with a
545        // separate queued task, backend scheduling decides when requests begin.
546        transaction
547            .global()
548            .storage_threads()
549            .send(IndexedDBThreadMsg::Async(
550                global.origin().immutable().clone(),
551                String::from(transaction.get_db_name()),
552                String::from(source.get_name()),
553                transaction.get_serial_number(),
554                request_id,
555                transaction_mode,
556                operation,
557            ))
558            .unwrap();
559
560        // Step 6
561        Ok(request)
562    }
563}
564
565impl IDBRequestMethods<crate::DomTypeHolder> for IDBRequest {
566    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbrequest-result>
567    fn GetResult(
568        &self,
569        _cx: &mut JSContext,
570        mut val: js::rust::MutableHandle<'_, js::jsapi::Value>,
571    ) -> Fallible<()> {
572        // Step 1. If this's done flag is false, then throw an "InvalidStateError" DOMException.
573        if !self.is_done() {
574            return Err(Error::InvalidState(Some(
575                "Cannot get result on a request that is still pending.".into(),
576            )));
577        }
578
579        // Step 2. Return this's result, or undefined if the request resulted in an error.
580        val.set(self.result.get());
581        Ok(())
582    }
583
584    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbrequest-error>
585    fn GetError(&self) -> Fallible<Option<DomRoot<DOMException>>> {
586        // Step 1. If this's done flag is false, then throw an "InvalidStateError" DOMException.
587        if !self.is_done() {
588            return Err(Error::InvalidState(Some(
589                "Cannot get error on a request that is still pending.".into(),
590            )));
591        }
592
593        // Step 2. Return this's error, or null if no error occurred.
594        Ok(self.error.get())
595    }
596
597    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbrequest-source>
598    fn GetSource(&self) -> Option<DomRoot<IDBObjectStore>> {
599        self.source.get()
600    }
601
602    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbrequest-transaction>
603    fn GetTransaction(&self) -> Option<DomRoot<IDBTransaction>> {
604        self.transaction.get()
605    }
606
607    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbrequest-readystate>
608    fn ReadyState(&self) -> IDBRequestReadyState {
609        self.ready_state.get()
610    }
611
612    // https://www.w3.org/TR/IndexedDB-3/#dom-idbrequest-onsuccess
613    event_handler!(success, GetOnsuccess, SetOnsuccess);
614
615    // https://www.w3.org/TR/IndexedDB-3/#dom-idbrequest-onerror
616    event_handler!(error, GetOnerror, SetOnerror);
617}