okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-own (final daf4ac087) into f-0213-int4d482e627

main
4.9 KiB123 linesraw
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:
21    def __init__(self, real, max_bytes: int = 1 << 20, max_chunks: int = 4000):
22        self._real = real
23        self.max_bytes, self.max_chunks = max_bytes, max_chunks
24        self._q: collections.deque[str] = collections.deque()
25        self._bytes = 0
26        self._cv = threading.Condition()
27        self._closing = False
28        self._idle = True
29        self.dropped_chunks = 0
30        self.dropped_bytes = 0
31        self._thread = threading.Thread(target=self._run, name="strata-console", daemon=True)
32        self._thread.start()
33
34    # ---- what the program calls: never blocks on the console
35    def write(self, text) -> int:
36        if not isinstance(text, str):
37            text = str(text)
38        if not text:
39            return 0
40        with self._cv:
41            if self._closing:
42                return len(text)
43            self._q.append(text)
44            self._bytes += len(text)
45            while self._q and (self._bytes > self.max_bytes or len(self._q) > self.max_chunks):
46                old = self._q.popleft()
47                self._bytes -= len(old)
48                self.dropped_chunks += 1
49                self.dropped_bytes += len(old)
50            self._cv.notify()
51        return len(text)
52
53    def flush(self) -> None:
54        return None                                    # the writer thread flushes the real stream
55
56    def writable(self) -> bool:
57        return True
58
59    def isatty(self) -> bool:
60        try:
61            return bool(self._real.isatty())
62        except (OSError, ValueError, AttributeError):
63            return False
64
65    def __getattr__(self, name):                        # encoding, errors, fileno, buffer ...: the real stream's
66        return getattr(self._real, name)
67
68    # ---- the one thread that may block
69    def _run(self) -> None:
70        while True:
71            with self._cv:
72                while not self._q and not self._closing:
73                    self._idle = True
74                    self._cv.notify_all()
75                    self._cv.wait()
76                if not self._q:
77                    self._idle = True
78                    self._cv.notify_all()
79                    return
80                self._idle = False
81                text = self._q.popleft()
82                self._bytes -= len(text)
83            try:
84                self._real.write(text)
85                self._real.flush()
86            except (OSError, ValueError, UnicodeError):
87                pass                                    # a closed or broken console: the text is lost, the server is not held
88
89    def drain(self, timeout: float = 2.0) -> bool:
90        """Wait (bounded) until everything queued has been handed to the real stream."""
91        import time
92        end = time.monotonic() + timeout
93        with self._cv:
94            while (self._q or not self._idle) and time.monotonic() < end:
95                self._cv.wait(timeout=max(0.01, end - time.monotonic()))
96            return not self._q and self._idle
97
98    def close(self, timeout: float = 2.0) -> None:
99        self.drain(timeout)
100        with self._cv:
101            self._closing = True
102            self._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
108    test runner's capture, or a stream somebody else replaced, is left alone).  Restored, and drained for a moment, at
109    the end."""
110    installed = []
111    for name in ("stdout", "stderr"):
112        cur = getattr(sys, name, None)
113        if cur is not None and cur is getattr(sys, "__" + name + "__", None):
114            wrapper = NonBlockingOut(cur)
115            setattr(sys, name, wrapper)
116            installed.append((name, cur, wrapper))
117    try:
118        yield [w for _, _, w in installed]
119    finally:
120        for name, orig, wrapper in installed:
121            wrapper.close()
122            if getattr(sys, name, None) is wrapper:
123                setattr(sys, name, orig)