Files
image-workbench-desktop/tests/storage-flush-persist-test.js
T

118 lines
5.7 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.
/* storage-flush-persist-test.js —— 「没变化就不写」之后,编辑必须仍然落盘(v3.26.247)
*
* 背景(2026-12-04 回归):244 引入「内容未变不写盘」后,启动那次 flush 变全同步
* (画布不脏 / 库不脏 / data.json 签名相同)。原实现是
* writing = (async () => { ... finally { writing = null } })()
* 函数体没有 await 时 IIFE 同步跑完,finally 先把 writing 置 null,随后赋值又把 writing 写成
* 一个已解决且永不清理的 promise ⇒ 此后每次 flush 都在 if (writing) return writing 处直接返回,
* 整个会话不再写盘(用户实测:画布改动重启后消失)。
*
* 本用例跑真实 src/storage-file.js + 假 Tauri fs(真实临时目录),断言行为:
* ① 启动后编辑画布 → flush → 磁盘文件变化 → 重载(新实例)仍在
* ② 启动(无改动)后连续 flush 两次不把写盘通道卡死
* ③ 非分板键写进 data.json
* ④ 资源库键写进 library/<文件>(含 gallery 新布局)
* ⑤ 一次性维护路径也经由 storage.setItem 标脏(不直写 mem)
*/
'use strict'
const fs = require('node:fs')
const os = require('node:os')
const path = require('node:path')
const assert = require('node:assert')
const SRC = fs.readFileSync(path.join(__dirname, '..', 'src', 'storage-file.js'), 'utf8')
const ROOT = fs.mkdtempSync(path.join(os.tmpdir(), 'iwb-flush-persist-'))
const writeSeed = (rel, text) => {
const abs = path.join(ROOT, rel)
fs.mkdirSync(path.dirname(abs), { recursive: true })
fs.writeFileSync(abs, text)
}
const readFile = (rel) => fs.readFileSync(path.join(ROOT, rel), 'utf8')
const makeFs = () => ({
readTextFile: async (p) => fs.readFileSync(p, 'utf8'),
writeTextFile: async (p, t, o) => {
fs.mkdirSync(path.dirname(p), { recursive: true })
if (o && o.append) fs.appendFileSync(p, t); else fs.writeFileSync(p, t)
},
writeFile: async (p, u8) => { fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, Buffer.from(u8)) },
readFile: async (p) => new Uint8Array(fs.readFileSync(p)),
rename: async (a, b) => { fs.mkdirSync(path.dirname(b), { recursive: true }); fs.renameSync(a, b) },
remove: async (p) => { try { fs.rmSync(p, { recursive: true, force: true }) } catch (e) { /* 不存在 */ } },
mkdir: async (p) => { fs.mkdirSync(p, { recursive: true }) },
exists: async (p) => fs.existsSync(p),
readDir: async (p) => {
if (!fs.existsSync(p)) throw new Error('ENOENT')
return fs.readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, isDirectory: d.isDirectory(), isFile: d.isFile() }))
},
stat: async (p) => fs.statSync(p),
})
// 每个「进程」一个独立 global:模拟重启
const boot = async () => {
const ls = new Map([['iwb.dataDir', ROOT]])
const g = {
__TAURI__: {
core: { invoke: async () => true },
path: { join: async (...p) => path.join(...p.map(String)), documentDir: async () => ROOT },
fs: makeFs(),
},
localStorage: {
getItem: (k) => (ls.has(k) ? ls.get(k) : null),
setItem: (k, v) => ls.set(k, String(v)),
removeItem: (k) => ls.delete(k),
key: (i) => Array.from(ls.keys())[i] || null,
get length() { return ls.size },
},
addEventListener() {},
document: { addEventListener() {}, visibilityState: 'visible' },
setTimeout, clearTimeout, crypto: globalThis.crypto, atob, btoa, console,
}
const load = new Function('window', 'globalThis', SRC + '\nreturn window.IWBStorageFile')
const F = load(g, g)
const ok = await F.ready({ dir: ROOT })
assert.ok(ok, '存储底座应能初始化')
return F
}
;(async () => {
const WS1 = '{"id":"ws1","name":"c1","nodes":[{"id":"n1","type":"text","data":{"text":"hello"}}],"edges":[],"groups":[]}'
writeSeed('canvases/ws1.json', WS1)
writeSeed('data.json', JSON.stringify({ v: 1, keys: {}, assets: {}, small: {} }))
const F1 = await boot()
assert.strictEqual(F1.storage().getItem('iwb_ws_ws1'), WS1, '① 启动应把画布文件读进内存表')
// ② 启动那次 flush 是全同步路径:连续两次不能让写盘通道卡死
await F1.flush()
await F1.flush()
const WS2 = WS1.replace('hello', 'hello-edited')
F1.storage().setItem('iwb_ws_ws1', WS2)
await F1.flush()
assert.ok(readFile('canvases/ws1.json').includes('hello-edited'), '① 画布编辑必须立刻落盘(会被 writing 卡死吞掉)')
F1.storage().setItem('iwb_web_config', '{"x":1}')
await F1.flush()
const data = JSON.parse(readFile('data.json'))
assert.strictEqual(data.keys.iwb_web_config, '{"x":1}', '③ 非分板键应写进 data.json')
writeSeed('library/gallery.json', '[]')
F1.storage().setItem('iwb_web_outputs', '[{"name":"a.png"}]')
await F1.flush()
assert.ok(readFile('library/gallery/index.json').includes('a.png'), '④ 图库清单应写到 library/gallery/index.json')
assert.ok(!fs.existsSync(path.join(ROOT, 'library/gallery.json')), '④ 新布局写成功后应删掉旧的平铺文件')
const F2 = await boot()
assert.ok(String(F2.storage().getItem('iwb_ws_ws1')).includes('hello-edited'), '① 重启后编辑仍在(用户实测的回归点)')
assert.strictEqual(F2.storage().getItem('iwb_web_config'), '{"x":1}', '③ 重启后非分板键仍在')
assert.ok(String(F2.storage().getItem('iwb_web_outputs')).includes('a.png'), '④ 重启后图库清单仍在')
assert.ok(!/mem\['iwb_web_outputs'\]\s*=\s*JSON\.stringify/.test(SRC), '⑤ 维护路径应经 storage.setItem 标脏,不能直写 mem 后 flush')
fs.rmSync(ROOT, { recursive: true, force: true })
console.log('storage-flush-persist: 8 通过 / 0 失败')
})().catch((e) => { console.error('storage-flush-persist FAILED:', e && (e.stack || e.message)); process.exit(1) })