I am writing a Google Chrome extension. It will monitor what is happening on a web page, communicate with a database-backed server, etc. I'm wondering if anyone knows good design patterns, given how asynchronous JavaScript is becoming. Here are the challenges:
- Before I can do anything, I need to read from chrome.storage. I can't even connect to a server before I've read settings to make that connection
- Before I can interact with the page, I would like to get data from the server
- On the other hand, I need to know what the page is doing the whole time; this is a place where I can't loose a bit.
In a synchronous programming environment, I would:
- Try to connect to the server
- If successful, finish loading the page, and use the data from the server to do back-and-forth with the page
- If unsuccessful, read the last state from chrome.storage, and use that to interact with the page, and save interactions to chrome.storage for sync when the server is back.
With async, it seems like there's a million dependencies, orders in which operations might happen, etc. I can design a complex state machine which queues up events from the page when the extension starts, while reading server settings, then connecting to the server, than modifying the page, but it seems super-complex, and like there's some elegant design pattern I'm missing.
The second piece is that even building a simply but robust event queue in chrome.storage seems complex, since there aren't atomic operations, which leads to race conditions. It doesn't even list an API for listing what keys are stored, so it seems easy to lose things if I store things under object-specific keys depending on race conditions. Again, I can build an FSM that avoids race conditions, but it seems super-complex.
Any suggestions on good articles, blog posts, or similar things I should look at?
The really critical thing -- actually -- is just to make sure I robustly capture every event of a certain type on the page, whenever it happens (even if it happens as the page is loading, if there's an outage communicating with my server, if the user randomly closes the browser, if two events come in within 1ms of each other, etc.).