Skip to content

Commit 57bd1a9

Browse files
Sheraffclaude
andauthored
fix(router-generator): don't scaffold over a route file mid in-place save (#8664)
* fix(router-generator): don't scaffold over a route file mid in-place save An in-place save truncates the file and then writes it. If the generator reads the route file in between, it sees empty content and scaffolds a template. Its mtime guard before renaming the template into place does not catch the completed save, because the truncation and the write usually share one mtime tick on Linux, so the user's content was replaced by the template. Route file writes now also confirm the file still has the content the generator read before replacing it. This was the main cause of flaky tanstack-react-start-e2e-hmr runs, where SSR rendered `Hello "/route"!` after the test restored a route file. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(router-generator): check for concurrent saves right before the rename safeFileWrite compared the target's mtime and content before preparing the temporary file's mode and owner, so a save completing during those steps was still replaced. Run the check last, immediately before the rename. The regression test now also completes the save during the temporary file stat, and keeps the generator's tmpDir inside the test directory so the rename never crosses filesystems (EXDEV on CI). Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(router-generator): match generator paths on Windows in concurrent save test The generator reads route files through forward-slash paths, also on Windows, so compare resolved paths when injecting the concurrent save. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(router-generator): only read files whose content is compared The final concurrent-change check before the rename read the whole target file even for the route tree, whose content is never compared. Stat it instead, as before, and read only route files. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent e66da18 commit 57bd1a9

3 files changed

Lines changed: 178 additions & 6 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/router-generator': patch
3+
---
4+
5+
Avoid overwriting a route file with the scaffold template when an in-place save finishes while the generator is reading the file.

