When is it safe to mutate data written to IndexedDB?

Viewed 88

Is it safe to mutate data passed to IDBObjectStore.put() immediately after the call? Or can an IndexedDB implementation access the data asynchronously?

MDN says that the cloning happens in a separate thread:

It returns an IDBRequest object, and, in a separate thread, creates a structured clone of the value and stores the cloned value in the object store.

But Google says cloning happens on the main thread:

The reason is because when IndexedDB stores an object, it must first create a structured clone of that object, and the structured cloning process happens on the main thread. The larger the object, the longer the blocking time will be.

These explanations seem to contradict each other. I wrote this code to test how browsers actually behave:

(async function() {
  // Open the database.
  const db = await new Promise(resolve => {
    const request = globalThis.indexedDB.open('test', 1);
    request.onupgradeneeded = () => {
      request.result.createObjectStore('store');
    };
    request.onsuccess = () => resolve(request.result);
  });

  // Write to db in one transaction...
  const obj = { value: 'original' };
  db.transaction('store', 'readwrite').objectStore('store').put(obj, 'key');

  // Mutate data immediately after writing.
  obj.value = 'mutated';

  // Read back in another transaction.
  const result = await new Promise(resolve => {
    const request = db.transaction('store').objectStore('store').get('key');
    request.onsuccess = () => resolve(request.result);
  });
  console.log(`value is '${result.value}'`);

  globalThis.indexedDB.deleteDatabase('test');
})();

Chrome, Safari, and Firefox all output "value is 'original'", so they behave as if the cloning is done immediately. But that doesn't necessarily mean that this behavior is required and guaranteed.

In my use case, I could be writing fairly large ArrayBuffers to IndexedDB. I of course could make copies for the writes (or run a test like this at page load), but I prefer not to unless it is necessary.

I have looked at the spec but I haven't yet found language that specifies whether or not it is safe to mutate write data before the request completes. My internet searches haven't turned up any articles warning that this is not safe, but I would like to know if there is any official or semi-official opinion.

0 Answers
Related