Files
apes-sidebar/tests/fs-operations.spec.ts
T
Menghuan1918 57fe6e657d test: 临时目录清理统一走 removeTree(修 Windows 上的 ENOTEMPTY 竞态)
CI 在 windows lane 上红在**清理**而不是断言:
`rmSync(scratch, { recursive: true, force: true })` 抛
`ENOTEMPTY: rmdir …archives-pvpAWR`——刚被 kill 的 zip/tar 子进程(以及刚关闭的
fs.watch / 刚结束的 git 子进程)还没被系统释放句柄,删除于是失败在一个**已经通过**
的用例的 afterEach 里(那一次 2466 个用例全过,只有清理挂掉,整个 lane 变红)。

`maxRetries` + `retryDelay` 正是 Node 为这种场景提供的对策,因此新增
`tests/temp-tree.ts` 的 `removeTree()`,把 30 份 spec(175 处 `{ recursive, force }`
写法)统一换过去,并清掉随之不再使用的 `rmSync` 导入。POSIX 上首次即成功、不触发
重试,行为不变。

本地:typecheck / lint 干净,全量 210 文件 / 2524 通过。
2026-10-16 00:51:11 +08:00

444 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { afterAll, describe, expect, it } from 'vitest'
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { renameWorkspaceEntry, removeWorkspaceEntry, mkdirWorkspaceEntry, writeWorkspaceUpload } from '../src/fs-operations.ts'
import { removeTree } from './temp-tree.ts'
/** The test workspace root (each suite gets its own temp tree). */
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-upload-'))
/** Symlink creation needs privileges on Windows; the link cases skip there. */
const canSymlink = (() => {
const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-upload-probe-'))
try {
symlinkSync(dir, join(dir, 'probe-link'))
return true
} catch {
return false
} finally {
removeTree(dir)
}
})()
afterAll(() => {
removeTree(root)
})
/** Names of leftover temp files under `dir` (must be empty after every run). */
function tmpLeftovers(dir: string): string[] {
return readdirSync(dir).filter(name => name.includes('.dsh-upload-'))
}
/** Turn a string into the async-iterable chunk shape the route receives. */
function chunksOf(text: string): AsyncIterable<string | Uint8Array> {
return {
async *[Symbol.asyncIterator]() {
// Split on two-byte boundaries so UTF-8 multi-byte sequences cross
// chunk edges (streaming must reassemble them as raw bytes, not text).
for (let i = 0; i < text.length; i += 2) yield text.slice(i, i + 2)
},
}
}
/** `count` copies of one buffer, generated lazily: the payload is never held in memory. */
function repeatedChunks(chunk: Uint8Array, count: number): AsyncIterable<string | Uint8Array> {
return {
async *[Symbol.asyncIterator]() {
for (let i = 0; i < count; i++) yield chunk
},
}
}
/** A body that yields `text` in chunks and then DIES, as a dropped upload does. */
function dyingChunks(text: string): AsyncIterable<string | Uint8Array> {
return {
async *[Symbol.asyncIterator]() {
for (let i = 0; i < text.length; i += 2) yield text.slice(i, i + 2)
throw new Error('stream died')
},
}
}
/**
* A temp project whose root directory carries letters, so a lowercase variant
* of its path is a real spelling of the SAME directory (the win32 cases) and a
* link to it stands for the project itself.
*/
function makeProject(): { ws: string; inner: string } {
const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-root-'))
const inner = join(ws, 'ProjDir')
mkdirSync(join(inner, 'src'), { recursive: true })
writeFileSync(join(inner, 'src', 'keep.ts'), 'x')
return { ws, inner }
}
describe('writeWorkspaceUpload', () => {
it('writes a file under the upload directory and returns its size', async () => {
const { path, size } = await writeWorkspaceUpload({
cwd: root,
dir: root,
relativePath: 'a.txt',
chunks: chunksOf('hello 世界'),
})
expect(path).toBe(join(root, 'a.txt'))
expect(size).toBe(Buffer.byteLength('hello 世界'))
expect(readFileSync(path, 'utf8')).toBe('hello 世界')
})
it('creates nested directories on demand (folder uploads)', async () => {
const { path } = await writeWorkspaceUpload({
cwd: root,
dir: root,
relativePath: 'docs/nested/deep.txt',
chunks: chunksOf('x'),
})
expect(existsSync(path)).toBe(true)
})
it('resolves relativePaths against the chosen directory', async () => {
const { path } = await writeWorkspaceUpload({
cwd: root,
dir: join(root, 'docs'),
relativePath: 'b.txt',
chunks: chunksOf('y'),
})
expect(path).toBe(join(root, 'docs', 'b.txt'))
})
it('refuses traversal, empty segments, and absolute relativePaths', async () => {
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: '../evil.txt', chunks: chunksOf('x'),
})).rejects.toMatchObject({ code: 'bad-request' })
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: './a.txt', chunks: chunksOf('x'),
})).rejects.toMatchObject({ code: 'bad-request' })
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: 'a/../b.txt', chunks: chunksOf('x'),
})).rejects.toMatchObject({ code: 'bad-request' })
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: '//', chunks: chunksOf('x'),
})).rejects.toMatchObject({ code: 'bad-request' })
// Empty segments are refused, not silently collapsed.
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: 'a//b.txt', chunks: chunksOf('x'),
})).rejects.toMatchObject({ code: 'bad-request' })
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: 'a/b/', chunks: chunksOf('x'),
})).rejects.toMatchObject({ code: 'bad-request' })
// Absolute paths (POSIX and Windows separators) are refused, not re-anchored.
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: '/x.txt', chunks: chunksOf('x'),
})).rejects.toMatchObject({ code: 'bad-request' })
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: '\\x.txt', chunks: chunksOf('x'),
})).rejects.toMatchObject({ code: 'bad-request' })
})
it('uploads into a directory outside the workspace (containment was removed)', async () => {
const outside = mkdtempSync(join(tmpdir(), 'dsh-sidebar-upload-outside-'))
try {
// ⚠️ PERMISSION CHANGE: the workspace fence is gone, so an absolute
// directory the host user can write is a valid upload target.
const result = await writeWorkspaceUpload({
cwd: root, dir: outside, relativePath: 'x.txt', chunks: chunksOf('x'),
})
expect(result).toEqual({ path: join(outside, 'x.txt'), size: 1 })
expect(readFileSync(join(outside, 'x.txt'), 'utf8')).toBe('x')
} finally {
removeTree(outside)
}
})
it('follows an upload directory symlink outside the workspace (no realpath guard)', async () => {
if (!canSymlink) return
const outside = mkdtempSync(join(tmpdir(), 'dsh-sidebar-upload-symlink-outside-'))
const link = join(root, 'upload-link')
try {
symlinkSync(outside, link)
const viaLink = await writeWorkspaceUpload({
cwd: root, dir: link, relativePath: 'a.txt', chunks: chunksOf('a'),
})
expect(viaLink.path).toBe(join(link, 'a.txt'))
// …and a relative path that walks through the link lands there too.
const viaRelative = await writeWorkspaceUpload({
cwd: root, dir: root, relativePath: 'upload-link/b.txt', chunks: chunksOf('b'),
})
expect(viaRelative.path).toBe(join(root, 'upload-link', 'b.txt'))
expect(readFileSync(join(outside, 'a.txt'), 'utf8')).toBe('a')
expect(readFileSync(join(outside, 'b.txt'), 'utf8')).toBe('b')
} finally {
rmSync(link, { force: true })
removeTree(outside)
}
})
it('streams a body well past the removed size cap and leaves nothing behind', async () => {
const target = join(root, 'big.bin')
// 16 KiB × 12288 = 192 MiB: half again the cap this case used to trip (the
// client pre-check and the host's per-request byte cap both refused at
// 128 MiB). Large bodies must simply flow through the same temp-file +
// rename path.
const chunk = Buffer.alloc(16 * 1024, 7)
const count = 12288
const expected = chunk.length * count
expect(expected).toBeGreaterThan(128 * 1024 * 1024)
const { path, size } = await writeWorkspaceUpload({
cwd: root, dir: root, relativePath: 'big.bin', chunks: repeatedChunks(chunk, count),
})
expect(path).toBe(target)
expect(size).toBe(expected)
expect(statSync(target).size).toBe(expected)
expect(tmpLeftovers(root)).toEqual([])
// Assertions are done; keep 192 MiB out of tmp for the rest of the run.
rmSync(target, { force: true })
})
it('keeps concurrent uploads to the same target independent', async () => {
const target = join(root, 'race.txt')
await Promise.all([
writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'race.txt', chunks: chunksOf('first') }),
writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'race.txt', chunks: chunksOf('second') }),
])
// Both renames succeed (unique temp names, no EEXIST cross-talk); the last
// rename wins and the losers leave nothing behind.
expect(['first', 'second']).toContain(readFileSync(target, 'utf8'))
expect(tmpLeftovers(root)).toEqual([])
})
it('does not overwrite an existing file when a retry dies mid-stream', async () => {
const target = join(root, 'keep.txt')
await writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'keep.txt', chunks: chunksOf('original') })
// The retry fails part-way (a dead body stream, not a size refusal): the
// bytes already spilled into the temp sibling are discarded with it, so the
// committed target keeps its original content.
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: 'keep.txt', chunks: dyingChunks('0123456789'),
})).rejects.toThrow('stream died')
expect(readFileSync(target, 'utf8')).toBe('original')
expect(tmpLeftovers(root)).toEqual([])
})
})
describe('renameWorkspaceEntry', () => {
it('renames a file within its directory', async () => {
writeFileSync(join(root, 'old-name.txt'), 'x')
const { path } = await renameWorkspaceEntry({ cwd: root, path: join(root, 'old-name.txt'), name: 'new-name.txt' })
// The returned path is CANONICAL (realpath-resolved ancestors — on macOS
// the tmpdir's /var becomes /private/var), so assert the shape, not the
// lexical spelling.
expect(path.endsWith('new-name.txt')).toBe(true)
expect(existsSync(join(root, 'old-name.txt'))).toBe(false)
expect(existsSync(join(root, 'new-name.txt'))).toBe(true)
})
it('renames a directory (recursive content moves with it)', async () => {
mkdirSync(join(root, 'olddir/nested'), { recursive: true })
writeFileSync(join(root, 'olddir/nested/deep.txt'), 'x')
await renameWorkspaceEntry({ cwd: root, path: join(root, 'olddir'), name: 'newdir' })
expect(readFileSync(join(root, 'newdir/nested/deep.txt'), 'utf8')).toBe('x')
})
it('is a no-op for the same name (destination-exists refusal must not bite)', async () => {
writeFileSync(join(root, 'same.txt'), 'x')
await renameWorkspaceEntry({ cwd: root, path: join(root, 'same.txt'), name: 'same.txt' })
expect(existsSync(join(root, 'same.txt'))).toBe(true)
})
it('refuses single-segment violations (empty, dot, traversal, separators)', async () => {
writeFileSync(join(root, 'r.txt'), 'x')
for (const name of ['', '.', '..', 'a/b', 'a\\b']) {
await expect(renameWorkspaceEntry({ cwd: root, path: join(root, 'r.txt'), name }))
.rejects.toMatchObject({ code: 'bad-request' })
}
})
it('refuses an existing destination instead of clobbering it', async () => {
writeFileSync(join(root, 'src.txt'), 'src')
writeFileSync(join(root, 'dst.txt'), 'dst')
await expect(renameWorkspaceEntry({ cwd: root, path: join(root, 'src.txt'), name: 'dst.txt' }))
.rejects.toMatchObject({ code: 'fs-error', status: 409 })
expect(readFileSync(join(root, 'dst.txt'), 'utf8')).toBe('dst')
})
it('refuses the workspace root and missing sources', async () => {
await expect(renameWorkspaceEntry({ cwd: root, path: root, name: 'nope' }))
.rejects.toMatchObject({ code: 'fs-error' })
await expect(renameWorkspaceEntry({ cwd: root, path: join(root, 'missing.txt'), name: 'x' }))
.rejects.toMatchObject({ code: 'fs-error' })
})
it('renames a symlink ROW, not its target', async () => {
writeFileSync(join(root, 'target.txt'), 't')
symlinkSync(join(root, 'target.txt'), join(root, 'alias.txt'))
await renameWorkspaceEntry({ cwd: root, path: join(root, 'alias.txt'), name: 'alias2.txt' })
expect(existsSync(join(root, 'alias.txt'))).toBe(false)
expect(existsSync(join(root, 'alias2.txt'))).toBe(true)
expect(readFileSync(join(root, 'target.txt'), 'utf8')).toBe('t')
})
})
describe('removeWorkspaceEntry', () => {
it('unlinks a file', async () => {
writeFileSync(join(root, 'gone.txt'), 'x')
await removeWorkspaceEntry({ cwd: root, path: join(root, 'gone.txt') })
expect(existsSync(join(root, 'gone.txt'))).toBe(false)
})
it('removes a directory recursively', async () => {
mkdirSync(join(root, 'tree/sub'), { recursive: true })
writeFileSync(join(root, 'tree/sub/leaf.txt'), 'x')
await removeWorkspaceEntry({ cwd: root, path: join(root, 'tree') })
expect(existsSync(join(root, 'tree'))).toBe(false)
})
it('unlinks a symlink row without touching (or recursing into) its target', async () => {
mkdirSync(join(root, 'realdir'), { recursive: true })
writeFileSync(join(root, 'realdir/keep.txt'), 'x')
symlinkSync(join(root, 'realdir'), join(root, 'linkdir'))
await removeWorkspaceEntry({ cwd: root, path: join(root, 'linkdir') })
expect(existsSync(join(root, 'linkdir'))).toBe(false)
expect(readFileSync(join(root, 'realdir/keep.txt'), 'utf8')).toBe('x')
})
it('refuses the workspace root and missing paths', async () => {
await expect(removeWorkspaceEntry({ cwd: root, path: root }))
.rejects.toMatchObject({ code: 'fs-error' })
await expect(removeWorkspaceEntry({ cwd: root, path: join(root, 'no-such.txt') }))
.rejects.toMatchObject({ code: 'fs-error' })
})
it.runIf(canSymlink)('unlinks a symlink aimed AT the root, leaving the project intact', async () => {
// The guard compares the ENTRY's own identity (the same `lstat` the
// removal below uses), never what the link resolves to: the link goes and
// the project behind it stays — the behaviour the string compare had.
const { ws, inner } = makeProject()
symlinkSync(inner, join(ws, 'link-to-proj'))
try {
await removeWorkspaceEntry({ cwd: inner, path: join(ws, 'link-to-proj') })
expect(existsSync(join(ws, 'link-to-proj'))).toBe(false)
expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true)
} finally {
removeTree(ws)
}
})
})
describe('session-relative targets (the shared resolution contract, #646)', () => {
it('uploads into a session-relative directory', async () => {
const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-relupload-'))
try {
const { path, size } = await writeWorkspaceUpload({
cwd: ws,
dir: '.',
relativePath: 'up/rel.txt',
chunks: chunksOf('rel'),
})
expect(path).toBe(join(ws, 'up', 'rel.txt'))
expect(size).toBe(3)
expect(readFileSync(path, 'utf8')).toBe('rel')
expect(tmpLeftovers(ws)).toEqual([])
} finally {
removeTree(ws)
}
})
it('renames a session-relative row', async () => {
const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-relrename-'))
try {
writeFileSync(join(ws, 'a.txt'), 'x')
const renamed = await renameWorkspaceEntry({ cwd: ws, path: 'a.txt', name: 'b.txt' })
expect(renamed.path).toBe(join(ws, 'b.txt'))
expect(existsSync(join(ws, 'b.txt'))).toBe(true)
} finally {
removeTree(ws)
}
})
it('removes a session-relative row', async () => {
const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-relremove-'))
try {
writeFileSync(join(ws, 'gone.txt'), 'x')
const removed = await removeWorkspaceEntry({ cwd: ws, path: 'gone.txt' })
expect(removed.path).toBe(join(ws, 'gone.txt'))
expect(existsSync(join(ws, 'gone.txt'))).toBe(false)
} finally {
removeTree(ws)
}
})
it('mkdirs under a session-relative parent', async () => {
const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-relmkdir-'))
try {
const made = await mkdirWorkspaceEntry({ cwd: ws, path: '.', name: 'sub' })
expect(made.path).toBe(join(ws, 'sub'))
expect(existsSync(join(ws, 'sub'))).toBe(true)
} finally {
removeTree(ws)
}
})
})
/**
* One directory has many SPELLINGS — a case variant, a `\\?\` prefix, an 8.3
* short name, a mapped drive. The root guard compared the two strings, so any
* of them walked past it and "delete this row" became a recursive delete of
* the whole project. The guard compares what the filesystem itself compares
* (`dev`+`ino`), which does not care how a path is spelled.
*
* Windows-only: on Linux the variant is a different directory, not a spelling
* of this one, and a case variant of a real path does not exist.
*/
describe.runIf(process.platform === 'win32')('workspace-root guard across path spellings', () => {
it('refuses a case variant of the root', async () => {
const { ws, inner } = makeProject()
try {
const variant = inner.toLowerCase()
// `ProjDir` carries capitals, so the lowercase spelling always differs —
// this does not depend on how the temp directory itself is spelled.
expect(variant).not.toBe(inner)
await expect(removeWorkspaceEntry({ cwd: inner, path: variant }))
.rejects.toMatchObject({ code: 'fs-error' })
expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true)
} finally {
removeTree(ws)
}
})
it('refuses the extended-length spelling of the root', async () => {
const { ws, inner } = makeProject()
try {
await expect(removeWorkspaceEntry({ cwd: inner, path: `\\\\?\\${inner}` }))
.rejects.toMatchObject({ code: 'fs-error' })
expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true)
} finally {
removeTree(ws)
}
})
it('refuses a case variant for rename too', async () => {
const { ws, inner } = makeProject()
try {
await expect(renameWorkspaceEntry({ cwd: inner, path: inner.toLowerCase(), name: 'moved' }))
.rejects.toMatchObject({ code: 'fs-error' })
expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true)
} finally {
removeTree(ws)
}
})
it('still removes a SUBdirectory reached through a spelled-out path', async () => {
const { ws, inner } = makeProject()
try {
mkdirSync(join(inner, 'Sub'))
// A spelled-out path that is NOT the root passes the guard — and unlike a
// case variant this holds on a case-SENSITIVE volume too.
await removeWorkspaceEntry({ cwd: inner, path: `\\\\?\\${join(inner, 'Sub')}` })
expect(existsSync(join(inner, 'Sub'))).toBe(false)
expect(existsSync(inner)).toBe(true)
} finally {
removeTree(ws)
}
})
})