‎packages/router-generator/src/generator.ts‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1146,6 +1146,7 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved
11461146
strategy: {
11471147
type: 'mtime',
11481148
expectedMtimeMs: updatedCacheEntry.mtimeMs,
1149+
expectedContent: existingRouteFile.fileContent,
11491150
},
11501151
})
11511152
updatedCacheEntry.mtimeMs = stats.mtimeMs
@@ -1206,6 +1207,9 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved
12061207
| {
12071208
type: 'mtime'
12081209
expectedMtimeMs: bigint
1210+
// An in-place save can truncate and rewrite a file within one mtime
1211+
// tick, so user-authored files also compare the content.
1212+
expectedContent?: string
12091213
}
12101214
| {
12111215
type: 'new-file'
@@ -1215,13 +1219,8 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved
12151219
await this.fs.writeFile(tmpPath, opts.newContent)
12161220

12171221
if (opts.strategy.type === 'mtime') {
1222+
const { expectedMtimeMs, expectedContent } = opts.strategy
12181223
const beforeStat = await this.fs.stat(opts.filePath)
1219-
if (beforeStat.mtimeMs !== opts.strategy.expectedMtimeMs) {
1220-
throw rerun({
1221-
msg: `File ${opts.filePath} was modified by another process during processing.`,
1222-
event: { type: 'update', path: opts.filePath },
1223-
})
1224-
}
12251224
const newFileState = await this.fs.stat(tmpPath)
12261225
if (newFileState.mode !== beforeStat.mode) {
12271226
await this.fs.chmod(tmpPath, beforeStat.mode)
@@ -1247,6 +1246,25 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved
12471246
}
12481247
}
12491248
}
1249+
// Check right before the rename so that changes made while the
1250+
// temporary file was prepared are not overwritten.
1251+
let changed: boolean
1252+
if (expectedContent === undefined) {
1253+
const current = await this.fs.stat(opts.filePath)
1254+
changed = current.mtimeMs !== expectedMtimeMs
1255+
} else {
1256+
const current = await this.fs.readFile(opts.filePath)
1257+
changed =
1258+
current === 'file-not-existing' ||
1259+
current.stat.mtimeMs !== expectedMtimeMs ||
1260+
current.fileContent !== expectedContent
1261+
}
1262+
if (changed) {
1263+
throw rerun({
1264+
msg: `File ${opts.filePath} was modified by another process during processing.`,
1265+
event: { type: 'update', path: opts.filePath },
1266+
})
1267+
}
12501268
} else {
12511269
if (await checkFileExists(opts.filePath)) {
12521270
throw rerun({
@@ -1370,6 +1388,7 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved
13701388
strategy: {
13711389
type: 'mtime',
13721390
expectedMtimeMs: rootNodeFile.stat.mtimeMs,
1391+
expectedContent: rootNodeFile.fileContent,
13731392
},
13741393
})
13751394
updatedCacheEntry.fileContent = rootRouteContent
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
import fs from 'node:fs/promises'
2+
import os from 'node:os'
3+
import path from 'node:path'
4+
import { afterEach, describe, expect, it } from 'vitest'
5+
6+
import { Generator, getConfig } from '../src'
7+
8+
const rootRouteSource = `import { createRootRoute } from '@tanstack/react-router'
9+
10+
export const Route = createRootRoute()
11+
`
12+
13+
const postsRouteSource = `import { createFileRoute } from '@tanstack/react-router'
14+
15+
export const Route = createFileRoute('/posts')({
16+
component: () => 'posts',
17+
})
18+
`
19+
20+
const savedPostsRouteSource = postsRouteSource.replace("'posts'", "'saved'")
21+
22+
let tempDir: string | undefined
23+
24+
afterEach(async () => {
25+
if (tempDir) {
26+
await fs.rm(tempDir, { recursive: true, force: true })
27+
tempDir = undefined
28+
}
29+
})
30+
31+
async function readFileWithStat(filePath: string) {
32+
try {
33+
const fileHandle = await fs.open(filePath, 'r')
34+
const stat = await fileHandle.stat({ bigint: true })
35+
const fileContent = (await fileHandle.readFile()).toString()
36+
await fileHandle.close()
37+
return { stat, fileContent }
38+
} catch (e: any) {
39+
if (e?.code === 'ENOENT') {
40+
return 'file-not-existing' as const
41+
}
42+
throw e
43+
}
44+
}
45+
46+
describe('generator with concurrent in-place saves', () => {
47+
it.each(['route file read', 'temporary file stat'] as const)(
48+
'does not scaffold over a route file whose in-place save completes during the %s',
49+
async (completeSaveDuring) => {
50+
tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'tsr-generator-race-'))
51+
const routesDirectory = path.join(tempDir, 'routes')
52+
const tmpDir = path.join(tempDir, 'tmp')
53+
const postsRoutePath = path.join(routesDirectory, 'posts.tsx')
54+
await fs.mkdir(routesDirectory)
55+
await fs.writeFile(
56+
path.join(routesDirectory, '__root.tsx'),
57+
rootRouteSource,
58+
)
59+
await fs.writeFile(postsRoutePath, postsRouteSource)
60+
61+
let saveRacesNextRead = false
62+
let completeSave: (() => Promise<void>) | undefined
63+
64+
const generator = new Generator({
65+
config: getConfig(
66+
{
67+
disableLogging: true,
68+
routesDirectory,
69+
generatedRouteTree: path.join(tempDir, 'routeTree.gen.ts'),
70+
tmpDir,
71+
},
72+
tempDir,
73+
),
74+
root: tempDir,
75+
fs: {
76+
rename: (oldPath, newPath) => fs.rename(oldPath, newPath),
77+
writeFile: (filePath, content) => fs.writeFile(filePath, content),
78+
readFile: async (filePath) => {
79+
// The generator passes route paths with forward slashes, also on
80+
// Windows.
81+
if (
82+
!saveRacesNextRead ||
83+
path.resolve(filePath) !== postsRoutePath
84+
) {
85+
return readFileWithStat(filePath)
86+
}
87+
saveRacesNextRead = false
88+
89+
// An editor saving in place truncates the file before writing the
90+
// new content, so the generator can observe an empty route file.
91+
await fs.truncate(postsRoutePath)
92+
const result = await readFileWithStat(postsRoutePath)
93+
if (result === 'file-not-existing') {
94+
throw new Error('expected the route file to exist')
95+
}
96+
97+
// The save then completes within the same timestamp tick, which is
98+
// common for filesystems with coarse mtime granularity.
99+
completeSave = async () => {
100+
completeSave = undefined
101+
await fs.writeFile(postsRoutePath, savedPostsRouteSource)
102+
const truncatedAt = new Date(Number(result.stat.mtimeMs))
103+
await fs.utimes(postsRoutePath, truncatedAt, truncatedAt)
104+
}
105+
if (completeSaveDuring === 'route file read') {
106+
await completeSave()
107+
}
108+
109+
return result
110+
},
111+
stat: async (filePath) => {
112+
if (completeSave && path.resolve(filePath).startsWith(tmpDir)) {
113+
await completeSave()
114+
}
115+
const stat = await fs.stat(filePath, { bigint: true })
116+
return {
117+
mtimeMs: stat.mtimeMs,
118+
mode: Number(stat.mode),
119+
uid: Number(stat.uid),
120+
gid: Number(stat.gid),
121+
}
122+
},
123+
chmod: (filePath, mode) => fs.chmod(filePath, mode),
124+
chown: (filePath, uid, gid) => fs.chown(filePath, uid, gid),
125+
},
126+
})
127+
128+
await generator.run()
129+
130+
// A first save makes the generator process the route file again, and the
131+
// next save races with that read.
132+
await fs.writeFile(
133+
postsRoutePath,
134+
postsRouteSource.replace("'posts'", "'edited'"),
135+
)
136+
const editedAt = new Date(Date.now() + 10_000)
137+
await fs.utimes(postsRoutePath, editedAt, editedAt)
138+
saveRacesNextRead = true
139+
await generator.run({ type: 'update', path: postsRoutePath })
140+
141+
expect(saveRacesNextRead).toBe(false)
142+
expect(completeSave).toBeUndefined()
143+
await expect(fs.readFile(postsRoutePath, 'utf8')).resolves.toBe(
144+
savedPostsRouteSource,
145+
)
146+
},
147+
)
148+
})

0 commit comments

Comments
 (0)