From 86c67e5955d3cf9a9c024891a93dd05583ff994d Mon Sep 17 00:00:00 2001 From: giles Date: Wed, 1 Apr 2026 13:45:07 +0000 Subject: [PATCH] Auto-restart HTTP server when binary changes Checks binary mtime every 10 requests. If the binary has been rebuilt, closes the listen socket and exec's itself. No more stale server after builds. Co-Authored-By: Claude Opus 4.6 (1M context) --- hosts/ocaml/bin/sx_server.ml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/hosts/ocaml/bin/sx_server.ml b/hosts/ocaml/bin/sx_server.ml index 4434de68..193394de 100644 --- a/hosts/ocaml/bin/sx_server.ml +++ b/hosts/ocaml/bin/sx_server.ml @@ -2658,10 +2658,30 @@ let http_mode port = Unix.bind sock (Unix.ADDR_INET (Unix.inet_addr_any, port)); Unix.listen sock 1024; Printf.eprintf "[sx-http] Listening on port %d (%d render workers, non-blocking)\n%!" port n_workers; + + (* Auto-restart: check if binary has changed every N requests *) + let binary_path = Sys.executable_name in + let binary_mtime = try (Unix.stat binary_path).Unix.st_mtime with _ -> 0.0 in + let request_count = ref 0 in + let check_interval = 10 in (* check every 10 requests *) + let check_restart () = + incr request_count; + if !request_count mod check_interval = 0 then begin + let current_mtime = try (Unix.stat binary_path).Unix.st_mtime with _ -> 0.0 in + if current_mtime > binary_mtime then begin + Printf.eprintf "[sx-http] Binary changed, restarting...\n%!"; + (* Close listen socket, then exec self *) + Unix.close sock; + Unix.execv binary_path (Array.of_list (Array.to_list Sys.argv)) + end + end + in + (try while true do (* Accept a connection *) let (client, _addr) = Unix.accept sock in + check_restart (); (* Read request — non-blocking: set a short timeout *) Unix.setsockopt_float client Unix.SO_RCVTIMEO 5.0; Unix.setsockopt_float client Unix.SO_SNDTIMEO 10.0;