Skip to content

Commit

Permalink
handle cli sub process clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
souporserious committed Oct 12, 2024
1 parent e4b8e04 commit d6c374b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 15 deletions.
5 changes: 5 additions & 0 deletions .changeset/poor-lions-enjoy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'renoun': patch
---

Handles CLI sub-process clean up better if an error in the WebSocket server occurs.
47 changes: 32 additions & 15 deletions packages/renoun/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,34 +19,51 @@ process.env.WS_NO_BUFFER_UTIL = 'true'
writeCollectionImports()

if (firstArgument === 'next' || firstArgument === 'waku') {
let subProcess: ReturnType<typeof spawn> | undefined

function cleanupAndExit(code: number) {
if (subProcess) {
subProcess.kill('SIGTERM')
}
process.exit(code)
}

const isDev = secondArgument === undefined || secondArgument === 'dev'

if (process.env.NODE_ENV === undefined) {
process.env.NODE_ENV = isDev ? 'development' : 'production'
}

function runSubProcess() {
const subProcess = spawn(
firstArgument,
[secondArgument, ...restArguments],
{
stdio: 'inherit',
shell: true,
env: {
...process.env,
RENOUN_SERVER: 'true',
},
}
)

subProcess.on('close', (code) => {
subProcess = spawn(firstArgument, [secondArgument, ...restArguments], {
stdio: 'inherit',
shell: true,
env: {
...process.env,
RENOUN_SERVER: 'true',
},
})

subProcess.on('close', (code: number) => {
server.cleanup()
process.exit(code)
cleanupAndExit(code)
})
}

const server = createServer()

runSubProcess()

// Handle Ctrl+C
process.on('SIGINT', () => cleanupAndExit(0))

// Handle kill commands
process.on('SIGTERM', () => cleanupAndExit(0))

process.on('uncaughtException', (error) => {
console.error('Uncaught exception:', error)
cleanupAndExit(1)
})
} else if (firstArgument === 'watch') {
if (process.env.NODE_ENV === undefined) {
process.env.NODE_ENV = 'development'
Expand Down

0 comments on commit d6c374b

Please sign in to comment.