feat(ingest): 结果图片落地管线基座(src/image-ingest.js + 24 条契约单测)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 58s
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 58s
背景:出图后输出节点直接用 <img src=远程CDN>、图库缩略图再各自 fetch 一次, CDN 慢/断流时就是「从上往下慢慢刷 / 卡住半张」,图库还晚一步。 先把「远程结果 → 本地字节」收敛成一条队列,本次只落基座,不接线(零行为变化)。 - src/image-ingest.js:状态机 queued/downloading/ready/failed/link-only; 幂等(同 url 复用记录)、重试 1s/2s/4s×3、并发 ≤2、失败保留 url、 释放字节(link-only)、启动恢复(queued/downloading 重排)、markMissing 自检入口。 依赖全注入(fetchBytes/writeRef/persist/onEvent/sleep),不读任何全局,便于单测。 - tests/image-ingest-test.js:24 条断言(正常落地/幂等/重试成功/彻底失败/manual retry/ 释放/恢复/取消/并发上限/统计),已进 test:unit。 - 注册:build.js 顺序 + 模块顺序快照 + 耦合面快照;global 写入口 121→122(单列命名空间)。 下一步(未做):接线到出图结果与图库、节点改吃本地副本、失败/进度 UI —— 需与显示层一起上。
This commit is contained in:
1 parent
200c1d35b1
commit
bca71e53b9
8 files changed
+399
-7
No files matched your search
@@ -0,0 +1,225 @@
|
||||
/* image-ingest.js —— 结果图片落地管线(2026-12-02)
|
||||
*
|
||||
* 解决什么:出图后输出节点直接用 <img src=远程CDN>,图库缩略图又各自去 fetch 一遍;
|
||||
* CDN 慢/断流时表现为「图片从上往下慢慢刷 / 卡住半张」,图库还晚一步才出现。
|
||||
* 这里把「远程结果 → 本地字节」收敛成一条队列:下载一次,节点/图库/队列页共用。
|
||||
*
|
||||
* 设计约束:
|
||||
* · 幂等:同一条记录重复 enqueue 不会重复下载(按 id 去重;id 缺省用 url 的稳定 hash)
|
||||
* · 不丢图:原始 url 永远保留在 entry 上;失败只改状态,不删记录
|
||||
* · 可恢复:状态由宿主持久化(deps.persist),启动时用 restore() 把 queued/downloading 重排
|
||||
* · 原子:先写字节再置 ready;写失败保持 failed,可重试
|
||||
* · 可关:宿主不接线就是不启用(本模块自身不读任何全局)
|
||||
*
|
||||
* 依赖全部注入(便于单测):
|
||||
* fetchBytes(url) -> Promise<{ ok, dataUrl?, bytes?, mime?, error? }>
|
||||
* writeRef(dataUrl)-> Promise<ref|null> // 走宿主的唯一引用化入口
|
||||
* persist(entry) -> void // 状态变化时持久化
|
||||
* onEvent(kind, entry) -> void // 进度节流事件(宿主用来刷新 UI)
|
||||
* now() -> number
|
||||
* sleep(ms) -> Promise // 测试可注入
|
||||
* concurrency -> number(默认 2)
|
||||
* retries -> number(默认 3)
|
||||
*/
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
|
||||
const STATE = { QUEUED: 'queued', DOWNLOADING: 'downloading', READY: 'ready', FAILED: 'failed', LINK_ONLY: 'link-only' }
|
||||
|
||||
function create (deps) {
|
||||
const d = deps || {}
|
||||
const concurrency = Math.max(1, Number(d.concurrency) || 2)
|
||||
const maxRetries = Math.max(0, Number(d.retries) || 3)
|
||||
const now = typeof d.now === 'function' ? d.now : () => Date.now()
|
||||
const sleep = typeof d.sleep === 'function' ? d.sleep : (ms) => new Promise((r) => setTimeout(r, ms))
|
||||
const entries = new Map() // id -> entry
|
||||
const queue = [] // 待下载 id
|
||||
let active = 0
|
||||
let seq = 0
|
||||
|
||||
const uid = () => 'ing_' + now().toString(36) + '_' + (++seq)
|
||||
function hash (s) {
|
||||
let h = 5381
|
||||
const str = String(s || '')
|
||||
for (let i = 0; i < str.length; i++) h = ((h * 33) ^ str.charCodeAt(i)) >>> 0
|
||||
return h.toString(36)
|
||||
}
|
||||
const emit = (kind, e) => { try { if (typeof d.onEvent === 'function') d.onEvent(kind, e) } catch (err) { /* ignore */ } }
|
||||
const persist = (e) => { try { if (typeof d.persist === 'function') d.persist(e) } catch (err) { /* ignore */ } }
|
||||
|
||||
function publicView (e) {
|
||||
return {
|
||||
id: e.id, url: e.url, source: e.source, status: e.status,
|
||||
bytes: e.bytes || 0, mime: e.mime || '', w: e.w || 0, h: e.h || 0,
|
||||
ref: e.ref || null, displayRef: e.displayRef || null, thumbRef: e.thumbRef || null,
|
||||
retries: e.retries || 0, lastError: e.lastError || '', requestId: e.requestId || '',
|
||||
createdAt: e.createdAt, updatedAt: e.updatedAt, meta: e.meta || {},
|
||||
}
|
||||
}
|
||||
|
||||
function get (id) { const e = entries.get(id); return e ? publicView(e) : null }
|
||||
function list () { return [...entries.values()].map(publicView) }
|
||||
function stats () {
|
||||
const out = { total: 0, queued: 0, downloading: 0, ready: 0, failed: 0, linkOnly: 0, active: 0 }
|
||||
for (const e of entries.values()) {
|
||||
out.total++
|
||||
if (e.status === STATE.QUEUED) out.queued++
|
||||
else if (e.status === STATE.DOWNLOADING) out.downloading++
|
||||
else if (e.status === STATE.READY) out.ready++
|
||||
else if (e.status === STATE.FAILED) out.failed++
|
||||
else if (e.status === STATE.LINK_ONLY) out.linkOnly++
|
||||
}
|
||||
out.active = active
|
||||
return out
|
||||
}
|
||||
|
||||
function setStatus (e, status, patch) {
|
||||
e.status = status
|
||||
e.updatedAt = now()
|
||||
if (patch) Object.assign(e, patch)
|
||||
persist(publicView(e))
|
||||
emit(status, publicView(e))
|
||||
}
|
||||
|
||||
async function runOne (e) {
|
||||
active++
|
||||
setStatus(e, STATE.DOWNLOADING, { lastError: '' })
|
||||
let lastErr = ''
|
||||
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
const got = typeof d.fetchBytes === 'function' ? await d.fetchBytes(e.url) : { ok: false, error: 'no-fetcher' }
|
||||
if (!got || !got.ok || !got.dataUrl) throw new Error((got && got.error) || 'fetch-failed')
|
||||
const ref = typeof d.writeRef === 'function' ? await d.writeRef(got.dataUrl) : null
|
||||
if (!ref) throw new Error('write-ref-failed')
|
||||
active--
|
||||
setStatus(e, STATE.READY, {
|
||||
ref,
|
||||
bytes: Number(got.bytes || 0) || Math.round(String(got.dataUrl).length * 0.75),
|
||||
mime: String(got.mime || ''),
|
||||
w: Number(got.w || 0) || e.w || 0,
|
||||
h: Number(got.h || 0) || e.h || 0,
|
||||
retries: attempt,
|
||||
lastError: '',
|
||||
})
|
||||
pump()
|
||||
return publicView(e)
|
||||
} catch (err) {
|
||||
lastErr = (err && err.message) ? err.message : String(err)
|
||||
if (attempt < maxRetries) {
|
||||
setStatus(e, STATE.DOWNLOADING, { retries: attempt + 1, lastError: lastErr })
|
||||
await sleep(Math.min(8000, 1000 * Math.pow(2, attempt)))
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
active--
|
||||
setStatus(e, STATE.FAILED, { retries: maxRetries, lastError: lastErr })
|
||||
pump()
|
||||
return publicView(e)
|
||||
}
|
||||
|
||||
function pump () {
|
||||
while (active < concurrency && queue.length) {
|
||||
const id = queue.shift()
|
||||
const e = entries.get(id)
|
||||
if (!e || e.status !== STATE.QUEUED) continue
|
||||
Promise.resolve().then(() => runOne(e))
|
||||
}
|
||||
}
|
||||
|
||||
// 入队:同一 url 已存在(且未失败)则直接返回旧记录,避免重复下载
|
||||
function enqueue (input) {
|
||||
const src = input || {}
|
||||
const url = String(src.url || '')
|
||||
if (!url) return null
|
||||
const id = String(src.id || ('u_' + hash(url)))
|
||||
const exist = entries.get(id)
|
||||
if (exist) {
|
||||
if (exist.status === STATE.FAILED) return retry(id)
|
||||
return publicView(exist)
|
||||
}
|
||||
const e = {
|
||||
id,
|
||||
url,
|
||||
source: String(src.source || 'gen'),
|
||||
status: STATE.QUEUED,
|
||||
bytes: 0, mime: '', w: Number(src.w || 0), h: Number(src.h || 0),
|
||||
ref: null, displayRef: null, thumbRef: null,
|
||||
retries: 0, lastError: '', requestId: String(src.requestId || ''),
|
||||
createdAt: now(), updatedAt: now(), meta: src.meta || {},
|
||||
}
|
||||
entries.set(id, e)
|
||||
queue.push(id)
|
||||
persist(publicView(e))
|
||||
emit(STATE.QUEUED, publicView(e))
|
||||
pump()
|
||||
return publicView(e)
|
||||
}
|
||||
|
||||
// 重试:复位状态重新排队(失败记录不删,url 保留)
|
||||
function retry (id) {
|
||||
const e = entries.get(id)
|
||||
if (!e) return null
|
||||
e.retries = 0
|
||||
setStatus(e, STATE.QUEUED, { lastError: '' })
|
||||
queue.push(id)
|
||||
pump()
|
||||
return publicView(e)
|
||||
}
|
||||
|
||||
// 取消:仅对排队中/下载中有效;字节未落地的记录回到 queued 之外的状态由宿主任意处理
|
||||
function cancel (id) {
|
||||
const e = entries.get(id)
|
||||
if (!e) return null
|
||||
const at = queue.indexOf(id)
|
||||
if (at >= 0) queue.splice(at, 1)
|
||||
if (e.status === STATE.QUEUED || e.status === STATE.DOWNLOADING) setStatus(e, STATE.LINK_ONLY, { lastError: 'cancelled' })
|
||||
return publicView(e)
|
||||
}
|
||||
|
||||
// 释放本地字节,保留记录与 url(「仅保留链接」)
|
||||
function release (id) {
|
||||
const e = entries.get(id)
|
||||
if (!e) return null
|
||||
setStatus(e, STATE.LINK_ONLY, { ref: null, displayRef: null, thumbRef: null })
|
||||
return publicView(e)
|
||||
}
|
||||
|
||||
function remove (id) {
|
||||
const at = queue.indexOf(id)
|
||||
if (at >= 0) queue.splice(at, 1)
|
||||
entries.delete(id)
|
||||
try { if (typeof d.removeEntry === 'function') d.removeEntry(id) } catch (e) { /* ignore */ }
|
||||
emit('removed', { id })
|
||||
return true
|
||||
}
|
||||
|
||||
// 启动恢复:queued / downloading 重新排队;ready 但宿主说字节不在了 → missing(keep url)
|
||||
function restore (saved) {
|
||||
const arr = Array.isArray(saved) ? saved : []
|
||||
for (const raw of arr) {
|
||||
if (!raw || !raw.id || !raw.url) continue
|
||||
const e = Object.assign({}, raw, { meta: raw.meta || {} })
|
||||
if (e.status === STATE.READY) e.status = STATE.READY
|
||||
else if (e.status === STATE.FAILED) e.status = STATE.FAILED
|
||||
else e.status = STATE.QUEUED
|
||||
entries.set(e.id, e)
|
||||
if (e.status === STATE.QUEUED) queue.push(e.id)
|
||||
}
|
||||
pump()
|
||||
return stats()
|
||||
}
|
||||
|
||||
// 宿主自检回调:索引是 ready 但字节读不出来 → 标 missing(仍保留 url,可 retry)
|
||||
function markMissing (id, reason) {
|
||||
const e = entries.get(id)
|
||||
if (!e) return null
|
||||
setStatus(e, STATE.FAILED, { lastError: String(reason || 'missing-bytes'), ref: null, displayRef: null })
|
||||
return publicView(e)
|
||||
}
|
||||
|
||||
return { enqueue, retry, cancel, release, remove, get, list, stats, restore, markMissing, STATE }
|
||||
}
|
||||
|
||||
global.IWBImageIngest = { create, STATE }
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
Reference in new issue
Block a user