Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions config/scripts/source-tree-walk-benchmark.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import assert from 'node:assert/strict'
import { createHash } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { stripTypeScriptTypes } from 'node:module'
import { resolve } from 'node:path'
import { performance } from 'node:perf_hooks'
import { buildCounterbalancedSchedule } from './counterbalanced-benchmark-schedule.mjs'
import { summarizeBenchmarkSamples } from './benchmark-sample-summary.mjs'

// git show <baseline-ref>:src/shared/source-scan/source-tree-scan.ts | node config/scripts/source-tree-walk-benchmark.mjs
async function load(source) {
const code = stripTypeScriptTypes(source)
return (await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`))
.scanSourceTree
}
const baseline = readFileSync(0, 'utf8')
assert.ok(baseline.includes('function scanSourceTree'), 'Pipe the baseline source into stdin')
const implementations = {
before: await load(baseline),
after: await load(readFileSync('src/shared/source-scan/source-tree-scan.ts', 'utf8'))
}
function fingerprint(files) {
const hash = createHash('sha256')
for (const file of files) {
for (const value of [file.path, file.relativePath, file.source]) {
hash
.update(String(Buffer.byteLength(value)))
.update(':')
.update(value)
}
}
return hash.digest('hex')
}
const results = []
for (const directory of ['src', 'mobile/src', 'cloud/apps']) {
const root = resolve(directory)
const original = implementations.before(root)
const expected = fingerprint(original)
assert.deepEqual(implementations.after(root), original)
const samples = { before: [], after: [] }
for (let warmup = 0; warmup < 2; warmup += 1) {
for (const run of Object.values(implementations)) {
run(root)
}
}
for (const pair of buildCounterbalancedSchedule(8, 'before', 'after')) {
for (const arm of pair) {
const started = performance.now()
const files = implementations[arm](root)
samples[arm].push(performance.now() - started)
assert.equal(fingerprint(files), expected, `${directory} ${arm} inventory changed`)
}
}
results.push({
directory,
files: original.length,
sourceBytes: original.reduce((bytes, file) => bytes + Buffer.byteLength(file.source), 0),
fingerprint: expected,
before: summarizeBenchmarkSamples(samples.before),
after: summarizeBenchmarkSamples(samples.after)
})
}
console.log(JSON.stringify({ node: process.version, platform: process.platform, results }, null, 2))
15 changes: 10 additions & 5 deletions src/shared/source-scan/source-tree-scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,21 @@ export function scanSourceTree(
const extensions = options.extensions ?? /\.tsx?$/
const found: ScannedFile[] = []
const visit = (directory: string): void => {
for (const entry of readdirSync(directory)) {
if (IGNORED_DIRECTORIES.has(entry) || entry.startsWith('.') || entry === '__fixtures__') {
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const name = entry.name
if (IGNORED_DIRECTORIES.has(name) || name.startsWith('.') || name === '__fixtures__') {
continue
}
const path = join(directory, entry)
if (statSync(path).isDirectory()) {
const path = join(directory, name)
// Ordinary entries carry their type from readdir. Links need a stat to follow
// them, and so does DT_UNKNOWN (every predicate false), or a real directory
// would be silently dropped from the scan.
const needsStat = entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory())
if (needsStat ? statSync(path).isDirectory() : entry.isDirectory()) {
visit(path)
continue
}
if (!extensions.test(entry)) {
if (!extensions.test(name)) {
continue
}
const relativePath = relative(root, path).replace(/\\/g, '/')
Expand Down
147 changes: 147 additions & 0 deletions src/shared/source-scan/source-tree-walk.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import {
mkdirSync,
mkdtempSync,
readdirSync,
rmSync,
statSync,
symlinkSync,
writeFileSync
} from 'node:fs'
import type * as Fs from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { scanSourceTree } from './source-tree-scan'

vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof Fs>()
return {
...actual,
readdirSync: vi.fn(actual.readdirSync),
statSync: vi.fn(actual.statSync)
}
})

const actualFs = await vi.importActual<typeof Fs>('node:fs')

Check failure on line 25 in src/shared/source-scan/source-tree-walk.test.ts

View workflow job for this annotation

GitHub Actions / typecheck

The current file is a CommonJS module and cannot use 'await' at the top level.

Check failure on line 25 in src/shared/source-scan/source-tree-walk.test.ts

View workflow job for this annotation

GitHub Actions / package (windows)

The current file is a CommonJS module and cannot use 'await' at the top level.

Check failure on line 25 in src/shared/source-scan/source-tree-walk.test.ts

View workflow job for this annotation

GitHub Actions / package

The current file is a CommonJS module and cannot use 'await' at the top level.

let root: string

beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'orca-source-tree-walk-'))
vi.mocked(readdirSync).mockReset()
vi.mocked(statSync).mockClear()
})

afterEach(() => {
rmSync(root, { recursive: true, force: true })
})

function file(relativePath: string, contents = relativePath): void {
writeFileSync(join(root, relativePath), contents)
}

describe('scanSourceTree filesystem traversal', () => {
it('reads nested source files without stat calls for ordinary directory entries', () => {
mkdirSync(join(root, 'nested'))
file('first.ts')
file(join('nested', 'second.tsx'), 'nested/second.tsx')
file('ignored.txt')
file('first.test.ts')

const files = scanSourceTree(root)

// readdir order is filesystem-dependent (tmpfs differs from APFS/ext4).
expect(files).toHaveLength(2)
expect(files).toEqual(
expect.arrayContaining([
{ path: join(root, 'first.ts'), relativePath: 'first.ts', source: 'first.ts' },
{
path: join(root, 'nested', 'second.tsx'),
relativePath: 'nested/second.tsx',
source: 'nested/second.tsx'
}
])
)
expect(statSync).not.toHaveBeenCalled()
})

it('keeps ignored directories, dotfiles, and test exclusions out of the inventory', () => {
for (const directory of ['node_modules', 'dist', 'out', 'build', '.cache', '__fixtures__']) {
mkdirSync(join(root, directory))
file(join(directory, 'hidden.ts'))
}
file('.hidden.ts')
file('sample.test.ts')
file('sample.spec.tsx')
file('test-harness.ts')
file('production.ts')

expect(scanSourceTree(root).map((entry) => entry.relativePath)).toEqual(['production.ts'])
})

it('keeps extension and test-inclusion options', () => {
file('module.mjs')
file('module.ts')
file('module.test.ts')

expect(
scanSourceTree(root, { includeTests: true })
.map((entry) => entry.relativePath)
.sort()
).toEqual(['module.test.ts', 'module.ts'])
expect(
scanSourceTree(root, { extensions: /\.mjs$/ }).map((entry) => entry.relativePath)
).toEqual(['module.mjs'])
})

it('follows directory links with stat while preserving the lexical path', () => {
const target = join(root, '.target')
mkdirSync(target)
writeFileSync(join(target, 'linked.ts'), 'linked source')
symlinkSync(target, join(root, 'alias'), 'junction')

expect(scanSourceTree(root)).toEqual([
{
path: join(root, 'alias', 'linked.ts'),
relativePath: 'alias/linked.ts',
source: 'linked source'
}
])
expect(statSync).toHaveBeenCalledExactlyOnceWith(join(root, 'alias'))
})

it('stats an entry whose type readdir could not report instead of dropping its subtree', () => {
mkdirSync(join(root, 'nested'))
file(join('nested', 'inner.ts'), 'inner source')
// Filesystems without d_type yield a Dirent where every predicate is false.
vi.mocked(readdirSync).mockImplementationOnce(((directory: Fs.PathLike) =>

Check failure on line 117 in src/shared/source-scan/source-tree-walk.test.ts

View workflow job for this annotation

GitHub Actions / static analysis

typescript(consistent-type-assertions)

Do not use any type assertions.
actualFs.readdirSync(directory, { withFileTypes: true }).map((entry) =>
entry.name === 'nested'
? Object.assign(Object.create(Object.getPrototypeOf(entry)), entry, {
isFile: () => false,
isDirectory: () => false,
isSymbolicLink: () => false
})
: entry
)) as typeof readdirSync)

expect(scanSourceTree(root)).toEqual([
{
path: join(root, 'nested', 'inner.ts'),
relativePath: 'nested/inner.ts',
source: 'inner source'
}
])
expect(statSync).toHaveBeenCalledExactlyOnceWith(join(root, 'nested'))
})

it('still reports a broken link instead of silently dropping it', () => {
const target = join(root, '.target')
mkdirSync(target)
symlinkSync(target, join(root, 'alias'), 'junction')
rmSync(target, { recursive: true })

expect(() => scanSourceTree(root)).toThrow(/ENOENT/)
expect(statSync).toHaveBeenCalledExactlyOnceWith(join(root, 'alias'))
})
})
Loading