| 207 | }; |
| 208 | |
| 209 | const watchdog = async () => { |
| 210 | let consecutiveFailures = 0; |
| 211 | let restarts = 0; |
| 212 | for (;;) { |
| 213 | await sleep(WATCHDOG_INTERVAL_MS); |
| 214 | if (stopping) return; |
| 215 | try { |
| 216 | await probe(); |
| 217 | consecutiveFailures = 0; |
| 218 | } catch (cause) { |
| 219 | consecutiveFailures += 1; |
| 220 | console.error( |
| 221 | `[dev-db][watchdog] probe failed (${consecutiveFailures}/${WATCHDOG_FAILURES_TO_RESTART}): ${String(cause)}`, |
| 222 | ); |
| 223 | if (consecutiveFailures < WATCHDOG_FAILURES_TO_RESTART) continue; |
| 224 | console.error( |
| 225 | `[dev-db][watchdog] socket server wedged; stats: ${JSON.stringify(server.getStats())}`, |
| 226 | ); |
| 227 | if (restarts >= WATCHDOG_MAX_RESTARTS) { |
| 228 | console.error( |
| 229 | `[dev-db][watchdog] still wedged after ${restarts} restarts — giving up so the boot supervisor reports it`, |
| 230 | ); |
| 231 | process.exit(1); |
| 232 | } |
| 233 | restarts += 1; |
| 234 | consecutiveFailures = 0; |
| 235 | console.error( |
| 236 | `[dev-db][watchdog] restarting socket server (${restarts}/${WATCHDOG_MAX_RESTARTS})`, |
| 237 | ); |
| 238 | // stop() itself goes through the query queue (detach rolls back open |
| 239 | // transactions), so a wedge deep enough can hang the restart too — |
| 240 | // bound it and treat that as fatal rather than hanging the watchdog. |
| 241 | const restart = async () => { |
| 242 | await server.stop(); |
| 243 | server = makeServer(); |
| 244 | await server.start(); |
| 245 | }; |
| 246 | try { |
| 247 | await Promise.race([ |
| 248 | restart(), |
| 249 | sleep(15_000).then(() => { |
| 250 | throw new Error("restart timed out after 15s"); |
| 251 | }), |
| 252 | ]); |
| 253 | console.error(`[dev-db][watchdog] socket server restarted`); |
| 254 | } catch (restartCause) { |
| 255 | console.error( |
| 256 | `[dev-db][watchdog] restart failed (${String(restartCause)}) — exiting so the boot supervisor reports it`, |
| 257 | ); |
| 258 | process.exit(1); |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | }; |
| 263 | |
| 264 | void watchdog(); |