Skip to content

AI-native design editor. Open-source Figma alternative.

refactor(app): standardize IndexedDB access

Danila Poyarkov16b74a2087b2
diff --git a/src/app/storage/idb-util.ts b/src/app/storage/idb-util.ts
deleted file mode 100644
index 9e23296c7..000000000
--- a/src/app/storage/idb-util.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-/** Shared IndexedDB plumbing for the local canvas store and the sync outbox. */
-
-export function openIdb(
- name: string,
- version: number,
- upgrade: (db: IDBDatabase) => void
-): Promise<IDBDatabase> {
- return new Promise((resolve, reject) => {
- if (typeof indexedDB === 'undefined') {
- reject(new Error('IndexedDB is not available'))
- return
- }
- const req = indexedDB.open(name, version)
- req.onerror = () => reject(req.error ?? new Error(`Failed to open ${name}`))
- req.onblocked = () => reject(new Error(`Opening ${name} blocked by another tab's connection`))
- req.onsuccess = () => resolve(req.result)
- req.onupgradeneeded = () => upgrade(req.result)
- })
-}
-
-export function reqToPromise<T>(req: IDBRequest<T>): Promise<T> {
- return new Promise((resolve, reject) => {
- req.onsuccess = () => resolve(req.result)
- req.onerror = () => reject(req.error ?? new Error('IndexedDB request failed'))
- })
-}
-
-export function txDone(tx: IDBTransaction): Promise<void> {
- return new Promise((resolve, reject) => {
- tx.oncomplete = () => resolve()
- tx.onerror = () => reject(tx.error ?? new Error('IndexedDB transaction failed'))
- tx.onabort = () => reject(tx.error ?? new Error('IndexedDB transaction aborted'))
- })
-}
diff --git a/src/app/storage/local-store/idb.ts b/src/app/storage/local-store/idb.ts
index 782723f88..d977fb41c 100644
--- a/src/app/storage/local-store/idb.ts
+++ b/src/app/storage/local-store/idb.ts
@@ -1,4 +1,5 @@
-import { openIdb, reqToPromise, txDone } from '@/app/storage/idb-util'
+import { openDB, type DBSchema, type IDBPDatabase } from 'idb'
+
import { buildIndexMeta, buildWriteMeta, sortAndFilterMetas } from '@/app/storage/local-store/meta'
import type { LocalCanvasStore } from '@/app/storage/local-store/store'
import type { LocalCanvasMeta, LocalCanvasWriteInput } from '@/app/storage/local-store/types'
@@ -6,99 +7,81 @@ import type { LocalCanvasMeta, LocalCanvasWriteInput } from '@/app/storage/local
const DB_NAME = 'open-pencil-cloud-local'
const DB_VERSION = 1
-const STORE_META = 'meta'
-const STORE_FIG = 'fig'
-const STORE_THUMB = 'thumb'
+type StoredBinary = ArrayBuffer | Uint8Array | Blob
-function openDb(): Promise<IDBDatabase> {
- return openIdb(DB_NAME, DB_VERSION, (db) => {
- if (!db.objectStoreNames.contains(STORE_META)) {
- db.createObjectStore(STORE_META, { keyPath: 'id' })
- }
- if (!db.objectStoreNames.contains(STORE_FIG)) {
- db.createObjectStore(STORE_FIG)
- }
- if (!db.objectStoreNames.contains(STORE_THUMB)) {
- db.createObjectStore(STORE_THUMB)
- }
- })
+interface LocalCanvasDatabase extends DBSchema {
+ meta: {
+ key: string
+ value: LocalCanvasMeta
+ }
+ fig: {
+ key: string
+ value: StoredBinary
+ }
+ thumb: {
+ key: string
+ value: StoredBinary
+ }
}
-/** Stored rows may be ArrayBuffer, typed array, or Blob depending on writer/browser. */
-async function rowToBytes(row: unknown): Promise<Uint8Array | null> {
- if (row == null) return null
+/** Stored rows may use older ArrayBuffer/Blob representations. */
+async function storedBinaryToBytes(row: StoredBinary | undefined): Promise<Uint8Array | null> {
+ if (!row) return null
if (row instanceof ArrayBuffer) return new Uint8Array(row)
- if (row instanceof Uint8Array) return new Uint8Array(row)
- if (row instanceof Blob) return new Uint8Array(await row.arrayBuffer())
- return null
+ if (row instanceof Uint8Array) return Uint8Array.from(row)
+ return new Uint8Array(await row.arrayBuffer())
}
-function bytesToBuffer(bytes: Uint8Array) {
- return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
-}
-
-async function readMetaRow(store: IDBObjectStore, id: string): Promise<LocalCanvasMeta | null> {
- return ((await reqToPromise(store.get(id))) as LocalCanvasMeta | undefined) ?? null
+function openDatabase(): Promise<IDBPDatabase<LocalCanvasDatabase>> {
+ return openDB<LocalCanvasDatabase>(DB_NAME, DB_VERSION, {
+ upgrade(database) {
+ if (!database.objectStoreNames.contains('meta')) {
+ database.createObjectStore('meta', { keyPath: 'id' })
+ }
+ if (!database.objectStoreNames.contains('fig')) database.createObjectStore('fig')
+ if (!database.objectStoreNames.contains('thumb')) database.createObjectStore('thumb')
+ }
+ })
}
/** IndexedDB-backed local canvas store (meta + fig/thumb blobs). */
export function createIdbLocalCanvasStore(): LocalCanvasStore {
- let dbPromise: Promise<IDBDatabase> | null = null
-
- function db() {
- if (!dbPromise) dbPromise = openDb()
- return dbPromise
- }
+ const database = openDatabase()
- async function readBlob(storeName: string, id: string): Promise<Uint8Array | null> {
- const database = await db()
- const tx = database.transaction(storeName, 'readonly')
- const row = await reqToPromise(tx.objectStore(storeName).get(id))
- await txDone(tx)
- return rowToBytes(row)
+ async function readBinary(storeName: 'fig' | 'thumb', id: string): Promise<Uint8Array | null> {
+ return storedBinaryToBytes(await (await database).get(storeName, id))
}
return {
async listMetas(includeTombstones = false) {
- const database = await db()
- const tx = database.transaction(STORE_META, 'readonly')
- const all = (await reqToPromise(tx.objectStore(STORE_META).getAll())) as LocalCanvasMeta[]
- await txDone(tx)
- return sortAndFilterMetas(all, includeTombstones)
+ return sortAndFilterMetas(await (await database).getAll('meta'), includeTombstones)
},
async getMeta(id: string) {
- const database = await db()
- const tx = database.transaction(STORE_META, 'readonly')
- const row = (await reqToPromise(tx.objectStore(STORE_META).get(id))) as
- | LocalCanvasMeta
- | undefined
- await txDone(tx)
- return row ?? null
+ return (await (await database).get('meta', id)) ?? null
},
async readFig(id: string) {
- return readBlob(STORE_FIG, id)
+ return readBinary('fig', id)
},
async readThumb(id: string) {
- return readBlob(STORE_THUMB, id)
+ return readBinary('thumb', id)
},
async writeCanvas(input: LocalCanvasWriteInput) {
- const database = await db()
- const tx = database.transaction([STORE_META, STORE_FIG, STORE_THUMB], 'readwrite')
- const figStore = tx.objectStore(STORE_FIG)
- const thumbStore = tx.objectStore(STORE_THUMB)
- const metaStore = tx.objectStore(STORE_META)
- const existing = await readMetaRow(metaStore, input.id)
+ const transaction = (await database).transaction(['meta', 'fig', 'thumb'], 'readwrite')
+ const figStore = transaction.objectStore('fig')
+ const thumbStore = transaction.objectStore('thumb')
+ const metaStore = transaction.objectStore('meta')
+ const existing = (await metaStore.get(input.id)) ?? null
let hasThumb = existing?.hasThumb ?? false
- figStore.put(bytesToBuffer(input.figBytes), input.id)
+ figStore.put(Uint8Array.from(input.figBytes), input.id)
if (input.thumbBytes != null) {
if (input.thumbBytes.byteLength > 0) {
- thumbStore.put(bytesToBuffer(input.thumbBytes), input.id)
+ thumbStore.put(Uint8Array.from(input.thumbBytes), input.id)
hasThumb = true
} else {
thumbStore.delete(input.id)
@@ -108,57 +91,51 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {
const meta = buildWriteMeta(input, existing, hasThumb)
metaStore.put(meta)
- await txDone(tx)
+ await transaction.done
return meta
},
async upsertIndexMeta(input) {
- const database = await db()
- const tx = database.transaction(STORE_META, 'readwrite')
- const store = tx.objectStore(STORE_META)
- const existing = await readMetaRow(store, input.id)
+ const transaction = (await database).transaction('meta', 'readwrite')
+ const store = transaction.objectStore('meta')
+ const existing = (await store.get(input.id)) ?? null
const meta = buildIndexMeta(input, existing)
store.put(meta)
- await txDone(tx)
+ await transaction.done
return meta
},
async writeThumb(id: string, thumbBytes: Uint8Array) {
- const database = await db()
- const tx = database.transaction([STORE_META, STORE_THUMB], 'readwrite')
- const metaStore = tx.objectStore(STORE_META)
- const existing = await readMetaRow(metaStore, id)
+ const transaction = (await database).transaction(['meta', 'thumb'], 'readwrite')
+ const metaStore = transaction.objectStore('meta')
+ const existing = await metaStore.get(id)
if (!existing) {
- await txDone(tx)
+ await transaction.done
return null
}
- tx.objectStore(STORE_THUMB).put(bytesToBuffer(thumbBytes), id)
+ transaction.objectStore('thumb').put(Uint8Array.from(thumbBytes), id)
// Thumb freshness is tracked by its own outbox job — never demote the
// document's syncStatus here (it orphaned rows as 'pending' forever).
- const meta: LocalCanvasMeta = {
- ...existing,
- hasThumb: true
- }
+ const meta: LocalCanvasMeta = { ...existing, hasThumb: true }
metaStore.put(meta)
- await txDone(tx)
+ await transaction.done
return meta
},
async updateMeta(id: string, patch: Partial<LocalCanvasMeta>, options) {
- const database = await db()
- const tx = database.transaction(STORE_META, 'readwrite')
- const store = tx.objectStore(STORE_META)
- const existing = await readMetaRow(store, id)
+ const transaction = (await database).transaction('meta', 'readwrite')
+ const store = transaction.objectStore('meta')
+ const existing = await store.get(id)
if (
!existing ||
(options?.expectedRevision != null && existing.revision !== options.expectedRevision)
) {
- await txDone(tx)
+ await transaction.done
return null
}
const next = { ...existing, ...patch, id: existing.id }
store.put(next)
- await txDone(tx)
+ await transaction.done
return next
},
@@ -171,37 +148,34 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {
},
async clearFig(id: string) {
- const database = await db()
- const tx = database.transaction([STORE_META, STORE_FIG], 'readwrite')
- const metaStore = tx.objectStore(STORE_META)
- const existing = await readMetaRow(metaStore, id)
+ const transaction = (await database).transaction(['meta', 'fig'], 'readwrite')
+ const metaStore = transaction.objectStore('meta')
+ const existing = await metaStore.get(id)
if (!existing) {
- await txDone(tx)
+ await transaction.done
return null
}
- tx.objectStore(STORE_FIG).delete(id)
+ transaction.objectStore('fig').delete(id)
const meta: LocalCanvasMeta = { ...existing, hasFig: false, figSize: 0 }
metaStore.put(meta)
- await txDone(tx)
+ await transaction.done
return meta
},
async remove(id: string) {
- const database = await db()
- const tx = database.transaction([STORE_META, STORE_FIG, STORE_THUMB], 'readwrite')
- tx.objectStore(STORE_META).delete(id)
- tx.objectStore(STORE_FIG).delete(id)
- tx.objectStore(STORE_THUMB).delete(id)
- await txDone(tx)
+ const transaction = (await database).transaction(['meta', 'fig', 'thumb'], 'readwrite')
+ transaction.objectStore('meta').delete(id)
+ transaction.objectStore('fig').delete(id)
+ transaction.objectStore('thumb').delete(id)
+ await transaction.done
},
async clearAll() {
- const database = await db()
- const tx = database.transaction([STORE_META, STORE_FIG, STORE_THUMB], 'readwrite')
- tx.objectStore(STORE_META).clear()
- tx.objectStore(STORE_FIG).clear()
- tx.objectStore(STORE_THUMB).clear()
- await txDone(tx)
+ const transaction = (await database).transaction(['meta', 'fig', 'thumb'], 'readwrite')
+ transaction.objectStore('meta').clear()
+ transaction.objectStore('fig').clear()
+ transaction.objectStore('thumb').clear()
+ await transaction.done
}
}
}
diff --git a/src/app/storage/sync/outbox.ts b/src/app/storage/sync/outbox.ts
index 13971d294..b079176d8 100644
--- a/src/app/storage/sync/outbox.ts
+++ b/src/app/storage/sync/outbox.ts
@@ -1,10 +1,18 @@
-import { openIdb, reqToPromise, txDone } from '@/app/storage/idb-util'
+import { openDB, type DBSchema } from 'idb'
+
import { makeJobId, supersedePutCanvasJobs, type OutboxJob } from '@/app/storage/sync/types'
const DB_NAME = 'open-pencil-cloud-outbox'
const DB_VERSION = 1
const STORE = 'jobs'
+interface OutboxDatabase extends DBSchema {
+ jobs: {
+ key: string
+ value: OutboxJob
+ }
+}
+
export type OutboxEnqueueInput = Omit<
OutboxJob,
'id' | 'createdAt' | 'attempts' | 'nextAttemptAt'
@@ -22,10 +30,12 @@ export type Outbox = {
clear(): Promise<void>
}
-function openDb(): Promise<IDBDatabase> {
- return openIdb(DB_NAME, DB_VERSION, (db) => {
- if (!db.objectStoreNames.contains(STORE)) {
- db.createObjectStore(STORE, { keyPath: 'id' })
+function openDatabase() {
+ return openDB<OutboxDatabase>(DB_NAME, DB_VERSION, {
+ upgrade(database) {
+ if (!database.objectStoreNames.contains(STORE)) {
+ database.createObjectStore(STORE, { keyPath: 'id' })
+ }
}
})
}
@@ -52,7 +62,8 @@ function withJobQueued(queue: OutboxJob[], job: OutboxJob): OutboxJob[] {
next = supersedePutCanvasJobs(next, job.canvasId, job.revision)
}
next = next.filter(
- (j) => !(j.canvasId === job.canvasId && j.type === job.type && j.type !== 'putCanvas')
+ (queued) =>
+ !(queued.canvasId === job.canvasId && queued.type === job.type && queued.type !== 'putCanvas')
)
return [...next, job]
}
@@ -62,7 +73,7 @@ export function createMemoryOutbox(): Outbox {
return {
async list() {
- return [...jobs].sort((a, b) => a.createdAt - b.createdAt)
+ return [...jobs].sort((left, right) => left.createdAt - right.createdAt)
},
async enqueue(partial) {
const job = buildJob(partial)
@@ -70,10 +81,10 @@ export function createMemoryOutbox(): Outbox {
return job
},
async update(job) {
- jobs = jobs.map((j) => (j.id === job.id ? job : j))
+ jobs = jobs.map((queued) => (queued.id === job.id ? job : queued))
},
async remove(id) {
- jobs = jobs.filter((j) => j.id !== id)
+ jobs = jobs.filter((job) => job.id !== id)
},
async clear() {
jobs = []
@@ -82,57 +93,40 @@ export function createMemoryOutbox(): Outbox {
}
export function createIdbOutbox(): Outbox {
- let dbPromise: Promise<IDBDatabase> | null = null
- function db() {
- if (!dbPromise) dbPromise = openDb()
- return dbPromise
- }
+ const database = openDatabase()
return {
async list() {
- const database = await db()
- const tx = database.transaction(STORE, 'readonly')
- const all = (await reqToPromise(tx.objectStore(STORE).getAll())) as OutboxJob[]
- await txDone(tx)
- return all.sort((a, b) => a.createdAt - b.createdAt)
+ const all = await (await database).getAll(STORE)
+ return all.sort((left, right) => left.createdAt - right.createdAt)
},
async enqueue(partial) {
const job = buildJob(partial)
// Read and write in ONE transaction so concurrent enqueues can't compute
// supersession from the same stale snapshot (duplicate/stale jobs).
- const database = await db()
- const tx = database.transaction(STORE, 'readwrite')
- const store = tx.objectStore(STORE)
- const existing = (await reqToPromise(store.getAll())) as OutboxJob[]
+ const transaction = (await database).transaction(STORE, 'readwrite')
+ const store = transaction.objectStore(STORE)
+ const existing = await store.getAll()
const next = withJobQueued(existing, job)
- for (const j of existing) {
- if (!next.some((n) => n.id === j.id)) store.delete(j.id)
+ for (const queued of existing) {
+ if (!next.some((candidate) => candidate.id === queued.id)) store.delete(queued.id)
}
store.put(job)
- await txDone(tx)
+ await transaction.done
return job
},
async update(job) {
- const database = await db()
- const tx = database.transaction(STORE, 'readwrite')
- tx.objectStore(STORE).put(job)
- await txDone(tx)
+ await (await database).put(STORE, job)
},
async remove(id) {
- const database = await db()
- const tx = database.transaction(STORE, 'readwrite')
- tx.objectStore(STORE).delete(id)
- await txDone(tx)
+ await (await database).delete(STORE, id)
},
async clear() {
- const database = await db()
- const tx = database.transaction(STORE, 'readwrite')
- tx.objectStore(STORE).clear()
- await txDone(tx)
+ await (await database).clear(STORE)
}
}
}