librats 3.0.5.dev2__py3-none-win_amd64.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.
librats_py/core.py ADDED
@@ -0,0 +1,743 @@
1
+ """
2
+ :class:`RatsNode` — one librats node, over the C ABI (``src/librats/bindings/rats.h``).
3
+
4
+ On its own a node is secure transport plus raw messaging on named channels;
5
+ discovery, NAT traversal, pub/sub, JSON messaging, file transfer, ping and
6
+ reconnection are subsystems enabled before :meth:`RatsNode.start`.
7
+
8
+ Callbacks run on a librats reactor thread. Each one is wrapped so that an
9
+ exception raised in it is printed to stderr instead of unwinding into C, and
10
+ every ``CFUNCTYPE`` object is kept for the node's lifetime: the C side may hold
11
+ the pointer until the node is destroyed.
12
+ """
13
+
14
+ import json
15
+ import sys
16
+ import weakref
17
+ from ctypes import byref, c_char_p, c_int, c_size_t, c_uint64, string_at
18
+ from typing import Any, Callable, List, Optional
19
+
20
+ from .ctypes_wrapper import (
21
+ RatsBtConfig, RatsConfig, RatsFileProgress, RatsPathStats, RatsPeerInfo, get_librats,
22
+ )
23
+ from .enums import (
24
+ BtEncryption, CloseReason, Congestion, Direction, FileProgress, FileTransferStatus,
25
+ LogLevel, NatMapping, PathStats, PeerInfo, RatsError as ErrorCode, Security, Transport,
26
+ TransportMask, VersionInfo,
27
+ )
28
+ from .exceptions import RatsError, RatsInvalidArgError, check_error
29
+ from .callbacks import (
30
+ DialFailedCallback, DialFailedCallbackType, DisconnectCallback, DisconnectCallbackType,
31
+ FileCompleteCallback, FileCompleteCallbackType, FileOfferCallback, FileOfferCallbackType,
32
+ FileProgressCallback, FileProgressCallbackType, JsonCallback, JsonCallbackType,
33
+ MessageCallback, MessageCallbackType, PathCallback, PathCallbackType, PeerCallback,
34
+ PeerCallbackType, TopicCallback, TopicCallbackType,
35
+ )
36
+
37
+
38
+ def _b(s: Optional[str]) -> Optional[bytes]:
39
+ return s.encode('utf-8') if s is not None else None
40
+
41
+
42
+ def _s(b: Optional[bytes]) -> str:
43
+ return b.decode('utf-8', errors='replace') if b else ""
44
+
45
+
46
+ def _bytes(ptr, length: int) -> bytes:
47
+ return string_at(ptr, length) if ptr and length else b""
48
+
49
+
50
+ def _report(exc: BaseException, where: str) -> None:
51
+ print(f"[librats_py] exception in {where} callback: {exc!r}", file=sys.stderr)
52
+
53
+
54
+ def _guard(where: str, fn: Callable) -> Callable:
55
+ """Wrap a trampoline so a Python exception never unwinds into C."""
56
+ def call(*args):
57
+ try:
58
+ fn(*args)
59
+ except BaseException as exc: # noqa: B902 — nothing may cross into C
60
+ _report(exc, where)
61
+ return call
62
+
63
+
64
+ def _path_stats(c: RatsPathStats) -> PathStats:
65
+ return PathStats(
66
+ bandwidth_bps=c.bandwidth_bps, app_limited=bool(c.app_limited),
67
+ pacing_bps=c.pacing_bps, srtt_us=c.srtt_us, min_rtt_us=c.min_rtt_us,
68
+ queued_bytes=c.queued_bytes, bytes_in_flight=c.bytes_in_flight, loss=c.loss,
69
+ bytes_delivered=c.bytes_delivered, bytes_lost=c.bytes_lost,
70
+ live_sent=c.live_sent, live_expired=c.live_expired,
71
+ live_repair_bytes=c.live_repair_bytes)
72
+
73
+
74
+ def _string_list(lib, fn, handle) -> List[str]:
75
+ count = c_size_t()
76
+ arr = fn(handle, byref(count))
77
+ if not arr:
78
+ return []
79
+ try:
80
+ return [_s(arr[i]) for i in range(count.value)]
81
+ finally:
82
+ lib.rats_strings_free(arr, count.value)
83
+
84
+
85
+ class RatsNode:
86
+ """A librats node.
87
+
88
+ Every keyword maps to a ``rats_config_t`` field; leaving one out keeps the
89
+ library default. Use it as a context manager to have it destroyed on exit::
90
+
91
+ with RatsNode(8080, protocol="myapp/1.0") as node:
92
+ node.on("chat", lambda peer, data: print(peer, data))
93
+ node.start()
94
+ """
95
+
96
+ def __init__(
97
+ self,
98
+ listen_port: int = 0,
99
+ *,
100
+ protocol: Optional[str] = None,
101
+ data_dir: Optional[str] = None,
102
+ security: Security = Security.NOISE,
103
+ bind_address: Optional[str] = None,
104
+ dial_only: bool = False,
105
+ max_peers: int = 0,
106
+ transports: TransportMask = TransportMask.NONE,
107
+ preferred_transport: Transport = Transport.UDP,
108
+ transport_fallback_ms: int = 0,
109
+ send_queue_limit: int = 0,
110
+ path_sample_ms: int = 0,
111
+ congestion_control: Congestion = Congestion.BBR,
112
+ udp_receive_window: int = 0,
113
+ udp_receive_budget: int = 0,
114
+ udp_offload: bool = True,
115
+ udp_idle_timeout_ms: int = 0,
116
+ reactor_threads: int = 0,
117
+ network_monitor: bool = True,
118
+ ):
119
+ """Create a node; no socket is opened until :meth:`start`.
120
+
121
+ Args:
122
+ listen_port: Port both transports listen on; 0 = ephemeral.
123
+ protocol: App id bound into the handshake, e.g. ``"myapp/1.0"``;
124
+ peers with a different one cannot connect. Default ``"librats/1.0"``.
125
+ data_dir: Directory for persistent state (identity, DHT routing
126
+ table, reconnect list). Without it the identity is new every run.
127
+ security: :class:`Security`; Noise by default.
128
+ bind_address: Interface to listen on; default ``"::"``, dual-stack.
129
+ dial_only: No listener: outbound connections only.
130
+ max_peers: Cap on established peers, enforced on inbound; 0 = none.
131
+ transports: :class:`TransportMask` of transports to run; NONE = both.
132
+ preferred_transport: Tried first by a dial; UDP by default.
133
+ transport_fallback_ms: How long the preferred transport dials alone
134
+ before the other is raced; 0 = 1200, :data:`FALLBACK_NEVER` = never.
135
+ send_queue_limit: Bytes a peer's queue may hold before a sender that
136
+ keeps going has it dropped (``CloseReason.SLOW_CONSUMER``);
137
+ :meth:`peer_writable` turns False at a quarter of it. Not a
138
+ message size limit. 0 = 8 MiB.
139
+ path_sample_ms: How often each peer's path is sampled for
140
+ :meth:`path_stats`; 0 = only while an :meth:`on_peer_path`
141
+ callback is registered, every 100 ms.
142
+ congestion_control: :class:`Congestion` of every UDP connection.
143
+ udp_receive_window: Ceiling one UDP connection's flow-control window
144
+ grows to (it starts at 1 MiB); 0 = 16 MiB.
145
+ udp_receive_budget: Bytes all UDP connections together may hold out of
146
+ order; 0 = 64 MiB.
147
+ udp_offload: Use the kernel's UDP segmentation offload where present.
148
+ udp_idle_timeout_ms: Silence from a peer after which its UDP
149
+ connection is closed as lost (``CloseReason.IDLE_TIMEOUT``);
150
+ keep-alives go out four times within it. 0 = 45 s.
151
+ reactor_threads: I/O threads; 0 = 1.
152
+ network_monitor: Watch the host for interface and address changes.
153
+
154
+ Raises:
155
+ RatsInvalidArgError: the config is impossible (no transport, or
156
+ TCP preferred while it is turned off).
157
+ """
158
+ self._lib = get_librats().lib
159
+ self._handle = None
160
+ self._running = False
161
+ # Every CFUNCTYPE handed to C, kept until the node is destroyed.
162
+ self._thunks: List[Any] = []
163
+
164
+ cfg = RatsConfig()
165
+ cfg.protocol = _b(protocol)
166
+ cfg.data_dir = _b(data_dir)
167
+ cfg.security = int(security)
168
+ cfg.listen_port = listen_port
169
+ cfg.bind_address = _b(bind_address)
170
+ cfg.dial_only = int(dial_only)
171
+ cfg.max_peers = max_peers
172
+ cfg.transports = int(transports)
173
+ cfg.preferred_transport = int(preferred_transport)
174
+ cfg.transport_fallback_ms = transport_fallback_ms
175
+ cfg.send_queue_limit = send_queue_limit
176
+ cfg.path_sample_ms = path_sample_ms
177
+ cfg.congestion_control = int(congestion_control)
178
+ cfg.udp_receive_window = udp_receive_window
179
+ cfg.udp_receive_budget = udp_receive_budget
180
+ cfg.disable_udp_offload = int(not udp_offload)
181
+ cfg.udp_idle_timeout_ms = udp_idle_timeout_ms
182
+ cfg.reactor_threads = reactor_threads
183
+ cfg.disable_network_monitor = int(not network_monitor)
184
+
185
+ handle = self._lib.rats_create(byref(cfg))
186
+ if not handle:
187
+ raise RatsInvalidArgError(
188
+ "rats_create refused the config: no transport, a contradictory "
189
+ "transport choice, an out-of-range value, or an unreadable data_dir")
190
+ self._handle = handle
191
+ self._finalizer = weakref.finalize(self, self._lib.rats_destroy, handle)
192
+
193
+ # ------------------------------------------------------------------ lifecycle
194
+
195
+ def __enter__(self):
196
+ return self
197
+
198
+ def __exit__(self, exc_type, exc_val, exc_tb):
199
+ self.destroy()
200
+ return False
201
+
202
+ @property
203
+ def _h(self):
204
+ # The C ABI does not check its handle: a call after destroy() would crash.
205
+ if self._handle is None:
206
+ raise RatsError("the node has been destroyed", ErrorCode.INVALID_ARG)
207
+ return self._handle
208
+
209
+ def start(self) -> None:
210
+ """Open the sockets and start every enabled subsystem.
211
+
212
+ Raises :class:`RatsBindError` if the listen port is taken.
213
+ """
214
+ check_error(self._lib.rats_start(self._h), "start")
215
+ self._running = True
216
+
217
+ def stop(self) -> None:
218
+ """Close every connection and stop. Idempotent."""
219
+ if self._handle is not None:
220
+ self._lib.rats_stop(self._handle)
221
+ self._running = False
222
+
223
+ @property
224
+ def running(self) -> bool:
225
+ return self._running
226
+
227
+ def destroy(self) -> None:
228
+ """Stop and free the native node now rather than at garbage collection.
229
+
230
+ Idempotent; every other method raises afterwards.
231
+ """
232
+ if self._handle is not None:
233
+ self._finalizer()
234
+ self._handle = None
235
+ self._running = False
236
+
237
+ # ------------------------------------------------------------------ this node
238
+
239
+ @property
240
+ def local_id(self) -> str:
241
+ """Our peer id, 64 lowercase hex characters."""
242
+ return _s(self._lib.rats_local_id(self._h))
243
+
244
+ @property
245
+ def protocol(self) -> str:
246
+ """The protocol bound into the handshake."""
247
+ return _s(self._lib.rats_protocol(self._h))
248
+
249
+ @property
250
+ def listen_port(self) -> int:
251
+ """The bound listen port (the real one when 0 was asked for); 0 before start."""
252
+ return self._lib.rats_listen_port(self._h)
253
+
254
+ @property
255
+ def transports(self) -> TransportMask:
256
+ """Transports actually running; NONE when not running.
257
+
258
+ Can be narrower than asked for: a UDP socket that cannot be bound leaves
259
+ the node TCP-only rather than failing to start.
260
+ """
261
+ return TransportMask(self._lib.rats_transports(self._h))
262
+
263
+ @property
264
+ def nat_mapping(self) -> NatMapping:
265
+ """What the mesh has shown about this node's NAT, from where UDP peers
266
+ report seeing its socket."""
267
+ return NatMapping(self._lib.rats_nat_mapping(self._h))
268
+
269
+ @property
270
+ def observed_addresses(self) -> List[str]:
271
+ """Our own addresses as peers report seeing us (``"ip:port"``)."""
272
+ return _string_list(self._lib, self._lib.rats_observed_addresses, self._h)
273
+
274
+ # ---------------------------------------------------------------------- peers
275
+
276
+ def connect(self, host: str, port: int) -> None:
277
+ """Dial ``host:port`` (a literal or a hostname). Needs a started node.
278
+
279
+ Non-blocking: success arrives at :meth:`on_peer_connected`, failure at
280
+ :meth:`on_dial_failed`.
281
+ """
282
+ check_error(self._lib.rats_connect(self._h, _b(host), port), f"connect to {host}:{port}")
283
+
284
+ def disconnect(self, peer_id: str) -> None:
285
+ """Close the connection to a peer. Raises :class:`RatsNoSuchPeerError`."""
286
+ check_error(self._lib.rats_disconnect(self._h, _b(peer_id)), f"disconnect {peer_id}")
287
+
288
+ @property
289
+ def peer_count(self) -> int:
290
+ return self._lib.rats_peer_count(self._h)
291
+
292
+ @property
293
+ def peer_ids(self) -> List[str]:
294
+ """Ids of the connected peers."""
295
+ return _string_list(self._lib, self._lib.rats_peer_ids, self._h)
296
+
297
+ def peer_info(self, peer_id: str) -> Optional[PeerInfo]:
298
+ """What the node knows about a connected peer, or ``None`` if it is not."""
299
+ out = RatsPeerInfo()
300
+ err = self._lib.rats_peer_info(self._h, _b(peer_id), byref(out))
301
+ if err == ErrorCode.NO_SUCH_PEER:
302
+ return None
303
+ check_error(err, f"peer_info {peer_id}")
304
+ return PeerInfo(transport=Transport(out.transport),
305
+ transports=TransportMask(out.transports),
306
+ direction=Direction(out.direction),
307
+ address=_s(out.address))
308
+
309
+ @property
310
+ def max_peers(self) -> int:
311
+ """Cap on established peers (0 = unlimited). Can be changed while running."""
312
+ return self._lib.rats_max_peers(self._h)
313
+
314
+ @max_peers.setter
315
+ def max_peers(self, value: int) -> None:
316
+ self._lib.rats_set_max_peers(self._h, value)
317
+
318
+ # ------------------------------------------------------------------ messaging
319
+
320
+ def send(self, peer_id: str, channel: str, data: bytes, lifetime_ms: int = 0) -> None:
321
+ """Queue ``data`` for one peer on a named channel.
322
+
323
+ Returning means queued, not arrived. ``lifetime_ms`` 0 is reliable and in
324
+ order with everything else this node sends on its channels. Non-zero
325
+ makes it a live message, worth delivering only within that many ms
326
+ (:data:`LIVE_MAX_LIFETIME_MS` at most, :data:`LIVE_MAX_PAYLOAD` bytes at
327
+ most): repaired while it can still arrive in time, dropped whole once it
328
+ cannot, never delivered partly or twice, and ordered with nothing. The
329
+ receiver's :meth:`on` handler is the same either way.
330
+
331
+ If you send in bulk, ask :meth:`peer_writable` after each send.
332
+ Raises :class:`RatsNoSuchPeerError` if the peer is not connected.
333
+ """
334
+ data = bytes(data)
335
+ check_error(self._lib.rats_send(self._h, _b(peer_id), _b(channel), data, len(data),
336
+ lifetime_ms),
337
+ f"send on '{channel}' to {peer_id}")
338
+
339
+ def broadcast(self, channel: str, data: bytes, lifetime_ms: int = 0) -> None:
340
+ """:meth:`send` to every connected peer."""
341
+ data = bytes(data)
342
+ check_error(self._lib.rats_broadcast(self._h, _b(channel), data, len(data), lifetime_ms),
343
+ f"broadcast on '{channel}'")
344
+
345
+ def peer_writable(self, peer_id: str) -> bool:
346
+ """Whether the peer's send queue has room (False also when not connected).
347
+
348
+ False means stop: what you sent was queued, but keep adding and the peer
349
+ is dropped with ``CloseReason.SLOW_CONSUMER``. Resume on
350
+ :meth:`on_peer_writable`, or poll this. Bytes just handed to :meth:`send`
351
+ are counted, so asking right after a send is exact.
352
+ """
353
+ return bool(self._lib.rats_peer_writable(self._h, _b(peer_id)))
354
+
355
+ def path_stats(self, peer_id: str) -> Optional[PathStats]:
356
+ """The latest path sample for a peer, or ``None`` if it is not connected or
357
+ nothing was sampled yet (sampling needs ``path_sample_ms`` or an
358
+ :meth:`on_peer_path` callback)."""
359
+ out = RatsPathStats()
360
+ err = self._lib.rats_path_stats(self._h, _b(peer_id), byref(out))
361
+ if err == ErrorCode.NO_SUCH_PEER:
362
+ return None
363
+ check_error(err, f"path_stats {peer_id}")
364
+ return _path_stats(out)
365
+
366
+ # ------------------------------------------------- callbacks (before start)
367
+
368
+ def _keep(self, thunk):
369
+ self._thunks.append(thunk)
370
+ return thunk
371
+
372
+ def on_peer_connected(self, callback: PeerCallback) -> None:
373
+ """``callback(peer_id)`` when a peer connects."""
374
+ thunk = self._keep(PeerCallbackType(_guard(
375
+ "peer connected", lambda _u, pid: callback(_s(pid)))))
376
+ check_error(self._lib.rats_on_peer_connected(self._h, thunk, None), "on_peer_connected")
377
+
378
+ def on_peer_disconnected(self, callback: DisconnectCallback) -> None:
379
+ """``callback(peer_id, reason: CloseReason)`` when a peer goes.
380
+
381
+ Branch on the reason: a peer that left is one to redial, while
382
+ ``SLOW_CONSUMER`` means this node sent faster than the link drained, and
383
+ redialing only repeats it.
384
+ """
385
+ thunk = self._keep(DisconnectCallbackType(_guard(
386
+ "peer disconnected", lambda _u, pid, why: callback(_s(pid), CloseReason(why)))))
387
+ check_error(self._lib.rats_on_peer_disconnected(self._h, thunk, None),
388
+ "on_peer_disconnected")
389
+
390
+ def on_dial_failed(self, callback: DialFailedCallback) -> None:
391
+ """``callback(address)`` when a dial to a numeric address failed over every
392
+ transport tried — one made by :meth:`connect` or by a discovery
393
+ subsystem. A dial by hostname is not reported."""
394
+ thunk = self._keep(DialFailedCallbackType(_guard(
395
+ "dial failed", lambda _u, addr: callback(_s(addr)))))
396
+ check_error(self._lib.rats_on_dial_failed(self._h, thunk, None), "on_dial_failed")
397
+
398
+ def on_peer_writable(self, callback: PeerCallback) -> None:
399
+ """``callback(peer_id)`` when a peer whose queue had filled has room again."""
400
+ thunk = self._keep(PeerCallbackType(_guard(
401
+ "peer writable", lambda _u, pid: callback(_s(pid)))))
402
+ check_error(self._lib.rats_on_peer_writable(self._h, thunk, None), "on_peer_writable")
403
+
404
+ def on_peer_path(self, callback: PathCallback) -> None:
405
+ """``callback(peer_id, stats: PathStats)`` for every connected peer, every
406
+ ``path_sample_ms`` (100 ms if 0). Registering turns sampling on; it runs
407
+ once per peer per interval, so keep it cheap."""
408
+ thunk = self._keep(PathCallbackType(_guard(
409
+ "peer path", lambda _u, pid, st: callback(
410
+ _s(pid), _path_stats(RatsPathStats.from_address(st))))))
411
+ check_error(self._lib.rats_on_peer_path(self._h, thunk, None), "on_peer_path")
412
+
413
+ def on(self, channel: str, callback: MessageCallback) -> None:
414
+ """``callback(peer_id, data: bytes)`` for messages on a named channel."""
415
+ thunk = self._keep(MessageCallbackType(_guard(
416
+ f"'{channel}' message", lambda _u, pid, data, n: callback(_s(pid), _bytes(data, n)))))
417
+ check_error(self._lib.rats_on(self._h, _b(channel), thunk, None), f"on('{channel}')")
418
+
419
+ # --------------------------------------------------- discovery (before start)
420
+
421
+ def enable_dht(self, dht_port: int = 0, discovery_key: Optional[str] = None) -> None:
422
+ """Mainline DHT: announce and search a key, dialing the peers found.
423
+
424
+ ``discovery_key`` defaults to the node's protocol, so only nodes that
425
+ could handshake find each other.
426
+ """
427
+ check_error(self._lib.rats_enable_dht(self._h, dht_port, _b(discovery_key)), "enable_dht")
428
+
429
+ def dht_set_keys(self, keys: List[str]) -> None:
430
+ """The keys the DHT announces and searches from now on, in place of the
431
+ ``discovery_key`` or the keys set before: a new one is announced and
432
+ searched at once, one gone no longer is. An empty list leaves none, so
433
+ the node finds and is found by nobody over the DHT. Needs
434
+ :meth:`enable_dht`; works before and after start, from any thread.
435
+ """
436
+ if isinstance(keys, (str, bytes)):
437
+ raise TypeError("keys must be a list of strings, not a single string")
438
+ encoded = [k.encode("utf-8") for k in keys]
439
+ array = (c_char_p * len(encoded))(*encoded)
440
+ check_error(self._lib.rats_dht_set_keys(self._h, array, len(encoded)), "dht_set_keys")
441
+
442
+ def enable_mdns(self) -> None:
443
+ """mDNS discovery on the local network."""
444
+ check_error(self._lib.rats_enable_mdns(self._h), "enable_mdns")
445
+
446
+ def enable_peer_exchange(self) -> None:
447
+ """Connected peers trade the addresses of peers they hold, so one contact
448
+ is enough to find the rest of the mesh."""
449
+ check_error(self._lib.rats_enable_peer_exchange(self._h), "enable_peer_exchange")
450
+
451
+ # ----------------------------------------------- NAT traversal (before start)
452
+
453
+ def enable_port_mapping(self, upnp: bool = True, natpmp: bool = True) -> None:
454
+ """Ask the router to forward the listen port (UPnP IGD and/or NAT-PMP)."""
455
+ check_error(self._lib.rats_enable_port_mapping(self._h, int(upnp), int(natpmp)),
456
+ "enable_port_mapping")
457
+
458
+ def enable_hole_punch(self, serve_rendezvous: bool = True) -> None:
459
+ """UDP hole punching through a peer both sides share. Every node involved
460
+ needs it; ``serve_rendezvous`` also passes other peers' rendezvous along
461
+ (a few dozen bytes per punch) — a mesh where nobody does cannot punch."""
462
+ check_error(self._lib.rats_enable_hole_punch(self._h, int(serve_rendezvous)),
463
+ "enable_hole_punch")
464
+
465
+ def punch_peer(self, peer_id: str) -> None:
466
+ """Start punching to a peer; success arrives at :meth:`on_peer_connected`.
467
+
468
+ Raises :class:`RatsDeclinedError` when already connected, already
469
+ punching, or no external endpoint of our own is known yet (that takes at
470
+ least one UDP peer).
471
+ """
472
+ check_error(self._lib.rats_punch_peer(self._h, _b(peer_id)), f"punch {peer_id}")
473
+
474
+ def enable_relay(self, serve: bool = False) -> None:
475
+ """Reach a peer nothing else can, through a node both ends are connected to.
476
+
477
+ Encryption stays end to end; :meth:`peer_info` reports ``Transport.RELAY``.
478
+ ``serve`` also carries OTHER peers' connections, which costs this node
479
+ their bandwidth. With hole punching enabled too, a punch that cannot work
480
+ falls back to a relay by itself, and a relayed peer is upgraded to a
481
+ direct connection when a later punch succeeds.
482
+ """
483
+ check_error(self._lib.rats_enable_relay(self._h, int(serve)), "enable_relay")
484
+
485
+ def connect_via_relay(self, peer_id: str) -> None:
486
+ """Start a relayed connection; success arrives at :meth:`on_peer_connected`.
487
+
488
+ Raises :class:`RatsDeclinedError` when already connected, already trying
489
+ or cooling down, or no connected peer could carry it.
490
+ """
491
+ check_error(self._lib.rats_connect_via_relay(self._h, _b(peer_id)),
492
+ f"connect_via_relay {peer_id}")
493
+
494
+ # -------------------------------------------------------------------- pub/sub
495
+
496
+ def enable_pubsub(self) -> None:
497
+ """GossipSub topics. Enable before start."""
498
+ check_error(self._lib.rats_enable_pubsub(self._h), "enable_pubsub")
499
+
500
+ def subscribe(self, topic: str, callback: TopicCallback) -> None:
501
+ """``callback(peer_id, topic, data: bytes)``. One handler per topic: a second
502
+ subscribe replaces the first."""
503
+ thunk = self._keep(TopicCallbackType(_guard(
504
+ f"topic '{topic}'",
505
+ lambda _u, pid, t, data, n: callback(_s(pid), _s(t), _bytes(data, n)))))
506
+ check_error(self._lib.rats_subscribe(self._h, _b(topic), thunk, None),
507
+ f"subscribe '{topic}'")
508
+
509
+ def unsubscribe(self, topic: str) -> None:
510
+ check_error(self._lib.rats_unsubscribe(self._h, _b(topic)), f"unsubscribe '{topic}'")
511
+
512
+ def publish(self, topic: str, data: bytes) -> None:
513
+ """Publish to every subscriber of the topic."""
514
+ data = bytes(data)
515
+ check_error(self._lib.rats_publish(self._h, _b(topic), data, len(data)),
516
+ f"publish '{topic}'")
517
+
518
+ # -------------------------------------------------------------- JSON messages
519
+
520
+ def enable_json(self) -> None:
521
+ """Typed messages carrying a JSON document. Enable before start."""
522
+ check_error(self._lib.rats_enable_json(self._h), "enable_json")
523
+
524
+ def _json_thunk(self, type_name: str, callback: JsonCallback):
525
+ return self._keep(JsonCallbackType(_guard(
526
+ f"JSON '{type_name}'", lambda _u, pid, text: callback(_s(pid), json.loads(text)))))
527
+
528
+ def on_json(self, type_name: str, callback: JsonCallback) -> None:
529
+ """``callback(peer_id, value)`` for messages of ``type_name``, ``value``
530
+ parsed from JSON. Adds a handler; may be called while running."""
531
+ check_error(self._lib.rats_on_json(self._h, _b(type_name),
532
+ self._json_thunk(type_name, callback), None),
533
+ f"on_json '{type_name}'")
534
+
535
+ def once_json(self, type_name: str, callback: JsonCallback) -> None:
536
+ """Like :meth:`on_json`; the handler is removed after its first message."""
537
+ check_error(self._lib.rats_once_json(self._h, _b(type_name),
538
+ self._json_thunk(type_name, callback), None),
539
+ f"once_json '{type_name}'")
540
+
541
+ def off_json(self, type_name: str) -> None:
542
+ """Remove every handler of ``type_name``."""
543
+ check_error(self._lib.rats_off_json(self._h, _b(type_name)), f"off_json '{type_name}'")
544
+
545
+ def send_json(self, peer_id: str, type_name: str, value: Any) -> None:
546
+ """Send ``value``, encoded with :func:`json.dumps`, to one peer."""
547
+ check_error(self._lib.rats_send_json(self._h, _b(peer_id), _b(type_name),
548
+ _b(json.dumps(value))),
549
+ f"send_json '{type_name}' to {peer_id}")
550
+
551
+ def broadcast_json(self, type_name: str, value: Any) -> None:
552
+ """:meth:`send_json` to every connected peer."""
553
+ check_error(self._lib.rats_broadcast_json(self._h, _b(type_name), _b(json.dumps(value))),
554
+ f"broadcast_json '{type_name}'")
555
+
556
+ # -------------------------------------------------------------- file transfer
557
+
558
+ def enable_file_transfer(self, temp_dir: Optional[str] = None) -> None:
559
+ """Push-style file transfer. ``temp_dir`` holds partial downloads (default
560
+ the working directory). Enable and set its callbacks before start."""
561
+ check_error(self._lib.rats_enable_file_transfer(self._h, _b(temp_dir)),
562
+ "enable_file_transfer")
563
+
564
+ def on_file_offer(self, callback: FileOfferCallback) -> None:
565
+ """``callback(peer_id, transfer_id, name, size, is_directory)`` for each
566
+ incoming offer; answer with :meth:`accept_file` or :meth:`reject_file`.
567
+ One handler: a second call replaces the first."""
568
+ thunk = self._keep(FileOfferCallbackType(_guard(
569
+ "file offer", lambda _u, pid, tid, name, size, is_dir: callback(
570
+ _s(pid), int(tid), _s(name), int(size), bool(is_dir)))))
571
+ check_error(self._lib.rats_on_file_offer(self._h, thunk, None), "on_file_offer")
572
+
573
+ def on_file_progress(self, callback: FileProgressCallback) -> None:
574
+ """``callback(progress: FileProgress)`` as transfers move, both directions."""
575
+ def trampoline(_u, ptr):
576
+ c = RatsFileProgress.from_address(ptr)
577
+ callback(FileProgress(
578
+ transfer_id=c.transfer_id, peer_id=_s(c.peer_id),
579
+ direction=Direction(c.direction), status=FileTransferStatus(c.status),
580
+ bytes_transferred=c.bytes_transferred, total_bytes=c.total_bytes,
581
+ files_completed=c.files_completed, total_files=c.total_files,
582
+ rate_bytes_per_sec=c.rate_bytes_per_sec))
583
+ thunk = self._keep(FileProgressCallbackType(_guard("file progress", trampoline)))
584
+ check_error(self._lib.rats_on_file_progress(self._h, thunk, None), "on_file_progress")
585
+
586
+ def on_file_complete(self, callback: FileCompleteCallback) -> None:
587
+ """``callback(peer_id, transfer_id, success, path)`` when a transfer ends."""
588
+ thunk = self._keep(FileCompleteCallbackType(_guard(
589
+ "file complete", lambda _u, pid, tid, ok, path: callback(
590
+ _s(pid), int(tid), bool(ok), _s(path)))))
591
+ check_error(self._lib.rats_on_file_complete(self._h, thunk, None), "on_file_complete")
592
+
593
+ def send_file(self, peer_id: str, path: str) -> int:
594
+ """Offer a file to a connected peer; returns the transfer id.
595
+
596
+ Raises RatsNoSuchPeerError if the peer is not connected and
597
+ RatsNotFoundError if the file cannot be read.
598
+ """
599
+ tid = c_uint64(0)
600
+ check_error(self._lib.rats_send_file(self._h, _b(peer_id), _b(path), byref(tid)),
601
+ "send_file")
602
+ return tid.value
603
+
604
+ def send_directory(self, peer_id: str, path: str) -> int:
605
+ """Offer a directory tree; returns and raises as send_file()."""
606
+ tid = c_uint64(0)
607
+ check_error(self._lib.rats_send_directory(self._h, _b(peer_id), _b(path), byref(tid)),
608
+ "send_directory")
609
+ return tid.value
610
+
611
+ def accept_file(self, peer_id: str, transfer_id: int, dest_path: str) -> None:
612
+ """Accept an offer: ``dest_path`` is the file to write for a file, the
613
+ directory to fill for a directory."""
614
+ check_error(self._lib.rats_accept_file(self._h, _b(peer_id), transfer_id, _b(dest_path)),
615
+ f"accept_file {transfer_id}")
616
+
617
+ def reject_file(self, peer_id: str, transfer_id: int) -> None:
618
+ check_error(self._lib.rats_reject_file(self._h, _b(peer_id), transfer_id),
619
+ f"reject_file {transfer_id}")
620
+
621
+ def cancel_file(self, peer_id: str, transfer_id: int) -> None:
622
+ """Cancel a transfer from either side. Raises :class:`RatsNotFoundError`."""
623
+ check_error(self._lib.rats_cancel_file(self._h, _b(peer_id), transfer_id),
624
+ f"cancel_file {transfer_id}")
625
+
626
+ def pause_file(self, peer_id: str, transfer_id: int) -> None:
627
+ check_error(self._lib.rats_pause_file(self._h, _b(peer_id), transfer_id),
628
+ f"pause_file {transfer_id}")
629
+
630
+ def resume_file(self, peer_id: str, transfer_id: int) -> None:
631
+ check_error(self._lib.rats_resume_file(self._h, _b(peer_id), transfer_id),
632
+ f"resume_file {transfer_id}")
633
+
634
+ # ----------------------------------------------------------- ping, reconnect
635
+
636
+ def enable_ping(self) -> None:
637
+ """Round-trip probing of every peer. Enable before start."""
638
+ check_error(self._lib.rats_enable_ping(self._h), "enable_ping")
639
+
640
+ def peer_rtt_ms(self, peer_id: str) -> Optional[int]:
641
+ """Last measured round trip to a peer in ms; ``None`` if unknown."""
642
+ rtt = self._lib.rats_peer_rtt_ms(self._h, _b(peer_id))
643
+ return None if rtt < 0 else rtt
644
+
645
+ def enable_reconnect(self) -> None:
646
+ """Redial dropped peers with backoff; with ``data_dir`` the list survives
647
+ restarts. Enable before start."""
648
+ check_error(self._lib.rats_enable_reconnect(self._h), "enable_reconnect")
649
+
650
+ def enable_reconnect_lost(self, lost_for_ms: int) -> None:
651
+ """:meth:`enable_reconnect`, and a peer *lost* — its connection closed
652
+ by neither side: gone quiet past the idle timeout, or stopped answering —
653
+ is dialed again where it was last known for ``lost_for_ms``, until it is
654
+ back over any route. A peer that left is not. Enable before start,
655
+ instead of :meth:`enable_reconnect`."""
656
+ check_error(self._lib.rats_enable_reconnect_lost(self._h, lost_for_ms),
657
+ "enable_reconnect_lost")
658
+
659
+ def add_reconnect(self, host: str, port: int) -> None:
660
+ """Keep an address connected. May be called while running."""
661
+ check_error(self._lib.rats_add_reconnect(self._h, _b(host), port),
662
+ f"add_reconnect {host}:{port}")
663
+
664
+ def remove_reconnect(self, host: str, port: int) -> None:
665
+ """Stop keeping an address connected and forget it."""
666
+ check_error(self._lib.rats_remove_reconnect(self._h, _b(host), port),
667
+ f"remove_reconnect {host}:{port}")
668
+
669
+ # ----------------------------------------------------------------- BitTorrent
670
+
671
+ def enable_bittorrent(
672
+ self,
673
+ listen_port: int = 0,
674
+ download_path: Optional[str] = None,
675
+ *,
676
+ outgoing_encryption: BtEncryption = BtEncryption.ENABLED,
677
+ incoming_encryption: BtEncryption = BtEncryption.ENABLED,
678
+ outgoing_utp: bool = True,
679
+ incoming_utp: bool = True,
680
+ ) -> None:
681
+ """A BitTorrent client beside the node. Only in libraries built with
682
+ ``RATS_SEARCH_FEATURES`` (else :class:`RatsNotEnabledError`). It runs its
683
+ own sockets; enable the DHT first and it shares the node's."""
684
+ cfg = RatsBtConfig()
685
+ cfg.listen_port = listen_port
686
+ cfg.download_path = _b(download_path)
687
+ cfg.outgoing_encryption = int(outgoing_encryption)
688
+ cfg.incoming_encryption = int(incoming_encryption)
689
+ cfg.disable_outgoing_utp = int(not outgoing_utp)
690
+ cfg.disable_incoming_utp = int(not incoming_utp)
691
+ check_error(self._lib.rats_enable_bittorrent(self._h, byref(cfg)), "enable_bittorrent")
692
+
693
+ def bt_add_magnet(self, magnet_uri: str, save_path: Optional[str] = None) -> None:
694
+ """Start a download from a magnet link. Needs a started node."""
695
+ check_error(self._lib.rats_bt_add_magnet(self._h, _b(magnet_uri), _b(save_path)),
696
+ "bt_add_magnet")
697
+
698
+ def bt_add_torrent_file(self, torrent_path: str, save_path: Optional[str] = None) -> None:
699
+ """Start a download from a .torrent file. Needs a started node."""
700
+ check_error(self._lib.rats_bt_add_torrent_file(self._h, _b(torrent_path), _b(save_path)),
701
+ f"bt_add_torrent_file {torrent_path!r}")
702
+
703
+ def bt_remove_torrent(self, info_hash_hex: str) -> None:
704
+ """Remove a torrent by its 40-char hex info-hash; downloaded files stay."""
705
+ check_error(self._lib.rats_bt_remove_torrent(self._h, _b(info_hash_hex)),
706
+ f"bt_remove_torrent {info_hash_hex}")
707
+
708
+
709
+ # --------------------------------------------------------------- process-wide
710
+
711
+ def set_log_level(level: LogLevel) -> None:
712
+ get_librats().lib.rats_set_log_level(int(level))
713
+
714
+
715
+ def set_log_file(path: Optional[str]) -> None:
716
+ """Also write logs to ``path``; ``None`` or ``""`` stops file logging."""
717
+ get_librats().lib.rats_set_log_file(_b(path))
718
+
719
+
720
+ def version() -> str:
721
+ """Library version, e.g. ``"1.2.3"``."""
722
+ return _s(get_librats().lib.rats_version_string())
723
+
724
+
725
+ def version_info() -> VersionInfo:
726
+ parts = [c_int() for _ in range(4)]
727
+ get_librats().lib.rats_version(*(byref(p) for p in parts))
728
+ return VersionInfo(*(p.value for p in parts))
729
+
730
+
731
+ def git_describe() -> str:
732
+ """``git describe`` of the build, e.g. ``"v1.2.3-4-gabcdef"``."""
733
+ return _s(get_librats().lib.rats_git_describe())
734
+
735
+
736
+ def abi() -> int:
737
+ """``(major << 16) | (minor << 8) | patch``."""
738
+ return get_librats().lib.rats_abi()
739
+
740
+
741
+ def error_str(code: int) -> str:
742
+ """Name of a ``rats_error_t`` code, e.g. ``"RATS_ERR_DECLINED"``."""
743
+ return _s(get_librats().lib.rats_error_str(int(code)))