|
| 1 | +// Load lightweight internal alias resolver to enable require("logger") |
| 2 | +require("../js/alias-resolver"); |
| 3 | + |
| 4 | +const { spawn } = require("child_process"); |
| 5 | +const fs = require("fs"); |
| 6 | +const path = require("path"); |
| 7 | +const net = require("net"); |
| 8 | +const http = require("http"); |
| 9 | +const Log = require("logger"); |
| 10 | +const { getConfigFilePath } = require("#server_functions"); |
| 11 | + |
| 12 | +const RESTART_DELAY_MS = 500; |
| 13 | +const PORT_CHECK_MAX_ATTEMPTS = 20; |
| 14 | +const PORT_CHECK_INTERVAL_MS = 500; |
| 15 | + |
| 16 | +let child = null; |
| 17 | +let restartTimer = null; |
| 18 | +let isShuttingDown = false; |
| 19 | +let isRestarting = false; |
| 20 | +let serverConfig = null; |
| 21 | +const rootDir = path.join(__dirname, ".."); |
| 22 | + |
| 23 | +/** |
| 24 | + * Get the server configuration (port and address) |
| 25 | + * @returns {{port: number, address: string}} The server config |
| 26 | + */ |
| 27 | +function getServerConfig () { |
| 28 | + if (serverConfig) return serverConfig; |
| 29 | + |
| 30 | + try { |
| 31 | + const configPath = getConfigFilePath(); |
| 32 | + delete require.cache[require.resolve(configPath)]; |
| 33 | + const config = require(configPath); |
| 34 | + serverConfig = { |
| 35 | + port: global.mmPort || config.port || 8080, |
| 36 | + address: config.address || "localhost" |
| 37 | + }; |
| 38 | + } catch (err) { |
| 39 | + serverConfig = { port: 8080, address: "localhost" }; |
| 40 | + } |
| 41 | + |
| 42 | + return serverConfig; |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * Check if a port is available on the configured address |
| 47 | + * @param {number} port The port to check |
| 48 | + * @returns {Promise<boolean>} True if port is available |
| 49 | + */ |
| 50 | +function isPortAvailable (port) { |
| 51 | + return new Promise((resolve) => { |
| 52 | + const server = net.createServer(); |
| 53 | + |
| 54 | + server.once("error", () => { |
| 55 | + resolve(false); |
| 56 | + }); |
| 57 | + |
| 58 | + server.once("listening", () => { |
| 59 | + server.close(); |
| 60 | + resolve(true); |
| 61 | + }); |
| 62 | + |
| 63 | + // Use the same address as the actual server will bind to |
| 64 | + const { address } = getServerConfig(); |
| 65 | + server.listen(port, address); |
| 66 | + }); |
| 67 | +} |
| 68 | + |
| 69 | +/** |
| 70 | + * Wait until port is available |
| 71 | + * @param {number} port The port to wait for |
| 72 | + * @param {number} maxAttempts Maximum number of attempts |
| 73 | + * @returns {Promise<void>} |
| 74 | + */ |
| 75 | +async function waitForPort (port, maxAttempts = PORT_CHECK_MAX_ATTEMPTS) { |
| 76 | + for (let i = 0; i < maxAttempts; i++) { |
| 77 | + if (await isPortAvailable(port)) { |
| 78 | + Log.info(`Port ${port} is now available`); |
| 79 | + return; |
| 80 | + } |
| 81 | + await new Promise((resolve) => setTimeout(resolve, PORT_CHECK_INTERVAL_MS)); |
| 82 | + } |
| 83 | + Log.warn(`Port ${port} still not available after ${maxAttempts} attempts`); |
| 84 | +} |
| 85 | + |
| 86 | +/** |
| 87 | + * Start the server process |
| 88 | + */ |
| 89 | +function startServer () { |
| 90 | + // Start node directly instead of via npm to avoid process tree issues |
| 91 | + child = spawn("node", ["./serveronly"], { |
| 92 | + stdio: "inherit", |
| 93 | + cwd: path.join(__dirname, "..") |
| 94 | + }); |
| 95 | + |
| 96 | + child.on("error", (error) => { |
| 97 | + Log.error("Failed to start server process:", error.message); |
| 98 | + child = null; |
| 99 | + }); |
| 100 | + |
| 101 | + child.on("exit", (code, signal) => { |
| 102 | + child = null; |
| 103 | + |
| 104 | + if (isShuttingDown) { |
| 105 | + return; |
| 106 | + } |
| 107 | + |
| 108 | + if (isRestarting) { |
| 109 | + // Expected restart - don't log as error |
| 110 | + isRestarting = false; |
| 111 | + } else { |
| 112 | + // Unexpected exit |
| 113 | + Log.error(`Server exited unexpectedly with code ${code} and signal ${signal}`); |
| 114 | + } |
| 115 | + }); |
| 116 | +} |
| 117 | + |
| 118 | +/** |
| 119 | + * Send reload notification to all connected clients |
| 120 | + */ |
| 121 | +function notifyClientsToReload () { |
| 122 | + const { port, address } = getServerConfig(); |
| 123 | + const options = { |
| 124 | + hostname: address, |
| 125 | + port: port, |
| 126 | + path: "/reload", |
| 127 | + method: "GET" |
| 128 | + }; |
| 129 | + |
| 130 | + const req = http.request(options, (res) => { |
| 131 | + if (res.statusCode === 200) { |
| 132 | + Log.info("Reload notification sent to clients"); |
| 133 | + } |
| 134 | + }); |
| 135 | + |
| 136 | + req.on("error", (err) => { |
| 137 | + // Server might not be running yet, ignore |
| 138 | + Log.debug(`Could not send reload notification: ${err.message}`); |
| 139 | + }); |
| 140 | + |
| 141 | + req.end(); |
| 142 | +} |
| 143 | + |
| 144 | +/** |
| 145 | + * Restart the server process |
| 146 | + * @param {string} reason The reason for the restart |
| 147 | + */ |
| 148 | +async function restartServer (reason) { |
| 149 | + if (restartTimer) clearTimeout(restartTimer); |
| 150 | + |
| 151 | + restartTimer = setTimeout(async () => { |
| 152 | + Log.info(reason); |
| 153 | + |
| 154 | + if (child) { |
| 155 | + isRestarting = true; |
| 156 | + |
| 157 | + // Get the actual port being used |
| 158 | + const { port } = getServerConfig(); |
| 159 | + |
| 160 | + // Notify clients to reload before restart |
| 161 | + notifyClientsToReload(); |
| 162 | + |
| 163 | + // Set up one-time listener for the exit event |
| 164 | + child.once("exit", async () => { |
| 165 | + // Wait until port is actually available |
| 166 | + await waitForPort(port); |
| 167 | + // Reset config cache in case it changed |
| 168 | + serverConfig = null; |
| 169 | + startServer(); |
| 170 | + }); |
| 171 | + |
| 172 | + child.kill("SIGTERM"); |
| 173 | + } else { |
| 174 | + startServer(); |
| 175 | + } |
| 176 | + }, RESTART_DELAY_MS); |
| 177 | +} |
| 178 | + |
| 179 | +/** |
| 180 | + * Watch a specific file for changes and restart the server on change |
| 181 | + * Watches the parent directory to handle editors that use atomic writes |
| 182 | + * @param {string} file The file path to watch |
| 183 | + */ |
| 184 | +function watchFile (file) { |
| 185 | + try { |
| 186 | + const fileName = path.basename(file); |
| 187 | + const dirName = path.dirname(file); |
| 188 | + |
| 189 | + const watcher = fs.watch(dirName, (_eventType, changedFile) => { |
| 190 | + // Only trigger for the specific file we're interested in |
| 191 | + if (changedFile !== fileName) return; |
| 192 | + |
| 193 | + Log.info(`[watchFile] Change detected in: ${file}`); |
| 194 | + if (restartTimer) clearTimeout(restartTimer); |
| 195 | + |
| 196 | + restartTimer = setTimeout(() => { |
| 197 | + Log.info(`[watchFile] Triggering restart due to change in: ${file}`); |
| 198 | + restartServer(`File changed: ${path.basename(file)} — restarting...`); |
| 199 | + }, RESTART_DELAY_MS); |
| 200 | + }); |
| 201 | + |
| 202 | + watcher.on("error", (error) => { |
| 203 | + Log.error(`Watcher error for ${file}:`, error.message); |
| 204 | + }); |
| 205 | + |
| 206 | + Log.log(`Watching file: ${file}`); |
| 207 | + } catch (error) { |
| 208 | + Log.error(`Failed to watch file ${file}:`, error.message); |
| 209 | + } |
| 210 | +} |
| 211 | + |
| 212 | +startServer(); |
| 213 | + |
| 214 | +// Setup file watching based on config |
| 215 | +try { |
| 216 | + const configPath = getConfigFilePath(); |
| 217 | + delete require.cache[require.resolve(configPath)]; |
| 218 | + const config = require(configPath); |
| 219 | + |
| 220 | + let watchTargets = []; |
| 221 | + if (Array.isArray(config.watchTargets) && config.watchTargets.length > 0) { |
| 222 | + watchTargets = config.watchTargets.filter((target) => typeof target === "string" && target.trim() !== ""); |
| 223 | + } |
| 224 | + |
| 225 | + if (watchTargets.length === 0) { |
| 226 | + Log.warn("Watch mode is enabled but no watchTargets are configured. No files will be monitored. Set the watchTargets array in your config.js to enable file watching."); |
| 227 | + } |
| 228 | + |
| 229 | + Log.log(`Watch mode enabled. Watching ${watchTargets.length} file(s)`); |
| 230 | + |
| 231 | + // Watch each target file |
| 232 | + for (const target of watchTargets) { |
| 233 | + const targetPath = path.isAbsolute(target) |
| 234 | + ? target |
| 235 | + : path.join(rootDir, target); |
| 236 | + |
| 237 | + // Check if file exists |
| 238 | + if (!fs.existsSync(targetPath)) { |
| 239 | + Log.warn(`Watch target does not exist: ${targetPath}`); |
| 240 | + continue; |
| 241 | + } |
| 242 | + |
| 243 | + // Check if it's a file (directories are not supported) |
| 244 | + const stats = fs.statSync(targetPath); |
| 245 | + if (stats.isFile()) { |
| 246 | + watchFile(targetPath); |
| 247 | + } else { |
| 248 | + Log.warn(`Watch target is not a file (directories not supported): ${targetPath}`); |
| 249 | + } |
| 250 | + } |
| 251 | +} catch (err) { |
| 252 | + // Config file might not exist or be invalid, use fallback targets |
| 253 | + Log.warn("Could not load watchTargets from config."); |
| 254 | +} |
| 255 | + |
| 256 | +process.on("SIGINT", () => { |
| 257 | + isShuttingDown = true; |
| 258 | + if (restartTimer) clearTimeout(restartTimer); |
| 259 | + if (child) child.kill("SIGTERM"); |
| 260 | + process.exit(0); |
| 261 | +}); |
0 commit comments