merge fix/file-tree-perf into dev(文件树:折叠链预加载与渲染共用 32 链上限;fs.trees 整批共享一个探测预算)
This commit is contained in:
commit
e45b45e2b5
11 files changed
+466
-34
No files matched your search
@@ -139,4 +139,4 @@
|
||||
- **测试不得依赖非普适二进制**:CI 跑 ubuntu + windows 两个 runner,`rg` / `fd` / `jq` 这类「开发机上有」的工具在 runner 上没有,代价是整个 spec 在**收集阶段**失败(`spawnSync rg ENOENT`)而本地永远绿——上一版的 `tests/primitives-exports.spec.ts` 就这么让分支红了两轮。取文件清单用 `readdirSync` 自己走,或只用 `git` / `tar` / `pnpm` / node 内置能力;确需外部工具时先探测存在性并跳过。
|
||||
- **测试 fixture 的文件名必须两个平台都合法**:Windows 上 `*` `?` `:` `"` `<` `>` `|` 不能出现在文件名里,`writeFileSync(join(tmp, 'a*b.ts'))` 会直接 `ENOENT`(本次 `tests/search-engines.spec.ts` 的真实引擎用例就这么红在 Windows lane 上,macOS 永远绿)。要验证「元字符按字面处理」就换一个**两平台都合法**的良构元字符(win32 用 `a[b]`,POSIX 用 `a*b`),**不要**用未闭合的 `a[b`——rg 对未转义的 `[` 报 `unclosed character class` 并退出,引擎被判 broken 后回退普通遍历,断言会被兜底路径**意外满足**,判别力归零。
|
||||
- **按「入参平台」推导路径的函数必须用同方言的 `node:path`**:`bundledRgCandidates(platform, …)` 这类函数若用宿主的 `sep` / `dirname` / `join`,在不同 OS 上就是不同的函数——Windows runner 上 `endsWith('\\node_modules')` 永不命中 POSIX 起始路径,整条走查产不出候选,而本地(macOS)永远绿。按 `platform` 选 `posix` / `win32`,让输出只依赖入参,测试也才能跨方言断言(`posix.join` / `win32.join`)。
|
||||
- **关键测试守护**:`tests/service.spec.ts` / `builtins.spec.ts`(注册表与内置清单:**6 tab + 4 viewer**——右列终端与浏览器已交还宿主,只读预览也按 §3.2 第 5 条让出,只剩 markdown / html / jsonl(v0.26.0 新增,逐行 JSON 记录预览 + 可保存编辑)/ code;第 6 个 tab 是 `terminal-bottom`(#774,`bottomOnly`,只投插件自己的底部工作台))/ `market-manifest.spec.ts`(市场约束,含 `pnpm pack` 后的产物面)/ `manifest-consistency.spec.ts`(registry 通道形状)/ `e2e-host-protocol.spec.ts`(RPC 双协议)/ `native-surface.spec.ts`(原生右侧栏承载面:guide 条目 id 唯一性、以及 `canOpen` 的「拒绝清单不得宽于宿主渲染器」双向边界)/ `native-registration.spec.ts`(原生 tab 注册生命周期:`files` 接管不得被通知拆建、注册失败必须回滚已占用的 id 与已建槽位、`bottomOnly` 描述符**不产生任何原生注册**(tab 类型 / slot / guide 条目,#774——此前只有挂载 lane 抓得住);断言写在注册表的事件日志上)/ `file-open-claim.spec.ts`(文件打开的认领判定:插件一切文件入口先问 `sidebarRightTabs.candidates`,被第三方认领的文件改走 `openResource`,无人认领/无注册表/探测抛错逐字保持 editor 原路径——#695,PR #696 移植;`editor-host.spec.tsx` 另钉合并模式原地切换同样让位)/ `theme.spec.ts`(皮肤契约,含空白面板胶囊几何)/ `plugin-list.spec.ts`(推荐插件目录)/ `fs-search.spec.ts`(host 文件名搜索,含 `explorerExclude` 排除探针:匹配条目不出现也不下钻)/ `fs-watch.spec.ts`(文件树目录 watch 的去抖、句柄上限与错误路径)/ `exclude-patterns.spec.ts` / `fs-tree-exclude.spec.ts` / `fs-tree-compact.spec.ts` / `file-tree-compact.spec.ts` / `file-tree-compact-fold.spec.tsx`(资源管理器排除模式与面包屑折叠:glob 子集编译器及其**缓存身份**——host 目录缓存按「路径 + 行额 + 模式集身份」分键,改排除列表即换键;`compact` 单目录链的 host 标记、client 折叠/整链开关与折叠链预加载)/ `smoke.spec.ts` 的 settings 段(按 entry id 读写表单、**一次性 legacy 迁移**、open 工具门控——其 GET 走真 `node:http`,因为字节路由现在要真 Writable,且必须 `closeAllConnections` 否则 undici 的 keep-alive 会把用例拖过超时)/ `file-stream-route.spec.ts`(字节路由流式化:`open` 成功后才 `writeHead`,所以不可读文件仍是 4xx JSON 信封;流中途失败走 `writeJson` 的 `headersSent` 守卫而不是 `ERR_HTTP_HEADERS_SENT`)/ `fs-read-page.spec.ts`(分页读取:按行对齐、超长单行不裁空、EOF 精确,以及**只锁宽字符编码**这一条:长 ASCII 前缀 + GBK 正文要逐页各自嗅探,纯 CJK 的 UTF-16 页不能推翻首页的宽编码判定)/ `jsonl.spec.ts` / `jsonl-language.spec.ts`(逐行 JSON 词法分析:400 条记录零错误节点(`json()` 是 402 个)、坏行不溢出到后一行、不为缺失结构编造错误)/ `archive.spec.ts` / `archive-tools.spec.ts`(打包改原生命令:argv 含 `-y`(防符号链接环)、公共祖先定位、注入式 spawn 的探测与 `unavailable`、临时文件在流结束后删除、`dispose()` 杀子进程;唯一一条真二进制用例自探测缺席即跳过)/ `editor-large-file.spec.tsx`(超限进入只读分页预览 + 下载出口 + 无 CodeMirror + 无保存按钮,并带可编辑反证)。
|
||||
- **关键测试守护**:`tests/service.spec.ts` / `builtins.spec.ts`(注册表与内置清单:**6 tab + 4 viewer**——右列终端与浏览器已交还宿主,只读预览也按 §3.2 第 5 条让出,只剩 markdown / html / jsonl(v0.26.0 新增,逐行 JSON 记录预览 + 可保存编辑)/ code;第 6 个 tab 是 `terminal-bottom`(#774,`bottomOnly`,只投插件自己的底部工作台))/ `market-manifest.spec.ts`(市场约束,含 `pnpm pack` 后的产物面)/ `manifest-consistency.spec.ts`(registry 通道形状)/ `e2e-host-protocol.spec.ts`(RPC 双协议)/ `native-surface.spec.ts`(原生右侧栏承载面:guide 条目 id 唯一性、以及 `canOpen` 的「拒绝清单不得宽于宿主渲染器」双向边界)/ `native-registration.spec.ts`(原生 tab 注册生命周期:`files` 接管不得被通知拆建、注册失败必须回滚已占用的 id 与已建槽位、`bottomOnly` 描述符**不产生任何原生注册**(tab 类型 / slot / guide 条目,#774——此前只有挂载 lane 抓得住);断言写在注册表的事件日志上)/ `file-open-claim.spec.ts`(文件打开的认领判定:插件一切文件入口先问 `sidebarRightTabs.candidates`,被第三方认领的文件改走 `openResource`,无人认领/无注册表/探测抛错逐字保持 editor 原路径——#695,PR #696 移植;`editor-host.spec.tsx` 另钉合并模式原地切换同样让位)/ `theme.spec.ts`(皮肤契约,含空白面板胶囊几何)/ `plugin-list.spec.ts`(推荐插件目录)/ `fs-search.spec.ts`(host 文件名搜索,含 `explorerExclude` 排除探针:匹配条目不出现也不下钻)/ `fs-watch.spec.ts`(文件树目录 watch 的去抖、句柄上限与错误路径)/ `exclude-patterns.spec.ts` / `fs-tree-exclude.spec.ts` / `fs-tree-compact.spec.ts` / `fs-tree-probe-gate.spec.ts`(请求级探测预算:`createProbeGate` 的在飞上界 / 排队任务抛错后释放且保持 FIFO / `limit<1` 夹紧,以及 `listDirectory` 每个目录探测恰花一个槽位、缓存命中不花——`fs.trees` 整批共享一个 gate,见 [docs/plans/2026-10-13-file-tree-perf-fold-preload-and-probe-budget.md](docs/plans/2026-10-13-file-tree-perf-fold-preload-and-probe-budget.md))/ `file-tree-compact.spec.ts` / `file-tree-compact-fold.spec.tsx`(资源管理器排除模式与面包屑折叠:glob 子集编译器及其**缓存身份**——host 目录缓存按「路径 + 行额 + 模式集身份」分键,改排除列表即换键;`compact` 单目录链的 host 标记、client 折叠/整链开关与折叠链预加载——预加载与渲染共用同一个 32 链上限,超出即停)/ `smoke.spec.ts` 的 settings 段(按 entry id 读写表单、**一次性 legacy 迁移**、open 工具门控——其 GET 走真 `node:http`,因为字节路由现在要真 Writable,且必须 `closeAllConnections` 否则 undici 的 keep-alive 会把用例拖过超时)/ `file-stream-route.spec.ts`(字节路由流式化:`open` 成功后才 `writeHead`,所以不可读文件仍是 4xx JSON 信封;流中途失败走 `writeJson` 的 `headersSent` 守卫而不是 `ERR_HTTP_HEADERS_SENT`)/ `fs-read-page.spec.ts`(分页读取:按行对齐、超长单行不裁空、EOF 精确,以及**只锁宽字符编码**这一条:长 ASCII 前缀 + GBK 正文要逐页各自嗅探,纯 CJK 的 UTF-16 页不能推翻首页的宽编码判定)/ `jsonl.spec.ts` / `jsonl-language.spec.ts`(逐行 JSON 词法分析:400 条记录零错误节点(`json()` 是 402 个)、坏行不溢出到后一行、不为缺失结构编造错误)/ `archive.spec.ts` / `archive-tools.spec.ts`(打包改原生命令:argv 含 `-y`(防符号链接环)、公共祖先定位、注入式 spawn 的探测与 `unavailable`、临时文件在流结束后删除、`dispose()` 杀子进程;唯一一条真二进制用例自探测缺席即跳过)/ `editor-large-file.spec.tsx`(超限进入只读分页预览 + 下载出口 + 无 CodeMirror + 无保存按钮,并带可编辑反证)。
|
||||
@@ -4,6 +4,9 @@
|
||||
|
||||
### Unreleased
|
||||
|
||||
- ⚡ **文件树两处性能放大收敛:折叠链预加载 + 宿主逐子目录探测**(逐条核查结论与「按用户决定不做」的清单见 [docs/plans/2026-10-13-file-tree-perf-fold-preload-and-probe-budget.md](docs/plans/2026-10-13-file-tree-perf-fold-preload-and-probe-budget.md)):① **折叠链的预加载与渲染现在共用同一个 32 链上限**——`compactLoadTargets` 此前扫描**所有已加载层**,而渲染侧 `compactChain` 在 `MAX_COMPACT_DEPTH` 就停手,于是渲染收在 32 节、预加载仍继续请求第 33、34… 节(每节一次串行 `fs.trees` POST 加一次全树 render,标签却不会再变长);现改为从渲染根(`cwd` + 展开集)沿**同一条** `compactChain` 下行,上限自然继承。顺带订正了「安全上限,健康缓存下永不触及」这处不准确注释:合法的深单子目录链(`src/main/java/com/...` 这类)真会触及,循环守卫是 `compactChain` 的 `visited` 而不是这个常量。② **`fs.trees` 整批共享一个探测预算**——新增 `PROBE_BUDGET` / `ProbeGate` / `createProbeGate`,`listDirectory` 增加可选 `gate` 参数(只在真实文件系统探测外层取槽,**缓存命中的层一次都不花**),路由每请求建一个 gate 并传给它的所有层:此前一个批次最多 64 条路径 × 每层 32 路探测可**同开约 2048 个 `opendir`**,冷挂载一棵宽目录树就是一次 syscall 风暴。单层与 `fs.tree` 单路径行为逐字不变(gate 缺省即原并发)。**明确未做**:文件树**不引入虚拟化**(memo 边界 + 每层 1000 行上限 + `truncated` 提示已够,用户判断当前性能无问题)、**watch 上限不加用户提示也不加全局句柄**(无法 watch 的机器本就存在,VS Code 同样不提示)、不改 `DirRow` 的 chain identity。
|
||||
- 🧪 测试:新增 `tests/fs-tree-probe-gate.spec.ts`(gate 在飞上界、排队任务抛错后释放且保持 FIFO、`limit<1` 夹紧;`listDirectory` 每个目录探测恰花一个槽位、缓存命中零开销;三层共享一个 gate 合计 9 次);`tests/file-tree-compact.spec.ts` 与 `tests/file-tree-compact-fold.spec.tsx` 新增「到渲染上限即停」(把实现回退到旧扫描,两条当场红:预加载会一路问到链尾);`tests/smoke.spec.ts` 新增路由级断言「一次 `fs.trees` 只建一个 gate」(`vi.mock` 包一层计数,其余导出保持真实)。
|
||||
|
||||
- 🖥️ **底部工作台可以同时开多个终端 Tab([#927](https://github.com/omdsh-dev/DSH-better-sidebar/issues/927),PR [#926](https://github.com/omdsh-dev/DSH-better-sidebar/pull/926))**:`terminal-bottom` 去掉 `single: true` 改为提供 `createTab`——每开一个 mint 一个 `terminal-bottom:<uuid>` 的 id,并在 `meta.terminalInstance` 里记下自己的实例;宿主侧的出现键与内容身份都带上它(`dsh-better-sidebar:terminal-bottom:<instance>[#run]`),于是两个 tab **各自一个 shell**、刷新后各回各的进程,关掉一个只结束它自己那条。**旧 tab(`meta` 里没有 `terminalInstance`)读出来仍是 `undefined`,身份与改造前逐字节相同**,恢复绑定不丢。**维护者收尾**:`nextTerminalMeta()` 必须把实例一起带过去——`patchTab` 是**整份替换 `meta`**,只回 `terminalRun` 会让「新建终端」之后的 tab 掉回旧命名空间,于是两个都换过进程的 tab 撞在同一个 `…terminal-bottom#1` 上、被宿主(按 `(sessionId, key)` 记忆一个 model)发成**同一个 shell**。设计文档 `docs/plans/2026-10-05-bottom-terminal-tab.md` 的「一个终端」限制随之标注放开。
|
||||
- 🧪 测试:`tests/terminal-tab.spec.tsx` +3(实例随「新建终端」保留、旧 tab 不长出实例;两个实例各自 `#1` 不撞、且都不等于旧的裸 `#1`;两个实例渲染出两个宿主终端与两条不同的 `(session,key,contentId)`),描述符关闭钩子补一条「带实例的 tab 只结束自己的终端」。判别性:把 `nextTerminalMeta` 退回只回 `terminalRun`,前两条当场红。
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# 文件树性能核查与两处收敛:折叠链预加载上限 + 请求级探测预算
|
||||
|
||||
日期:2026-10-13 分支:`fix/file-tree-perf`(从 `dev` 切出)
|
||||
|
||||
## 1. 背景与核查结论
|
||||
|
||||
用户带着六条断言要求核查「文件 Tab」与「深层级文件」的性能问题。逐条落到代码后的结论(每条都有实测/直读证据,未采纳的项见 §4):
|
||||
|
||||
| 断言 | 结论 | 证据 |
|
||||
|---|---|---|
|
||||
| 文件 Tab「无 memo 边界」 | **不成立** | `FileRow`/`DirRow`/`RootRow` 三个 `memo` 组件(`src/client/FileTree.tsx:249/331/413`),`actions` 经 `useMemo` 稳定(`:1252`),props 刻意只传原始值/稳定引用(git 状态以 `gitTone`/`gitLetter` 原始值传入,`:237-247`) |
|
||||
| 文件 Tab「无虚拟化」 | 成立(本轮不处理) | 递归直出(`:2025-2127`),全客户端无 windowing/`contain`/`content-visibility`;每层受 `listLimit`(默认 1000)与 `truncated` 提示约束 |
|
||||
| 宿主每列一层、每个子目录一次探测 | **成立** | `fs-tree.ts` 的 `readDirectory` → `probeCompactRows` → `hasSingletonChild`(`src/fs-tree.ts:263-291`):每个目录行一次 `opendir` + ≤2 次 dirent 读;缓解是 1.5s TTL 层缓存 + 单层并发 32 |
|
||||
| ↳ 并发放大(核查中新增) | **成立** | `fs.trees` 对 ≤64 路径 `Promise.all`(`src/index.ts:712-727`)× 每层 32 路 → 冷挂载宽目录树时单请求理论上同开约 2048 个 `opendir` |
|
||||
| 折叠链「一节一次往返」 | **成立且严格串行** | 下一节名字只能从上一节 listing 得到(`src/client/file-tree-compact.ts:48-53`),预加载 effect 依赖 `data`(`src/client/FileTree.tsx:1004-1012`)→ N 节 = N 个串行 POST(每波跨链合批上限 64)。`tests/file-tree-compact-fold.spec.tsx` 钉的是**被请求路径集合**,不锁 POST 次数 |
|
||||
| 「超 32 节静默截断」 | **成立**(折叠链维度,非路径截断) | `MAX_COMPACT_DEPTH = 32` 只在渲染侧生效(`file-tree-compact.ts:27/40`),而 `compactLoadTargets` 旧实现**无深度上限**——渲染在 32 停手、预加载继续往下;注释里「健康缓存永不触及」也不准确,合法的深单子目录链真会触及 |
|
||||
| watch 64 上限「静默击穿」 | 单连接**未**击穿;「静默」与进程级无全局上限成立 | 上限 64、超限 `add()` 返回 false(`src/fs-watch.ts:31/104`),测试钉住前 64 接受且不驱逐(`tests/fs-watch.spec.ts:119-132`);拒绝只回 `{dir, ok:false}` 而客户端不处理该分支(`src/client/use-dir-watch.ts:116-125`);cap 是 per-WebSocket,`keepMounted` 下多会话同时挂载时进程总句柄可达 64×N |
|
||||
|
||||
核查中另行记录(未入选本轮):`DirRow` 的 `chain` 数组来自 `useMemo(…, [data])`(`FileTree.tsx:1842-1851`),层级缓存一变整份重建 → 每次 watch 通知/展开/改名都让**所有目录行**重渲染(`FileRow` 仍能 bail);git 状态每 2.5s 在请求开始与结束各 `notify` 一次(`src/client/ui/git-status.ts:211/236`),导致整树每 2.5s 重建一次 element 树(快照 identity 保留机制见 `:216-224`)。
|
||||
|
||||
## 2. 改动一:折叠链预加载与渲染共用同一深度口径(client)
|
||||
|
||||
`compactLoadTargets` 从「扫描所有已加载层」改为「从**渲染根**沿折叠链下行」,上限由同一个 `compactChain` 天然继承(它本就按 `MAX_COMPACT_DEPTH` 截断):
|
||||
|
||||
```ts
|
||||
compactLoadTargets(levels, roots) // roots = [cwd, ...expanded]
|
||||
work list(非递归,深树不压栈)+ visited 去重
|
||||
对每个已加载层的每个目录行:
|
||||
chain = compactChain(entry, levelOf) // ≤ 32 链接,停在首个未加载链接
|
||||
tail = chain.at(-1)
|
||||
tail 仍 compact 且该层未加载 → 收集为 frontier(唯一需要加载的一节)
|
||||
否则链尾已加载:chain.length < 32 才下行扫下一节(收敛点)
|
||||
```
|
||||
|
||||
- **为什么这样就能封顶**:链长到 32 时 `compactChain` 不再延伸,于是永远拿不出第 33 节作为目标——不需要额外的深度计数。
|
||||
- **语义等价性**:非 compact 目录的 `compactChain` 立即返回单元素链,只在下行时探查其(已展开才存在的)已加载层,与旧全局扫描覆盖相同;折叠行未展开也继续长齐标签的行为保留(逐波补链)。
|
||||
- **调用点**:`FileTree.tsx:1015` 传 `[cwd, ...propsRef.current.expanded]`,effect 依赖保持 `[cwd, data, loadLevels]`(`data` 是真到达信号,展开总会伴随可见集 effect 的加载,故不需要把 `expanded` 放进依赖)。
|
||||
- **注释订正**:`MAX_COMPACT_DEPTH` 上方原先「健康缓存下永不触及」的表述改为准确口径(合法深链会触及;循环守卫是 `compactChain` 的 `visited`,不是这个常量)。
|
||||
|
||||
旧实现下 `tests/file-tree-compact.spec.ts` 与 `tests/file-tree-compact-fold.spec.tsx` 的新用例实测变红(`expected 40 to be 32`、`['/elsewhere/x']`、第 33 节被请求),证明用例有判别力。
|
||||
|
||||
## 3. 改动二:请求级探测预算(host)
|
||||
|
||||
- `src/fs-tree.ts` 新增 `PROBE_BUDGET = 32`、`ProbeGate`、`createProbeGate(limit)`(FIFO 信号量,`limit < 1` 夹到 1;`run` 用 `try/finally` 释放;释放时把槽位直接交给队首)。
|
||||
- `listDirectory(path, maxEntries, exclude?, gate?)` → `listDirectoryCached` → `readDirectory`(**仅缓存未命中**路径),两个 probe(symlink stat / compact opendir)都经 `runProbe(gate, …)`。缓存命中不占额度。
|
||||
- `src/index.ts` 的 `fs.trees`(`:711`)在 `Promise.all` 之前建**一个** gate 并传给每个 `listDirectory`;`fs.tree` 单路径路由传 `undefined`,行为逐字不变。
|
||||
- 值取 32 = 现有单层常量:单层/单路径行为与改前完全一致,只是「层数 × 32」变成了「每请求 ≤32」。
|
||||
- 实现偏差记录:第一版把 gate 取槽放在 `forEachRow` 的**行访问**上,于是 symlink probe 对非链接行、compact probe 对文件行也各取一次空转槽位——计数单测立刻暴露(期望 9 实际 18)。改为只在真实 fs 调用外层取槽(`runProbe`)。
|
||||
- `forEachRow` 因此保持原三参签名不变,per-level 的 `SYMLINK_PROBE_CONCURRENCY` / `COMPACT_PROBE_CONCURRENCY = 32` 继续作为单层 worker 池。
|
||||
|
||||
## 4. 明确不做(用户已定,记录以免重复争论)
|
||||
|
||||
1. **不引入虚拟化**,也不为此加压力测试/文档:memo 边界 + 每层 1000 行上限 + `truncated` 提示已够用(用户判断「目前性能看起来都没问题」)。
|
||||
2. **watch 上限不加任何用户提示、不加全局(跨连接)句柄上限**:有的机器本来就无法 watch,VS Code 自动刷新失败同样不提示(保留 per-连接语义与既有日志行为)。
|
||||
3. **不改 `DirRow` 的 chain identity**(每层级变动全目录行重渲染)。
|
||||
4. **不处理 git 每 2.5s 导致的整树 element 重建**。
|
||||
|
||||
## 5. 测试与验证
|
||||
|
||||
- `tests/file-tree-compact.spec.ts`:`compactLoadTargets` 两条既有用例改新签名 + roots;新增「只从渲染根走」(不可达层不再贡献目标)与「到渲染上限即停」(fixture 是 MAX_COMPACT_DEPTH+1 条已加载链接、第 33 节存在但未加载,旧实现会收它)。
|
||||
- `tests/file-tree-compact-fold.spec.tsx`:既有「折叠成一行 + 预加载整条链」断言保持;新增一条 40 节链的用例——预加载最深恰为 `MAX_COMPACT_DEPTH`、绝不请求第 33 节。
|
||||
- `tests/fs-tree-probe-gate.spec.ts`(新,真实临时目录,不 mock `node:fs`):`createProbeGate` 的在飞上界 / 排队任务抛错后槽位释放且保持 FIFO / `limit<1` 夹紧;`listDirectory` 每个目录探测恰好花一个槽位、缓存命中花零个;三个层共享一个 gate 时合计 9 次(3 层 × 3 个目录行)。
|
||||
- `tests/smoke.spec.ts`:新增路由级断言——一次 `fs.trees` 请求只调一次 `createProbeGate`(用 `vi.mock(…, importOriginal)` 包一层计数,其余导出保持真实),即「批次共享一个预算」;`fs.tree` 单路径与其余路由行为回归由既有用例覆盖。
|
||||
- 既有 `tests/fs-tree*.spec.ts` / `tests/fs-watch.spec.ts` 全绿(`gate` 是可选参数,既有调用逐字不变)。
|
||||
- **与本轮无关的既有 flaky**:`tests/fs-watch.spec.ts` 的「treats a repeat add as already-watched」是 `fs.watch` + 真实写入的 15s 等待,在多副本并行跑时会在任意副本上偶发红;把全部改动 stash 掉后同样复现,故不是本轮引入。
|
||||
|
||||
## 6. 交付说明
|
||||
|
||||
门禁:`pnpm typecheck`、`pnpm lint`、`pnpm test`(本轮不涉及 e2e/挂载 lane)。改动仅 4 个源文件 + 3 个测试文件 + 本文件;`fs.tree` 单路径路由与 `fs-watch` 行为未触碰,未新增 UI 文案或 locale key。
|
||||
@@ -1006,9 +1006,15 @@ export function FileTree(props: {
|
||||
// levels are loaded ahead of any expansion (without them the breadcrumb
|
||||
// label would grow one segment at a time as the user clicks). Each arrival
|
||||
// can reveal the next link, hence the rescan on every cache update;
|
||||
// loadLevels skips what is already loaded, so this settles.
|
||||
// loadLevels skips what is already loaded, so this settles. The roots are
|
||||
// read LIVE through `propsRef`, keeping this effect's dependencies at
|
||||
// [cwd, data, loadLevels]: the level cache is the real trigger (an arrival
|
||||
// reveals the next link), and an expansion is always accompanied by the
|
||||
// visible-set effect above loading (or having loaded) that level. The walk
|
||||
// itself stops at the render cap, so a chain the row stopped folding at
|
||||
// MAX_COMPACT_DEPTH never keeps pulling deeper levels.
|
||||
if (cwd === undefined) return
|
||||
loadLevels(compactLoadTargets(dataRef.current))
|
||||
loadLevels(compactLoadTargets(dataRef.current, [cwd, ...propsRef.current.expanded]))
|
||||
}, [cwd, data, loadLevels])
|
||||
|
||||
// A torn-down tree must not write the answer of an in-flight batch into a
|
||||
|
||||
@@ -20,9 +20,13 @@ export interface CompactLevel {
|
||||
}
|
||||
|
||||
/**
|
||||
* Safety cap on one fold chain. Real directories cannot cycle, so this is
|
||||
* never reached on a healthy cache — it bounds the chain when a stale cache
|
||||
* lies about a level's contents.
|
||||
* Cap on one fold chain, shared by what the row RENDERS and what the preload
|
||||
* loads ahead of it ({@link compactLoadTargets}) so a chain never pays for
|
||||
* links the breadcrumb would not show. A legitimate deep singleton chain
|
||||
* (a Java package path, a chain of single-child project folders) does reach
|
||||
* this; past it the breadcrumb stops folding and the next link appears as its
|
||||
* own row on expansion. The stale-cache cycle guard is {@link compactChain}'s
|
||||
* `visited` set, not this.
|
||||
*/
|
||||
export const MAX_COMPACT_DEPTH = 32
|
||||
|
||||
@@ -58,19 +62,47 @@ export function compactChain(entry: FsEntry, levelOf: (path: string) => CompactL
|
||||
|
||||
/**
|
||||
* The collapsed singleton directories whose levels still need loading, so
|
||||
* fold chains can extend past what the user has expanded. Scans every
|
||||
* LOADED level once; each arrival may reveal the next link, so the caller
|
||||
* re-runs this after every cache update. Chains cannot cycle (host never
|
||||
* marks symlink children), so the walk terminates at the chain's real end.
|
||||
* fold chains can extend past what the user has expanded. Walks down from the
|
||||
* RENDERED levels (`roots` — the workspace root plus every expanded
|
||||
* directory) along the very same {@link compactChain} the row renderer builds
|
||||
* its label with, so the walk inherits that chain's
|
||||
* {@link MAX_COMPACT_DEPTH} cap: past the cap the breadcrumb stops folding and
|
||||
* the preload stops asking for links the renderer would never draw. (The
|
||||
* previous every-loaded-level scan kept pulling link 33, 34, … for a chain
|
||||
* the row had already stopped folding at 32 — one serial POST plus one
|
||||
* whole-tree render per wasted link.)
|
||||
*
|
||||
* Each arrival may reveal the next link, so the caller re-runs this after
|
||||
* every cache update. `visited` dedupes that walk and keeps it terminating:
|
||||
* chains cannot cycle (the host never marks symlink children).
|
||||
* @param levels - the tree's level cache, keyed by absolute path.
|
||||
* @param roots - the levels the tree actually renders, in any order.
|
||||
* @returns the absolute paths of the frontier links still to load.
|
||||
*/
|
||||
export function compactLoadTargets(levels: Record<string, CompactLevel>): string[] {
|
||||
export function compactLoadTargets(levels: Record<string, CompactLevel>, roots: readonly string[]): string[] {
|
||||
const targets = new Set<string>()
|
||||
for (const level of Object.values(levels)) {
|
||||
if (level.entries === undefined) continue
|
||||
const visited = new Set<string>()
|
||||
// A work list, not recursion: a deep expanded tree must not grow the stack.
|
||||
const pending = [...roots]
|
||||
while (pending.length > 0) {
|
||||
const dir = pending.pop()!
|
||||
if (visited.has(dir)) continue
|
||||
visited.add(dir)
|
||||
const level = levels[dir]
|
||||
// Unloaded, in-flight (`{}`) or failed level: nothing to scan here.
|
||||
if (level?.entries === undefined) continue
|
||||
for (const entry of level.entries) {
|
||||
if (entry.isDir && entry.compact === true && levels[entry.path] === undefined) {
|
||||
targets.add(entry.path)
|
||||
if (!entry.isDir) continue
|
||||
const chain = compactChain(entry, path => levels[path])
|
||||
const tail = chain[chain.length - 1]!
|
||||
// The chain's frontier: its tail still folds but that level is unloaded.
|
||||
if (tail.compact === true && levels[tail.path] === undefined) {
|
||||
targets.add(tail.path)
|
||||
continue
|
||||
}
|
||||
// Tail already loaded: descend for the next frontier link — but stop at
|
||||
// the render cap, which is exactly where the label stops extending.
|
||||
if (chain.length < MAX_COMPACT_DEPTH) pending.push(tail.path)
|
||||
}
|
||||
}
|
||||
return [...targets]
|
||||
|
||||
+87
-14
@@ -124,12 +124,13 @@ export function invalidateDirectoryCache(path?: string): void {
|
||||
const DIRECTORY_CACHE_MAX = 512
|
||||
|
||||
/** Read one level through the cache when it is fresh. */
|
||||
async function listDirectoryCached(path: string, maxEntries: number, exclude?: ExcludeMatcher): Promise<SidebarFsListing> {
|
||||
async function listDirectoryCached(path: string, maxEntries: number, exclude?: ExcludeMatcher, gate?: ProbeGate): Promise<SidebarFsListing> {
|
||||
const key = cacheKey(path, maxEntries, exclude)
|
||||
const now = Date.now()
|
||||
const hit = directoryCache.get(key)
|
||||
// A cached level runs no filesystem probe at all, so it never spends budget.
|
||||
if (hit !== undefined && now - hit.at < DIRECTORY_CACHE_TTL_MS) return hit.listing
|
||||
const listing = await readDirectory(path, maxEntries, exclude)
|
||||
const listing = await readDirectory(path, maxEntries, exclude, gate)
|
||||
// Bounded: a deep walk of many directories must not grow this map without
|
||||
// limit (entries are tiny, but an unbounded map in a long-lived host is a
|
||||
// leak). Map iteration order is insertion order, so the first key is oldest.
|
||||
@@ -148,15 +149,18 @@ async function listDirectoryCached(path: string, maxEntries: number, exclude?: E
|
||||
* @param exclude - compiled exclude-pattern probe (the explorerExclude pref):
|
||||
* matched entries are dropped from the listing AND the singleton fold probe,
|
||||
* so they never render nor block a breadcrumb fold.
|
||||
* @param gate - optional shared probe budget; a batch listing many levels
|
||||
* passes ONE gate ({@link createProbeGate}) so the per-level probe bounds do
|
||||
* not multiply. Cache hits never touch it.
|
||||
* @returns the sorted listing.
|
||||
* @throws {SidebarError} fs-error when the level is unreadable or not a directory.
|
||||
*/
|
||||
export async function listDirectory(path: string, maxEntries = 1000, exclude?: ExcludeMatcher): Promise<SidebarFsListing> {
|
||||
return await listDirectoryCached(path, maxEntries, exclude)
|
||||
export async function listDirectory(path: string, maxEntries = 1000, exclude?: ExcludeMatcher, gate?: ProbeGate): Promise<SidebarFsListing> {
|
||||
return await listDirectoryCached(path, maxEntries, exclude, gate)
|
||||
}
|
||||
|
||||
/** Read one level straight from the filesystem (the cache's slow path). */
|
||||
async function readDirectory(path: string, maxEntries: number, exclude?: ExcludeMatcher): Promise<SidebarFsListing> {
|
||||
async function readDirectory(path: string, maxEntries: number, exclude?: ExcludeMatcher, gate?: ProbeGate): Promise<SidebarFsListing> {
|
||||
let dirents
|
||||
try {
|
||||
// One syscall batch instead of an `opendir` stream: `readdir` with types is
|
||||
@@ -197,15 +201,70 @@ async function readDirectory(path: string, maxEntries: number, exclude?: Exclude
|
||||
// symlink-heavy level (UNC/network targets) would otherwise serialize up to
|
||||
// maxEntries stat calls and stall the explorer. Non-symlink rows are skipped,
|
||||
// so levels without links stay as cheap as before.
|
||||
await probeSymlinkTargets(rows)
|
||||
await probeSymlinkTargets(rows, gate)
|
||||
// Mark singleton-directory rows AFTER the symlink probe (it finalizes
|
||||
// isDir/broken), so the client can fold compact chains without an extra
|
||||
// round trip per collapsed level.
|
||||
await probeCompactRows(rows, exclude)
|
||||
await probeCompactRows(rows, exclude, gate)
|
||||
rows.sort(compareEntries)
|
||||
return { path, entries: rows, truncated }
|
||||
}
|
||||
|
||||
/**
|
||||
* In-flight filesystem probes ONE listing request may run across ALL of its
|
||||
* levels. The per-level bounds below are exactly that — per level — while a
|
||||
* batch request lists up to `FS_TREES_MAX_PATHS` levels concurrently
|
||||
* (`fs.trees`), so without a shared budget a cold mount of a wide tree could
|
||||
* hold levels × per-level probes open at once (64 × 32). Equal to the
|
||||
* per-level constant on purpose: a single-level listing behaves as before.
|
||||
*/
|
||||
export const PROBE_BUDGET = 32
|
||||
|
||||
/** A FIFO gate bounding how many probe operations run at the same time. */
|
||||
export interface ProbeGate {
|
||||
/**
|
||||
* Run one probe operation under the gate.
|
||||
* @param task - the probe; it must not acquire the gate itself.
|
||||
* @returns the task's own result.
|
||||
*/
|
||||
run<T>(task: () => Promise<T>): Promise<T>
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the probe gate one listing request shares across its levels.
|
||||
* @param limit - maximum probes in flight; below 1 is clamped to 1.
|
||||
* @returns the gate.
|
||||
*/
|
||||
export function createProbeGate(limit = PROBE_BUDGET): ProbeGate {
|
||||
const max = Math.max(1, Math.floor(limit))
|
||||
let active = 0
|
||||
const waiting: (() => void)[] = []
|
||||
const acquire = (): Promise<void> => new Promise((resolve) => {
|
||||
if (active < max) {
|
||||
active += 1
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
waiting.push(() => { active += 1; resolve() })
|
||||
})
|
||||
const release = (): void => {
|
||||
active -= 1
|
||||
// Hand the freed slot straight to the next waiter (it re-increments), so
|
||||
// `active` never reports fewer probes than are actually running.
|
||||
waiting.shift()?.()
|
||||
}
|
||||
return {
|
||||
async run<T>(task: () => Promise<T>): Promise<T> {
|
||||
await acquire()
|
||||
try {
|
||||
return await task()
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Visit every row with at most `concurrency` visitors in flight, in row order.
|
||||
* Both probes below spend one await per row (a network stat, an opendir) on a
|
||||
@@ -225,13 +284,26 @@ async function forEachRow(rows: readonly SidebarFsEntry[], concurrency: number,
|
||||
await Promise.all(workers)
|
||||
}
|
||||
|
||||
/**
|
||||
* Run one FILESYSTEM probe under the request's budget.
|
||||
*
|
||||
* The slot is taken here, around the syscall, not around the row visit: a row
|
||||
* the visitor skips without touching the filesystem must not spend budget.
|
||||
* @param gate - the request's gate, or absent for an unbounded probe.
|
||||
* @param task - the probe operation.
|
||||
* @returns the probe's own result.
|
||||
*/
|
||||
function runProbe<T>(gate: ProbeGate | undefined, task: () => Promise<T>): Promise<T> {
|
||||
return gate === undefined ? task() : gate.run(task)
|
||||
}
|
||||
|
||||
/** Probe each symlink row's target once (bounded concurrency, order-preserving). */
|
||||
async function probeSymlinkTargets(rows: SidebarFsEntry[], concurrency = SYMLINK_PROBE_CONCURRENCY): Promise<void> {
|
||||
async function probeSymlinkTargets(rows: SidebarFsEntry[], gate?: ProbeGate, concurrency = SYMLINK_PROBE_CONCURRENCY): Promise<void> {
|
||||
await forEachRow(rows, concurrency, async (row) => {
|
||||
if (!row.isSymlink) return
|
||||
// stat follows the chain; any failure (missing target, ELOOP, permission)
|
||||
// leaves the row as a broken file-shaped link the editor refuses to read.
|
||||
const info = await stat(row.path).catch(() => undefined)
|
||||
const info = await runProbe(gate, () => stat(row.path)).catch(() => undefined)
|
||||
row.isDir = info !== undefined ? info.isDirectory() : row.isDir
|
||||
row.broken = info === undefined
|
||||
})
|
||||
@@ -246,14 +318,15 @@ const COMPACT_PROBE_CONCURRENCY = 32
|
||||
* row. The terminal link (sole FILE child) is marked too: the client
|
||||
* preloads marked levels to stabilize the fold label before expansion.
|
||||
* Bounded concurrency like the symlink probe: each probe is one opendir + up
|
||||
* to two dirent reads, so a directory-heavy level stays responsive. Probe
|
||||
* failures (unreadable child level) leave the row unmarked — it simply does
|
||||
* not fold.
|
||||
* to two dirent reads, so a directory-heavy level stays responsive. A shared
|
||||
* {@link ProbeGate} also keeps a whole batch's levels within one probe budget.
|
||||
* Probe failures (unreadable child level) leave the row unmarked — it simply
|
||||
* does not fold.
|
||||
*/
|
||||
async function probeCompactRows(rows: SidebarFsEntry[], exclude?: ExcludeMatcher, concurrency = COMPACT_PROBE_CONCURRENCY): Promise<void> {
|
||||
async function probeCompactRows(rows: SidebarFsEntry[], exclude?: ExcludeMatcher, gate?: ProbeGate, concurrency = COMPACT_PROBE_CONCURRENCY): Promise<void> {
|
||||
await forEachRow(rows, concurrency, async (row) => {
|
||||
if (!row.isDir || row.broken) return
|
||||
if (await hasSingletonChild(row.path, exclude)) row.compact = true
|
||||
if (await runProbe(gate, () => hasSingletonChild(row.path, exclude))) row.compact = true
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+7
-2
@@ -29,7 +29,7 @@ import {
|
||||
type SidebarConfig,
|
||||
type SidebarPrefs,
|
||||
} from './config.ts'
|
||||
import { listDirectory, messageOf, parentOf, requireAbsolute, rootLabel, type SidebarFsEntry } from './fs-tree.ts'
|
||||
import { createProbeGate, listDirectory, messageOf, parentOf, requireAbsolute, rootLabel, type SidebarFsEntry } from './fs-tree.ts'
|
||||
import { resolveSessionPath } from './session-path.ts'
|
||||
import { createWorkspaceFile, mkdirWorkspaceEntry, renameWorkspaceEntry, removeWorkspaceEntry, writeWorkspaceText, writeWorkspaceUpload } from './fs-operations.ts'
|
||||
import { ensureWorkspacePath } from './path-security.ts'
|
||||
@@ -709,6 +709,11 @@ function buildApi(
|
||||
// explorerExclude pref has to be compiled here too, or the exclude list
|
||||
// would simply not reach the only surface the explorer reads.
|
||||
const exclude = compileExcludePatterns(record?.exclude, cwd)
|
||||
// ONE probe budget for the whole request: every level keeps its own
|
||||
// per-level probe bound, but a batch of up to FS_TREES_MAX_PATHS levels
|
||||
// shares one gate, so the bounds do not multiply (64 × 32 opendirs on a
|
||||
// cold mount of a wide tree). Cache hits never touch the gate.
|
||||
const gate = createProbeGate()
|
||||
const levels = await Promise.all(paths.map(async (raw): Promise<SidebarFsLevel> => {
|
||||
// A session-relative path is accepted here (the tree already carries
|
||||
// cwd-relative paths); `fs.tree` itself keeps requiring absolute
|
||||
@@ -718,7 +723,7 @@ function buildApi(
|
||||
const homeRelative = raw === '~' || raw.startsWith('~/') || raw.startsWith('~\\')
|
||||
const requested = isAbsolute(raw) || homeRelative ? raw : `${cwd}${sep}${raw}`
|
||||
try {
|
||||
return await listDirectory(await ensureWorkspacePath(cwd, requested), resolved.listLimit, exclude)
|
||||
return await listDirectory(await ensureWorkspacePath(cwd, requested), resolved.listLimit, exclude, gate)
|
||||
} catch (error) {
|
||||
// Per-level failure: the batch itself stays a success (one unreadable
|
||||
// directory must not blank the whole tree).
|
||||
|
||||
@@ -19,6 +19,7 @@ import { createElement } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import { FileTree } from '../src/client/FileTree.tsx'
|
||||
import { MAX_COMPACT_DEPTH } from '../src/client/file-tree-compact.ts'
|
||||
|
||||
import { setupReactAct } from './test-utils.ts'
|
||||
setupReactAct()
|
||||
@@ -236,6 +237,39 @@ describe('FileTree breadcrumb folding', () => {
|
||||
expect(harness.container.textContent).toContain('readme.md')
|
||||
})
|
||||
|
||||
it('stops the preload at the render cap instead of requesting deeper links', async () => {
|
||||
// A chain longer than a row can fold: every level is a singleton dir for
|
||||
// MAX_COMPACT_DEPTH + 8 links. The breadcrumb stops folding at the cap, so
|
||||
// the preload must stop asking there too — the every-loaded-level scan it
|
||||
// replaced kept requesting link 33, 34, … (one serial POST plus one
|
||||
// whole-tree render each) for a chain the renderer never drew.
|
||||
const DEPTH = MAX_COMPACT_DEPTH + 8
|
||||
const linkAt = (index: number): string => index === 0
|
||||
? '/tmp'
|
||||
: `/tmp/${Array.from({ length: index }, (_, step) => `l${step + 1}`).join('/')}`
|
||||
const depthOf = (path: string): number => path === '/tmp' ? 0 : path.split('/').length - 2
|
||||
fsTrees.mockImplementation(async (_scope: unknown, paths: readonly string[]) => ({
|
||||
levels: paths.map((path) => {
|
||||
const depth = depthOf(path)
|
||||
return {
|
||||
path,
|
||||
entries: depth < DEPTH ? [dir(linkAt(depth + 1), true)] : [file(`${path}/leaf.txt`)],
|
||||
truncated: false,
|
||||
}
|
||||
}),
|
||||
}))
|
||||
harness = mountTree()
|
||||
// One wave per link (each arrival reveals the next frontier link); a
|
||||
// generous fixed bound keeps a regression that loops on the cap from
|
||||
// hanging the run — it fails on the assertion below instead.
|
||||
for (let wave = 0; wave < DEPTH * 4; wave += 1) await flush()
|
||||
|
||||
// The preload followed the chain all the way to the cap…
|
||||
expect(Math.max(...requestedPaths().map(depthOf))).toBe(MAX_COMPACT_DEPTH)
|
||||
// …and never asked for the link past it.
|
||||
expect(new Set(requestedPaths()).has(linkAt(MAX_COMPACT_DEPTH + 1))).toBe(false)
|
||||
})
|
||||
|
||||
it('toggles the WHOLE chain on a plain click, so the row closes as one', async () => {
|
||||
// The head was expanded by an earlier interaction (before the fold formed):
|
||||
// closing the row must collapse every link, not just the head.
|
||||
|
||||
@@ -128,7 +128,7 @@ describe('compactLoadTargets', () => {
|
||||
'/root/a/b': {},
|
||||
}
|
||||
// Only marked, not-yet-loaded dirs qualify: files and plain dirs never do.
|
||||
expect(compactLoadTargets(levels)).toEqual(['/root/a/c'])
|
||||
expect(compactLoadTargets(levels, ['/root'])).toEqual(['/root/a/c'])
|
||||
})
|
||||
|
||||
it('skips already-loaded paths and dedupes repeat appearances', () => {
|
||||
@@ -138,6 +138,32 @@ describe('compactLoadTargets', () => {
|
||||
'/alt': { entries: [row] },
|
||||
'/root/a': { entries: [] },
|
||||
}
|
||||
expect(compactLoadTargets(levels)).toEqual([])
|
||||
expect(compactLoadTargets(levels, ['/root'])).toEqual([])
|
||||
})
|
||||
|
||||
it('only walks from the rendered roots', () => {
|
||||
// `/elsewhere` is loaded but no chain reaches it from what the tree
|
||||
// renders, so its singleton child needs no preload.
|
||||
const levels: Record<string, CompactLevel> = {
|
||||
'/root': { entries: [dir('/root/plain')] },
|
||||
'/elsewhere': { entries: [dir('/elsewhere/x', true)] },
|
||||
}
|
||||
expect(compactLoadTargets(levels, ['/root'])).toEqual([])
|
||||
})
|
||||
|
||||
it('stops at the render cap instead of pulling deeper links', () => {
|
||||
// MAX_COMPACT_DEPTH + 1 loaded links, each one a singleton: the row's
|
||||
// breadcrumb already stops folding at the cap, so the link PAST it — the
|
||||
// one the deepest loaded level names — must not be preloaded. The
|
||||
// every-loaded-level scan this replaced collected exactly that link, and
|
||||
// with it link 34, 35, … (one serial POST and one whole-tree render each).
|
||||
const levels: Record<string, CompactLevel> = {}
|
||||
for (let index = 1; index <= MAX_COMPACT_DEPTH + 1; index += 1) {
|
||||
levels[`/${'x'.repeat(index)}`] = { entries: [dir(`/${'x'.repeat(index + 1)}`, true)] }
|
||||
}
|
||||
// The fixture is cap-limited, not data-limited: the head's chain IS full…
|
||||
expect(compactChain(dir('/x', true), path => levels[path])).toHaveLength(MAX_COMPACT_DEPTH)
|
||||
// …so nothing past the cap is requested.
|
||||
expect(compactLoadTargets(levels, ['/x'])).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* The request-wide probe budget behind `fs.trees`.
|
||||
*
|
||||
* One batch lists up to `FS_TREES_MAX_PATHS` levels concurrently, and each
|
||||
* level runs its own bounded probe pool (a `stat` per symlink row, an
|
||||
* `opendir` per directory row for the singleton fold mark). Without a shared
|
||||
* budget those bounds multiply — a cold mount of a wide tree could hold
|
||||
* levels × pool probes open at once. The bound itself is proved on the gate;
|
||||
* these tests prove the WIRING: every probe of every level spends the one
|
||||
* gate the request was given (and a cache hit spends nothing at all). The
|
||||
* route's per-request gate SHARING is asserted in tests/smoke.spec.ts.
|
||||
*/
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createProbeGate, listDirectory, type ProbeGate } from '../src/fs-tree.ts'
|
||||
|
||||
/** A gate that only COUNTS acquisitions: it bounds nothing of its own, so the
|
||||
* count it reports is exactly the probes the caller routed through it. */
|
||||
function countingGate(): { gate: ProbeGate; calls: () => number } {
|
||||
const state = { calls: 0 }
|
||||
return {
|
||||
gate: {
|
||||
async run<T>(task: () => Promise<T>): Promise<T> {
|
||||
state.calls += 1
|
||||
return await task()
|
||||
},
|
||||
},
|
||||
calls: () => state.calls,
|
||||
}
|
||||
}
|
||||
|
||||
describe('createProbeGate', () => {
|
||||
it('keeps at most `limit` tasks in flight', async () => {
|
||||
const gate = createProbeGate(2)
|
||||
let live = 0
|
||||
let peak = 0
|
||||
await Promise.all(Array.from({ length: 8 }, () => gate.run(async () => {
|
||||
live += 1
|
||||
peak = Math.max(peak, live)
|
||||
await new Promise(resolve => setTimeout(resolve, 1))
|
||||
live -= 1
|
||||
})))
|
||||
expect(peak).toBe(2)
|
||||
expect(live).toBe(0)
|
||||
})
|
||||
|
||||
it('releases the slot when a queued task throws, in FIFO order', async () => {
|
||||
const gate = createProbeGate(1)
|
||||
const order: string[] = []
|
||||
const first = gate.run(async () => {
|
||||
await new Promise(resolve => setTimeout(resolve, 1))
|
||||
order.push('first')
|
||||
})
|
||||
const failing = gate.run(async () => {
|
||||
order.push('failing')
|
||||
throw new Error('probe failed')
|
||||
})
|
||||
const last = gate.run(async () => {
|
||||
order.push('last')
|
||||
return 'ok'
|
||||
})
|
||||
await first
|
||||
await expect(failing).rejects.toThrow('probe failed')
|
||||
// A thrown probe must not strand the waiter behind it.
|
||||
await expect(last).resolves.toBe('ok')
|
||||
expect(order).toEqual(['first', 'failing', 'last'])
|
||||
})
|
||||
|
||||
it('clamps a limit below one so the gate still runs', async () => {
|
||||
const gate = createProbeGate(0)
|
||||
const settled = await Promise.race([
|
||||
gate.run(async () => 'ok'),
|
||||
new Promise<string>(resolve => { setTimeout(() => { resolve('timed out') }, 100) }),
|
||||
])
|
||||
expect(settled).toBe('ok')
|
||||
})
|
||||
})
|
||||
|
||||
describe('listDirectory probe budget', () => {
|
||||
it('spends one gate slot per directory probe, and none on a cache hit', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-probe-gate-'))
|
||||
try {
|
||||
// Four singleton dirs (one child each) plus one ordinary dir: every
|
||||
// directory row costs exactly one compact probe.
|
||||
for (let index = 0; index < 4; index += 1) {
|
||||
mkdirSync(join(dir, `only-${index}`))
|
||||
writeFileSync(join(dir, `only-${index}`, 'child.txt'), 'x')
|
||||
}
|
||||
mkdirSync(join(dir, 'plain'))
|
||||
writeFileSync(join(dir, 'plain', 'a.txt'), 'x')
|
||||
writeFileSync(join(dir, 'plain', 'b.txt'), 'x')
|
||||
|
||||
const counted = countingGate()
|
||||
const listing = await listDirectory(dir, 1000, undefined, counted.gate)
|
||||
expect(counted.calls()).toBe(5)
|
||||
expect(listing.entries.filter(entry => entry.compact === true).map(entry => entry.name).sort())
|
||||
.toEqual(['only-0', 'only-1', 'only-2', 'only-3'])
|
||||
|
||||
// A fresh call is answered from the level cache, which runs no probe at
|
||||
// all — so it must not spend budget either.
|
||||
const spent = counted.calls()
|
||||
const cached = await listDirectory(dir, 1000, undefined, counted.gate)
|
||||
expect(counted.calls()).toBe(spent)
|
||||
expect(cached).toBe(listing)
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('routes a whole batch of levels through ONE shared gate', async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-probe-batch-'))
|
||||
try {
|
||||
const levels: string[] = []
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
const level = join(root, `l${index}`)
|
||||
mkdirSync(level)
|
||||
for (let child = 0; child < 3; child += 1) {
|
||||
mkdirSync(join(level, `s${child}`))
|
||||
writeFileSync(join(level, `s${child}`, 'child.txt'), 'x')
|
||||
}
|
||||
levels.push(level)
|
||||
}
|
||||
|
||||
const counted = countingGate()
|
||||
// Exactly the shape the `fs.trees` route builds: one gate, many levels.
|
||||
const listings = await Promise.all(levels.map(level => listDirectory(level, 1000, undefined, counted.gate)))
|
||||
// 3 levels × 3 directory rows: every probe went through the shared gate.
|
||||
expect(counted.calls()).toBe(9)
|
||||
for (const listing of listings) {
|
||||
expect(listing.entries.filter(entry => entry.compact === true)).toHaveLength(3)
|
||||
}
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
+47
-1
@@ -3,7 +3,7 @@
|
||||
* exercises the real integrations — route registration, git against the
|
||||
* actual repository, and a real directory listing. Runs with `pnpm test`.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir, homedir } from 'node:os'
|
||||
@@ -18,6 +18,25 @@ import * as git from '../src/git.ts'
|
||||
import { listDirectory } from '../src/fs-tree.ts'
|
||||
import type { SidebarWebRoute, SidebarWebUpgradeRoute } from '../src/context-types.ts'
|
||||
|
||||
/**
|
||||
* The probe-budget factory is spied on so a batch's gate SHARING is asserted
|
||||
* rather than assumed: `fs.trees` lists many levels at once and must build ONE
|
||||
* gate per request, or the per-level probe bounds multiply. Everything else
|
||||
* about the module stays real, so this file's own `listDirectory` calls (and
|
||||
* every other route) behave exactly as before.
|
||||
*/
|
||||
const probeGateCalls = vi.hoisted(() => [] as unknown[][])
|
||||
vi.mock('../src/fs-tree.ts', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/fs-tree.ts')>()
|
||||
return {
|
||||
...actual,
|
||||
createProbeGate: (...args: Parameters<typeof actual.createProbeGate>) => {
|
||||
probeGateCalls.push(args)
|
||||
return actual.createProbeGate(...args)
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
/** Symlink creation may require elevated privileges on Windows. */
|
||||
const canCreateSymlink = (() => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-security-probe-'))
|
||||
@@ -1153,6 +1172,33 @@ describe('session cwd resolution over the API route', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('fs.trees shares ONE probe gate across the batch levels', async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-trees-gate-'))
|
||||
const workspace = join(root, 'workspace')
|
||||
const level = join(workspace, 'level')
|
||||
mkdirSync(level, { recursive: true })
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
mkdirSync(join(level, `only-${index}`))
|
||||
writeFileSync(join(level, `only-${index}`, 'child.txt'), 'x')
|
||||
}
|
||||
try {
|
||||
const route = mount({ sessions: { get: () => ({ header: { cwd: workspace } }) } })
|
||||
const before = probeGateCalls.length
|
||||
const answer = await invoke(route, 'fs.trees', { sessionId: 's-tree-gate', paths: [workspace, level] })
|
||||
expect(answer.ok).toBe(true)
|
||||
// ONE gate for the whole request: a per-level gate would let each level's
|
||||
// probe pool run at full width, which is the runaway this bounds.
|
||||
expect(probeGateCalls.length - before).toBe(1)
|
||||
// The shared budget changed nothing about what the levels report.
|
||||
const levels = (answer.value as {
|
||||
levels: { path: string; entries: { compact?: boolean }[] }[]
|
||||
}).levels
|
||||
expect(levels.find(entry => entry.path === level)?.entries.filter(row => row.compact === true)).toHaveLength(3)
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it.skipIf(!canCreateSymlink)('lists a workspace symlink that resolves outside the workspace', async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-symlink-security-'))
|
||||
const workspace = join(root, 'workspace')
|
||||
|
||||
Reference in new issue
Block a user