blob: 33fc303a6ffcfcad9038bb53e70376c048fcb1fe [file] [log] [blame]
Yury Selivanov6370f342017-12-10 18:36:12 -05001__all__ = (
2 'StreamReader', 'StreamWriter', 'StreamReaderProtocol',
Andrew Svetlov0baa72f2018-09-11 10:13:04 -07003 'open_connection', 'start_server')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07004
Yury Selivanovb057c522014-02-18 12:15:06 -05005import socket
Andrew Svetlova5d1eb82018-09-12 11:43:04 -07006import sys
7import weakref
Yury Selivanovb057c522014-02-18 12:15:06 -05008
Guido van Rossume3e786c2014-02-18 10:24:30 -08009if hasattr(socket, 'AF_UNIX'):
Yury Selivanov6370f342017-12-10 18:36:12 -050010 __all__ += ('open_unix_connection', 'start_unix_server')
Guido van Rossume3e786c2014-02-18 10:24:30 -080011
Victor Stinnerf951d282014-06-29 00:46:45 +020012from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070013from . import events
Andrew Svetlov0baa72f2018-09-11 10:13:04 -070014from . import exceptions
Andrew Svetlova5d1eb82018-09-12 11:43:04 -070015from . import format_helpers
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070016from . import protocols
Victor Stinneracdb7822014-07-14 18:33:40 +020017from .log import logger
Andrew Svetlov5f841b52017-12-09 00:23:48 +020018from .tasks import sleep
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070019
20
Victor Stinner9551f772018-05-29 16:02:07 +020021_DEFAULT_LIMIT = 2 ** 16 # 64 KiB
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070022
Guido van Rossuma849be92014-01-30 16:05:28 -080023
Andrew Svetlov5f841b52017-12-09 00:23:48 +020024async def open_connection(host=None, port=None, *,
25 loop=None, limit=_DEFAULT_LIMIT, **kwds):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070026 """A wrapper for create_connection() returning a (reader, writer) pair.
27
28 The reader returned is a StreamReader instance; the writer is a
Victor Stinner183e3472014-01-23 17:40:03 +010029 StreamWriter instance.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070030
31 The arguments are all the usual arguments to create_connection()
32 except protocol_factory; most common are positional host and port,
33 with various optional keyword arguments following.
34
35 Additional optional keyword arguments are loop (to set the event loop
36 instance to use) and limit (to set the buffer limit passed to the
37 StreamReader).
38
39 (If you want to customize the StreamReader and/or
40 StreamReaderProtocol classes, just copy the code -- there's
41 really nothing special here except some convenience.)
42 """
43 if loop is None:
44 loop = events.get_event_loop()
45 reader = StreamReader(limit=limit, loop=loop)
Guido van Rossumefef9d32014-01-10 13:26:38 -080046 protocol = StreamReaderProtocol(reader, loop=loop)
Andrew Svetlov5f841b52017-12-09 00:23:48 +020047 transport, _ = await loop.create_connection(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070048 lambda: protocol, host, port, **kwds)
Guido van Rossum355491d2013-10-18 15:17:11 -070049 writer = StreamWriter(transport, protocol, reader, loop)
50 return reader, writer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070051
52
Andrew Svetlov5f841b52017-12-09 00:23:48 +020053async def start_server(client_connected_cb, host=None, port=None, *,
54 loop=None, limit=_DEFAULT_LIMIT, **kwds):
Guido van Rossum1540b162013-11-19 11:43:38 -080055 """Start a socket server, call back for each client connected.
56
57 The first parameter, `client_connected_cb`, takes two parameters:
58 client_reader, client_writer. client_reader is a StreamReader
59 object, while client_writer is a StreamWriter object. This
60 parameter can either be a plain callback function or a coroutine;
61 if it is a coroutine, it will be automatically converted into a
62 Task.
63
64 The rest of the arguments are all the usual arguments to
65 loop.create_server() except protocol_factory; most common are
66 positional host and port, with various optional keyword arguments
67 following. The return value is the same as loop.create_server().
68
69 Additional optional keyword arguments are loop (to set the event loop
70 instance to use) and limit (to set the buffer limit passed to the
71 StreamReader).
72
73 The return value is the same as loop.create_server(), i.e. a
74 Server object which can be used to stop the service.
75 """
76 if loop is None:
77 loop = events.get_event_loop()
78
79 def factory():
80 reader = StreamReader(limit=limit, loop=loop)
81 protocol = StreamReaderProtocol(reader, client_connected_cb,
82 loop=loop)
83 return protocol
84
Andrew Svetlov5f841b52017-12-09 00:23:48 +020085 return await loop.create_server(factory, host, port, **kwds)
Guido van Rossum1540b162013-11-19 11:43:38 -080086
87
Yury Selivanovb057c522014-02-18 12:15:06 -050088if hasattr(socket, 'AF_UNIX'):
89 # UNIX Domain Sockets are supported on this platform
90
Andrew Svetlov5f841b52017-12-09 00:23:48 +020091 async def open_unix_connection(path=None, *,
92 loop=None, limit=_DEFAULT_LIMIT, **kwds):
Yury Selivanovb057c522014-02-18 12:15:06 -050093 """Similar to `open_connection` but works with UNIX Domain Sockets."""
94 if loop is None:
95 loop = events.get_event_loop()
96 reader = StreamReader(limit=limit, loop=loop)
97 protocol = StreamReaderProtocol(reader, loop=loop)
Andrew Svetlov5f841b52017-12-09 00:23:48 +020098 transport, _ = await loop.create_unix_connection(
Yury Selivanovb057c522014-02-18 12:15:06 -050099 lambda: protocol, path, **kwds)
100 writer = StreamWriter(transport, protocol, reader, loop)
101 return reader, writer
102
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200103 async def start_unix_server(client_connected_cb, path=None, *,
104 loop=None, limit=_DEFAULT_LIMIT, **kwds):
Yury Selivanovb057c522014-02-18 12:15:06 -0500105 """Similar to `start_server` but works with UNIX Domain Sockets."""
106 if loop is None:
107 loop = events.get_event_loop()
108
109 def factory():
110 reader = StreamReader(limit=limit, loop=loop)
111 protocol = StreamReaderProtocol(reader, client_connected_cb,
112 loop=loop)
113 return protocol
114
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200115 return await loop.create_unix_server(factory, path, **kwds)
Yury Selivanovb057c522014-02-18 12:15:06 -0500116
117
Guido van Rossum4d62d0b2014-01-29 14:24:45 -0800118class FlowControlMixin(protocols.Protocol):
119 """Reusable flow control logic for StreamWriter.drain().
120
121 This implements the protocol methods pause_writing(),
John Chen8f5c28b2017-12-01 20:33:40 +0800122 resume_writing() and connection_lost(). If the subclass overrides
Guido van Rossum4d62d0b2014-01-29 14:24:45 -0800123 these it must call the super methods.
124
Victor Stinner31e7bfa2014-07-22 12:03:40 +0200125 StreamWriter.drain() must wait for _drain_helper() coroutine.
Guido van Rossum4d62d0b2014-01-29 14:24:45 -0800126 """
127
128 def __init__(self, loop=None):
Victor Stinner70db9e42015-01-09 21:32:05 +0100129 if loop is None:
130 self._loop = events.get_event_loop()
131 else:
132 self._loop = loop
Guido van Rossum4d62d0b2014-01-29 14:24:45 -0800133 self._paused = False
134 self._drain_waiter = None
Victor Stinner31e7bfa2014-07-22 12:03:40 +0200135 self._connection_lost = False
Guido van Rossum4d62d0b2014-01-29 14:24:45 -0800136
137 def pause_writing(self):
138 assert not self._paused
139 self._paused = True
Victor Stinneracdb7822014-07-14 18:33:40 +0200140 if self._loop.get_debug():
141 logger.debug("%r pauses writing", self)
Guido van Rossum4d62d0b2014-01-29 14:24:45 -0800142
143 def resume_writing(self):
144 assert self._paused
145 self._paused = False
Victor Stinneracdb7822014-07-14 18:33:40 +0200146 if self._loop.get_debug():
147 logger.debug("%r resumes writing", self)
148
Guido van Rossum4d62d0b2014-01-29 14:24:45 -0800149 waiter = self._drain_waiter
150 if waiter is not None:
151 self._drain_waiter = None
152 if not waiter.done():
153 waiter.set_result(None)
154
155 def connection_lost(self, exc):
Victor Stinner31e7bfa2014-07-22 12:03:40 +0200156 self._connection_lost = True
Guido van Rossum4d62d0b2014-01-29 14:24:45 -0800157 # Wake up the writer if currently paused.
158 if not self._paused:
159 return
160 waiter = self._drain_waiter
161 if waiter is None:
162 return
163 self._drain_waiter = None
164 if waiter.done():
165 return
166 if exc is None:
167 waiter.set_result(None)
168 else:
169 waiter.set_exception(exc)
170
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200171 async def _drain_helper(self):
Victor Stinner31e7bfa2014-07-22 12:03:40 +0200172 if self._connection_lost:
173 raise ConnectionResetError('Connection lost')
Guido van Rossum4d62d0b2014-01-29 14:24:45 -0800174 if not self._paused:
Victor Stinner31e7bfa2014-07-22 12:03:40 +0200175 return
Guido van Rossum4d62d0b2014-01-29 14:24:45 -0800176 waiter = self._drain_waiter
177 assert waiter is None or waiter.cancelled()
Yury Selivanov7661db62016-05-16 15:38:39 -0400178 waiter = self._loop.create_future()
Guido van Rossum4d62d0b2014-01-29 14:24:45 -0800179 self._drain_waiter = waiter
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200180 await waiter
Guido van Rossum4d62d0b2014-01-29 14:24:45 -0800181
182
183class StreamReaderProtocol(FlowControlMixin, protocols.Protocol):
184 """Helper class to adapt between Protocol and StreamReader.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700185
186 (This is a helper class instead of making StreamReader itself a
187 Protocol subclass, because the StreamReader has other potential
188 uses, and to prevent the user of the StreamReader to accidentally
189 call inappropriate methods of the protocol.)
190 """
191
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700192 _source_traceback = None
193
Guido van Rossum1540b162013-11-19 11:43:38 -0800194 def __init__(self, stream_reader, client_connected_cb=None, loop=None):
Guido van Rossum4d62d0b2014-01-29 14:24:45 -0800195 super().__init__(loop=loop)
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700196 if stream_reader is not None:
197 self._stream_reader_wr = weakref.ref(stream_reader,
198 self._on_reader_gc)
199 self._source_traceback = stream_reader._source_traceback
200 else:
201 self._stream_reader_wr = None
202 if client_connected_cb is not None:
203 # This is a stream created by the `create_server()` function.
204 # Keep a strong reference to the reader until a connection
205 # is established.
206 self._strong_reader = stream_reader
207 self._reject_connection = False
Guido van Rossum1540b162013-11-19 11:43:38 -0800208 self._stream_writer = None
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700209 self._transport = None
Guido van Rossum1540b162013-11-19 11:43:38 -0800210 self._client_connected_cb = client_connected_cb
Yury Selivanov3dc51292016-05-20 11:31:40 -0400211 self._over_ssl = False
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200212 self._closed = self._loop.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700213
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700214 def _on_reader_gc(self, wr):
215 transport = self._transport
216 if transport is not None:
217 # connection_made was called
218 context = {
219 'message': ('An open stream object is being garbage '
220 'collected; call "stream.close()" explicitly.')
221 }
222 if self._source_traceback:
223 context['source_traceback'] = self._source_traceback
224 self._loop.call_exception_handler(context)
225 transport.abort()
226 else:
227 self._reject_connection = True
228 self._stream_reader_wr = None
229
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700230 @property
231 def _stream_reader(self):
232 if self._stream_reader_wr is None:
233 return None
234 return self._stream_reader_wr()
235
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700236 def connection_made(self, transport):
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700237 if self._reject_connection:
238 context = {
239 'message': ('An open stream was garbage collected prior to '
240 'establishing network connection; '
241 'call "stream.close()" explicitly.')
242 }
243 if self._source_traceback:
244 context['source_traceback'] = self._source_traceback
245 self._loop.call_exception_handler(context)
246 transport.abort()
247 return
248 self._transport = transport
249 reader = self._stream_reader
250 if reader is not None:
251 reader.set_transport(transport)
Yury Selivanov3dc51292016-05-20 11:31:40 -0400252 self._over_ssl = transport.get_extra_info('sslcontext') is not None
Guido van Rossum1540b162013-11-19 11:43:38 -0800253 if self._client_connected_cb is not None:
254 self._stream_writer = StreamWriter(transport, self,
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700255 reader,
Guido van Rossum1540b162013-11-19 11:43:38 -0800256 self._loop)
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700257 res = self._client_connected_cb(reader,
Guido van Rossum1540b162013-11-19 11:43:38 -0800258 self._stream_writer)
Victor Stinnerf951d282014-06-29 00:46:45 +0200259 if coroutines.iscoroutine(res):
Victor Stinner896a25a2014-07-08 11:29:25 +0200260 self._loop.create_task(res)
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700261 self._strong_reader = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700262
263 def connection_lost(self, exc):
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700264 reader = self._stream_reader
265 if reader is not None:
Yury Selivanov32dae3d2016-05-13 15:58:00 -0400266 if exc is None:
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700267 reader.feed_eof()
Yury Selivanov32dae3d2016-05-13 15:58:00 -0400268 else:
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700269 reader.set_exception(exc)
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200270 if not self._closed.done():
271 if exc is None:
272 self._closed.set_result(None)
273 else:
274 self._closed.set_exception(exc)
Guido van Rossum4d62d0b2014-01-29 14:24:45 -0800275 super().connection_lost(exc)
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700276 self._stream_reader_wr = None
Yury Selivanov32dae3d2016-05-13 15:58:00 -0400277 self._stream_writer = None
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700278 self._transport = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700279
280 def data_received(self, data):
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700281 reader = self._stream_reader
282 if reader is not None:
283 reader.feed_data(data)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700284
285 def eof_received(self):
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700286 reader = self._stream_reader
287 if reader is not None:
288 reader.feed_eof()
Yury Selivanov3dc51292016-05-20 11:31:40 -0400289 if self._over_ssl:
290 # Prevent a warning in SSLProtocol.eof_received:
291 # "returning true from eof_received()
292 # has no effect when using ssl"
293 return False
Victor Stinnereaf16ab2015-07-25 02:40:40 +0200294 return True
Guido van Rossum355491d2013-10-18 15:17:11 -0700295
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200296 def __del__(self):
297 # Prevent reports about unhandled exceptions.
298 # Better than self._closed._log_traceback = False hack
299 closed = self._closed
300 if closed.done() and not closed.cancelled():
301 closed.exception()
302
Guido van Rossum355491d2013-10-18 15:17:11 -0700303
304class StreamWriter:
305 """Wraps a Transport.
306
307 This exposes write(), writelines(), [can_]write_eof(),
308 get_extra_info() and close(). It adds drain() which returns an
309 optional Future on which you can wait for flow control. It also
Guido van Rossumefef9d32014-01-10 13:26:38 -0800310 adds a transport property which references the Transport
Guido van Rossum355491d2013-10-18 15:17:11 -0700311 directly.
312 """
313
314 def __init__(self, transport, protocol, reader, loop):
315 self._transport = transport
316 self._protocol = protocol
Martin Panter7462b6492015-11-02 03:37:02 +0000317 # drain() expects that the reader has an exception() method
Victor Stinner31e7bfa2014-07-22 12:03:40 +0200318 assert reader is None or isinstance(reader, StreamReader)
Guido van Rossum355491d2013-10-18 15:17:11 -0700319 self._reader = reader
320 self._loop = loop
321
Victor Stinneracdb7822014-07-14 18:33:40 +0200322 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500323 info = [self.__class__.__name__, f'transport={self._transport!r}']
Victor Stinneracdb7822014-07-14 18:33:40 +0200324 if self._reader is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -0500325 info.append(f'reader={self._reader!r}')
326 return '<{}>'.format(' '.join(info))
Victor Stinneracdb7822014-07-14 18:33:40 +0200327
Guido van Rossum355491d2013-10-18 15:17:11 -0700328 @property
329 def transport(self):
330 return self._transport
331
332 def write(self, data):
333 self._transport.write(data)
334
335 def writelines(self, data):
336 self._transport.writelines(data)
337
338 def write_eof(self):
339 return self._transport.write_eof()
340
341 def can_write_eof(self):
342 return self._transport.can_write_eof()
343
Victor Stinner406204c2015-01-15 21:50:19 +0100344 def close(self):
Andrew Svetlov11194c82018-09-13 16:53:49 -0700345 self._transport.close()
Victor Stinner406204c2015-01-15 21:50:19 +0100346
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200347 def is_closing(self):
348 return self._transport.is_closing()
349
350 async def wait_closed(self):
351 await self._protocol._closed
352
Guido van Rossum355491d2013-10-18 15:17:11 -0700353 def get_extra_info(self, name, default=None):
354 return self._transport.get_extra_info(name, default)
355
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200356 async def drain(self):
Victor Stinner31e7bfa2014-07-22 12:03:40 +0200357 """Flush the write buffer.
Guido van Rossum355491d2013-10-18 15:17:11 -0700358
359 The intended use is to write
360
361 w.write(data)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200362 await w.drain()
Guido van Rossum355491d2013-10-18 15:17:11 -0700363 """
Victor Stinner31e7bfa2014-07-22 12:03:40 +0200364 if self._reader is not None:
365 exc = self._reader.exception()
366 if exc is not None:
367 raise exc
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200368 if self._transport.is_closing():
369 # Yield to the event loop so connection_lost() may be
370 # called. Without this, _drain_helper() would return
371 # immediately, and code that calls
372 # write(...); await drain()
373 # in a loop would never call connection_lost(), so it
374 # would not see an error when the socket is closed.
375 await sleep(0, loop=self._loop)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200376 await self._protocol._drain_helper()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700377
Andrew Svetlov11194c82018-09-13 16:53:49 -0700378 async def aclose(self):
379 self.close()
380 await self.wait_closed()
381
382 async def awrite(self, data):
383 self.write(data)
384 await self.drain()
385
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700386
387class StreamReader:
388
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700389 _source_traceback = None
390
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700391 def __init__(self, limit=_DEFAULT_LIMIT, loop=None):
392 # The line length limit is a security feature;
393 # it also doubles as half the buffer limit.
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500394
395 if limit <= 0:
396 raise ValueError('Limit cannot be <= 0')
397
Guido van Rossum355491d2013-10-18 15:17:11 -0700398 self._limit = limit
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700399 if loop is None:
Victor Stinner70db9e42015-01-09 21:32:05 +0100400 self._loop = events.get_event_loop()
401 else:
402 self._loop = loop
Yury Selivanove694c972014-02-05 18:11:13 -0500403 self._buffer = bytearray()
Victor Stinnerc2c12e42015-01-14 00:53:37 +0100404 self._eof = False # Whether we're done.
405 self._waiter = None # A future used by _wait_for_data()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700406 self._exception = None
407 self._transport = None
408 self._paused = False
Andrew Svetlova5d1eb82018-09-12 11:43:04 -0700409 if self._loop.get_debug():
410 self._source_traceback = format_helpers.extract_stack(
411 sys._getframe(1))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700412
Victor Stinnereaf16ab2015-07-25 02:40:40 +0200413 def __repr__(self):
414 info = ['StreamReader']
415 if self._buffer:
Yury Selivanov6370f342017-12-10 18:36:12 -0500416 info.append(f'{len(self._buffer)} bytes')
Victor Stinnereaf16ab2015-07-25 02:40:40 +0200417 if self._eof:
418 info.append('eof')
419 if self._limit != _DEFAULT_LIMIT:
Yury Selivanov6370f342017-12-10 18:36:12 -0500420 info.append(f'limit={self._limit}')
Victor Stinnereaf16ab2015-07-25 02:40:40 +0200421 if self._waiter:
Yury Selivanov6370f342017-12-10 18:36:12 -0500422 info.append(f'waiter={self._waiter!r}')
Victor Stinnereaf16ab2015-07-25 02:40:40 +0200423 if self._exception:
Yury Selivanov6370f342017-12-10 18:36:12 -0500424 info.append(f'exception={self._exception!r}')
Victor Stinnereaf16ab2015-07-25 02:40:40 +0200425 if self._transport:
Yury Selivanov6370f342017-12-10 18:36:12 -0500426 info.append(f'transport={self._transport!r}')
Victor Stinnereaf16ab2015-07-25 02:40:40 +0200427 if self._paused:
428 info.append('paused')
Yury Selivanov6370f342017-12-10 18:36:12 -0500429 return '<{}>'.format(' '.join(info))
Victor Stinnereaf16ab2015-07-25 02:40:40 +0200430
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700431 def exception(self):
432 return self._exception
433
434 def set_exception(self, exc):
435 self._exception = exc
436
Guido van Rossum355491d2013-10-18 15:17:11 -0700437 waiter = self._waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700438 if waiter is not None:
Guido van Rossum355491d2013-10-18 15:17:11 -0700439 self._waiter = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700440 if not waiter.cancelled():
441 waiter.set_exception(exc)
442
Victor Stinnerc2c12e42015-01-14 00:53:37 +0100443 def _wakeup_waiter(self):
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500444 """Wakeup read*() functions waiting for data or EOF."""
Victor Stinnerc2c12e42015-01-14 00:53:37 +0100445 waiter = self._waiter
446 if waiter is not None:
447 self._waiter = None
448 if not waiter.cancelled():
449 waiter.set_result(None)
450
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700451 def set_transport(self, transport):
452 assert self._transport is None, 'Transport already set'
453 self._transport = transport
454
455 def _maybe_resume_transport(self):
Yury Selivanove694c972014-02-05 18:11:13 -0500456 if self._paused and len(self._buffer) <= self._limit:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700457 self._paused = False
Guido van Rossum57497ad2013-10-18 07:58:20 -0700458 self._transport.resume_reading()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700459
460 def feed_eof(self):
Guido van Rossum355491d2013-10-18 15:17:11 -0700461 self._eof = True
Victor Stinnerc2c12e42015-01-14 00:53:37 +0100462 self._wakeup_waiter()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700463
Yury Selivanovf0020f52014-02-06 00:14:30 -0500464 def at_eof(self):
465 """Return True if the buffer is empty and 'feed_eof' was called."""
466 return self._eof and not self._buffer
467
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700468 def feed_data(self, data):
Yury Selivanove694c972014-02-05 18:11:13 -0500469 assert not self._eof, 'feed_data after feed_eof'
470
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700471 if not data:
472 return
473
Yury Selivanove694c972014-02-05 18:11:13 -0500474 self._buffer.extend(data)
Victor Stinnerc2c12e42015-01-14 00:53:37 +0100475 self._wakeup_waiter()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700476
477 if (self._transport is not None and
Yury Selivanovb4617912016-05-16 16:32:38 -0400478 not self._paused and
479 len(self._buffer) > 2 * self._limit):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700480 try:
Guido van Rossum57497ad2013-10-18 07:58:20 -0700481 self._transport.pause_reading()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700482 except NotImplementedError:
483 # The transport can't be paused.
484 # We'll just have to buffer all data.
485 # Forget the transport so we don't keep trying.
486 self._transport = None
487 else:
488 self._paused = True
489
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200490 async def _wait_for_data(self, func_name):
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500491 """Wait until feed_data() or feed_eof() is called.
492
493 If stream was paused, automatically resume it.
494 """
Victor Stinner183e3472014-01-23 17:40:03 +0100495 # StreamReader uses a future to link the protocol feed_data() method
496 # to a read coroutine. Running two read coroutines at the same time
497 # would have an unexpected behaviour. It would not possible to know
498 # which coroutine would get the next data.
499 if self._waiter is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -0500500 raise RuntimeError(
501 f'{func_name}() called while another coroutine is '
502 f'already waiting for incoming data')
Victor Stinnerc2c12e42015-01-14 00:53:37 +0100503
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500504 assert not self._eof, '_wait_for_data after EOF'
505
506 # Waiting for data while paused will make deadlock, so prevent it.
Yury Selivanov3e56ff02016-10-05 18:01:12 -0400507 # This is essential for readexactly(n) for case when n > self._limit.
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500508 if self._paused:
509 self._paused = False
510 self._transport.resume_reading()
511
Yury Selivanov7661db62016-05-16 15:38:39 -0400512 self._waiter = self._loop.create_future()
Victor Stinnerc2c12e42015-01-14 00:53:37 +0100513 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200514 await self._waiter
Victor Stinnerc2c12e42015-01-14 00:53:37 +0100515 finally:
516 self._waiter = None
Victor Stinner183e3472014-01-23 17:40:03 +0100517
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200518 async def readline(self):
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500519 """Read chunk of data from the stream until newline (b'\n') is found.
520
521 On success, return chunk that ends with newline. If only partial
522 line can be read due to EOF, return incomplete line without
523 terminating newline. When EOF was reached while no bytes read, empty
524 bytes object is returned.
525
526 If limit is reached, ValueError will be raised. In that case, if
527 newline was found, complete line including newline will be removed
528 from internal buffer. Else, internal buffer will be cleared. Limit is
529 compared against part of the line without newline.
530
531 If stream was paused, this function will automatically resume it if
532 needed.
533 """
534 sep = b'\n'
535 seplen = len(sep)
536 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200537 line = await self.readuntil(sep)
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700538 except exceptions.IncompleteReadError as e:
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500539 return e.partial
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700540 except exceptions.LimitOverrunError as e:
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500541 if self._buffer.startswith(sep, e.consumed):
542 del self._buffer[:e.consumed + seplen]
543 else:
544 self._buffer.clear()
545 self._maybe_resume_transport()
546 raise ValueError(e.args[0])
547 return line
548
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200549 async def readuntil(self, separator=b'\n'):
Yury Selivanovb4617912016-05-16 16:32:38 -0400550 """Read data from the stream until ``separator`` is found.
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500551
Yury Selivanovb4617912016-05-16 16:32:38 -0400552 On success, the data and separator will be removed from the
553 internal buffer (consumed). Returned data will include the
554 separator at the end.
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500555
Yury Selivanovb4617912016-05-16 16:32:38 -0400556 Configured stream limit is used to check result. Limit sets the
557 maximal length of data that can be returned, not counting the
558 separator.
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500559
Yury Selivanovb4617912016-05-16 16:32:38 -0400560 If an EOF occurs and the complete separator is still not found,
561 an IncompleteReadError exception will be raised, and the internal
562 buffer will be reset. The IncompleteReadError.partial attribute
563 may contain the separator partially.
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500564
Yury Selivanovb4617912016-05-16 16:32:38 -0400565 If the data cannot be read because of over limit, a
566 LimitOverrunError exception will be raised, and the data
567 will be left in the internal buffer, so it can be read again.
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500568 """
569 seplen = len(separator)
570 if seplen == 0:
571 raise ValueError('Separator should be at least one-byte string')
572
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700573 if self._exception is not None:
574 raise self._exception
575
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500576 # Consume whole buffer except last bytes, which length is
577 # one less than seplen. Let's check corner cases with
578 # separator='SEPARATOR':
579 # * we have received almost complete separator (without last
580 # byte). i.e buffer='some textSEPARATO'. In this case we
581 # can safely consume len(separator) - 1 bytes.
582 # * last byte of buffer is first byte of separator, i.e.
583 # buffer='abcdefghijklmnopqrS'. We may safely consume
584 # everything except that last byte, but this require to
585 # analyze bytes of buffer that match partial separator.
586 # This is slow and/or require FSM. For this case our
587 # implementation is not optimal, since require rescanning
588 # of data that is known to not belong to separator. In
589 # real world, separator will not be so long to notice
590 # performance problems. Even when reading MIME-encoded
591 # messages :)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700592
Yury Selivanovb4617912016-05-16 16:32:38 -0400593 # `offset` is the number of bytes from the beginning of the buffer
594 # where there is no occurrence of `separator`.
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500595 offset = 0
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700596
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500597 # Loop until we find `separator` in the buffer, exceed the buffer size,
598 # or an EOF has happened.
599 while True:
600 buflen = len(self._buffer)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700601
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500602 # Check if we now have enough data in the buffer for `separator` to
603 # fit.
604 if buflen - offset >= seplen:
605 isep = self._buffer.find(separator, offset)
606
607 if isep != -1:
Yury Selivanovb4617912016-05-16 16:32:38 -0400608 # `separator` is in the buffer. `isep` will be used later
609 # to retrieve the data.
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500610 break
611
612 # see upper comment for explanation.
613 offset = buflen + 1 - seplen
614 if offset > self._limit:
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700615 raise exceptions.LimitOverrunError(
Yury Selivanovb4617912016-05-16 16:32:38 -0400616 'Separator is not found, and chunk exceed the limit',
617 offset)
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500618
619 # Complete message (with full separator) may be present in buffer
620 # even when EOF flag is set. This may happen when the last chunk
621 # adds data which makes separator be found. That's why we check for
622 # EOF *ater* inspecting the buffer.
Guido van Rossum355491d2013-10-18 15:17:11 -0700623 if self._eof:
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500624 chunk = bytes(self._buffer)
625 self._buffer.clear()
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700626 raise exceptions.IncompleteReadError(chunk, None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700627
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500628 # _wait_for_data() will resume reading if stream was paused.
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200629 await self._wait_for_data('readuntil')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700630
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500631 if isep > self._limit:
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700632 raise exceptions.LimitOverrunError(
Yury Selivanovb4617912016-05-16 16:32:38 -0400633 'Separator is found, but chunk is longer than limit', isep)
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500634
635 chunk = self._buffer[:isep + seplen]
636 del self._buffer[:isep + seplen]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700637 self._maybe_resume_transport()
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500638 return bytes(chunk)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700639
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200640 async def read(self, n=-1):
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500641 """Read up to `n` bytes from the stream.
642
643 If n is not provided, or set to -1, read until EOF and return all read
644 bytes. If the EOF was received and the internal buffer is empty, return
645 an empty bytes object.
646
Martin Panter0be894b2016-09-07 12:03:06 +0000647 If n is zero, return empty bytes object immediately.
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500648
649 If n is positive, this function try to read `n` bytes, and may return
650 less or equal bytes than requested, but at least one byte. If EOF was
651 received before any byte is read, this function returns empty byte
652 object.
653
Yury Selivanovb4617912016-05-16 16:32:38 -0400654 Returned value is not limited with limit, configured at stream
655 creation.
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500656
657 If stream was paused, this function will automatically resume it if
658 needed.
659 """
660
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700661 if self._exception is not None:
662 raise self._exception
663
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500664 if n == 0:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700665 return b''
666
667 if n < 0:
Guido van Rossumbf88ffb2014-05-12 10:04:37 -0700668 # This used to just loop creating a new waiter hoping to
669 # collect everything in self._buffer, but that would
670 # deadlock if the subprocess sends more than self.limit
671 # bytes. So just call self.read(self._limit) until EOF.
672 blocks = []
673 while True:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200674 block = await self.read(self._limit)
Guido van Rossumbf88ffb2014-05-12 10:04:37 -0700675 if not block:
676 break
677 blocks.append(block)
678 return b''.join(blocks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700679
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500680 if not self._buffer and not self._eof:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200681 await self._wait_for_data('read')
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500682
683 # This will work right even if buffer is less than n bytes
684 data = bytes(self._buffer[:n])
685 del self._buffer[:n]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700686
Yury Selivanove694c972014-02-05 18:11:13 -0500687 self._maybe_resume_transport()
688 return data
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700689
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200690 async def readexactly(self, n):
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500691 """Read exactly `n` bytes.
692
Yury Selivanovb4617912016-05-16 16:32:38 -0400693 Raise an IncompleteReadError if EOF is reached before `n` bytes can be
694 read. The IncompleteReadError.partial attribute of the exception will
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500695 contain the partial read bytes.
696
697 if n is zero, return empty bytes object.
698
Yury Selivanovb4617912016-05-16 16:32:38 -0400699 Returned value is not limited with limit, configured at stream
700 creation.
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500701
702 If stream was paused, this function will automatically resume it if
703 needed.
704 """
Yury Selivanovdddc7812015-12-11 11:32:59 -0500705 if n < 0:
706 raise ValueError('readexactly size can not be less than zero')
707
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700708 if self._exception is not None:
709 raise self._exception
710
Yury Selivanovd9d0e862016-01-11 12:28:19 -0500711 if n == 0:
712 return b''
713
Yury Selivanov3e56ff02016-10-05 18:01:12 -0400714 while len(self._buffer) < n:
715 if self._eof:
716 incomplete = bytes(self._buffer)
717 self._buffer.clear()
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700718 raise exceptions.IncompleteReadError(incomplete, n)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700719
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200720 await self._wait_for_data('readexactly')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700721
Yury Selivanov3e56ff02016-10-05 18:01:12 -0400722 if len(self._buffer) == n:
723 data = bytes(self._buffer)
724 self._buffer.clear()
725 else:
726 data = bytes(self._buffer[:n])
727 del self._buffer[:n]
728 self._maybe_resume_transport()
729 return data
Yury Selivanovd08c3632015-05-13 15:15:56 -0400730
Yury Selivanovfaa135a2017-10-06 02:08:57 -0400731 def __aiter__(self):
732 return self
Yury Selivanovd08c3632015-05-13 15:15:56 -0400733
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200734 async def __anext__(self):
735 val = await self.readline()
Yury Selivanovfaa135a2017-10-06 02:08:57 -0400736 if val == b'':
737 raise StopAsyncIteration
738 return val