|
| 1 | +/** |
| 2 | + * Daemon process entry point. |
| 3 | + * This file is forked as a detached child process by `startDaemon`. |
| 4 | + * It creates a kernel, starts the RPC server, and writes the PID file. |
| 5 | + */ |
| 6 | +import '@metamask/kernel-shims/endoify-node'; |
| 7 | + |
| 8 | +// These packages are used at runtime in the daemon process but cannot be |
| 9 | +// listed as direct dependencies of @ocap/cli due to Turbo cyclic dependency |
| 10 | +// constraints (they depend on @metamask/ocap-kernel). |
| 11 | +/* eslint-disable import-x/no-extraneous-dependencies */ |
| 12 | +import { rpcHandlers } from '@metamask/kernel-browser-runtime'; |
| 13 | +import { RpcService } from '@metamask/kernel-rpc-methods'; |
| 14 | +import { makeSQLKernelDatabase } from '@metamask/kernel-store/sqlite/nodejs'; |
| 15 | +import { Logger } from '@metamask/logger'; |
| 16 | +import { Kernel } from '@metamask/ocap-kernel'; |
| 17 | +import { |
| 18 | + DB_FILE, |
| 19 | + PID_FILE, |
| 20 | + SOCK_FILE, |
| 21 | + LOG_FILE, |
| 22 | + createDaemonServer, |
| 23 | +} from '@ocap/kernel-daemon'; |
| 24 | +import { NodejsPlatformServices } from '@ocap/nodejs'; |
| 25 | +/* eslint-enable import-x/no-extraneous-dependencies */ |
| 26 | +import { appendFile, writeFile, access, unlink } from 'node:fs/promises'; |
| 27 | +import type { Server } from 'node:net'; |
| 28 | + |
| 29 | +const logger = new Logger('kernel-daemon'); |
| 30 | + |
| 31 | +let server: Server | undefined; |
| 32 | +let kernel: Kernel | undefined; |
| 33 | + |
| 34 | +/** |
| 35 | + * Redirect logger output to log file. |
| 36 | + * |
| 37 | + * @param message - The message to log. |
| 38 | + * @param args - Additional arguments. |
| 39 | + */ |
| 40 | +async function logToFile(message: string, ...args: unknown[]): Promise<void> { |
| 41 | + const timestamp = new Date().toISOString(); |
| 42 | + const line = `[${timestamp}] ${message} ${args.map(String).join(' ')}\n`; |
| 43 | + await appendFile(LOG_FILE, line); |
| 44 | +} |
| 45 | + |
| 46 | +/** |
| 47 | + * Check whether a file exists at the given path. |
| 48 | + * |
| 49 | + * @param filePath - The path to check. |
| 50 | + * @returns True if the file exists. |
| 51 | + */ |
| 52 | +async function fileExists(filePath: string): Promise<boolean> { |
| 53 | + try { |
| 54 | + await access(filePath); |
| 55 | + return true; |
| 56 | + } catch { |
| 57 | + return false; |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +/** |
| 62 | + * Perform graceful shutdown: stop kernel, close server, clean up files. |
| 63 | + */ |
| 64 | +async function shutdown(): Promise<void> { |
| 65 | + await logToFile('Shutting down daemon...'); |
| 66 | + |
| 67 | + if (kernel) { |
| 68 | + try { |
| 69 | + await kernel.stop(); |
| 70 | + } catch (error) { |
| 71 | + await logToFile('Error stopping kernel:', String(error)); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + if (server) { |
| 76 | + server.close(); |
| 77 | + } |
| 78 | + |
| 79 | + if (await fileExists(PID_FILE)) { |
| 80 | + await unlink(PID_FILE); |
| 81 | + } |
| 82 | + if (await fileExists(SOCK_FILE)) { |
| 83 | + await unlink(SOCK_FILE); |
| 84 | + } |
| 85 | + |
| 86 | + // eslint-disable-next-line n/no-process-exit |
| 87 | + process.exit(0); |
| 88 | +} |
| 89 | + |
| 90 | +/** |
| 91 | + * |
| 92 | + */ |
| 93 | +async function main(): Promise<void> { |
| 94 | + await logToFile('Starting daemon process...'); |
| 95 | + |
| 96 | + // Write PID file |
| 97 | + await writeFile(PID_FILE, String(process.pid)); |
| 98 | + await logToFile(`PID ${process.pid} written to ${PID_FILE}`); |
| 99 | + |
| 100 | + // Create platform services |
| 101 | + const platformServices = new NodejsPlatformServices({ |
| 102 | + logger: logger.subLogger({ tags: ['platform-services'] }), |
| 103 | + }); |
| 104 | + |
| 105 | + // Create kernel database with persistent storage |
| 106 | + const kernelDatabase = await makeSQLKernelDatabase({ |
| 107 | + dbFilename: DB_FILE, |
| 108 | + }); |
| 109 | + |
| 110 | + // Create kernel |
| 111 | + kernel = await Kernel.make(platformServices, kernelDatabase, { |
| 112 | + logger: logger.subLogger({ tags: ['kernel'] }), |
| 113 | + }); |
| 114 | + |
| 115 | + await logToFile('Kernel created successfully'); |
| 116 | + |
| 117 | + // Initialize kernel identity (peer ID, crypto) for OCAP URL operations |
| 118 | + await kernel.initIdentity(); |
| 119 | + await logToFile('Kernel identity initialized'); |
| 120 | + |
| 121 | + // Build the RPC dispatcher from the standard kernel handlers |
| 122 | + const rpcService = new RpcService(rpcHandlers, { |
| 123 | + kernel, |
| 124 | + executeDBQuery: (sql: string) => kernelDatabase.executeQuery(sql), |
| 125 | + }); |
| 126 | + |
| 127 | + // Start RPC server |
| 128 | + server = createDaemonServer({ |
| 129 | + rpcDispatcher: rpcService, |
| 130 | + logger: logger.subLogger({ tags: ['rpc-server'] }), |
| 131 | + onShutdown: shutdown, |
| 132 | + }); |
| 133 | + |
| 134 | + await logToFile('Daemon server started'); |
| 135 | + |
| 136 | + // Register signal handlers for graceful shutdown |
| 137 | + process.on('SIGINT', () => { |
| 138 | + shutdown().catch(async (error) => |
| 139 | + logToFile('Error during shutdown:', String(error)), |
| 140 | + ); |
| 141 | + }); |
| 142 | + process.on('SIGTERM', () => { |
| 143 | + shutdown().catch(async (error) => |
| 144 | + logToFile('Error during shutdown:', String(error)), |
| 145 | + ); |
| 146 | + }); |
| 147 | +} |
| 148 | + |
| 149 | +main().catch(async (error) => { |
| 150 | + await logToFile('Fatal error starting daemon:', String(error)); |
| 151 | + // eslint-disable-next-line n/no-process-exit |
| 152 | + process.exit(1); |
| 153 | +}); |
0 commit comments