fix: harden core build system against silent failures

- Wrap rebuild() in try/finally to guarantee mutex release (prevents deadlock)
- Surface rebuild errors via .catch() instead of discarding with void
- Add null checks for vfile.data.relativePath (prevents crash on virtual files)
- Add try-finally for worker pool cleanup in parse.ts (prevents thread leaks)
- Remove process.exit(1) from parse error handler (let errors propagate)
- Add per-emitter error handling in emit phase with degraded-build warning
- Replace unsafe Map.get()! assertions with null-checked access in config-loader
This commit is contained in:
saberzero1
2026-05-24 17:09:46 +02:00
parent 17aa8ab233
commit caa55037f7
4 changed files with 192 additions and 160 deletions
+137 -118
View File
@@ -124,7 +124,12 @@ async function startWatching(
for (const content of initialContent) {
const [_tree, vfile] = content
contentMap.set(vfile.data.relativePath!, {
const relPath = vfile.data.relativePath
if (!relPath) {
console.warn(`Skipping file with no relativePath: ${vfile.path}`)
continue
}
contentMap.set(relPath, {
type: "markdown",
content,
})
@@ -165,19 +170,25 @@ async function startWatching(
fp = toPosixPath(fp)
if (buildData.ignored(fp)) return
changes.push({ path: fp as FilePath, type: "add" })
void rebuild(changes, clientRefresh, buildData)
rebuild(changes, clientRefresh, buildData).catch((err) => {
console.error(styleText("red", "Rebuild failed:"), err.message ?? err)
})
})
.on("change", (fp) => {
fp = toPosixPath(fp)
if (buildData.ignored(fp)) return
changes.push({ path: fp as FilePath, type: "change" })
void rebuild(changes, clientRefresh, buildData)
rebuild(changes, clientRefresh, buildData).catch((err) => {
console.error(styleText("red", "Rebuild failed:"), err.message ?? err)
})
})
.on("unlink", (fp) => {
fp = toPosixPath(fp)
if (buildData.ignored(fp)) return
changes.push({ path: fp as FilePath, type: "delete" })
void rebuild(changes, clientRefresh, buildData)
rebuild(changes, clientRefresh, buildData).catch((err) => {
console.error(styleText("red", "Rebuild failed:"), err.message ?? err)
})
})
return async () => {
@@ -194,147 +205,155 @@ async function rebuild(changes: ChangeEvent[], clientRefresh: () => void, buildD
buildData.lastBuildMs = new Date().getTime()
const numChangesInBuild = changes.length
const release = await mut.acquire()
// if there's another build after us, release and let them do it
if (ctx.buildId !== buildId) {
release()
return
}
const perf = new PerfTimer()
perf.addEvent("rebuild")
console.log(styleText("yellow", "Detected change, rebuilding..."))
// update changesSinceLastBuild
for (const change of changes) {
changesSinceLastBuild[change.path] = change.type
}
const staticResources = getStaticResourcesFromPlugins(ctx)
const pathsToParse: FilePath[] = []
for (const [fp, type] of Object.entries(changesSinceLastBuild)) {
if (type === "delete" || path.extname(fp) !== ".md") continue
const fullPath = joinSegments(argv.directory, toPosixPath(fp)) as FilePath
pathsToParse.push(fullPath)
}
const parsed = await parseMarkdown(ctx, pathsToParse)
for (const content of parsed) {
contentMap.set(content[1].data.relativePath!, {
type: "markdown",
content,
})
}
// update state using changesSinceLastBuild
// we do this weird play of add => compute change events => remove
// so that partialEmitters can do appropriate cleanup based on the content of deleted files
for (const [file, change] of Object.entries(changesSinceLastBuild)) {
if (change === "delete") {
// universal delete case
contentMap.delete(file as FilePath)
try {
// if there's another build after us, release and let them do it
if (ctx.buildId !== buildId) {
return
}
// manually track non-markdown files as processed files only
// contains markdown files
if (change === "add" && path.extname(file) !== ".md") {
contentMap.set(file as FilePath, {
type: "other",
const perf = new PerfTimer()
perf.addEvent("rebuild")
console.log(styleText("yellow", "Detected change, rebuilding..."))
// update changesSinceLastBuild
for (const change of changes) {
changesSinceLastBuild[change.path] = change.type
}
const staticResources = getStaticResourcesFromPlugins(ctx)
const pathsToParse: FilePath[] = []
for (const [fp, type] of Object.entries(changesSinceLastBuild)) {
if (type === "delete" || path.extname(fp) !== ".md") continue
const fullPath = joinSegments(argv.directory, toPosixPath(fp)) as FilePath
pathsToParse.push(fullPath)
}
const parsed = await parseMarkdown(ctx, pathsToParse)
for (const content of parsed) {
const relPath = content[1].data.relativePath
if (!relPath) {
console.warn(`Skipping file with no relativePath: ${content[1].path}`)
continue
}
contentMap.set(relPath, {
type: "markdown",
content,
})
}
}
const changeEvents: ChangeEvent[] = Object.entries(changesSinceLastBuild).map(([fp, type]) => {
const path = fp as FilePath
const processedContent = contentMap.get(path)
if (processedContent?.type === "markdown") {
const [_tree, file] = processedContent.content
// update state using changesSinceLastBuild
// we do this weird play of add => compute change events => remove
// so that partialEmitters can do appropriate cleanup based on the content of deleted files
for (const [file, change] of Object.entries(changesSinceLastBuild)) {
if (change === "delete") {
// universal delete case
contentMap.delete(file as FilePath)
}
// manually track non-markdown files as processed files only
// contains markdown files
if (change === "add" && path.extname(file) !== ".md") {
contentMap.set(file as FilePath, {
type: "other",
})
}
}
const changeEvents: ChangeEvent[] = Object.entries(changesSinceLastBuild).map(([fp, type]) => {
const path = fp as FilePath
const processedContent = contentMap.get(path)
if (processedContent?.type === "markdown") {
const [_tree, file] = processedContent.content
return {
type,
path,
file,
}
}
return {
type,
path,
file,
}
})
// update allFiles and then allSlugs with the consistent view of content map
ctx.allFiles = Array.from(contentMap.keys())
ctx.allSlugs = ctx.allFiles.map((fp) => slugifyFilePath(fp as FilePath))
const markdownContent = Array.from(contentMap.values())
.filter((file) => file.type === "markdown")
.map((file) => file.content)
reportSlugCollisions(markdownContent)
let processedFiles = filterContent(ctx, markdownContent)
let emittedFiles = 0
// Phase 1: Run PageTypeDispatcher first so it populates ctx.virtualPages
const dispatcher = cfg.plugins.emitters.find((e) => e.name === "PageTypeDispatcher")
if (dispatcher) {
ctx.virtualPages = []
const emitFn = dispatcher.partialEmit ?? dispatcher.emit
const emitted = await emitFn(ctx, processedFiles, staticResources, changeEvents)
if (emitted !== null) {
if (Symbol.asyncIterator in emitted) {
for await (const file of emitted) {
emittedFiles++
if (ctx.argv.verbose) {
console.log(`[emit:${dispatcher.name}] ${file}`)
}
}
} else {
emittedFiles += emitted.length
if (ctx.argv.verbose) {
for (const file of emitted) {
console.log(`[emit:${dispatcher.name}] ${file}`)
}
}
}
}
}
return {
type,
path,
}
})
// Phase 2: Run all other emitters with content extended by virtual pages
const contentWithVirtual =
ctx.virtualPages.length > 0 ? [...processedFiles, ...ctx.virtualPages] : processedFiles
for (const emitter of cfg.plugins.emitters) {
if (emitter.name === "PageTypeDispatcher") continue
// Try to use partialEmit if available, otherwise assume the output is static
const emitFn = emitter.partialEmit ?? emitter.emit
const emitted = await emitFn(ctx, contentWithVirtual, staticResources, changeEvents)
if (emitted === null) {
continue
}
// update allFiles and then allSlugs with the consistent view of content map
ctx.allFiles = Array.from(contentMap.keys())
ctx.allSlugs = ctx.allFiles.map((fp) => slugifyFilePath(fp as FilePath))
const markdownContent = Array.from(contentMap.values())
.filter((file) => file.type === "markdown")
.map((file) => file.content)
reportSlugCollisions(markdownContent)
let processedFiles = filterContent(ctx, markdownContent)
let emittedFiles = 0
// Phase 1: Run PageTypeDispatcher first so it populates ctx.virtualPages
const dispatcher = cfg.plugins.emitters.find((e) => e.name === "PageTypeDispatcher")
if (dispatcher) {
ctx.virtualPages = []
const emitFn = dispatcher.partialEmit ?? dispatcher.emit
const emitted = await emitFn(ctx, processedFiles, staticResources, changeEvents)
if (emitted !== null) {
if (Symbol.asyncIterator in emitted) {
// Async generator case
for await (const file of emitted) {
emittedFiles++
if (ctx.argv.verbose) {
console.log(`[emit:${dispatcher.name}] ${file}`)
console.log(`[emit:${emitter.name}] ${file}`)
}
}
} else {
// Array case
emittedFiles += emitted.length
if (ctx.argv.verbose) {
for (const file of emitted) {
console.log(`[emit:${dispatcher.name}] ${file}`)
console.log(`[emit:${emitter.name}] ${file}`)
}
}
}
}
console.log(
`Emitted ${emittedFiles} files to \`${argv.output}\` in ${perf.timeSince("rebuild")}`,
)
console.log(styleText("green", `Done rebuilding in ${perf.timeSince()}`))
changes.splice(0, numChangesInBuild)
clientRefresh()
} finally {
release()
}
// Phase 2: Run all other emitters with content extended by virtual pages
const contentWithVirtual =
ctx.virtualPages.length > 0 ? [...processedFiles, ...ctx.virtualPages] : processedFiles
for (const emitter of cfg.plugins.emitters) {
if (emitter.name === "PageTypeDispatcher") continue
// Try to use partialEmit if available, otherwise assume the output is static
const emitFn = emitter.partialEmit ?? emitter.emit
const emitted = await emitFn(ctx, contentWithVirtual, staticResources, changeEvents)
if (emitted === null) {
continue
}
if (Symbol.asyncIterator in emitted) {
// Async generator case
for await (const file of emitted) {
emittedFiles++
if (ctx.argv.verbose) {
console.log(`[emit:${emitter.name}] ${file}`)
}
}
} else {
// Array case
emittedFiles += emitted.length
if (ctx.argv.verbose) {
for (const file of emitted) {
console.log(`[emit:${emitter.name}] ${file}`)
}
}
}
}
console.log(`Emitted ${emittedFiles} files to \`${argv.output}\` in ${perf.timeSince("rebuild")}`)
console.log(styleText("green", `Done rebuilding in ${perf.timeSince()}`))
changes.splice(0, numChangesInBuild)
clientRefresh()
release()
}
export default async (argv: Argv, mut: Mutex, clientRefresh: () => void) => {