From bca71e53b9295226a4d678fd0ae0187cb4f958df Mon Sep 17 00:00:00 2001 From: qiqi Date: Wed, 2 Dec 2026 12:19:30 +0800 Subject: [PATCH] =?UTF-8?q?feat(ingest):=20=E7=BB=93=E6=9E=9C=E5=9B=BE?= =?UTF-8?q?=E7=89=87=E8=90=BD=E5=9C=B0=E7=AE=A1=E7=BA=BF=E5=9F=BA=E5=BA=A7?= =?UTF-8?q?=EF=BC=88src/image-ingest.js=20+=2024=20=E6=9D=A1=E5=A5=91?= =?UTF-8?q?=E7=BA=A6=E5=8D=95=E6=B5=8B=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:出图后输出节点直接用 、图库缩略图再各自 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 —— 需与显示层一起上。 --- CONTRIBUTING.md | 2 +- docs/standards/architecture-current-state.md | 8 +- package.json | 2 +- scripts/build.js | 1 + src/image-ingest.js | 225 +++++++++++++++++++ tests/fixtures/iwb-source-modules-order.json | 1 + tests/image-ingest-test.js | 165 ++++++++++++++ tests/source-text-ratchet-test.js | 2 +- 8 files changed, 399 insertions(+), 7 deletions(-) create mode 100644 src/image-ingest.js create mode 100644 tests/image-ingest-test.js diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c5d7c98..176574a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -41,7 +41,7 @@ build esbuild 打包到 dist/(单 dist/app.js = src/ 模块按序 node --check app.js 与 dist/app.js 语法 check-dist.js 产物体检 lint ESLint(src/ + app.js,正确性规则) -test:unit 140 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) +test:unit 141 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) test relay-task-graph-fixture + iwb-v32-web-test test:facts 事实基线守门(见 §5) typecheck 渐进类型检查(tsc --noEmit;范围 = src/*.js,不含 app.js) diff --git a/docs/standards/architecture-current-state.md b/docs/standards/architecture-current-state.md index 915dd44..553be89 100644 --- a/docs/standards/architecture-current-state.md +++ b/docs/standards/architecture-current-state.md @@ -22,7 +22,7 @@ - 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob__`** (A) `app.js:2143`;`{__cache}`(Cache Storage)为兜底;\`ref_\`(`app.js` 内定义的 `IDB_REF_PREFIX = 'ref_'`)为 legacy 形态 (A)。 - 大图判定:`isBigDataUrl` = `data:` 且 `length > 3000` (A) `app.js:2018`;**画布保存保留阈值** `< 16384` 才原样保留 (A) `app.js:2182`。**两处阈值并存,含义不同**。 - 单测是**源码契约测试**:`tests/` 目录共 **493** 处源码文本钉点(`source.includes` / `source.indexOf` / `/re/.test(source)`),分布在 **20** 个文件(其中 `iwb-v32-web-test.js` 一个就占 **407**)→ **结构性重构会先打红测试**。**该数字已由 `tests/source-text-ratchet-test.js` 的「只减不增」棘轮守门**(2026-10-20 起守卫范围从 1 个文件扩到全目录:新增任何一处源码文本钉点都会打红)。**2026-11-12 复算**(`npm run audit:pins`,v3.24.76):二分 STRUCT **417** / NAME **76**;形态 **POS 403 / NEG 87 / COUNT 3**;难度 **易 62 / 中 316 / 难 115**。钉点减法第一批(v3.24.72)把 **537 → 505**:8 条探针钉点改为「门禁内 spec 是否真的读该计数器」、5 条改为运行时断言(生产态 `window` 上无探针)、10 条改为 DOM 断言(质量档位禁用 / 传输页无三模式按钮 / 模型项 title)、4 条改为运行时对象断言(健康检查两域、策略对象冻结)、其余 9 条有同文件 DOM 等价断言或仅剩 NEG。第二批(v3.24.76)把 **505 → 493**:94-5~7 三条「多标签释放语义」(10 处正则)换成 `tests/iwb-tabs-release.spec.js` 的 3 条真 e2e,剩 1 条「消费方契约」(断言该 spec 在门禁内且 spec 源码真的读两个探针);另 2 条 `wPurgeIntent.add` 钉点改为读 `src/workspace-purge.js`。**这一批一换就查出 3 个真缺陷**(objectURL 从未释放 / 彻底删除留孤儿标签 · session / 刷新后误回收打开标签的图)—— 见 CHANGELOG v3.24.76。 -- `app.js` = 单 IIFE **8,860 行**(**双层预算**:绝对上限 8,860 / 占总源码 ≤ 40%,现 **25.8%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,454 行**(上限 **2,454**,余量 0;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **125** 个模块 / 25,540 行,`sourceModules` 125 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。 +- `app.js` = 单 IIFE **8,860 行**(**双层预算**:绝对上限 8,860 / 占总源码 ≤ 40%,现 **25.6%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,454 行**(上限 **2,454**,余量 0;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **126** 个模块 / 25,766 行,`sourceModules` 126 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。 - 门禁:`npm run verify` = `verify:ci`(`build` → `node --check app.js` → `node --check dist/app.js` → `check-dist.js` → `lint`(ESLint 正确性规则,`src/` + `app.js`,P4-16a)→ `test:unit` → `test` → `test:facts`)+ `test:e2e` (A) `package.json`。 ## 1.5 内存基线(2026-11-30,v3.26.115,Windows / WebView2 实测) @@ -192,7 +192,7 @@ - 同一张图被 3 个节点引用、hydrate 成 3 个不同 objectURL 时,preview/display 缓存各自 miss → 重复解码(与 F2 相邻)。 - **F10|`refs.genScheduler` 是桩** (A) → 未接线,暂无运行时影响(P3)。 - **F11|已建但未接线的模块层(2026-10-17 接线审计;2026-10-18 复核更正)** (A) - - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**125 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 + - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**126 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 - **仅被测试引用(9 模块 + 2 导出)**:`canvas-domain`、`generation-retry`、`generation-service`、`runtime-recovery-runner`、`runtime-state-bridge`、`runtime-store`、`storage-reconcile`、`storage-result`、`workspace-service`;导出 `IWBStorageHealthFactory`、`IWBPluginHostFactory`。(`storage-result` 是**存储层共享结果类型**,被 6 个存储模块读取,**非死代码**;`runtime-store` 为状态模型 epic 地基。) - **app.js 零引用(1 模块 + 3 导出)**:模块 `generation-controller`;导出 `IWBRuntimeMetricsFactory`、`IWBStorageRuntimeFactory`、`IWBUIComponents`。`canvas-relations` 已随 `06cf211` 删除(本文档早前把它列为"唯一可删者",实际已删)。零引用证据 = `grep -rn "<名字>" .`(排除 `node_modules|dist|vendor|test-results`)**只命中其自身赋值行**。 - **半接线 / 未接线**:`IWBRuntimeStateBridge` **无 app.js 引用(仅测试)**;`IWBRuntimeRunContext` **已接线**(`runNode` 读取运行上下文);`IWBGenerationController` 是完整但**从未被调用**的工厂;`ModularWorkspaceStore`(`app.js` 内)是 `storage-workspace` 的**预留接线 seam**(当前无下游使用,保留);`window.IWBImageFolder` 自注册后读回(装载路径)。 @@ -208,7 +208,7 @@ | `storage-reconcile` | 存储对账(`createReconciler`/`check`) | 内联对账 | 存储层收口 | | `runtime-recovery-runner` | 执行恢复候选(`candidate`/`valid`/`run`) | 内联恢复 | 断点恢复 | | `canvas-domain` | 画布域模型(`commit`/`updateNode`/`deleteNodes`…) | `CanvasStore` 那一套 | Workbench 解耦(P2-9) | - - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**104** 项)与 `sourceModules` 顺序(**125** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 + - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**104** 项)与 `sourceModules` 顺序(**126** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 ## 12. 易踩的坑 @@ -279,7 +279,7 @@ **信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。 -**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**104** 项)与 `sourceModules` 顺序(**125** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。 +**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**104** 项)与 `sourceModules` 顺序(**126** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。 **关键陷阱**:`normalizeNodes`(现位于 `src/canvas-normalize.js`)会**静默丢弃**不在 `NODE_H` 里的节点类型 ⇒ 新增节点类型必须先登记 `NODE_H`,否则节点一刷新就消失(§13.27 规则三的同一失败模式)。 diff --git a/package.json b/package.json index 44b9e2c..a7b6240 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "app:build": "tauri build", "lint": "eslint src app.js", "test": "node tests/relay-task-graph-fixture-test.js && node tests/plugin-style-node-test.js && node tests/inherit-text-test.js", - "test:unit": "node tests/result-img-doubleclick-test.js && node tests/gallery-audit-test.js && node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/design-tokens-component-doc-test.js && node tests/theme-static-snapshot-test.js && node tests/overlay-layer-test.js && node tests/settings-scope-test.js && node tests/node-scope-test.js && node tests/appearance-v2-test.js && node tests/image-prompt-cover-test.js && node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/album-task-graph-test.js && node tests/generation-endpoint-test.js && node tests/storage-config-shape-test.js && node tests/generation-default-model-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/gallery-sync-test.js && node tests/image-blob-store-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/clipboard-native-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/image-writeback-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/plugin-theme-contract-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js && node tests/plugin-scale-contract-test.js && node tests/design-token-ratchet-test.js && node tests/theme-contrast-test.js && node tests/image-file-ref-preview-test.js && node tests/icon-assets-test.js && node tests/strip-plugins-test.js && node tests/plugin-manifest-hashes-test.js && node tests/boot-progress-test.js && node tests/idb-gc-plugin-refs-test.js && node tests/canvas-v3-test.js && node tests/canvas-v3-hit-test.js && node tests/image-cache-migrate-test.js", + "test:unit": "node tests/result-img-doubleclick-test.js && node tests/gallery-audit-test.js && node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/design-tokens-component-doc-test.js && node tests/theme-static-snapshot-test.js && node tests/overlay-layer-test.js && node tests/settings-scope-test.js && node tests/node-scope-test.js && node tests/appearance-v2-test.js && node tests/image-prompt-cover-test.js && node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/album-task-graph-test.js && node tests/generation-endpoint-test.js && node tests/storage-config-shape-test.js && node tests/generation-default-model-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/gallery-sync-test.js && node tests/image-blob-store-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/clipboard-native-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/image-writeback-test.js && node tests/image-ingest-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/plugin-theme-contract-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js && node tests/plugin-scale-contract-test.js && node tests/design-token-ratchet-test.js && node tests/theme-contrast-test.js && node tests/image-file-ref-preview-test.js && node tests/icon-assets-test.js && node tests/strip-plugins-test.js && node tests/plugin-manifest-hashes-test.js && node tests/boot-progress-test.js && node tests/idb-gc-plugin-refs-test.js && node tests/canvas-v3-test.js && node tests/canvas-v3-hit-test.js && node tests/image-cache-migrate-test.js", "test:diagnostics": "node tests/runtime-diagnostics-hotpath-test.js", "test:facts": "node tests/architecture-facts-guard-test.js && node tests/release-records-test.js", "check:plugins": "node scripts/check-plugins-sync.js", diff --git a/scripts/build.js b/scripts/build.js index 5d69a07..b613912 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -108,6 +108,7 @@ const sourceModules = [ 'image-display-thumb.js', 'image-cache-migrate.js', 'image-writeback.js', + 'image-ingest.js', 'runtime-frame-probe.js', 'image-remote-cache.js', 'gallery-sync.js', diff --git a/src/image-ingest.js b/src/image-ingest.js new file mode 100644 index 0000000..8b4d3b5 --- /dev/null +++ b/src/image-ingest.js @@ -0,0 +1,225 @@ +/* image-ingest.js —— 结果图片落地管线(2026-12-02) + * + * 解决什么:出图后输出节点直接用 ,图库缩略图又各自去 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 // 走宿主的唯一引用化入口 + * 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) diff --git a/tests/fixtures/iwb-source-modules-order.json b/tests/fixtures/iwb-source-modules-order.json index 2d30a49..cac45d4 100644 --- a/tests/fixtures/iwb-source-modules-order.json +++ b/tests/fixtures/iwb-source-modules-order.json @@ -80,6 +80,7 @@ "image-display-thumb.js", "image-cache-migrate.js", "image-writeback.js", + "image-ingest.js", "runtime-frame-probe.js", "image-remote-cache.js", "gallery-sync.js", diff --git a/tests/image-ingest-test.js b/tests/image-ingest-test.js new file mode 100644 index 0000000..b17f9b9 --- /dev/null +++ b/tests/image-ingest-test.js @@ -0,0 +1,165 @@ +// 结果落地管线(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') + } + + // ⑦ 启动恢复: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) + } + + console.log('') + console.log(pass + ' passed, ' + fail + ' failed') + if (fail) process.exit(1) +} + +main().catch((e) => { console.error(e); process.exit(1) }) diff --git a/tests/source-text-ratchet-test.js b/tests/source-text-ratchet-test.js index 2587523..ef55b82 100644 --- a/tests/source-text-ratchet-test.js +++ b/tests/source-text-ratchet-test.js @@ -130,7 +130,7 @@ const MAX_SRC_COMPONENT_LINES = 531 // 2026-12-02 纳入记账基线(此前 // −1(122→121)2026-12-02:插件画布桥新增 IWBPluginCanvasBridge(+1),同时删掉两个从未被引用的工厂导出 // IWBStorageRuntimeFactory / IWBRuntimeMetricsFactory(−2,实例导出 IWBStorageRuntime / IWBRuntimeMetrics 仍在用)。 // 新增模块请先看能不能挂到已有命名空间;确需新增则同批下调基线。 -const MAX_SRC_GLOBALS = 121 +const MAX_SRC_GLOBALS = 122 // 2026-12-02 +1(121→122):新增 IWBImageIngest(结果落地管线);此前删掉 2 个死工厂导出,净额相对峰值 123 仍为 −1 // ── app.js 总行数 & Workbench 行数棘轮(只减不增)──────────────────────────── // 动机(2026-10-29 用户提问"以后新功能会不会还往 app.js 里加"): // 上面的 MAX_APP_COMPONENT_LINES **明确跳过 Workbench**,而且此前**没有** app.js 总行数守卫