329 lines
15 KiB
JavaScript
329 lines
15 KiB
JavaScript
/* 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 || {}
|
||
// 2026-12-03(用户裁定):默认 30 并发,设置页可调(1–64);getConcurrency 让改动立即生效。
|
||
const concurrencyOf = () => {
|
||
const v = (typeof d.getConcurrency === 'function') ? d.getConcurrency() : d.concurrency
|
||
return Math.max(1, Math.min(64, Number(v) || 30))
|
||
}
|
||
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,
|
||
progress: e.progress || 0, receivedBytes: e.receivedBytes || 0, totalBytes: e.totalBytes || 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 由 pump 在「决定启动」时同步 +1(见 pump):放在这里会晚一个微任务,
|
||
// pump 的 while 就会在 active 还是 0 时把整个队列一次性放出去(2026-12-03 实测并发限制从未生效)。
|
||
setStatus(e, STATE.DOWNLOADING, { lastError: '', progress: 0, receivedBytes: 0, totalBytes: 0 })
|
||
let lastErr = ''
|
||
// 2026-12-02:下载进度(有 content-length 才算百分比;拿不到就退回「下载中」文案)。
|
||
// 事件节流 250ms —— 每 chunk 都触发会让画布整树重渲染,反而拖慢下载。
|
||
const onProgress = (received, total) => {
|
||
const rcv = Math.max(0, Number(received) || 0)
|
||
const tot = Math.max(0, Number(total) || 0)
|
||
e.receivedBytes = rcv
|
||
e.totalBytes = tot
|
||
e.progress = tot > 0 ? Math.min(1, rcv / tot) : 0
|
||
const t = now()
|
||
e.updatedAt = t
|
||
if (t - (e._progAt || 0) < 250 && !(tot > 0 && rcv >= tot)) return
|
||
e._progAt = t
|
||
emit('progress', publicView(e))
|
||
}
|
||
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||
try {
|
||
const got = typeof d.fetchBytes === 'function' ? await d.fetchBytes(e.url, onProgress) : { 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,
|
||
progress: 1,
|
||
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 < concurrencyOf() && queue.length) {
|
||
const id = queue.shift()
|
||
const e = entries.get(id)
|
||
if (!e || e.status !== STATE.QUEUED) continue
|
||
active++
|
||
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 || exist.status === STATE.LINK_ONLY) 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)
|
||
}
|
||
|
||
// 清空已结束的记录(ready/failed/link-only);进行中的保留(正在下载/排队),避免清掉在飞任务。
|
||
function clearFinished () {
|
||
let n = 0
|
||
for (const [id, e] of Array.from(entries.entries())) {
|
||
if (e.status === STATE.READY || e.status === STATE.FAILED || e.status === STATE.LINK_ONLY) {
|
||
entries.delete(id)
|
||
try { if (typeof d.removeEntry === 'function') d.removeEntry(id) } catch (err) { /* ignore */ }
|
||
n++
|
||
}
|
||
}
|
||
if (n) emit('cleared', { count: n })
|
||
return n
|
||
}
|
||
|
||
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 if (e.status === STATE.LINK_ONLY) e.status = STATE.LINK_ONLY
|
||
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, clearFinished, get, list, stats, restore, markMissing, STATE }
|
||
}
|
||
|
||
// 带进度的取字节:流式读 body,按 content-length 报百分比;拿不到长度就只报已收字节。
|
||
// 失败(CORS/非 2xx/无 body)抛错,交给宿主回退到既有 wBlobFromSrc。
|
||
function blobToDataUrl (blob) {
|
||
return new Promise((resolve) => {
|
||
try {
|
||
const fr = new FileReader()
|
||
fr.onload = () => resolve(String(fr.result || ''))
|
||
fr.onerror = () => resolve('')
|
||
fr.readAsDataURL(blob)
|
||
} catch (e) { resolve('') }
|
||
})
|
||
}
|
||
async function fetchWithProgress (url, onProgress) {
|
||
const res = await fetch(url)
|
||
if (!res || !res.ok) throw new Error('http-' + String((res && res.status) || 'error'))
|
||
const total = Number(res.headers && res.headers.get && res.headers.get('content-length')) || 0
|
||
let blob = null
|
||
if (res.body && typeof res.body.getReader === 'function') {
|
||
const reader = res.body.getReader()
|
||
const chunks = []
|
||
let received = 0
|
||
for (;;) {
|
||
const step = await reader.read()
|
||
if (!step || step.done) break
|
||
if (step.value) { chunks.push(step.value); received += step.value.length || 0 }
|
||
if (typeof onProgress === 'function') onProgress(received, total)
|
||
}
|
||
blob = new Blob(chunks, { type: String((res.headers && res.headers.get && res.headers.get('content-type')) || '') })
|
||
} else {
|
||
blob = await res.blob()
|
||
if (typeof onProgress === 'function') onProgress(blob ? blob.size : 0, total)
|
||
}
|
||
const dataUrl = blob ? await blobToDataUrl(blob) : ''
|
||
if (!dataUrl) return { ok: false, error: 'empty-bytes' }
|
||
return { ok: true, dataUrl, mime: String((blob && blob.type) || ''), bytes: (blob && blob.size) || 0 }
|
||
}
|
||
|
||
// 宿主取字节适配器:流式(带进度)→ 失败回退宿主既有 blob 取法;整体带超时。
|
||
// 放进本模块是为了让 app.js 只留一行装配(Workbench 行数棘轮)。
|
||
function createFetchBytes (deps) {
|
||
const d = deps || {}
|
||
const timeoutMs = Math.max(1000, Number(d.timeoutMs) || 300000)
|
||
return async function fetchBytes (url, onProgress) {
|
||
// 2026-12-03(用户裁定):优先用系统网络栈(Rust reqwest)—— 不受 CORS/WebView 限制,
|
||
// 图床/CDN 对 XHR 的限速、挂起、防盗链都不会再影响下载。拿不到再退回 WebView fetch。
|
||
if (typeof d.rustFetch === 'function') {
|
||
try {
|
||
const r = await d.rustFetch(url)
|
||
if (r && r.ok && r.b64) {
|
||
const mime = String(r.mime || 'application/octet-stream')
|
||
if (typeof onProgress === 'function') onProgress(Number(r.bytes) || 0, Number(r.bytes) || 0)
|
||
return { ok: true, dataUrl: 'data:' + mime + ';base64,' + String(r.b64), mime: mime, bytes: Number(r.bytes) || 0 }
|
||
}
|
||
} catch (eR) { /* 非 Tauri / 命令缺失 → 回退 WebView fetch */ }
|
||
}
|
||
let timer = null
|
||
const job = fetchWithProgress(url, onProgress).catch(async () => {
|
||
const blob = await d.blobFromSrc(url)
|
||
const dataUrl = blob ? await d.blobToDataUrl(blob) : ''
|
||
return dataUrl ? { ok: true, dataUrl, mime: String((blob && blob.type) || '') } : { ok: false, error: 'empty-bytes' }
|
||
})
|
||
const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve({ ok: false, error: 'timeout' }), timeoutMs) })
|
||
try { return await Promise.race([job, timeout]) } catch (e) { return { ok: false, error: String((e && e.message) || 'fetch-failed') } } finally { try { if (timer) clearTimeout(timer) } catch (e2) { /* ignore */ } }
|
||
}
|
||
}
|
||
|
||
global.IWBImageIngest = { create, STATE, fetchWithProgress, createFetchBytes }
|
||
})(typeof window !== 'undefined' ? window : globalThis)
|