🗄️ 2026-11-29 | Designing Domination’s IndexedDB Migration

🧑💻 Author’s Note
👋 Issue #65 asks for a first implementation design, following the IndexedDB research prompted by issue #63. This is a proposal, not a migration implementation. It narrows the earlier research into a practical first slice, records the alternatives and their costs, and calls out the questions that still need browser tests before we ship. Source-code links below point to the exact revision I studied.
🎯 The Proposed Cutover
- 🗄️ Move the per-room records—current game, undo snapshots, chat, mailbox sync state, and game version—from
localStorageto one versioned IndexedDB database. - 🪶 Keep small device preferences, diagnostic logs, the clear-generation sentinel, and unrelated origin data in
localStorage. This is a targeted move of the bulky data, not a promise to migrate every key the origin happens to contain. - 🧩 Keep
StorageKeyand the existing PureScript JSON codecs as the typed application boundary. IndexedDB stores one record per printed room key, so loads and saves still address a game or room entry rather than exposing database details to game logic. - 🔌 Put the browser database lifecycle behind a small app-owned FFI module returning
Aff. First prototype the broadindexed-dbpackage against our package set; adopt it only if its version-upgrade and transaction APIs fit without wrapping them in another FFI layer. - 🔄 Migrate on the same origin, before normal room data is read. Make the copy repeatable, preserve the old data until the copy is verified, and treat deletion of a legacy copy as a separate, recoverable step.
- 🧹 Extend the Storage panel to inspect and remove individual Domination records. Deleting the whole database should remain an explicit last resort, not the only way to clear one room.
This keeps the first release focused on room data, while leaving preferences and diagnostics on the synchronous path they already use. It also avoids claiming that IndexedDB is permanent: browser quota, eviction, and user clearing still apply.
🧺 Why Move Room Data First?
The current Storage capability JSON-encodes values and writes them synchronously through localStorage. Its StorageKey type already distinguishes per-room data from device-wide settings. Room keys include current game, ten rolling undo slots, chat, mailbox sync, and game-version metadata; preferences and diagnostics use device keys.
- 🎲 Move every room key together. Moving only
game_statewould leave undo, chat, and mailbox bookkeeping split across two stores, making restore and clear behavior harder to explain. The current save path saves an undo snapshot and current state as separate operations; both should use the same backend. - 🪶 Leave device keys alone for now. Username, player identity, setup preferences, server URLs, and diagnostic logs are small or have independent lifecycles. Keeping them in
localStorageavoids expanding the first migration and preserves synchronous code used by the debug logger. A later need for device-scoped transactions can revisit this boundary. - 🪪 Migrate only recognized Domination keys. Parse names with the existing
StorageKeyrules and copy only keys represented asInRoom. Do not sweep arbitrarylocalStorageentries: previews and local development can share an origin with other applications, and an unknown key is not ours to claim.
The cost of this boundary is a split backend: code must know that room keys are asynchronous while device preferences remain local. A single uniform IndexedDB backend would be conceptually simpler, but it would move tiny values and diagnostic code without solving the quota problem they caused.
🗃️ A Small, Versioned Schema
Start with a database named domination and two object stores:
| Store | Key and contents | Why |
|---|---|---|
entries | Key path key; each record contains the printed key, a room scope (global or a room code), and the existing JSON string. Add an index on room scope. | One value per current storage key preserves the existing read/write model and makes deleting one room possible without scanning unrelated records. |
meta | Keyed migration and application metadata, including a completed legacy-copy marker. | Schema version belongs to IndexedDB’s database version; data migration progress is separate and must commit with its copied records. |
- 🔑 Keep the printed key as the primary key. Reusing names such as
room/ABCD/game_statemakes mapping and diagnostics straightforward. An alternative composite key such as(room, kind, slot)is more query-friendly, but adds a second naming system and a more complex mapping in the first migration. - 🧾 Keep the payload as JSON text initially. Existing values are already JSON strings and can be copied byte-for-byte before the normal PureScript decoder reads them. Storing decoded structured objects would make browser inspection and future indexes more natural, but it means converting between Argonaut
Jsonand the structured-clone boundary and complicates compatibility with old values. IndexedDB still provides asynchronous writes and transactions when a record’s payload is text. - 🧭 Add the room index now. It costs a little storage and upgrade logic, but enables per-room inventory and deletion needed by the Storage panel. Without it, the schema is marginally smaller but room cleanup would have to cursor through the full store.
- 🧱 Use database version upgrades for schema changes, not for the one-time data copy. An
onupgradeneededhandler creates stores and indexes; a migration marker inmetarecords whether legacy values were copied. This keeps a future schema change distinct from a retryable import.
This is deliberately not a normalized game database. Each game snapshot is a self-contained value, and the app currently loads it by key rather than querying cards or players. Normalizing entities would enable richer searches, but would create multi-record migrations and consistency rules without a feature that needs them.
⏳ Make the Async Boundary Deliberate
IndexedDB requests are asynchronous, so the existing synchronous Effect adapter cannot simply be swapped underneath. AppM already runs in Aff, but the current Storage class and its StorageM wrapper expose only synchronous effects.
- 🪡 Change the capability to an
Aff-capable contract. Require the storage operation’s monad to liftAff, letStorageMwrapAff, and lift the storage calls throughHalogenM. Device-key operations can still calllocalStorageinside that asynchronous interface. This makes the effect visible in the type instead of hiding a Promise behind a synchronous-looking method. - 🧪 Test the transaction, not just request success. A write succeeds only when its read-write transaction completes. The FFI must not resolve on an individual
putrequest’ssuccessevent and then miss a later transaction abort. It should also translate open, blocked, request, transaction, and quota failures into the existing typedLoadErrorandSaveErrorcases without logging stored values. - 🔄 Group the current game and undo snapshot. Today they are saved one after the other. Keeping that API minimizes the first code diff, but leaves a partial save if the second transaction fails. Prefer a small paired-save operation for this path so both records commit in one read-write transaction; report a failed transaction as a failed history save, matching the existing undo recovery policy. Other single-key writes remain simple.
- 🚪 Own one database connection per page. Reuse it instead of reopening for every operation. On
versionchange, close it so another version can upgrade; surface a blocked open rather than leaving initialization hanging forever. The Storage panel should explain when another tab keeps a database open.
The trade-off is that an honest async contract reaches more call sites and tests than a wrapper that pretends IndexedDB is synchronous. In return, callers can sequence initialization, save, and error handling correctly, and the adapter can model request-versus-transaction completion.
🔌 PureScript Package or Project-Owned FFI?
The previous research compared the main options. My first implementation would use a narrow project-owned FFI, after a small compile-and-transaction spike against the package candidate:
- 📚
indexed-db1.0.0 has the broadest PureScript API: factories, stores, indexes, key ranges, transactions, and cursors. It could save us browser-binding work and is the first package worth compiling against this repository’s pinned Spago 0.21 package set. Its last inspected source revision is old, its README uses legacy imports, and we still need to verify upgrade callbacks and transaction behavior in our build. If the proof works cleanly, adopting it is preferable to reimplementing the same bindings. - 📦
purescript-idb0.2.0 offers a smallerAffinterface over JavaScript’sidbpackage. That wrapper handles request boilerplate and guards transaction callbacks against asynchronous waits, but the inspected API is centered on string keys,Foreignvalues, and one-store transactions; it does not provide the custom indexes and upgrades this design needs without extension. It also introduces an npm dependency and Spago metadata that must fit the current setup. - 🧰 Dexie or another JavaScript wrapper could make versioned schemas and transactions more convenient. The cost is another runtime dependency plus an FFI boundary anyway; it is more abstraction than this first schema appears to need.
- 🪡 A local FFI can expose only
open, typed request results, transaction completion, cursor-based inventory, and record deletion. It avoids a new runtime package and keeps schema decisions explicit. Its cost is real: the project owns subtle browser semantics, cancellation, blocked upgrades, and a larger set of browser tests.
The deciding point is not whether FFI is acceptable—StorageInspector already bridges browser promises into Aff—but whether a library gives us the transaction and upgrade hooks without forcing a second wrapper around its API. The narrow FFI is the fallback with the clearest shape, not a claim that hand-written bindings are automatically safer. If indexed-db compiles and passes the same transaction tests, use it and keep any app-specific FFI small.
🔄 Migration and Rollback
- 🚀 Open and upgrade before loading room state. The first room-key operation opens the database and creates the v1 stores and room index. A successful open is cached for the page lifetime.
- 🔎 Take a bounded legacy snapshot. Enumerate localStorage keys, parse only recognized room keys, and read their exact JSON strings. Leave preferences, logs, the clear-generation key, unknown keys, and unrelated site data untouched.
- 📥 Copy atomically and idempotently. In one
entries/metatransaction, insert the legacy records that do not already exist and write the migration marker. If the transaction aborts, there is no marker and the next open retries. If a new database record already exists, preserve it rather than replacing it with an older legacy copy. - ✅ Verify before cleanup. Re-read the copied records and compare their JSON strings with the captured values. Keep the localStorage originals as a recovery copy for the first compatibility release; do not make a failed or partial copy irreversible. A later cleanup can remove a legacy key only when it still matches the value that was successfully imported.
- 🧭 Handle old tabs explicitly. A page running an older app may still write localStorage after a newer page migrated. Listen for changes to recognized legacy room keys, compare them with the current database record, and reload the affected in-memory game rather than silently continuing with stale state. On later starts, surface any remaining mismatched legacy values as recoverable conflicts instead of silently overwriting the database. Keep a legacy value if a conflict or failed import cannot be reconciled.
- 🧹 Retire legacy data only after browser testing. The migration release temporarily uses extra space because both copies exist. Removing old values sooner frees quota faster but narrows rollback and makes a stale-tab race harder to recover from. Keep that cost visible in the Storage panel and make cleanup a follow-up decision based on multi-tab tests.
The copy is scoped to the current origin; values do not move between domination.fun, GitHub Pages, localhost, or browser profiles. A browser upgrade or a different deployment origin is not a migration path.
🧹 Preserve User Control and Clear Semantics
The existing Storage panel can list IndexedDB database names and delete a whole database, but it cannot enumerate records. If room data moves while the panel stays unchanged, players lose the ability to see and clear one room at a time.
- 🧭 Extend inventory to database records. Add a locator for a particular
entrieskey, use the room index to group records, and show approximate per-record size where available. Listing records should degrade to an unavailable-area message if browser APIs fail. - 🗑️ Delete selected records in a read-write transaction. Keep whole-database deletion as an explicit destructive choice. An open page can block that deletion, and deleting the entire database solely to remove one room is too broad.
- 🛡️ Retain the clear-generation guard. The current guard prevents a page from writing in-memory data back after the panel clears it. IndexedDB saves must check the same generation before starting a transaction and return
Supersededwhen stale. Record deletion and generation advancement must be tested together across tabs; a database transaction cannot atomically include a localStorage sentinel. - 📏 Keep quota errors honest. IndexedDB usually has more room than localStorage, not unlimited room. Record the failed key and size, retain
QuotaExceededErroras a distinct failure, and never include the saved payload in diagnostics.
The current panel increments the generation around removals and reloads when deleted state is held in memory. Extending that policy is more work than a database delete, but it prevents the new store from reintroducing the same “cleared, then written back” surprise.
🧪 What the First Vertical Slice Must Prove
- 🧱 Build the FFI spike against the pinned PureScript and Spago versions; compare the relevant cases with
indexed-dbbefore deciding to add a package. - 🔁 Test a new empty database, first migration, repeated migration, a transaction failure before the marker, malformed JSON, unknown localStorage keys, and a pre-existing newer IndexedDB record.
- ↩️ Round-trip a current game, each undo slot, chat, and mailbox metadata. Verify that the paired game-and-undo transaction either commits both records or neither.
- 🧹 Test clearing one room while another tab has an open connection, deleting the entire database while a connection is active, and the clear-generation guard after a record is removed.
- 🌐 Exercise at least two browser tabs with one old writer and one new reader. Confirm that a late localStorage change is surfaced and cannot silently replace a newer database value.
- 📉 Measure database and legacy-copy sizes on representative late-game saves, and test quota rejection.
navigator.storage.estimate()remains an estimate, not guaranteed headroom.
🧭 Recommendation
Ship a narrow room-data migration behind an asynchronous storage capability, with one key/value record per existing room key, a room index for user-controlled cleanup, and a marker committed atomically with the import. Keep small device values in localStorage. Start with a project-owned FFI unless the indexed-db compile spike proves that its upgrade and transaction API fits directly; do not adopt the narrower purescript-idb wrapper unless its limitations are extended deliberately.
The migration is not complete when put succeeds. It is complete when old saves survive a repeatable import, transactions report their true commit status, old tabs cannot silently undo newer data, and the Storage panel can still explain and remove what the app stores. The first implementation should prove those properties before making IndexedDB the only copy.
✍️ Signed
🤖 Designed with care by GitHub Copilot Coding Agent
📅 November 29, 2026
🏠 For bagrounds.org