Files
image-workbench-desktop/tests/image-ingest-test.js
T
qiqi 2ff1ccd2d1
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 48s
feat(download): 走系统网络栈(Rust)+并发默认30可调;修并发限制从未生效
2026-12-03 17:29:48 +08:00

216 lines
9.3 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.
// 结果落地管线(src/image-ingest.js)契约测试 —— 2026-12-02
// 钉住的都是「会真丢图 / 会真重复下载」的点:幂等、重试、失败保留 url、恢复、释放。
'use strict'
const fs = require('fs')
const path = require('path')
const src = fs.readFileSync(path.join(__dirname, '..', 'src', 'image-ingest.js'), 'utf8')
const box = {}
new Function('window', 'globalThis', src)(box, box)
let pass = 0, fail = 0
const ok = (name, cond, extra) => {
if (cond) { pass++; console.log(' ✅ ' + name) } else { fail++; console.log(' ❌ ' + name + (extra !== undefined ? ' → ' + JSON.stringify(extra) : '')) }
}
const tick = () => new Promise((r) => setTimeout(r, 5))
async function until (fn, ms) {
const end = Date.now() + (ms || 1000)
while (Date.now() < end) { if (fn()) return true; await tick() }
return false
}
function make (opts) {
const o = opts || {}
const st = { fetched: [], written: [], persisted: [], events: [], maxActive: 0, active: 0 }
let attempt = 0
const ingest = box.IWBImageIngest.create({
concurrency: o.concurrency || 2,
retries: o.retries === undefined ? 3 : o.retries,
sleep: async () => {}, // 测试里不真等退避
now: () => 1000,
fetchBytes: async (url) => {
st.fetched.push(url)
st.active++
st.maxActive = Math.max(st.maxActive, st.active)
try {
if (o.failTimes && st.fetched.length <= o.failTimes) return { ok: false, error: 'net-' + st.fetched.length }
if (o.alwaysFail) return { ok: false, error: 'net-down' }
return { ok: true, dataUrl: 'data:image/png;base64,AAAA', bytes: 1234, mime: 'image/png' }
} finally { st.active-- }
},
writeRef: async (dataUrl) => { st.written.push(dataUrl); return { __blob: 'b' + st.written.length } },
persist: (e) => st.persisted.push(e.id + ':' + e.status),
onEvent: (k) => st.events.push(k),
removeEntry: () => {},
})
return { ingest, st }
}
async function main () {
// ① 正常落地
{
const { ingest, st } = make()
const e = ingest.enqueue({ url: 'https://cdn/x.png', source: 'gen', w: 1024, h: 1024 })
ok('①-1 入队立刻可见(queued)', !!ingest.get(e.id) && ingest.get(e.id).status === 'queued')
await until(() => ingest.get(e.id).status === 'ready')
const r = ingest.get(e.id)
ok('①-2 落地后 ready + ref + bytes', r.status === 'ready' && !!r.ref && r.bytes === 1234, r)
ok('①-3 只下载一次、只写一次引用', st.fetched.length === 1 && st.written.length === 1, { f: st.fetched.length, w: st.written.length })
ok('①-4 状态变化被持久化', st.persisted.indexOf(e.id + ':ready') >= 0, st.persisted)
}
// ② 幂等:同 url 再入队不重复下载
{
const { ingest, st } = make()
const a = ingest.enqueue({ url: 'https://cdn/y.png' })
await until(() => ingest.get(a.id).status === 'ready')
const b = ingest.enqueue({ url: 'https://cdn/y.png' })
await tick()
ok('②-1 同 url 复用同一条记录', a.id === b.id)
ok('②-2 没有第二次下载', st.fetched.length === 1, st.fetched.length)
ok('②-3 重复 enqueue 不会把 ready 打回 queued', ingest.get(a.id).status === 'ready')
}
// ③ 重试:失败两次后成功
{
const { ingest } = make({ failTimes: 2 })
const e = ingest.enqueue({ url: 'https://cdn/retry.png' })
await until(() => ingest.get(e.id).status === 'ready')
const r = ingest.get(e.id)
ok('③-1 第 3 次成功后 ready', r.status === 'ready', r.status)
ok('③-2 重试次数如实记录', r.retries === 2, r.retries)
ok('③-3 成功后清空 lastError', r.lastError === '', r.lastError)
}
// ④ 彻底失败:保留 url、可重试
{
const { ingest } = make({ alwaysFail: true, retries: 2 })
const e = ingest.enqueue({ url: 'https://cdn/bad.png' })
await until(() => ingest.get(e.id).status === 'failed', 2000)
const r = ingest.get(e.id)
ok('④-1 重试用尽后 failed', r.status === 'failed', r.status)
ok('④-2 原始 url 原样保留(不丢图)', r.url === 'https://cdn/bad.png')
ok('④-3 带可读错误', /net-down/.test(r.lastError), r.lastError)
ok('④-4 记录仍在列表里', ingest.list().length === 1)
}
// ⑤ 失败后手动 retry 能恢复
{
const { ingest } = make({ alwaysFail: true, retries: 1 })
const e = ingest.enqueue({ url: 'https://cdn/later.png' })
await until(() => ingest.get(e.id).status === 'failed', 2000)
const again = ingest.retry(e.id)
ok('⑤-1 retry 复位为 queued', !!again && again.retries === 0)
}
// ⑥ 释放字节(仅保留链接)
{
const { ingest } = make()
const e = ingest.enqueue({ url: 'https://cdn/rel.png' })
await until(() => ingest.get(e.id).status === 'ready')
const r = ingest.release(e.id)
ok('⑥-1 变为 link-only', r.status === 'link-only')
ok('⑥-2 引用被清空但 url 保留', r.ref === null && r.url === 'https://cdn/rel.png')
// 任务队列「下载」会再次 enqueue 同 url:link-only 必须回到 queued(否则永远不下)
const again = ingest.enqueue({ url: 'https://cdn/rel.png' })
ok('⑥-3 link-only 再次 enqueue → queued', again && again.status === 'queued', again && again.status)
await until(() => ingest.get(e.id).status === 'ready', 2000)
}
// ⑦ 启动恢复:downloading/queued 重排,ready 保持
{
const { ingest, st } = make()
ingest.restore([
{ id: 'a', url: 'https://cdn/a.png', status: 'downloading', createdAt: 1, updatedAt: 1 },
{ id: 'b', url: 'https://cdn/b.png', status: 'queued', createdAt: 1, updatedAt: 1 },
{ id: 'c', url: 'https://cdn/c.png', status: 'ready', ref: { __blob: 'x' }, createdAt: 1, updatedAt: 1 },
{ id: 'd', url: 'https://cdn/d.png', status: 'failed', lastError: 'net', createdAt: 1, updatedAt: 1 },
])
ok('⑦-1 failed 不被自动重排', ingest.get('d').status === 'failed')
ok('⑦-2 ready 保持 ready', ingest.get('c').status === 'ready')
await until(() => ingest.get('a').status === 'ready' && ingest.get('b').status === 'ready')
ok('⑦-3 downloading/queued 恢复后自动跑完', ingest.get('a').status === 'ready' && ingest.get('b').status === 'ready')
}
// ⑧ 取消排队中的
{
const { ingest } = make({ concurrency: 1 })
ingest.enqueue({ url: 'https://cdn/busy.png' })
const q = ingest.enqueue({ url: 'https://cdn/wait.png' })
ingest.cancel(q.id)
ok('⑧-1 排队中被取消 → link-only', ingest.get(q.id).status === 'link-only', ingest.get(q.id).status)
}
// ⑨ 并发上限
{
const { ingest, st } = make({ concurrency: 2 })
for (let i = 0; i < 6; i++) ingest.enqueue({ url: 'https://cdn/c' + i + '.png' })
await until(() => ingest.stats().ready === 6, 3000)
ok('⑨-1 6 条全部落地', ingest.stats().ready === 6, ingest.stats())
ok('⑨-2 同时下载不超过 2 路', st.maxActive <= 2, st.maxActive)
}
// ⑩ 统计
{
const { ingest } = make()
const a = ingest.enqueue({ url: 'https://cdn/s1.png' })
await until(() => ingest.get(a.id).status === 'ready')
ingest.enqueue({ url: 'https://cdn/s2.png' })
await tick()
const s = ingest.stats()
ok('⑩-1 total/ready/queued 计数正确', s.total === 2 && s.ready >= 1, s)
}
// ⑪ 下载优先走系统网络栈(Rust);失败/不可用才回退 WebView fetch
{
let rustCalls = 0
const fb = box.IWBImageIngest.createFetchBytes({
rustFetch: async () => { rustCalls++; return { ok: true, mime: 'image/png', bytes: 3, b64: 'AAA' } },
blobFromSrc: async () => null,
blobToDataUrl: async () => '',
})
const r = await fb('https://cdn/rust.png', () => {})
ok('⑪-1 rustFetch 成功 → dataUrl + bytes', r.ok && r.dataUrl === 'data:image/png;base64,AAA' && r.bytes === 3 && rustCalls === 1, r)
const fb2 = box.IWBImageIngest.createFetchBytes({
rustFetch: async () => ({ ok: false, error: 'http-403' }),
blobFromSrc: async () => ({ size: 1 }),
blobToDataUrl: async () => 'data:image/png;base64,BB',
})
const r2 = await fb2('https://cdn/fallback.png', () => {})
ok('⑪-2 rustFetch 失败 → 回退宿主取字节', r2.ok && r2.dataUrl === 'data:image/png;base64,BB', r2)
}
// ⑫ 并发数走 getConcurrency(默认 30,设置页可调)
{
let release = null
const gate = new Promise((r) => { release = r })
let active = 0, maxActive = 0
const ing = box.IWBImageIngest.create({
getConcurrency: () => 3,
retries: 0,
sleep: async () => {},
now: () => 1000,
fetchBytes: async () => {
active++; maxActive = Math.max(maxActive, active)
await gate
active--
return { ok: true, dataUrl: 'data:image/png;base64,AA', bytes: 1, mime: 'image/png' }
},
writeRef: async () => ({ __blob: 'b' }),
persist: () => {}, onEvent: () => {}, removeEntry: () => {},
})
for (let i = 0; i < 5; i++) ing.enqueue({ url: 'https://cdn/g' + i + '.png' })
await until(() => maxActive === 3, 500)
ok('⑫-1 同时下载按 getConcurrency 生效(3 路)', maxActive === 3, maxActive)
release()
await until(() => ing.stats().ready === 5, 1500)
ok('⑫-2 释放后 5 条全部完成', ing.stats().ready === 5, ing.stats())
}
console.log('')
console.log(pass + ' passed, ' + fail + ' failed')
if (fail) process.exit(1)
}
main().catch((e) => { console.error(e); process.exit(1) })