1import errno
2import io
3import socket
4from io import SEEK_END
5from typing import Optional, Union
6
7from ..exceptions import ConnectionError, TimeoutError
8from ..utils import SENTINEL, SSL_AVAILABLE, is_os_level_timeout
9
10NONBLOCKING_EXCEPTION_ERROR_NUMBERS = {BlockingIOError: errno.EWOULDBLOCK}
11
12if SSL_AVAILABLE:
13 import ssl
14
15 if hasattr(ssl, "SSLWantReadError"):
16 NONBLOCKING_EXCEPTION_ERROR_NUMBERS[ssl.SSLWantReadError] = 2
17 NONBLOCKING_EXCEPTION_ERROR_NUMBERS[ssl.SSLWantWriteError] = 2
18 else:
19 NONBLOCKING_EXCEPTION_ERROR_NUMBERS[ssl.SSLError] = 2
20
21NONBLOCKING_EXCEPTIONS = tuple(NONBLOCKING_EXCEPTION_ERROR_NUMBERS.keys())
22
23SERVER_CLOSED_CONNECTION_ERROR = "Connection closed by server."
24
25SYM_CRLF = b"\r\n"
26
27
28class SocketBuffer:
29 def __init__(
30 self, socket: socket.socket, socket_read_size: int, socket_timeout: float
31 ):
32 self._sock = socket
33 self.socket_read_size = socket_read_size
34 self.socket_timeout = socket_timeout
35 self._buffer = io.BytesIO()
36
37 def _live_buffer(self) -> io.BytesIO:
38 """
39 The read buffer, or a ConnectionError when the connection is already gone.
40
41 ``close()`` closes the buffer before dropping it, and it can run while another
42 thread reads: the multi-database client closes connections from its health
43 check thread when a database is taken out of service, so a reader finds either
44 a closed ``BytesIO`` or ``None``. The connection is gone either way, so report
45 it the way every other teardown here is reported and let the retry layers act
46 on it, instead of surfacing ``ValueError: I/O operation on closed file`` to the
47 caller of the command.
48 """
49 buffer = self._buffer
50
51 if buffer is None or buffer.closed:
52 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
53
54 return buffer
55
56 def unread_bytes(self) -> int:
57 """
58 Remaining unread length of buffer
59 """
60 buffer = self._live_buffer()
61
62 try:
63 pos = buffer.tell()
64 end = buffer.seek(0, SEEK_END)
65 buffer.seek(pos)
66 except ValueError:
67 # Closed between the check above and here.
68 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) from None
69
70 return end - pos
71
72 def _read_from_socket(
73 self,
74 length: Optional[int] = None,
75 timeout: Union[float, object] = SENTINEL,
76 raise_on_timeout: Optional[bool] = True,
77 ) -> bool:
78 sock = self._sock
79 socket_read_size = self.socket_read_size
80 marker = 0
81 custom_timeout = timeout is not SENTINEL
82
83 buf = self._live_buffer()
84
85 if sock is None:
86 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
87
88 try:
89 current_pos = buf.tell()
90 buf.seek(0, SEEK_END)
91 except ValueError:
92 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) from None
93
94 if custom_timeout:
95 sock.settimeout(timeout)
96 try:
97 while True:
98 data = sock.recv(socket_read_size)
99 # an empty string indicates the server shutdown the socket
100 if isinstance(data, bytes) and len(data) == 0:
101 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
102 buf.write(data)
103 data_length = len(data)
104 marker += data_length
105
106 if length is not None and length > marker:
107 continue
108 return True
109 except socket.timeout as e:
110 if is_os_level_timeout(e):
111 # ETIMEDOUT from the OS (e.g. after a network change): the
112 # connection is dead, not slow. Reporting it as a timeout - or
113 # as "no data" when polling - would hide a broken connection.
114 raise ConnectionError(f"Error while reading from socket: {e.args}")
115 if raise_on_timeout:
116 raise TimeoutError("Timeout reading from socket")
117 return False
118 except NONBLOCKING_EXCEPTIONS as ex:
119 # if we're in nonblocking mode and the recv raises a
120 # blocking error, simply return False indicating that
121 # there's no data to be read. otherwise raise the
122 # original exception.
123 allowed = NONBLOCKING_EXCEPTION_ERROR_NUMBERS.get(ex.__class__, -1)
124 if ex.errno == allowed:
125 if not raise_on_timeout:
126 return False
127 if timeout == 0:
128 raise TimeoutError("Timeout reading from socket")
129 raise ConnectionError(f"Error while reading from socket: {ex.args}")
130 except ValueError:
131 # The buffer was closed by another thread while this read was in flight.
132 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) from None
133 finally:
134 try:
135 buf.seek(current_pos)
136 except ValueError:
137 # Closed by another thread while recv was blocked. Whatever the body
138 # of the read raised is the outcome to report, so this stays quiet
139 # rather than replacing it - the next read raises ConnectionError.
140 pass
141 if custom_timeout:
142 try:
143 sock.settimeout(self.socket_timeout)
144 except OSError:
145 # Same window as the seek above: the close that dropped the
146 # buffer closed the socket too, so there is nothing left to
147 # restore the timeout on. Staying quiet keeps the outcome the
148 # body reported instead of replacing it with EBADF.
149 pass
150
151 def can_read(self, timeout: float = 0) -> bool:
152 return bool(self.unread_bytes()) or self._read_from_socket(
153 timeout=timeout, raise_on_timeout=False
154 )
155
156 def read(self, length: int, timeout: Union[float, object] = SENTINEL) -> bytes:
157 length = length + 2 # make sure to read the \r\n terminator
158 buf = self._live_buffer()
159 try:
160 # BufferIO will return less than requested if buffer is short
161 data = buf.read(length)
162 missing = length - len(data)
163 if missing:
164 # fill up the buffer and read the remainder
165 self._read_from_socket(length=missing, timeout=timeout)
166 data += buf.read(missing)
167 except ValueError:
168 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) from None
169 return data[:-2]
170
171 def readline(self, timeout: Union[float, object] = SENTINEL) -> bytes:
172 buf = self._live_buffer()
173 try:
174 data = buf.readline()
175 while not data.endswith(SYM_CRLF):
176 # there's more data in the socket that we need
177 self._read_from_socket(timeout=timeout)
178 data += buf.readline()
179 except ValueError:
180 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) from None
181
182 return data[:-2]
183
184 def get_pos(self) -> int:
185 """
186 Get current read position
187 """
188 try:
189 return self._live_buffer().tell()
190 except ValueError:
191 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) from None
192
193 def rewind(self, pos: int) -> None:
194 """
195 Rewind the buffer to a specific position, to re-start reading
196 """
197 buffer = self._buffer
198
199 # Best effort: the caller is unwinding a read that already failed, and a
200 # buffer closed by another thread has nothing to rewind. Raising here would
201 # replace the exception the caller is propagating.
202 if buffer is None:
203 return
204
205 try:
206 buffer.seek(pos)
207 except ValueError:
208 pass
209
210 def purge(self) -> None:
211 """
212 After a successful read, purge the read part of buffer
213 """
214 try:
215 self._purge()
216 except (ConnectionError, ValueError):
217 # Closed by another thread while the response was being read. The
218 # response is already parsed, so there is nothing to report and nothing
219 # left to purge.
220 return
221
222 def _purge(self) -> None:
223 unread = self.unread_bytes()
224
225 # Only if we have read all of the buffer do we truncate, to
226 # reduce the amount of memory thrashing. This heuristic
227 # can be changed or removed later.
228 if unread > 0:
229 return
230
231 # Bind the buffer once: another thread's ``close()`` can drop
232 # ``self._buffer`` to None between the read above and the truncate below,
233 # and the resulting AttributeError would escape ``purge()``'s best effort
234 # wrapper. A local reference to an already closed buffer raises
235 # ValueError, which ``purge()`` handles.
236 buffer = self._live_buffer()
237
238 if unread > 0:
239 # move unread data to the front
240 view = buffer.getbuffer()
241 view[:unread] = view[-unread:]
242 buffer.truncate(unread)
243 buffer.seek(0)
244
245 def close(self) -> None:
246 try:
247 self._buffer.close()
248 except Exception:
249 # issue #633 suggests the purge/close somehow raised a
250 # BadFileDescriptor error. Perhaps the client ran out of
251 # memory or something else? It's probably OK to ignore
252 # any error being raised from purge/close since we're
253 # removing the reference to the instance below.
254 pass
255 self._buffer = None
256 self._sock = None