okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
326e39118
main
1"""Parent-loss guard and graceful-stop channel for a server launched by the local runtime host. 2 3The inherited pipe has exactly one writer, held by the host. EOF therefore 4means the host exited, including after SIGKILL. 5 6POSIX: the server has its own process group so its engine subprocesses receive 7the emergency stop as well. Windows: the host passes the pipe as the server's 8standard input (``--owner-fd 0``) and ends the server's whole process tree 9through a kill-on-close job object if it dies; the pipe is also how the host 10asks the server to drain and exit (it closes its end), because Windows has no 11SIGTERM to send. EOF is turned into a Ctrl+C in the main thread, which is the 12path the server already drains and stops cleanly on. 13""" 14 15from __future__import annotations 16 17import os 18import signal 19import stat 20import threading 21import time 22 23 24def _stop_gracefully ()-> None : 25import _thread 26_thread .interrupt_main () 27 28 29def start (fd :int ,on_loss = None ,grace :float = 60.0 )-> None : 30if os .name == "nt" : 31if fd < 0 or not stat .S_ISFIFO (os .fstat (fd ).st_mode ): 32raise ValueError ("--owner-fd must be an inherited pipe" ) 33 34def watch_windows ()-> None : 35try : 36while os .read (fd ,1 ): 37pass 38except OSError : 39pass 40 (on_loss or _stop_gracefully )() 41 42threading .Thread (target = watch_windows ,name = "strata-owner-guard" ,daemon = True ).start () 43return 44if os .name != "posix" or fd < 0 or os .getpgrp ()!= os .getpid (): 45raise ValueError ("--owner-fd requires a dedicated POSIX server process group" ) 46if not stat .S_ISFIFO (os .fstat (fd ).st_mode ): 47raise ValueError ("--owner-fd must be an inherited pipe" ) 48 49def watch ()-> None : 50try : 51while os .read (fd ,1 ): 52pass 53except OSError : 54pass # a broken guard must never authorize another process to manage us 55finally : 56os .close (fd ) 57# This is an emergency path. Signal the whole dedicated group so an engine already spawned during model 58# loading cannot be orphaned. SIGTERM is the clean stop (the server drains and closes its engine); if the 59# group is still there after `grace` seconds, SIGKILL ends whatever is left. 60pgid = os .getpgrp () 61try : 62os .killpg (pgid ,signal .SIGTERM ) 63deadline = time .monotonic ()+ grace 64while time .monotonic ()< deadline : 65time .sleep (0.5 ) 66os .killpg (pgid ,signal .SIGKILL ) 67except OSError : 68pass 69 70threading .Thread (target = watch ,name = "strata-owner-guard" ,daemon = True ).start ()