fix: use singleton IndexedDB connection to prevent blocking

Replaced open/close-per-operation pattern with a single persistent
connection held for the app lifetime. This prevents the DB upgrade
(v1→v2) from being blocked by lingering connections, and eliminates
transaction contention.

Also added onblocked handler that surfaces a clear error instead of
hanging indefinitely.
This commit is contained in:
2026-08-01 18:52:12 +08:00
parent a7697fd4a1
commit 97e294f1d6
3 changed files with 75 additions and 87 deletions
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -5,7 +5,7 @@
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MJPEG Stream Viewer</title>
<script type="module" crossorigin src="/assets/index-CW6NDYF0.js"></script>
<script type="module" crossorigin src="/assets/index-B6qcBY8r.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-BTgh_FTp.css">
</head>
<body>
+73 -85
View File
@@ -1,15 +1,12 @@
/**
* IndexedDB wrapper for storing MJPEG recordings.
* IndexedDB wrapper — singleton connection, never closed during app lifetime.
*
* All frames are packed into a single Blob (binary format) so that
* IndexedDB writes one object per recording — fast and reliable.
* All frames packed into a single Blob per recording to avoid
* multi-blob transaction issues.
*
* Binary format inside `data` Blob:
* [4 bytes BE: uint32 frameCount]
* For each frame:
* [4 bytes BE: uint32 timestamp (ms)]
* [4 bytes BE: uint32 jpegDataLength]
* [jpegDataLength bytes: JPEG]
* Binary format inside `data`:
* [4B BE uint32 frameCount]
* Per frame: [4B BE uint32 timestamp] [4B BE uint32 jpegLen] [JPEG bytes]
*/
export interface Frame {
@@ -23,7 +20,6 @@ export interface Recording {
createdAt: Date
duration: number
frameCount: number
/** Packed binary: all frames + timing in a single Blob */
data: Blob
}
@@ -31,113 +27,114 @@ const DB_NAME = 'mjpeg-viewer'
const DB_VERSION = 2
const STORE_NAME = 'recordings'
// ---- Singleton connection ----
let db: IDBDatabase | null = null
let dbPromise: Promise<IDBDatabase> | null = null
function getDB(): Promise<IDBDatabase> {
if (db) return Promise.resolve(db)
if (dbPromise) return dbPromise
dbPromise = new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION)
request.onupgradeneeded = () => {
const d = request.result
if (d.objectStoreNames.contains(STORE_NAME)) {
d.deleteObjectStore(STORE_NAME)
}
d.createObjectStore(STORE_NAME, { keyPath: 'id' })
}
request.onsuccess = () => {
db = request.result
// If connection is lost (browser closes it), reset
db.onclose = () => {
db = null
dbPromise = null
}
resolve(db)
}
request.onerror = () => {
dbPromise = null
reject(request.error)
}
request.onblocked = () => {
// A previous connection is still open — this shouldn't happen
// with singleton pattern, but if it does, reject to trigger retry
dbPromise = null
reject(new Error('Database blocked by another connection'))
}
})
return dbPromise
}
// ---- Binary pack / unpack ----
export function packFrames(frames: { timestamp: number; blob: Blob }[]): Blob {
const headerSize = 4 // frameCount
let totalSize = headerSize
const parts: ArrayBuffer[] = []
const countBuf = new ArrayBuffer(4)
new DataView(countBuf).setUint32(0, frames.length)
totalSize += countBuf.byteLength
for (const f of frames) {
const tsBuf = new ArrayBuffer(4)
new DataView(tsBuf).setUint32(0, f.timestamp)
const lenBuf = new ArrayBuffer(4)
new DataView(lenBuf).setUint32(0, f.blob.size)
parts.push(tsBuf, lenBuf)
totalSize += 8 + f.blob.size
}
// Build header + index, then append blob data
const headerAndIndex = new ArrayBuffer(totalSize)
const view = new DataView(headerAndIndex)
const headerSize = 4 + frames.length * 8
const header = new ArrayBuffer(headerSize)
const view = new DataView(header)
view.setUint32(0, frames.length)
let offset = 4
const parts: BlobPart[] = [header]
for (const f of frames) {
view.setUint32(offset, f.timestamp)
view.setUint32(offset + 4, f.blob.size)
offset += 8
parts.push(f.blob)
}
// Now build the final blob: header/index + all JPEG data
const allParts: BlobPart[] = [headerAndIndex]
for (const f of frames) {
allParts.push(f.blob)
}
return new Blob(allParts, { type: 'application/octet-stream' })
return new Blob(parts, { type: 'application/octet-stream' })
}
export async function unpackFrames(data: Blob): Promise<Frame[]> {
const buf = await data.arrayBuffer()
const view = new DataView(buf)
const frameCount = view.getUint32(0)
let offset = 4
const frames: Frame[] = []
let offset = 4
for (let i = 0; i < frameCount; i++) {
const timestamp = view.getUint32(offset)
const jpegLen = view.getUint32(offset + 4)
offset += 8
const jpegData = buf.slice(offset, offset + jpegLen)
frames.push({
timestamp,
blob: new Blob([jpegData], { type: 'image/jpeg' }),
blob: new Blob([buf.slice(offset, offset + jpegLen)], { type: 'image/jpeg' }),
})
offset += jpegLen
}
return frames
}
// ---- IndexedDB ----
function openDB(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION)
request.onupgradeneeded = () => {
const db = request.result
if (db.objectStoreNames.contains(STORE_NAME)) {
db.deleteObjectStore(STORE_NAME)
}
db.createObjectStore(STORE_NAME, { keyPath: 'id' })
}
request.onsuccess = () => resolve(request.result)
request.onerror = () => reject(request.error)
})
}
// ---- CRUD ----
export async function saveRecording(recording: Recording): Promise<void> {
const db = await openDB()
const d = await getDB()
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, 'readwrite')
const tx = d.transaction(STORE_NAME, 'readwrite')
const store = tx.objectStore(STORE_NAME)
store.put({
...recording,
createdAt: recording.createdAt.toISOString(),
})
tx.oncomplete = () => {
db.close()
resolve()
}
tx.onerror = () => {
db.close()
reject(tx.error)
}
tx.oncomplete = () => resolve()
tx.onerror = () => reject(tx.error)
tx.onabort = () => reject(new Error('Transaction aborted'))
})
}
export async function getAllRecordings(): Promise<Recording[]> {
const db = await openDB()
const d = await getDB()
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, 'readonly')
const tx = d.transaction(STORE_NAME, 'readonly')
const store = tx.objectStore(STORE_NAME)
const request = store.getAll()
request.onsuccess = () => {
db.close()
const results = (request.result || []).map((r: any) => ({
...r,
createdAt: new Date(r.createdAt),
@@ -145,26 +142,17 @@ export async function getAllRecordings(): Promise<Recording[]> {
results.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
resolve(results)
}
request.onerror = () => {
db.close()
reject(request.error)
}
request.onerror = () => reject(request.error)
})
}
export async function deleteRecording(id: string): Promise<void> {
const db = await openDB()
const d = await getDB()
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, 'readwrite')
const tx = d.transaction(STORE_NAME, 'readwrite')
const store = tx.objectStore(STORE_NAME)
store.delete(id)
tx.oncomplete = () => {
db.close()
resolve()
}
tx.onerror = () => {
db.close()
reject(tx.error)
}
tx.oncomplete = () => resolve()
tx.onerror = () => reject(tx.error)
})
}