Files
image-workbench-desktop/src/storage-health.js
T

213 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
;(function (global) {
'use strict'
const statuses = ['unknown', 'checking', 'healthy', 'degraded', 'unavailable', 'blocked']
function now() { return Date.now() }
function makeEntry() { return { status: 'unknown', lastCheckedAt: 0, error: null, degraded: false } }
// 存储体检(只读):对「IDB 键 + 图库索引」做一致性计数,**不删任何东西**。
// 暴露悬空索引(索引有条目但字节已没 —— 正是 clear() 先删字节后清索引的形态)与孤儿输出字节。
function audit(input) {
const data = input || {}
const idbKeys = Array.isArray(data.idbKeys) ? data.idbKeys : []
const outputs = Array.isArray(data.outputsIndex) ? data.outputsIndex : []
const p = data.prefixes || {}
const P = { blob: String(p.blob || 'imgblob_'), ref: String(p.ref || 'ref_'), out: String(p.out || 'out_'), orig: String(p.orig || 'out_orig_') }
const keySet = new Set()
const counts = { total: idbKeys.length, blob: 0, ref: 0, out: 0, orig: 0, other: 0 }
for (const raw of idbKeys) {
const s = String(raw); keySet.add(s)
if (P.blob && s.indexOf(P.blob) === 0) counts.blob++
else if (P.orig && s.indexOf(P.orig) === 0) counts.orig++
else if (P.out && s.indexOf(P.out) === 0) counts.out++
else if (P.ref && s.indexOf(P.ref) === 0) counts.ref++
else counts.other++
}
const referenced = new Set()
let danglingOutputIndex = 0
for (const it of outputs) {
if (!it) continue
for (const f of ['idb', 'origIdb']) {
const k = it[f] ? String(it[f]) : ''
if (!k) continue
referenced.add(k)
if (!keySet.has(k)) danglingOutputIndex++
}
}
let orphanOutputBytes = 0
for (const raw of idbKeys) {
const s = String(raw)
const isOut = (P.out && s.indexOf(P.out) === 0) || (P.orig && s.indexOf(P.orig) === 0)
if (isOut && !referenced.has(s)) orphanOutputBytes++
}
return { total: counts.total, counts, danglingOutputIndex, orphanOutputBytes, outputsIndexSize: outputs.length }
}
function createHealth(options) {
const opt = options || {}
// 与 StorageContract.indexedDb 保持同源:探测用的库名/版本/表清单必须和应用完全一致,
// 否则探测自己就会建出结构不完整的库(见下方 onupgradeneeded 注释)。
const contract = opt.contract || (global.IWBStorageContract && global.IWBStorageContract.indexedDb) || null
const dbName = opt.databaseName || (contract && contract.name) || 'iwb_web'
const dbVersion = Number(opt.version) || Number(contract && contract.version) || 3
const dbStores = Array.isArray(opt.stores)
? opt.stores.slice()
: ((contract && Array.isArray(contract.stores)) ? contract.stores.slice() : ['images', 'logs', 'kv'])
const state = {
localStorage: makeEntry(),
indexedDB: makeEntry(),
workspace: makeEntry(),
groups: makeEntry(),
outputs: makeEntry(),
// 持久化存储(2026-11-07):默认非持久 = 浏览器空间紧张时**可被直接清掉**。
// 记录 unknown/granted/denied/unsupported 四种结果,仅供诊断展示,不影响主流程。
persist: { status: 'unknown', askedAt: 0, error: null }
}
const listeners = []
function notify() {
const snapshot = get()
// 订阅者回调抛错此前被**静默吞掉**:一个订阅者的失败既不通知它自己,也不让其他
// 订阅者知道 ⇒ 健康状态变化时可能"没人收到通知",而现场毫无线索。
// 现在逐个隔离并留痕(CrashLog 是 src/runtime-crash-log.js 导出的模块化接口,
// 非 app.js 的 window 全局 ⇒ 不违反 §11.2 反向依赖边界)。
listeners.slice().forEach((listener, i) => {
try {
listener(snapshot)
} catch (e) {
try {
const cl = global.IWBCrashLog
if (cl && typeof cl.record === 'function') {
cl.record('storage-health-listener-error', {
scope: 'storage-health',
message: '健康状态订阅者 #' + i + ' 抛错:' + String((e && e.message) || e),
})
}
} catch (err) { /* ignore */ }
}
})
}
function set(name, patch) {
if (!state[name]) return get()
const next = patch || {}
const status = statuses.indexOf(next.status) >= 0 ? next.status : state[name].status
Object.assign(state[name], next, { status, lastCheckedAt: next.lastCheckedAt || now() })
state[name].degraded = status === 'degraded' || status === 'unavailable' || status === 'blocked'
notify()
return get()
}
function get() {
const result = {}
Object.keys(state).forEach((name) => { result[name] = Object.assign({}, state[name]) })
result.ok = Object.keys(state).every((name) => !state[name].degraded)
result.checkedAt = Math.max.apply(null, Object.keys(state).map((name) => state[name].lastCheckedAt))
return result
}
function subscribe(listener) {
if (typeof listener !== 'function') return function () {}
listeners.push(listener)
return function () { const index = listeners.indexOf(listener); if (index >= 0) listeners.splice(index, 1) }
}
async function check() {
set('localStorage', { status: 'checking', error: null })
set('indexedDB', { status: 'checking', error: null })
let localOk = false
try {
const storage = Object.prototype.hasOwnProperty.call(opt, 'localStorage') ? opt.localStorage : global.localStorage
if (!storage) throw new Error('localStorage unavailable')
const key = '__iwb_health__'
storage.setItem(key, '1')
localOk = storage.getItem(key) === '1'
storage.removeItem(key)
} catch (error) {
set('localStorage', { status: 'unavailable', error: error.message || String(error) })
}
if (localOk) set('localStorage', { status: 'healthy', error: null })
let idbOk = false
let idbMissing = null
try {
const idb = Object.prototype.hasOwnProperty.call(opt, 'indexedDB') ? opt.indexedDB : global.indexedDB
if (!idb) throw new Error('indexedDB unavailable')
if (typeof idb.open !== 'function') throw new Error('indexedDB unsupported')
await new Promise((resolve, reject) => {
let request
try { request = idb.open(dbName, dbVersion) } catch (error) { reject(error); return }
// 关键:探测本身也必须负责建表。否则在全新 profile 上探测会抢先建出
// 「version 正确但零 object store」的库;之后应用以同一版本 open 永远不会再触发
// onupgradeneeded,IndexedDB 路径(大图持久化)就永久不可用且无法自愈。
request.onupgradeneeded = () => {
const database = request.result
if (!database || typeof database.createObjectStore !== 'function') return
for (const store of dbStores) {
try {
const names = database.objectStoreNames
if (!names || typeof names.contains !== 'function' || !names.contains(store)) database.createObjectStore(store)
} catch (e) { /* ignore */ }
}
}
request.onsuccess = () => resolve(request.result)
request.onerror = () => reject(request.error || new Error('indexedDB open failed'))
}).then((db) => {
try {
// 历史版本探测可能已经把库建成空壳:此时不能谎报健康,否则大图持久化会静默失败。
if (db && db.objectStoreNames && typeof db.objectStoreNames.contains === 'function') {
const missing = dbStores.filter((store) => !db.objectStoreNames.contains(store))
if (missing.length) idbMissing = missing
}
} finally { try { if (db && typeof db.close === 'function') db.close() } catch (e) { /* 清理失败无害:连接由 GC 回收 */ } }
})
idbOk = true
} catch (error) {
set('indexedDB', { status: 'unavailable', error: error.message || String(error) })
}
if (idbOk && idbMissing) set('indexedDB', { status: 'degraded', error: 'IndexedDB 缺少数据表:' + /** @type {any} */ (idbMissing).join('、') + '(大图将无法持久化,请清空本地数据后重试)' })
else if (idbOk) set('indexedDB', { status: 'healthy', error: null })
return get()
}
function markDomain(name, result) {
const failed = result && result.ok === false
return set(name, { status: failed ? (result.degraded ? 'degraded' : 'unavailable') : 'healthy', error: failed ? result.error || null : null })
}
// 请求「持久化存储」(2026-11-07)
// 语义:persist 成功后浏览器不会因"空间紧张"自行驱逐本域数据(仍可被用户手动清除)。
// 注意:Chrome 按站点参与度决定是否授予 —— 拒绝是**正常结果**,不弹窗、不打扰,只记状态。
// 同一浏览器会话内只问一次;已持久化则直接返回。
async function requestPersistent() {
const s = state.persist
if (s.status === 'granted' || s.status === 'unsupported') return { status: s.status }
const nav = global.navigator
const storage = nav && nav.storage
if (!storage || typeof storage.persist !== 'function') {
state.persist = { status: 'unsupported', askedAt: now(), error: null }
return { status: 'unsupported' }
}
try {
if (typeof storage.persisted === 'function' && await storage.persisted()) {
state.persist = { status: 'granted', askedAt: now(), error: null }
return { status: 'granted' }
}
const granted = await storage.persist()
state.persist = { status: granted ? 'granted' : 'denied', askedAt: now(), error: granted ? null : '浏览器未授予(可用度/安装状态不足)' }
return { status: state.persist.status, error: state.persist.error }
} catch (e) {
state.persist = { status: 'denied', askedAt: now(), error: String((e && e.message) || e) }
return { status: 'denied', error: state.persist.error }
}
}
// 已用/配额(用于诊断展示;浏览器不支持时返回 null)
async function estimate() {
const nav = global.navigator
const storage = nav && nav.storage
if (!storage || typeof storage.estimate !== 'function') return null
try {
const e2 = await storage.estimate()
return { usage: Number(e2 && e2.usage) || 0, quota: Number(e2 && e2.quota) || 0 }
} catch (e) { return null }
}
return { get, set, subscribe, check, markDomain, requestPersistent, estimate, audit }
}
global.IWBStorageHealthFactory = createHealth
global.IWBStorageHealth = createHealth()
})(typeof window !== 'undefined' ? window : globalThis)