transports.py 9.9 KB

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