Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/opencode/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { EOL } from "os"
import { WebCommand } from "./cli/cmd/web"
import { PrCommand } from "./cli/cmd/pr"
import { SessionCommand } from "./cli/cmd/session"
import { registerSignalHandlers } from "./signal"

process.on("unhandledRejection", (e) => {
Log.Default.error("rejection", {
Expand All @@ -39,6 +40,8 @@ process.on("uncaughtException", (e) => {
})
})

registerSignalHandlers()

const cli = yargs(hideBin(process.argv))
.parserConfiguration({ "populate--": true })
.scriptName("opencode")
Expand Down
47 changes: 47 additions & 0 deletions packages/opencode/src/signal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Instance } from "./project/instance"
import { Log } from "./util/log"

const SHUTDOWN_TIMEOUT_MS = 5000

const SIGNAL_EXIT_CODES: Record<string, number> = {
SIGTERM: 128 + 15,
SIGINT: 128 + 2,
SIGHUP: 128 + 1,
SIGQUIT: 128 + 3,
}

let shuttingDown = false

async function gracefulShutdown(signal: string) {
if (shuttingDown) return
shuttingDown = true

const log = Log.create({ service: "signal" })
log.info("received signal, shutting down gracefully", { signal })

const timeout = setTimeout(() => {
log.warn("shutdown timeout, forcing exit", {
timeoutMs: SHUTDOWN_TIMEOUT_MS,
signal,
})
process.exit(SIGNAL_EXIT_CODES[signal] ?? 1)
}, SHUTDOWN_TIMEOUT_MS)
timeout.unref()

try {
await Instance.disposeAll()
} catch (error) {
log.error("error during shutdown", { error })
} finally {
clearTimeout(timeout)
process.exit(SIGNAL_EXIT_CODES[signal] ?? 0)
}
}

export function registerSignalHandlers() {
for (const signal of ["SIGTERM", "SIGINT", "SIGHUP", "SIGQUIT"]) {
process.on(signal, () => {
void gracefulShutdown(signal)
})
}
}
Loading