true-level-replication 0.10.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
replication/net.py ADDED
@@ -0,0 +1,678 @@
1
+ # ##### BEGIN GPL LICENSE BLOCK #####
2
+ #
3
+ # This program is free software: you can redistribute it and/or modify
4
+ # it under the terms of the GNU General Public License as published by
5
+ # the Free Software Foundation, either version 3 of the License, or
6
+ # (at your option) any later version.
7
+ #
8
+ # This program is distributed in the hope that it will be useful,
9
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
+ # GNU General Public License for more details.
12
+ #
13
+ # You should have received a copy of the GNU General Public License
14
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
15
+ #
16
+ # ##### END GPL LICENSE BLOCK #####
17
+
18
+ """
19
+ Stdlib-only (socket/selectors/queue) replacement for the zmq ROUTER/DEALER
20
+ transport this library used to depend on.
21
+
22
+ Wire format for one message (used identically by Dealer and Router
23
+ connections):
24
+ 4 bytes: chunk count (big-endian unsigned)
25
+ for each chunk:
26
+ 4 bytes: chunk length (big-endian unsigned)
27
+ N bytes: chunk payload
28
+
29
+ Connect handshake (sent once, immediately after a TCP connect, read once by
30
+ Listener right after accept):
31
+ 4 bytes: identity length (big-endian unsigned)
32
+ N bytes: identity
33
+ 1 byte: role (ROLE_COMMAND / ROLE_DATA / ROLE_TTL)
34
+
35
+ All raw-socket connect/bind calls are funneled through _tcp_connect/_tcp_bind
36
+ and all framed read/write lives in _Connection, so a future non-TCP transport
37
+ (p2p/QUIC) only has to replace those, not every call site in the library.
38
+ """
39
+
40
+ import collections
41
+ import logging
42
+ import queue
43
+ import selectors
44
+ import socket
45
+ import struct
46
+ import threading
47
+ import time
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+ _LEN = struct.Struct("!I")
52
+
53
+ MAX_CHUNK_SIZE = (
54
+ 512 * 1024 * 1024
55
+ ) # sanity cap, guards against a corrupt/adversarial length prefix
56
+ MAX_IDENTITY_SIZE = 256
57
+ HANDSHAKE_TIMEOUT = 5.0
58
+ DEFAULT_BACKLOG = 64
59
+ RECV_BUFFER_SIZE = 65536
60
+
61
+ ROLE_COMMAND = b"C"
62
+ ROLE_DATA = b"D"
63
+ ROLE_TTL = b"T"
64
+ _VALID_ROLES = {ROLE_COMMAND, ROLE_DATA, ROLE_TTL}
65
+
66
+
67
+ class NetworkError(Exception):
68
+ """Base error for the net package"""
69
+
70
+
71
+ class HandshakeError(NetworkError):
72
+ """Raised when a peer's connect handshake is invalid, oversized or times out"""
73
+
74
+
75
+ def encode_message(chunks) -> bytes:
76
+ parts = [_LEN.pack(len(chunks))]
77
+ for chunk in chunks:
78
+ parts.append(_LEN.pack(len(chunk)))
79
+ parts.append(chunk)
80
+ return b"".join(parts)
81
+
82
+
83
+ class FrameReader:
84
+ """Incremental parser turning a raw byte stream into complete messages.
85
+
86
+ Feed it bytes as they arrive off a non-blocking socket; it returns
87
+ whichever messages (each a list of byte chunks) became fully available.
88
+ Never assumes one recv() == one message.
89
+ """
90
+
91
+ _WAIT_COUNT, _WAIT_CHUNK_LEN, _WAIT_CHUNK_DATA = range(3)
92
+
93
+ def __init__(self):
94
+ self._buffer = bytearray()
95
+ self._state = self._WAIT_COUNT
96
+ self._remaining_chunks = 0
97
+ self._current_chunks = []
98
+ self._current_len = 0
99
+
100
+ def feed(self, data: bytes) -> list:
101
+ if not data:
102
+ return []
103
+ self._buffer.extend(data)
104
+ messages = []
105
+ while True:
106
+ if self._state == self._WAIT_COUNT:
107
+ if len(self._buffer) < 4:
108
+ break
109
+ (self._remaining_chunks,) = _LEN.unpack_from(self._buffer, 0)
110
+ del self._buffer[:4]
111
+ self._current_chunks = []
112
+ if self._remaining_chunks == 0:
113
+ messages.append(self._current_chunks)
114
+ self._current_chunks = []
115
+ continue
116
+ self._state = self._WAIT_CHUNK_LEN
117
+ elif self._state == self._WAIT_CHUNK_LEN:
118
+ if len(self._buffer) < 4:
119
+ break
120
+ (self._current_len,) = _LEN.unpack_from(self._buffer, 0)
121
+ if self._current_len > MAX_CHUNK_SIZE:
122
+ raise NetworkError(
123
+ f"frame chunk too large ({self._current_len} bytes)"
124
+ )
125
+ del self._buffer[:4]
126
+ self._state = self._WAIT_CHUNK_DATA
127
+ elif self._state == self._WAIT_CHUNK_DATA:
128
+ if len(self._buffer) < self._current_len:
129
+ break
130
+ chunk = bytes(self._buffer[: self._current_len])
131
+ del self._buffer[: self._current_len]
132
+ self._current_chunks.append(chunk)
133
+ self._remaining_chunks -= 1
134
+ if self._remaining_chunks == 0:
135
+ messages.append(self._current_chunks)
136
+ self._current_chunks = []
137
+ self._state = self._WAIT_COUNT
138
+ else:
139
+ self._state = self._WAIT_CHUNK_LEN
140
+ return messages
141
+
142
+
143
+ def _tcp_connect(address, port, timeout=None) -> socket.socket:
144
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
145
+ sock.settimeout(timeout)
146
+ try:
147
+ sock.connect((address, port))
148
+ except OSError:
149
+ # Not doing this leaks the socket: the caller never gets a
150
+ # reference to it if connect() raises, since the exception
151
+ # propagates before this function returns anything.
152
+ sock.close()
153
+ raise
154
+ return sock
155
+
156
+
157
+ def _tcp_bind(address, port, backlog=DEFAULT_BACKLOG) -> socket.socket:
158
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
159
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
160
+ sock.bind((address, port))
161
+ sock.listen(backlog)
162
+ return sock
163
+
164
+
165
+ def _recv_exact(sock: socket.socket, n: int) -> bytes:
166
+ """Blocking exact-length read, used only during the connect handshake."""
167
+ buf = bytearray()
168
+ while len(buf) < n:
169
+ chunk = sock.recv(n - len(buf))
170
+ if not chunk:
171
+ raise HandshakeError("peer closed during handshake")
172
+ buf.extend(chunk)
173
+ return bytes(buf)
174
+
175
+
176
+ class _Connection:
177
+ """One non-blocking TCP connection with framed send/recv buffering.
178
+
179
+ Shared by Dealer (one persistent outbound connection) and Router (many
180
+ accepted connections) so the partial-read/partial-write logic exists in
181
+ exactly one place.
182
+ """
183
+
184
+ def __init__(self, sock: socket.socket, identity: bytes):
185
+ self.identity = identity
186
+ self._sock = sock
187
+ self._sock.setblocking(False)
188
+ try:
189
+ self._sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
190
+ except OSError:
191
+ pass
192
+ self._reader = FrameReader()
193
+ self._out_buffer = bytearray()
194
+ self._pending = []
195
+ self._closed = False
196
+
197
+ def fileno(self):
198
+ return self._sock.fileno()
199
+
200
+ @property
201
+ def closed(self):
202
+ return self._closed
203
+
204
+ @property
205
+ def wants_write(self):
206
+ return bool(self._out_buffer)
207
+
208
+ def queue_send(self, chunks):
209
+ if self._closed:
210
+ return
211
+ self._out_buffer.extend(encode_message(chunks))
212
+
213
+ def flush(self) -> bool:
214
+ """Try to send queued bytes. Returns False if the connection died."""
215
+ if self._closed:
216
+ return False
217
+ if not self._out_buffer:
218
+ return True
219
+ try:
220
+ sent = self._sock.send(self._out_buffer)
221
+ except (BlockingIOError, InterruptedError):
222
+ return True
223
+ except OSError:
224
+ self._mark_closed()
225
+ return False
226
+ del self._out_buffer[:sent]
227
+ return True
228
+
229
+ def _read_ready(self):
230
+ """Read available bytes and decode whichever messages completed.
231
+ Returns None if the connection died."""
232
+ try:
233
+ data = self._sock.recv(RECV_BUFFER_SIZE)
234
+ except (BlockingIOError, InterruptedError):
235
+ return []
236
+ except OSError:
237
+ self._mark_closed()
238
+ return None
239
+ if data == b"":
240
+ self._mark_closed()
241
+ return None
242
+ try:
243
+ return self._reader.feed(data)
244
+ except NetworkError as e:
245
+ logger.error(
246
+ "Corrupted frame from %r, closing connection: %s", self.identity, e
247
+ )
248
+ self._mark_closed()
249
+ return None
250
+
251
+ def service(self, readable: bool, writable: bool) -> bool:
252
+ """Called by Poller when this connection is select()-ready.
253
+ Returns False if the connection died (caller should drop it)."""
254
+ if writable:
255
+ if not self.flush():
256
+ return False
257
+ if readable:
258
+ messages = self._read_ready()
259
+ if messages is None:
260
+ return False
261
+ self._pending.extend(messages)
262
+ return not self._closed
263
+
264
+ def pop_pending(self):
265
+ msgs, self._pending = self._pending, []
266
+ return msgs
267
+
268
+ def _mark_closed(self):
269
+ if self._closed:
270
+ return
271
+ self._closed = True
272
+ try:
273
+ self._sock.shutdown(socket.SHUT_RDWR)
274
+ except OSError:
275
+ pass
276
+ try:
277
+ self._sock.close()
278
+ except OSError:
279
+ pass
280
+
281
+ def close(self):
282
+ # linger=0 semantics: drop unsent buffered bytes immediately, don't
283
+ # try to drain the outbound buffer first.
284
+ self._mark_closed()
285
+
286
+
287
+ class Poller:
288
+ """Thin wrapper around one selectors.DefaultSelector.
289
+
290
+ Only ever touched by the thread that owns it (never share one Poller
291
+ across threads).
292
+ """
293
+
294
+ def __init__(self):
295
+ self._sel = selectors.DefaultSelector()
296
+ self._masks = {}
297
+ # Transports registered before they had a usable fileno() yet (e.g.
298
+ # a Dealer still background-retrying its connect) - retried on each
299
+ # poll() until they're ready to actually register with the selector.
300
+ self._pending = []
301
+
302
+ def register(self, transport):
303
+ if not self._try_register(transport):
304
+ self._pending.append(transport)
305
+
306
+ def _try_register(self, transport):
307
+ try:
308
+ transport.fileno()
309
+ except (OSError, ValueError, AttributeError):
310
+ return False
311
+ mask = selectors.EVENT_READ
312
+ self._sel.register(transport, mask, transport)
313
+ self._masks[transport] = mask
314
+ return True
315
+
316
+ def unregister(self, transport):
317
+ try:
318
+ self._sel.unregister(transport)
319
+ except KeyError:
320
+ pass
321
+ self._masks.pop(transport, None)
322
+ if transport in self._pending:
323
+ self._pending.remove(transport)
324
+
325
+ def poll(self, timeout_ms=0):
326
+ """Service every registered transport and return the subset that had
327
+ read activity this pass (mirrors the old `dict(zmq_poller.poll())` +
328
+ `X in socks` idiom)."""
329
+ timeout = None if timeout_ms is None else timeout_ms / 1000.0
330
+
331
+ if self._pending:
332
+ still_pending = []
333
+ for transport in self._pending:
334
+ if not self._try_register(transport):
335
+ still_pending.append(transport)
336
+ self._pending = still_pending
337
+
338
+ if not self._masks:
339
+ # select() on Windows raises OSError (WinError 10022) when called
340
+ # with zero registered descriptors - nothing to wait on either way.
341
+ if timeout:
342
+ time.sleep(timeout)
343
+ return {}
344
+
345
+ for transport, mask in list(self._masks.items()):
346
+ wants_write = transport.wants_write
347
+ desired = selectors.EVENT_READ | (
348
+ selectors.EVENT_WRITE if wants_write else 0
349
+ )
350
+ if desired != mask:
351
+ self._sel.modify(transport, desired, transport)
352
+ self._masks[transport] = desired
353
+
354
+ ready = {}
355
+ for key, mask in self._sel.select(timeout):
356
+ transport = key.data
357
+ alive = transport.service(
358
+ readable=bool(mask & selectors.EVENT_READ),
359
+ writable=bool(mask & selectors.EVENT_WRITE),
360
+ )
361
+ if not alive:
362
+ self.unregister(transport)
363
+ continue
364
+ if mask & selectors.EVENT_READ:
365
+ ready[transport] = mask
366
+ return ready
367
+
368
+ def close(self):
369
+ self._sel.close()
370
+
371
+
372
+ class Dealer:
373
+ """One persistent outbound TCP connection with a fixed identity."""
374
+
375
+ def __init__(self, address, port, identity: bytes, role: bytes):
376
+ if role not in _VALID_ROLES:
377
+ raise ValueError(f"invalid role {role!r}")
378
+ self._address = address
379
+ self._port = port
380
+ self._identity = identity
381
+ self._role = role
382
+ self._conn = None
383
+ self._pending_outbound = []
384
+ self._closed = False
385
+ self._lock = threading.Lock()
386
+ self._connect_thread = None
387
+
388
+ @property
389
+ def identity(self):
390
+ return self._identity
391
+
392
+ @property
393
+ def closed(self):
394
+ if self._closed:
395
+ return True
396
+ return self._conn is not None and self._conn.closed
397
+
398
+ @property
399
+ def wants_write(self):
400
+ return self._conn is not None and self._conn.wants_write
401
+
402
+ def connect(self, timeout=None, retry=True, retry_interval=0.2):
403
+ """Connect to the peer.
404
+
405
+ retry=True (default): returns immediately and keeps retrying in the
406
+ background until it succeeds or close() is called - this is needed
407
+ because some callers (e.g. Session.host()) construct and connect a
408
+ Remote's Dealers *before* the server process they're about to spawn
409
+ even exists yet (mirrors zmq DEALER's own connect-before-peer-exists
410
+ tolerance). Anything sent via send() before the connection completes
411
+ is queued and flushed once it does.
412
+
413
+ retry=False: a single bounded blocking connect attempt, raising on
414
+ failure - for one-shot callers (e.g. porcelain.request_session_info)
415
+ that want a fast, clear failure rather than a silent background
416
+ retry loop.
417
+ """
418
+ if not retry:
419
+ sock = _tcp_connect(self._address, self._port, timeout=timeout)
420
+ self._finish_connect(sock)
421
+ return
422
+
423
+ self._connect_thread = threading.Thread(
424
+ target=self._connect_loop, args=(retry_interval,), daemon=True
425
+ )
426
+ self._connect_thread.start()
427
+
428
+ def _connect_loop(self, retry_interval):
429
+ while not self._closed:
430
+ try:
431
+ sock = _tcp_connect(self._address, self._port, timeout=retry_interval)
432
+ except OSError:
433
+ time.sleep(retry_interval)
434
+ continue
435
+ try:
436
+ self._finish_connect(sock)
437
+ except OSError:
438
+ try:
439
+ sock.close()
440
+ except OSError:
441
+ pass
442
+ time.sleep(retry_interval)
443
+ continue
444
+ return
445
+
446
+ def _finish_connect(self, sock):
447
+ handshake = _LEN.pack(len(self._identity)) + self._identity + self._role
448
+ sock.sendall(handshake)
449
+ sock.settimeout(None)
450
+ conn = _Connection(sock, self._identity)
451
+ with self._lock:
452
+ if self._closed:
453
+ conn.close()
454
+ return
455
+ self._conn = conn
456
+ for chunks in self._pending_outbound:
457
+ conn.queue_send(chunks)
458
+ self._pending_outbound.clear()
459
+ # Actually put anything queued on the wire now - queuing alone
460
+ # leaves it sitting in the buffer forever unless something else
461
+ # happens to poll/flush this Dealer afterwards.
462
+ conn.flush()
463
+
464
+ def fileno(self):
465
+ return self._conn.fileno()
466
+
467
+ def send(self, chunks) -> bool:
468
+ # Held for the whole operation, not just the None-check: _finish_connect()
469
+ # (running on the background connect thread) mutates the same
470
+ # _Connection's buffer under this same lock, and queue_send()+flush()
471
+ # are not safe to run concurrently with that from a different thread.
472
+ with self._lock:
473
+ if self._conn is None:
474
+ if self._closed:
475
+ return False
476
+ self._pending_outbound.append(chunks)
477
+ return True
478
+ self._conn.queue_send(chunks)
479
+ return self._conn.flush()
480
+
481
+ def service(self, readable, writable):
482
+ with self._lock:
483
+ if self._conn is None:
484
+ return True
485
+ return self._conn.service(readable, writable)
486
+
487
+ def poll(self, timeout_ms=0):
488
+ """Standalone convenience poll for a single Dealer used outside of a
489
+ shared Poller (e.g. the ttl.py heartbeat subprocess, or tests)."""
490
+ if self._conn is None:
491
+ # Still background-connecting - wait (in short increments) for
492
+ # it rather than sleeping out the whole timeout and returning,
493
+ # which callers (e.g. ttl.py) would otherwise misread as "timed
494
+ # out waiting for a reply" and give up on the very first poll.
495
+ deadline = None if timeout_ms is None else time.time() + timeout_ms / 1000.0
496
+ check_interval = 0.05
497
+ while self._conn is None:
498
+ if deadline is not None and time.time() >= deadline:
499
+ return
500
+ remaining = (
501
+ check_interval
502
+ if deadline is None
503
+ else min(check_interval, max(0.0, deadline - time.time()))
504
+ )
505
+ time.sleep(remaining)
506
+ if deadline is not None:
507
+ timeout_ms = max(0.0, (deadline - time.time()) * 1000.0)
508
+
509
+ sel = selectors.DefaultSelector()
510
+ mask = selectors.EVENT_READ | (selectors.EVENT_WRITE if self.wants_write else 0)
511
+ sel.register(self, mask, self)
512
+ timeout = None if timeout_ms is None else timeout_ms / 1000.0
513
+ for _key, ready_mask in sel.select(timeout):
514
+ self.service(
515
+ bool(ready_mask & selectors.EVENT_READ),
516
+ bool(ready_mask & selectors.EVENT_WRITE),
517
+ )
518
+ sel.close()
519
+
520
+ def recv(self):
521
+ with self._lock:
522
+ if self._conn is None:
523
+ return None
524
+ pending = self._conn.pop_pending()
525
+ if not pending:
526
+ return None
527
+ # Re-queue any extra messages decoded in the same pass so recv()
528
+ # keeps its "one message per call" contract.
529
+ if len(pending) > 1:
530
+ self._conn._pending = pending[1:] + self._conn._pending
531
+ return pending[0]
532
+
533
+ def close(self):
534
+ with self._lock:
535
+ self._closed = True
536
+ if self._conn is not None:
537
+ self._conn.close()
538
+
539
+
540
+ class Router:
541
+ """Multiplexes many already-accepted connections that share one role.
542
+
543
+ Connections are handed in via add_connection() (normally fed by a
544
+ Listener's accept loop through a per-role queue), not accepted directly
545
+ by this class.
546
+ """
547
+
548
+ def __init__(self):
549
+ self._poller = Poller()
550
+ self._connections = {} # identity -> _Connection
551
+ self._inbox = collections.deque()
552
+
553
+ def add_connection(self, identity: bytes, sock: socket.socket):
554
+ old = self._connections.get(identity)
555
+ if old is not None:
556
+ # A reconnect always wins over a stale/still-registered old
557
+ # connection for the same identity (mirrors zmq ROUTER behavior).
558
+ logger.debug("Replacing existing connection for identity %r", identity)
559
+ self._poller.unregister(old)
560
+ old.close()
561
+ conn = _Connection(sock, identity)
562
+ self._connections[identity] = conn
563
+ self._poller.register(conn)
564
+
565
+ def send(self, identity: bytes, chunks) -> bool:
566
+ conn = self._connections.get(identity)
567
+ if conn is None or conn.closed:
568
+ logger.debug(
569
+ "Router.send: unknown/dead identity %r, dropping message", identity
570
+ )
571
+ return False
572
+ conn.queue_send(chunks)
573
+ return conn.flush()
574
+
575
+ def disconnect(self, identity: bytes):
576
+ conn = self._connections.pop(identity, None)
577
+ if conn is not None:
578
+ self._poller.unregister(conn)
579
+ conn.close()
580
+
581
+ def poll(self, timeout_ms=0):
582
+ ready = self._poller.poll(timeout_ms)
583
+ for conn in ready:
584
+ for chunks in conn.pop_pending():
585
+ self._inbox.append((conn.identity, chunks))
586
+ dead = [identity for identity, conn in self._connections.items() if conn.closed]
587
+ for identity in dead:
588
+ del self._connections[identity]
589
+
590
+ def recv(self):
591
+ if not self._inbox:
592
+ return None
593
+ return self._inbox.popleft()
594
+
595
+ @property
596
+ def identities(self):
597
+ return list(self._connections.keys())
598
+
599
+ def close(self):
600
+ for conn in list(self._connections.values()):
601
+ conn.close()
602
+ self._connections.clear()
603
+ self._poller.close()
604
+
605
+
606
+ class Listener:
607
+ """Owns the single bound/listening TCP socket for the whole server.
608
+
609
+ Runs its own accept loop in a background thread. Each accepted
610
+ connection's handshake (identity + role) is read on its own short-lived
611
+ thread, so one slow/silent/malicious peer can never block the shared
612
+ accept loop from servicing the other roles.
613
+ """
614
+
615
+ def __init__(self, port, address="0.0.0.0", handshake_timeout=HANDSHAKE_TIMEOUT):
616
+ self._sock = _tcp_bind(address, port)
617
+ self._handshake_timeout = handshake_timeout
618
+ self._queues = {}
619
+ self._exit_event = threading.Event()
620
+ self._thread = threading.Thread(
621
+ target=self._accept_loop, name="net-listener", daemon=True
622
+ )
623
+
624
+ @property
625
+ def port(self):
626
+ return self._sock.getsockname()[1]
627
+
628
+ def register_role(self, role: bytes, target_queue: "queue.Queue"):
629
+ if role not in _VALID_ROLES:
630
+ raise ValueError(f"invalid role {role!r}")
631
+ self._queues[role] = target_queue
632
+
633
+ def start(self):
634
+ self._thread.start()
635
+
636
+ def _accept_loop(self):
637
+ self._sock.settimeout(0.5)
638
+ while not self._exit_event.is_set():
639
+ try:
640
+ conn, _addr = self._sock.accept()
641
+ except socket.timeout:
642
+ continue
643
+ except OSError:
644
+ break
645
+ threading.Thread(target=self._handshake, args=(conn,), daemon=True).start()
646
+
647
+ def _handshake(self, conn: socket.socket):
648
+ conn.settimeout(self._handshake_timeout)
649
+ try:
650
+ (identity_len,) = _LEN.unpack(_recv_exact(conn, 4))
651
+ if identity_len > MAX_IDENTITY_SIZE:
652
+ raise HandshakeError(f"identity too large ({identity_len} bytes)")
653
+ identity = _recv_exact(conn, identity_len)
654
+ role = _recv_exact(conn, 1)
655
+ if role not in _VALID_ROLES:
656
+ raise HandshakeError(f"unknown role {role!r}")
657
+ except (HandshakeError, socket.timeout, OSError) as e:
658
+ logger.warning("Rejecting connection during handshake: %s", e)
659
+ try:
660
+ conn.close()
661
+ except OSError:
662
+ pass
663
+ return
664
+
665
+ target_queue = self._queues.get(role)
666
+ if target_queue is None:
667
+ logger.warning("No queue registered for role %r, dropping connection", role)
668
+ conn.close()
669
+ return
670
+ target_queue.put((identity, conn))
671
+
672
+ def stop(self):
673
+ self._exit_event.set()
674
+ try:
675
+ self._sock.close()
676
+ except OSError:
677
+ pass
678
+ self._thread.join(timeout=2.0)