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