Debian Codegraph @

src/trio/_core/_wakeup_socketpair.py

raw
1 from __future__ import annotations
2
3 import contextlib
4 import signal
5 import socket
6 import warnings
7
8 from .. import _core
9 from .._util import is_main_thread
10
11
12 class WakeupSocketpair:
13 def __init__(self) -> None:
14 # explicitly typed to please `pyright --verifytypes` without `--ignoreexternal`
15 self.wakeup_sock: socket.socket
16 self.write_sock: socket.socket
17
18 self.wakeup_sock, self.write_sock = socket.socketpair()
19 self.wakeup_sock.setblocking(False)
20 self.write_sock.setblocking(False)
21 # This somewhat reduces the amount of memory wasted queueing up data
22 # for wakeups. With these settings, maximum number of 1-byte sends
23 # before getting BlockingIOError:
24 # Linux 4.8: 6
25 # macOS (darwin 15.5): 1
26 # Windows 10: 525347
27 # Windows you're weird. (And on Windows setting SNDBUF to 0 makes send
28 # blocking, even on non-blocking sockets, so don't do that.)
29 self.wakeup_sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1)
30 self.write_sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1)
31 # On Windows this is a TCP socket so this might matter. On other
32 # platforms this fails b/c AF_UNIX sockets aren't actually TCP.
33 with contextlib.suppress(OSError):
34 self.write_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
35 self.old_wakeup_fd: int | None = None
36
37 def wakeup_thread_and_signal_safe(self) -> None:
38 with contextlib.suppress(BlockingIOError):
39 self.write_sock.send(b"\x00")
40
41 async def wait_woken(self) -> None:
42 await _core.wait_readable(self.wakeup_sock)
43 self.drain()
44
45 def drain(self) -> None:
46 try:
47 while True:
48 self.wakeup_sock.recv(2**16)
49 except BlockingIOError:
50 pass
51
52 def wakeup_on_signals(self) -> None:
53 assert self.old_wakeup_fd is None
54 if not is_main_thread():
55 return
56 fd = self.write_sock.fileno()
57 self.old_wakeup_fd = signal.set_wakeup_fd(fd, warn_on_full_buffer=False)
58 if self.old_wakeup_fd != -1:
59 warnings.warn(
60 RuntimeWarning(
61 "It looks like Trio's signal handling code might have "
62 "collided with another library you're using. If you're "
63 "running Trio in guest mode, then this might mean you "
64 "should set host_uses_signal_set_wakeup_fd=True. "
65 "Otherwise, file a bug on Trio and we'll help you figure "
66 "out what's going on.",
67 ),
68 stacklevel=1,
69 )
70
71 def close(self) -> None:
72 self.wakeup_sock.close()
73 self.write_sock.close()
74 if self.old_wakeup_fd is not None:
75 signal.set_wakeup_fd(self.old_wakeup_fd)