transports.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. """Abstract Transport class."""
  2. __all__ = (
  3. 'BaseTransport', 'ReadTransport', 'WriteTransport',
  4. 'Transport', 'DatagramTransport', 'SubprocessTransport',
  5. )
  6. class BaseTransport:
  7. """Base class for transports."""
  8. __slots__ = ('_extra',)
  9. def __init__(self, extra=None):
  10. if extra is None:
  11. extra = {}
  12. self._extra = extra
  13. def get_extra_info(self, name, default=None):
  14. """Get optional transport information."""
  15. return self._extra.get(name, default)
  16. def is_closing(self):
  17. """Return True if the transport is closing or closed."""
  18. raise NotImplementedError
  19. def close(self):
  20. """Close the transport.
  21. Buffered data will be flushed asynchronously. No more data
  22. will be received. After all buffered data is flushed, the
  23. protocol's connection_lost() method will (eventually) be
  24. called with None as its argument.
  25. """
  26. raise NotImplementedError
  27. def set_protocol(self, protocol):
  28. """Set a new protocol."""
  29. raise NotImplementedError
  30. def get_protocol(self):
  31. """Return the current protocol."""
  32. raise NotImplementedError
  33. class ReadTransport(BaseTransport):
  34. """Interface for read-only transports."""
  35. __slots__ = ()
  36. def is_reading(self):
  37. """Return True if the transport is receiving."""
  38. raise NotImplementedError
  39. def pause_reading(self):
  40. """Pause the receiving end.
  41. No data will be passed to the protocol's data_received()
  42. method until resume_reading() is called.
  43. """
  44. raise NotImplementedError
  45. def resume_reading(self):
  46. """Resume the receiving end.
  47. Data received will once again be passed to the protocol's
  48. data_received() method.
  49. """
  50. raise NotImplementedError
  51. class WriteTransport(BaseTransport):
  52. """Interface for write-only transports."""
  53. __slots__ = ()
  54. def set_write_buffer_limits(self, high=None, low=None):
  55. """Set the high- and low-water limits for write flow control.
  56. These two values control when to call the protocol's
  57. pause_writing() and resume_writing() methods. If specified,
  58. the low-water limit must be less than or equal to the
  59. high-water limit. Neither value can be negative.
  60. The defaults are implementation-specific. If only the
  61. high-water limit is given, the low-water limit defaults to an
  62. implementation-specific value less than or equal to the
  63. high-water limit. Setting high to zero forces low to zero as
  64. well, and causes pause_writing() to be called whenever the
  65. buffer becomes non-empty. Setting low to zero causes
  66. resume_writing() to be called only once the buffer is empty.
  67. Use of zero for either limit is generally sub-optimal as it
  68. reduces opportunities for doing I/O and computation
  69. concurrently.
  70. """
  71. raise NotImplementedError
  72. def get_write_buffer_size(self):
  73. """Return the current size of the write buffer."""
  74. raise NotImplementedError
  75. def get_write_buffer_limits(self):
  76. """Get the high and low watermarks for write flow control.
  77. Return a tuple (low, high) where low and high are
  78. positive number of bytes."""
  79. raise NotImplementedError
  80. def write(self, data):
  81. """Write some data bytes to the transport.
  82. This does not block; it buffers the data and arranges for it
  83. to be sent out asynchronously.
  84. """
  85. raise NotImplementedError
  86. def writelines(self, list_of_data):
  87. """Write a list (or any iterable) of data bytes to the transport.
  88. The default implementation concatenates the arguments and
  89. calls write() on the result.
  90. """
  91. data = b''.join(list_of_data)
  92. self.write(data)
  93. def write_eof(self):
  94. """Close the write end after flushing buffered data.
  95. (This is like typing ^D into a UNIX program reading from stdin.)
  96. Data may still be received.
  97. """
  98. raise NotImplementedError
  99. def can_write_eof(self):
  100. """Return True if this transport supports write_eof(), False if not."""
  101. raise NotImplementedError
  102. def abort(self):
  103. """Close the transport immediately.
  104. Buffered data will be lost. No more data will be received.
  105. The protocol's connection_lost() method will (eventually) be
  106. called with None as its argument.
  107. """
  108. raise NotImplementedError
  109. class Transport(ReadTransport, WriteTransport):
  110. """Interface representing a bidirectional transport.
  111. There may be several implementations, but typically, the user does
  112. not implement new transports; rather, the platform provides some
  113. useful transports that are implemented using the platform's best
  114. practices.
  115. The user never instantiates a transport directly; they call a
  116. utility function, passing it a protocol factory and other
  117. information necessary to create the transport and protocol. (E.g.
  118. EventLoop.create_connection() or EventLoop.create_server().)
  119. The utility function will asynchronously create a transport and a
  120. protocol and hook them up by calling the protocol's
  121. connection_made() method, passing it the transport.
  122. The implementation here raises NotImplemented for every method
  123. except writelines(), which calls write() in a loop.
  124. """
  125. __slots__ = ()
  126. class DatagramTransport(BaseTransport):
  127. """Interface for datagram (UDP) transports."""
  128. __slots__ = ()
  129. def sendto(self, data, addr=None):
  130. """Send data to the transport.
  131. This does not block; it buffers the data and arranges for it
  132. to be sent out asynchronously.
  133. addr is target socket address.
  134. If addr is None use target address pointed on transport creation.
  135. """
  136. raise NotImplementedError
  137. def abort(self):
  138. """Close the transport immediately.
  139. Buffered data will be lost. No more data will be received.
  140. The protocol's connection_lost() method will (eventually) be
  141. called with None as its argument.
  142. """
  143. raise NotImplementedError
  144. class SubprocessTransport(BaseTransport):
  145. __slots__ = ()
  146. def get_pid(self):
  147. """Get subprocess id."""
  148. raise NotImplementedError
  149. def get_returncode(self):
  150. """Get subprocess returncode.
  151. See also
  152. http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode
  153. """
  154. raise NotImplementedError
  155. def get_pipe_transport(self, fd):
  156. """Get transport for pipe with number fd."""
  157. raise NotImplementedError
  158. def send_signal(self, signal):
  159. """Send signal to subprocess.
  160. See also:
  161. docs.python.org/3/library/subprocess#subprocess.Popen.send_signal
  162. """
  163. raise NotImplementedError
  164. def terminate(self):
  165. """Stop the subprocess.
  166. Alias for close() method.
  167. On Posix OSs the method sends SIGTERM to the subprocess.
  168. On Windows the Win32 API function TerminateProcess()
  169. is called to stop the subprocess.
  170. See also:
  171. http://docs.python.org/3/library/subprocess#subprocess.Popen.terminate
  172. """
  173. raise NotImplementedError
  174. def kill(self):
  175. """Kill the subprocess.
  176. On Posix OSs the function sends SIGKILL to the subprocess.
  177. On Windows kill() is an alias for terminate().
  178. See also:
  179. http://docs.python.org/3/library/subprocess#subprocess.Popen.kill
  180. """
  181. raise NotImplementedError
  182. class _FlowControlMixin(Transport):
  183. """All the logic for (write) flow control in a mix-in base class.
  184. The subclass must implement get_write_buffer_size(). It must call
  185. _maybe_pause_protocol() whenever the write buffer size increases,
  186. and _maybe_resume_protocol() whenever it decreases. It may also
  187. override set_write_buffer_limits() (e.g. to specify different
  188. defaults).
  189. The subclass constructor must call super().__init__(extra). This
  190. will call set_write_buffer_limits().
  191. The user may call set_write_buffer_limits() and
  192. get_write_buffer_size(), and their protocol's pause_writing() and
  193. resume_writing() may be called.
  194. """
  195. __slots__ = ('_loop', '_protocol_paused', '_high_water', '_low_water')
  196. def __init__(self, extra=None, loop=None):
  197. super().__init__(extra)
  198. assert loop is not None
  199. self._loop = loop
  200. self._protocol_paused = False
  201. self._set_write_buffer_limits()
  202. def _maybe_pause_protocol(self):
  203. size = self.get_write_buffer_size()
  204. if size <= self._high_water:
  205. return
  206. if not self._protocol_paused:
  207. self._protocol_paused = True
  208. try:
  209. self._protocol.pause_writing()
  210. except (SystemExit, KeyboardInterrupt):
  211. raise
  212. except BaseException as exc:
  213. self._loop.call_exception_handler({
  214. 'message': 'protocol.pause_writing() failed',
  215. 'exception': exc,
  216. 'transport': self,
  217. 'protocol': self._protocol,
  218. })
  219. def _maybe_resume_protocol(self):
  220. if (self._protocol_paused and
  221. self.get_write_buffer_size() <= self._low_water):
  222. self._protocol_paused = False
  223. try:
  224. self._protocol.resume_writing()
  225. except (SystemExit, KeyboardInterrupt):
  226. raise
  227. except BaseException as exc:
  228. self._loop.call_exception_handler({
  229. 'message': 'protocol.resume_writing() failed',
  230. 'exception': exc,
  231. 'transport': self,
  232. 'protocol': self._protocol,
  233. })
  234. def get_write_buffer_limits(self):
  235. return (self._low_water, self._high_water)
  236. def _set_write_buffer_limits(self, high=None, low=None):
  237. if high is None:
  238. if low is None:
  239. high = 64 * 1024
  240. else:
  241. high = 4 * low
  242. if low is None:
  243. low = high // 4
  244. if not high >= low >= 0:
  245. raise ValueError(
  246. f'high ({high!r}) must be >= low ({low!r}) must be >= 0')
  247. self._high_water = high
  248. self._low_water = low
  249. def set_write_buffer_limits(self, high=None, low=None):
  250. self._set_write_buffer_limits(high=high, low=low)
  251. self._maybe_pause_protocol()
  252. def get_write_buffer_size(self):
  253. raise NotImplementedError