Skip to content

Commit

Permalink
chore: when dev server restarts, ensure exiting the parent process ki…
Browse files Browse the repository at this point in the history
…lls child process (#8703)
  • Loading branch information
AlessioGr authored Oct 14, 2024
1 parent e3957d7 commit f1ebf56
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
13 changes: 11 additions & 2 deletions test/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { loadEnv } from 'payload/node'

import { getNextRootDir } from './helpers/getNextRootDir.js'
import { runInit } from './runInit.js'
import { safelyRunScriptFunction } from './safelyRunScript.js'
import { child, safelyRunScriptFunction } from './safelyRunScript.js'
import { createTestHooks } from './testHooks.js'

const prod = process.argv.includes('--prod')
Expand Down Expand Up @@ -59,6 +59,15 @@ await nextDev({ port }, 'default', rootDir)
void fetch(`http://localhost:${port}${adminRoute}`)

// This ensures that the next-server process is killed when this process is killed and doesn't linger around.
process.on('SIGINT', function () {
process.on('SIGINT', () => {
if (child) {
child.kill('SIGINT')
}
process.exit(0)
})
process.on('SIGTERM', () => {
if (child) {
child.kill('SIGINT')
}
process.exit(0) // Exit the parent process
})
22 changes: 14 additions & 8 deletions test/safelyRunScript.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { spawn } from 'child_process'
import path from 'path'

export let child

/**
* Sometimes, running certain functions in certain scripts from the command line will cause the script to be terminated
* with a "Detected unsettled top-level await" error. This often happens if that function imports the payload config.
Expand Down Expand Up @@ -29,22 +31,26 @@ export async function safelyRunScriptFunction(
})
}

function restartProcess(reason: string): never {
function restartProcess(reason: string) {
console.warn(`Restarting process: ${reason}`)

// Get the path to the current script
const scriptPath = process.argv[1]
const absoluteScriptPath = path.resolve(scriptPath)

// Spawn a new process
const child = spawn('tsx', [absoluteScriptPath, ...process.argv.slice(2)], {
child = spawn('tsx', [absoluteScriptPath, ...process.argv.slice(2)], {
stdio: 'inherit',
detached: true,
// detached: true,
})

// Unref the child process so the parent can exit
child.unref()

// Exit the current process
process.exit(0)
// Setup signal handlers to ensure child process exits correctly
process.on('SIGINT', () => {
child.kill('SIGINT') // Forward SIGINT to child process
process.exit(0) // Exit the parent process
})
process.on('SIGTERM', () => {
child.kill('SIGTERM') // Forward SIGTERM to child process
process.exit(0) // Exit the parent process
})
}

0 comments on commit f1ebf56

Please sign in to comment.