Add structured logging and ensure CLI shuts down cleanly

This commit is contained in:
Shantur Rathore
2025-11-17 20:21:39 +00:00
parent 08d81f8bb5
commit 719a9c9c74
13 changed files with 255 additions and 55 deletions

View File

@@ -10,12 +10,15 @@ import { FileSystemBrowser } from "./filesystem/browser"
import { EventBus } from "./events/bus"
import { ServerMeta } from "./api-types"
import { InstanceStore } from "./storage/instance-store"
import { createLogger } from "./logger"
interface CliOptions {
port: number
host: string
rootDir: string
configPath: string
logLevel?: string
logDestination?: string
}
function parseCliOptions(argv: string[]): CliOptions {
@@ -34,20 +37,26 @@ function parseCliOptions(argv: string[]): CliOptions {
host: args.get("host") ?? process.env.CLI_HOST ?? "127.0.0.1",
rootDir: args.get("root") ?? process.cwd(),
configPath: args.get("config") ?? process.env.CLI_CONFIG ?? "~/.config/codenomad/config.json",
logLevel: args.get("log-level") ?? process.env.CLI_LOG_LEVEL,
logDestination: args.get("log-destination") ?? process.env.CLI_LOG_DESTINATION,
}
}
async function main() {
const options = parseCliOptions(process.argv.slice(2))
const logger = createLogger({ level: options.logLevel, destination: options.logDestination })
const eventBus = new EventBus()
const configStore = new ConfigStore(options.configPath, eventBus)
const binaryRegistry = new BinaryRegistry(configStore, eventBus)
logger.info({ options }, "Starting CodeNomad CLI server")
const eventBus = new EventBus(logger)
const configStore = new ConfigStore(options.configPath, eventBus, logger)
const binaryRegistry = new BinaryRegistry(configStore, eventBus, logger)
const workspaceManager = new WorkspaceManager({
rootDir: options.rootDir,
configStore,
binaryRegistry,
eventBus,
logger,
})
const fileSystemBrowser = new FileSystemBrowser({ rootDir: options.rootDir })
const instanceStore = new InstanceStore()
@@ -69,13 +78,36 @@ async function main() {
eventBus,
serverMeta,
instanceStore,
logger,
})
await server.start()
logger.info({ port: options.port, host: options.host }, "HTTP server listening")
let shuttingDown = false
const shutdown = async () => {
await server.stop()
await workspaceManager.shutdown()
if (shuttingDown) {
logger.info("Shutdown already in progress, ignoring signal")
return
}
shuttingDown = true
logger.info("Received shutdown signal, closing server")
try {
await server.stop()
logger.info("HTTP server stopped")
} catch (error) {
logger.error({ err: error }, "Failed to stop HTTP server")
}
try {
await workspaceManager.shutdown()
logger.info("Workspace manager shutdown complete")
} catch (error) {
logger.error({ err: error }, "Workspace manager shutdown failed")
}
logger.info("Exiting process")
process.exit(0)
}
@@ -84,6 +116,7 @@ async function main() {
}
main().catch((error) => {
console.error("CLI server crashed", error)
const logger = createLogger()
logger.error({ err: error }, "CLI server crashed")
process.exit(1)
})