12

Overview: I am trying to avoid a race condition with accessing an IndexedDB from both a webpage and a web-worker.

Setup: Webpage that is saving items to the local IndexedDB as the user works with the site. Whenever a user saves data to the local DB the record is marked as "Unsent".

Web-worker background thread that is pulling data from the IndexedDB, sending it to the server and once the server receives it, marking the data in the IndexedDB as "Sent".

Problem: Since access to the IndexedDB is asynchronous, I can not be guaranteed that the user won't update a record at the same time the web-worker is sending it to the server. The timeline is shown below:

  1. Web-worker gets data from DB and sends it to the server
  2. While the transfer is happening, the user updates the data saving it to the DB.
  3. The web-worker gets the response from the server and then updates the DB to "Sent"
  4. There is now data in DB that hasn't been sent to the server but marked as "Sent"

Failed Solution: After getting the response from the server, I can recheck to row to see if anything has been changed. However I am still left with a small window where data can be written to the DB and it will never be sent to the server.

Example: After server says data is saved, then:

IndexedDB.HasDataChanged(
    function(changed) { 
        // Since this is async, this changed boolean could be lying.
        // The data might have been updated after I checked and before I was called.
        if (!changed){ 
          IndexedDB.UpdateToSent() }
    });

Other notes: There is a sync api according to the W3 spec, but no one has implemented it yet so it can not be used (http://www.w3.org/TR/IndexedDB/#sync-database). The sync api was designed to be used by web-workers, to avoid this exact situation I would assume.

Any thoughts on this would be greatly appreciated. Have been working on it for about a week and haven't been able to come up with anything that will work.

4

3 回答 3

3

我想我现在找到了解决方法。没有我想要的那么干净,但它似乎是线程安全的。

每当我更新数据时,我都会首先将日期时间存储到 LastEdit 字段中。从网络工作者那里,我向浏览器发布了一条消息。

self.postMessage('UpdateDataSent#' + data.ID + '#' + data.LastEdit);

然后在浏览器中我更新我的发送标志,只要最后编辑日期没有改变。

// Get the data from the DB in a transaction
if (data.LastEdit == lastEdit)
{
    data.Sent = true;
    var saveStore = trans.objectStore("Data");
    var saveRequest = saveStore.put(data);
    console.log('Data updated to Sent');
}

由于这一切都是在浏览器端的事务中完成的,它似乎工作正常。一旦浏览器支持 Sync API,我无论如何都可以把它扔掉。

于 2012-01-28T16:27:17.787 回答
0

可以使用交易吗?
https://developer.mozilla.org/en/IndexedDB/IDBTransaction

于 2012-01-28T10:47:11.047 回答
0

旧线程但使用事务将解决Failed Solution方法。即事务只需要跨越检查IndexedDB中的数据在发送后没有变化,如果没有变化则将其标记为已发送。如果发生变化,则交易结束,无需写入。

于 2020-09-29T15:50:47.763 回答