Debian Codegraph @

src/trio/_windows_pipes.py

raw
1 from __future__ import annotations
2
3 import sys
4 from typing import TYPE_CHECKING
5
6 from . import _core
7 from ._abc import ReceiveStream, SendStream
8 from ._core._windows_cffi import _handle, kernel32, raise_winerror
9 from ._util import ConflictDetector, final
10
11 assert sys.platform == "win32" or not TYPE_CHECKING
12
13 # XX TODO: don't just make this up based on nothing.
14 DEFAULT_RECEIVE_SIZE = 65536
15
16
17 # See the comments on _unix_pipes._FdHolder for discussion of why we set the
18 # handle to -1 when it's closed.
19 class _HandleHolder:
20 def __init__(self, handle: int) -> None:
21 self.handle = -1
22 if not isinstance(handle, int):
23 raise TypeError("handle must be an int")
24 self.handle = handle
25 _core.register_with_iocp(self.handle)
26
27 @property
28 def closed(self) -> bool:
29 return self.handle == -1
30
31 def close(self) -> None:
32 if self.closed:
33 return
34 handle = self.handle
35 self.handle = -1
36 if not kernel32.CloseHandle(_handle(handle)):
37 raise_winerror()
38
39 def __del__(self) -> None:
40 self.close()
41
42
43 @final
44 class PipeSendStream(SendStream):
45 """Represents a send stream over a Windows named pipe that has been
46 opened in OVERLAPPED mode.
47 """
48
49 def __init__(self, handle: int) -> None:
50 self._handle_holder = _HandleHolder(handle)
51 self._conflict_detector = ConflictDetector(
52 "another task is currently using this pipe",
53 )
54
55 async def send_all(self, data: bytes | bytearray | memoryview[int]) -> None:
56 with self._conflict_detector:
57 if self._handle_holder.closed:
58 raise _core.ClosedResourceError("this pipe is already closed")
59
60 if not data:
61 await _core.checkpoint()
62 return
63
64 try:
65 written = await _core.write_overlapped(self._handle_holder.handle, data)
66 except BrokenPipeError as ex:
67 raise _core.BrokenResourceError from ex
68 # By my reading of MSDN, this assert is guaranteed to pass so long
69 # as the pipe isn't in nonblocking mode, but... let's just
70 # double-check.
71 assert written == len(data)
72
73 async def wait_send_all_might_not_block(self) -> None:
74 with self._conflict_detector:
75 if self._handle_holder.closed:
76 raise _core.ClosedResourceError("This pipe is already closed")
77
78 # not implemented yet, and probably not needed
79 await _core.checkpoint()
80
81 def close(self) -> None:
82 self._handle_holder.close()
83
84 async def aclose(self) -> None:
85 self.close()
86 await _core.checkpoint()
87
88
89 @final
90 class PipeReceiveStream(ReceiveStream):
91 """Represents a receive stream over an os.pipe object."""
92
93 def __init__(self, handle: int) -> None:
94 self._handle_holder = _HandleHolder(handle)
95 self._conflict_detector = ConflictDetector(
96 "another task is currently using this pipe",
97 )
98
99 async def receive_some(self, max_bytes: int | None = None) -> bytes | bytearray:
100 with self._conflict_detector:
101 if self._handle_holder.closed:
102 raise _core.ClosedResourceError("this pipe is already closed")
103
104 if max_bytes is None:
105 max_bytes = DEFAULT_RECEIVE_SIZE
106 else:
107 if not isinstance(max_bytes, int):
108 raise TypeError("max_bytes must be integer >= 1")
109 if max_bytes < 1:
110 raise ValueError("max_bytes must be integer >= 1")
111
112 buffer = bytearray(max_bytes)
113 try:
114 size = await _core.readinto_overlapped(
115 self._handle_holder.handle,
116 buffer,
117 )
118 except BrokenPipeError:
119 if self._handle_holder.closed:
120 raise _core.ClosedResourceError(
121 "another task closed this pipe",
122 ) from None
123
124 # Windows raises BrokenPipeError on one end of a pipe
125 # whenever the other end closes, regardless of direction.
126 # Convert this to the Unix behavior of returning EOF to the
127 # reader when the writer closes.
128 #
129 # And since we're not raising an exception, we have to
130 # checkpoint. But readinto_overlapped did raise an exception,
131 # so it might not have checkpointed for us. So we have to
132 # checkpoint manually.
133 await _core.checkpoint()
134 return b""
135 else:
136 del buffer[size:]
137 return buffer
138
139 def close(self) -> None:
140 self._handle_holder.close()
141
142 async def aclose(self) -> None:
143 self.close()
144 await _core.checkpoint()