Skip to content

Commit 474f188

Browse files
therealbradclaude
andauthored
fix(audit): bundling-safe CLI guard in apply-triggers (stop worker crash-loop) (#469)
`require.main === module` is unreliable once apply-triggers.ts is bundled: esbuild inlines it into dist/workers/auditLogWorker.js, where `require.main === module` evaluates TRUE for the bundle entry. That ran the apply-triggers CLI main() inside the audit-log worker, which connected to the worker's placeholder DATABASE_URL (localhost:5432), hit ECONNREFUSED, and process.exit(1) — crash-looping the worker so the audit-logs queue stopped draining and Loop B materialization stalled. (The Next/webpack web build was unaffected, so the web canary passed.) Gate the CLI on the process entry-script path instead: argv[1] contains "apply-triggers" only when invoked directly (tsx scripts/apply-triggers.ts), never when bundled into the worker or the Next server. applyAuditTriggers() remains a side-effect-free import for the boot hooks. Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 33b0dab commit 474f188

1 file changed

Lines changed: 8 additions & 3 deletions

File tree

testplanit/scripts/apply-triggers.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -355,9 +355,14 @@ async function main() {
355355
await applyAuditTriggers();
356356
}
357357

358-
// CLI entry only — guarded so importing applyAuditTriggers() (e.g. the instrumentation boot hook)
359-
// never auto-runs the apply or calls process.exit. `require.main` is undefined when bundled.
360-
if (typeof require !== "undefined" && require.main === module) {
358+
// CLI entry only. `require.main === module` is NOT safe here: esbuild inlines this file into the
359+
// worker bundle (dist/workers/auditLogWorker.js), where `require.main === module` is TRUE for the
360+
// bundle entry — so it would wrongly run the CLI, connect to the worker's placeholder DB, and crash
361+
// it on a loop. Gate on the actual process entry-script path instead: argv[1] only contains
362+
// "apply-triggers" when this is invoked directly as the CLI (tsx scripts/apply-triggers.ts), and
363+
// never when bundled into auditLogWorker.js or the Next server.
364+
const isCliEntry = /apply-triggers/.test(process.argv[1] ?? "");
365+
if (isCliEntry) {
361366
main().catch((err) => {
362367
console.error("[apply-triggers] apply failed:", err);
363368
process.exit(1);

0 commit comments

Comments
 (0)