okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4d482e627
main
1"""#4479 / #2481: the server's console output must not hold a request. 2 3A console that stops taking output (a Windows console in QuickEdit/selection mode, a terminal that is paused, a launcher 4that stopped reading the server's pipe) blocks `print()` in whatever thread called it - and some of those threads own the 5engine's turn, a cancel, or an admission. `NonBlockingOut` stands in for sys.stdout / sys.stderr while the server runs: 6write() puts the text on a bounded queue and returns; one daemon thread writes it to the real stream, and may block there 7as long as it likes. When the queue is full the OLDEST text is dropped (the newest lines matter most) and counted in 8`dropped_chunks` / `dropped_bytes`; nothing about a request waits for the console. 9 10Only diagnostics go through here. Protocol output (the engine's pipe, the HTTP replies) does not. 11""" 12from __future__import annotations 13 14import collections 15import contextlib 16import sys 17import threading 18 19 20class NonBlockingOut : 21def __init__ (self ,real ,max_bytes :int = 1 << 20 ,max_chunks :int = 4000 ): 22self ._real = real 23self .max_bytes ,self .max_chunks = max_bytes ,max_chunks 24self ._q :collections .deque [str ]= collections .deque () 25self ._bytes = 0 26self ._cv = threading .Condition () 27self ._closing = False 28self ._idle = True 29self .dropped_chunks = 0 30self .dropped_bytes = 0 31self ._thread = threading .Thread (target = self ._run ,name = "strata-console" ,daemon = True ) 32self ._thread .start () 33 34# ---- what the program calls: never blocks on the console 35def write (self ,text )-> int : 36if not isinstance (text ,str ): 37text = str (text ) 38if not text : 39return 0 40with self ._cv : 41if self ._closing : 42return len (text ) 43self ._q .append (text ) 44self ._bytes += len (text ) 45while self ._q and (self ._bytes > self .max_bytes or len (self ._q )> self .max_chunks ): 46old = self ._q .popleft () 47self ._bytes -= len (old ) 48self .dropped_chunks += 1 49self .dropped_bytes += len (old ) 50self ._cv .notify () 51return len (text ) 52 53def flush (self )-> None : 54return None # the writer thread flushes the real stream 55 56def writable (self )-> bool : 57return True 58 59def isatty (self )-> bool : 60try : 61return bool (self ._real .isatty ()) 62except (OSError ,ValueError ,AttributeError ): 63return False 64 65def __getattr__ (self ,name ):# encoding, errors, fileno, buffer ...: the real stream's 66return getattr (self ._real ,name ) 67 68# ---- the one thread that may block 69def _run (self )-> None : 70while True : 71with self ._cv : 72while not self ._q and not self ._closing : 73self ._idle = True 74self ._cv .notify_all () 75self ._cv .wait () 76if not self ._q : 77self ._idle = True 78self ._cv .notify_all () 79return 80self ._idle = False 81text = self ._q .popleft () 82self ._bytes -= len (text ) 83try : 84self ._real .write (text ) 85self ._real .flush () 86except (OSError ,ValueError ,UnicodeError ): 87pass # a closed or broken console: the text is lost, the server is not held 88 89def drain (self ,timeout :float = 2.0 )-> bool : 90"""Wait (bounded) until everything queued has been handed to the real stream.""" 91import time 92end = time .monotonic ()+ timeout 93with self ._cv : 94while (self ._q or not self ._idle )and time .monotonic ()< end : 95self ._cv .wait (timeout = max (0.01 ,end - time .monotonic ())) 96return not self ._q and self ._idle 97 98def close (self ,timeout :float = 2.0 )-> None : 99self .drain (timeout ) 100with self ._cv : 101self ._closing = True 102self ._cv .notify_all () 103 104 105@ contextlib . contextmanager 106def decoupled_console (): 107"""While the server runs: stdout and stderr go through NonBlockingOut, when they are the process's own streams (a 108test runner's capture, or a stream somebody else replaced, is left alone). Restored, and drained for a moment, at 109the end.""" 110installed = [] 111for name in ("stdout" ,"stderr" ): 112cur = getattr (sys ,name ,None ) 113if cur is not None and cur is getattr (sys ,"__" + name + "__" ,None ): 114wrapper = NonBlockingOut (cur ) 115setattr (sys ,name ,wrapper ) 116installed .append ((name ,cur ,wrapper )) 117try : 118yield [w for _ ,_ ,w in installed ] 119finally : 120for name ,orig ,wrapper in installed : 121wrapper .close () 122if getattr (sys ,name ,None )is wrapper : 123setattr (sys ,name ,orig )