offline-protocol-sdk 0.28.0__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.
Files changed (40) hide show
  1. offline_protocol_sdk/__init__.py +22 -0
  2. offline_protocol_sdk/_callback_reentrancy.py +64 -0
  3. offline_protocol_sdk/address_declaration.py +207 -0
  4. offline_protocol_sdk/ble_manager.py +595 -0
  5. offline_protocol_sdk/ble_peripheral.py +673 -0
  6. offline_protocol_sdk/dnssd_bridge.py +614 -0
  7. offline_protocol_sdk/gateway_attach_policy.py +437 -0
  8. offline_protocol_sdk/gateway_manager.py +1217 -0
  9. offline_protocol_sdk/gateway_verdict_tracker.py +97 -0
  10. offline_protocol_sdk/internet_manager.py +1444 -0
  11. offline_protocol_sdk/legacy_store_adoption.py +184 -0
  12. offline_protocol_sdk/local_api/__init__.py +34 -0
  13. offline_protocol_sdk/local_api/authz.py +180 -0
  14. offline_protocol_sdk/local_api/cli.py +171 -0
  15. offline_protocol_sdk/local_api/codec.py +210 -0
  16. offline_protocol_sdk/local_api/dispatch.py +537 -0
  17. offline_protocol_sdk/local_api/mux.py +239 -0
  18. offline_protocol_sdk/local_api/server.py +546 -0
  19. offline_protocol_sdk/local_api/session.py +86 -0
  20. offline_protocol_sdk/local_api/table.py +849 -0
  21. offline_protocol_sdk/offline_protocol.py +13508 -0
  22. offline_protocol_sdk/peer_stream_manager.py +1303 -0
  23. offline_protocol_sdk/presence_watch_policy.py +102 -0
  24. offline_protocol_sdk/protocol_manager.py +1108 -0
  25. offline_protocol_sdk/relay_answer_prefixes.py +61 -0
  26. offline_protocol_sdk/secure_storage.py +551 -0
  27. offline_protocol_sdk/services.py +195 -0
  28. offline_protocol_sdk/state_storage.py +452 -0
  29. offline_protocol_sdk/storage_namespace.py +33 -0
  30. offline_protocol_sdk/transport_manager.py +138 -0
  31. offline_protocol_sdk/uniffi.dll +0 -0
  32. offline_protocol_sdk-0.28.0.dist-info/METADATA +519 -0
  33. offline_protocol_sdk-0.28.0.dist-info/RECORD +40 -0
  34. offline_protocol_sdk-0.28.0.dist-info/WHEEL +5 -0
  35. offline_protocol_sdk-0.28.0.dist-info/entry_points.txt +2 -0
  36. offline_protocol_sdk-0.28.0.dist-info/licenses/EXPORT.md +68 -0
  37. offline_protocol_sdk-0.28.0.dist-info/licenses/LICENSE +661 -0
  38. offline_protocol_sdk-0.28.0.dist-info/licenses/LICENSE-COMMERCIAL.md +89 -0
  39. offline_protocol_sdk-0.28.0.dist-info/licenses/THIRD-PARTY-NOTICES.md +6645 -0
  40. offline_protocol_sdk-0.28.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,614 @@
1
+ """DNS-SD for services: publish this node's registrations on the LAN, and
2
+ import what the LAN's neighbours publish, under ``docs/spec/dns-sd-mapping.md``.
3
+
4
+ Three rules from the chapter shape everything here, each with the failure it
5
+ prevents:
6
+
7
+ 1. **A LAN record proves nothing.** A mesh discovery response is signed by
8
+ the provider; a DNS-SD record is an unsigned multicast answer from whoever
9
+ is on the segment. Every import leaves this module as a
10
+ ``service_discovered`` event with ``source: "lan"``, and as a
11
+ :class:`~.services.ServiceRecord` with ``source == "lan"``, so that an
12
+ application cannot mistake it for a discovery without ignoring the field.
13
+ 2. **A LAN record is never re-advertised on the mesh.** Imports go to this
14
+ bridge's own registry and to the application's event handler, and never
15
+ to :meth:`Services.register`. A registration made on the strength of an
16
+ anonymous LAN record would go out in signed discovery responses under this
17
+ node's identity, and every mesh peer would trust the forged claim on the
18
+ strength of that signature.
19
+ 3. **A field that does not fit is refused, never truncated.** A truncated
20
+ service id names a different service. A registration whose descriptor
21
+ does not fit the record is not published, and the mesh registration is
22
+ untouched; :meth:`DnsSdBridge.publish` returns ``False`` and the log says
23
+ why.
24
+
25
+ The bridge needs the optional ``zeroconf`` dependency
26
+ (``pip install 'offline-protocol-sdk[lan]'``), imported at :meth:`start` so
27
+ the base install never imports it. Records are published under the subtype
28
+ ``_svc._sub._offlineprotocol._tcp`` of the type the peer-stream transport
29
+ already uses; a peer-stream browser ignores any record carrying ``sid``, and
30
+ this browser only ever browses the subtype.
31
+
32
+ The bounds are the chapter's, mirrored here as literals and pinned as
33
+ literals in ``test_dnssd_bridge.py`` for the reason the bridge rules give
34
+ (C5): a test that read them from this module would agree with any edit.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import asyncio
40
+ import hashlib
41
+ import logging
42
+ import time
43
+ from dataclasses import dataclass
44
+ from typing import Any, Callable, Mapping
45
+
46
+ from .peer_stream_manager import SERVICE_TYPE, advertised_addresses, service_host_name
47
+ from .services import SOURCE_LAN, SOURCE_LOCAL, ServiceRecord, Services
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+ #: Service instances live under this subtype of the peer-stream type.
52
+ SUBTYPE = "_svc._sub." + SERVICE_TYPE
53
+ #: The first TXT entry, and the only mapping version a reader accepts.
54
+ TXT_VERSION = "1"
55
+ #: The instance name is this prefix and sixteen hex digits of a digest.
56
+ INSTANCE_PREFIX = "svc-"
57
+ #: RFC 6763 section 4.1.1: an instance name is at most 63 octets.
58
+ MAX_INSTANCE_NAME_OCTETS = 63
59
+ #: RFC 6763 section 6.1: one ``key=value`` string is at most 255 bytes.
60
+ MAX_TXT_STRING_BYTES = 255
61
+ #: The chapter's bound on ``sid``: the engine's 256 does not fit one string.
62
+ MAX_SID_BYTES = 200
63
+ #: RFC 6763 section 6.2: the whole record, one length octet per string.
64
+ MAX_TXT_RECORD_BYTES = 1300
65
+ #: What a canonical address starts with; a record's ``addr`` must too.
66
+ ADDRESS_PREFIX = "off1"
67
+ #: How long an import is kept without resolving again, in seconds. Records
68
+ #: age out of a browser's cache after 75 minutes; a headless neighbour that
69
+ #: died without a goodbye should not be offered for that long.
70
+ DEFAULT_TTL = 300.0
71
+ #: How long one resolution may take.
72
+ RESOLVE_TIMEOUT_MS = 3000
73
+
74
+ _TXT_KEYS_FIXED = ("txtvers", "sid", "ver", "addr")
75
+ _CAPABILITY_PREFIX = "c."
76
+
77
+
78
+ class RecordRefused(ValueError):
79
+ """A descriptor that does not fit the record, and the reason."""
80
+
81
+
82
+ # -- the mapping, as pure functions ---------------------------------------------
83
+
84
+
85
+ def instance_label(address: str, service_id: str) -> str:
86
+ """``svc-`` plus the first sixteen hex digits of
87
+ ``SHA-256(address || 0x00 || service_id)``."""
88
+ digest = hashlib.sha256(address.encode("utf-8") + b"\x00" + service_id.encode("utf-8"))
89
+ return INSTANCE_PREFIX + digest.hexdigest()[:16]
90
+
91
+
92
+ def service_instance_name(address: str, service_id: str) -> str:
93
+ """The fully qualified instance name under the peer-stream type. The
94
+ subtype is where it is browsed, not part of its name."""
95
+ return f"{instance_label(address, service_id)}.{SERVICE_TYPE}"
96
+
97
+
98
+ def _check_key(key: str) -> None:
99
+ if not key:
100
+ raise RecordRefused("a TXT key cannot be empty")
101
+ for ch in key:
102
+ code = ord(ch)
103
+ if code < 0x20 or code > 0x7E or ch == "=":
104
+ raise RecordRefused(
105
+ f"TXT key {key!r} is not printable ASCII without '=' (RFC 6763 section 6.4)"
106
+ )
107
+
108
+
109
+ def txt_record(record: ServiceRecord, address: str) -> dict[str, str]:
110
+ """Lay a descriptor out as the chapter's TXT record, in the chapter's
111
+ order, or raise :class:`RecordRefused`. Nothing is ever shortened."""
112
+ if not address.startswith(ADDRESS_PREFIX):
113
+ raise RecordRefused(f"{address!r} is not a canonical address")
114
+ sid = record.service_id.encode("utf-8")
115
+ if len(sid) > MAX_SID_BYTES:
116
+ raise RecordRefused(
117
+ f"service id is {len(sid)} bytes; the record carries at most {MAX_SID_BYTES}"
118
+ )
119
+ entries: dict[str, str] = {
120
+ "txtvers": TXT_VERSION,
121
+ "sid": record.service_id,
122
+ "ver": record.version,
123
+ "addr": address,
124
+ }
125
+ # TXT keys are case-insensitive (RFC 6763 section 6.4), so two
126
+ # capability keys that fold to one are one key: refused, never one of
127
+ # them dropped (a different claim) or both published (a duplicate the
128
+ # reader ignores the record for).
129
+ folded: dict[str, str] = {}
130
+ for key in record.capabilities:
131
+ _check_key(key)
132
+ other = folded.setdefault(key.lower(), key)
133
+ if other != key:
134
+ raise RecordRefused(
135
+ f"capability keys {other!r} and {key!r} are one key under case folding "
136
+ "(RFC 6763 section 6.4)"
137
+ )
138
+ for key in sorted(record.capabilities, key=lambda k: k.lower().encode("utf-8")):
139
+ entries[_CAPABILITY_PREFIX + key] = record.capabilities[key]
140
+ for key, value in entries.items():
141
+ string = len(key.encode("utf-8")) + 1 + len(value.encode("utf-8"))
142
+ if string > MAX_TXT_STRING_BYTES:
143
+ raise RecordRefused(
144
+ f"TXT entry {key!r} is {string} bytes; one string carries at most "
145
+ f"{MAX_TXT_STRING_BYTES} (RFC 6763 section 6.1)"
146
+ )
147
+ size = txt_record_size(entries)
148
+ if size > MAX_TXT_RECORD_BYTES:
149
+ raise RecordRefused(
150
+ f"the TXT record is {size} bytes; the chapter allows {MAX_TXT_RECORD_BYTES}"
151
+ )
152
+ return entries
153
+
154
+
155
+ def txt_record_size(entries: Mapping[str, str]) -> int:
156
+ """The record's size on the wire: one length octet per ``key=value``."""
157
+ return sum(1 + len(k.encode("utf-8")) + 1 + len(v.encode("utf-8")) for k, v in entries.items())
158
+
159
+
160
+ def parse_txt(raw: bytes) -> list[tuple[bytes, bytes | None]] | None:
161
+ """The strings of a TXT record as ``(key, value)`` pairs, in order, or
162
+ ``None`` when a length octet runs past the end. A string with no ``=``
163
+ is a key with no value (RFC 6763 section 6.4); an empty string is
164
+ skipped, as the RFC says a reader must."""
165
+ pairs: list[tuple[bytes, bytes | None]] = []
166
+ offset = 0
167
+ while offset < len(raw):
168
+ length = raw[offset]
169
+ offset += 1
170
+ if offset + length > len(raw):
171
+ return None
172
+ string = raw[offset : offset + length]
173
+ offset += length
174
+ if not string:
175
+ continue
176
+ key, sep, value = string.partition(b"=")
177
+ pairs.append((key, value if sep else None))
178
+ return pairs
179
+
180
+
181
+ def record_from_txt(raw: bytes) -> ServiceRecord | None:
182
+ """A LAN neighbour's claim, from the raw TXT record of a resolved
183
+ instance, or ``None`` for a record the chapter says to ignore: another
184
+ ``txtvers``, a missing ``sid`` or ``addr``, an ``addr`` that is not an
185
+ address, a key twice, a value that is not UTF-8, or anything over the
186
+ bounds a publisher would have been refused on."""
187
+ pairs = parse_txt(raw)
188
+ if pairs is None or len(raw) > MAX_TXT_RECORD_BYTES:
189
+ return None
190
+ seen: set[str] = set()
191
+ fields: dict[str, str] = {}
192
+ capabilities: dict[str, str] = {}
193
+ for key, value in pairs:
194
+ try:
195
+ # Keys are case-insensitive (RFC 6763 section 6.4): folded
196
+ # before the duplicate check and the fixed-key match, so
197
+ # `SID=` is `sid=` and `c.Foo` is `c.foo`.
198
+ name = key.decode("ascii").lower()
199
+ _check_key(name)
200
+ text = "" if value is None else value.decode("utf-8")
201
+ except (UnicodeDecodeError, RecordRefused):
202
+ return None
203
+ if name in seen:
204
+ return None
205
+ seen.add(name)
206
+ if name in _TXT_KEYS_FIXED:
207
+ fields[name] = text
208
+ elif name.startswith(_CAPABILITY_PREFIX) and len(name) > len(_CAPABILITY_PREFIX):
209
+ capabilities[name[len(_CAPABILITY_PREFIX) :]] = text
210
+ if fields.get("txtvers") != TXT_VERSION:
211
+ return None
212
+ service_id = fields.get("sid")
213
+ address = fields.get("addr")
214
+ if not service_id or len(service_id.encode("utf-8")) > MAX_SID_BYTES:
215
+ return None
216
+ if not address or not address.startswith(ADDRESS_PREFIX):
217
+ return None
218
+ return ServiceRecord(
219
+ service_id=service_id,
220
+ version=fields.get("ver", ""),
221
+ capabilities=capabilities,
222
+ provider=address,
223
+ source=SOURCE_LAN,
224
+ )
225
+
226
+
227
+ def lan_service_event(record: ServiceRecord) -> dict[str, Any]:
228
+ """The event a LAN import produces: the mesh ``service_discovered``
229
+ fields, an empty ``query_id`` (no query was sent), ``hop_count`` 0 (the
230
+ record came from the segment) and ``source: "lan"``."""
231
+ return {
232
+ "type": "service_discovered",
233
+ "source": SOURCE_LAN,
234
+ "query_id": "",
235
+ "service_id": record.service_id,
236
+ "version": record.version,
237
+ "provider_peer_id": record.provider,
238
+ "capabilities": dict(record.capabilities),
239
+ "hop_count": 0,
240
+ }
241
+
242
+
243
+ # -- the responder behind the bridge ------------------------------------------
244
+
245
+
246
+ class ZeroconfBackend:
247
+ """The optional ``zeroconf`` package, behind the five calls the bridge
248
+ makes. Tests substitute a fake with the same five."""
249
+
250
+ def __init__(self) -> None:
251
+ try:
252
+ from zeroconf import IPVersion, ServiceInfo, ServiceStateChange
253
+ from zeroconf.asyncio import AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconf
254
+ except ImportError as exc:
255
+ raise ImportError(
256
+ "DNS-SD for services needs the optional dependency: "
257
+ "pip install 'offline-protocol-sdk[lan]'"
258
+ ) from exc
259
+ self._ServiceInfo = ServiceInfo
260
+ self._ServiceStateChange = ServiceStateChange
261
+ self._AsyncServiceBrowser = AsyncServiceBrowser
262
+ self._AsyncServiceInfo = AsyncServiceInfo
263
+ self._zc = AsyncZeroconf(ip_version=IPVersion.All)
264
+ self._browser: Any = None
265
+
266
+ async def register(
267
+ self, *, name: str, port: int, txt: Mapping[str, str], server: str, addresses: list[str]
268
+ ) -> Any:
269
+ info = self._ServiceInfo(
270
+ SUBTYPE,
271
+ name,
272
+ port=port,
273
+ properties=dict(txt),
274
+ server=server,
275
+ parsed_addresses=list(addresses),
276
+ )
277
+ await self._zc.async_register_service(info)
278
+ return info
279
+
280
+ async def unregister(self, handle: Any) -> None:
281
+ await self._zc.async_unregister_service(handle)
282
+
283
+ def browse(self, on_change: Callable[[str, bool], None]) -> None:
284
+ removed = self._ServiceStateChange.Removed
285
+
286
+ def handler(zeroconf: Any, service_type: str, name: str, state_change: Any) -> None:
287
+ on_change(name, state_change is removed)
288
+
289
+ self._browser = self._AsyncServiceBrowser(self._zc.zeroconf, SUBTYPE, handlers=[handler])
290
+
291
+ async def resolve(self, name: str, timeout_ms: int) -> bytes | None:
292
+ info = self._AsyncServiceInfo(SUBTYPE, name)
293
+ if await info.async_request(self._zc.zeroconf, timeout_ms):
294
+ return bytes(info.text)
295
+ return None
296
+
297
+ async def close(self) -> None:
298
+ if self._browser is not None:
299
+ await self._browser.async_cancel()
300
+ self._browser = None
301
+ await self._zc.async_close()
302
+
303
+
304
+ @dataclass
305
+ class _LanEntry:
306
+ record: ServiceRecord
307
+ seen_at: float
308
+
309
+
310
+ class DnsSdBridge:
311
+ """Publishes a :class:`Services` registry on the LAN and imports the
312
+ LAN's into a registry of its own.
313
+
314
+ Start it after ``ProtocolManager.start()``, with the address the engine
315
+ derived (``pm.local_address``); stop it before the manager. Registrations
316
+ made while it runs are published as they happen, through the
317
+ :class:`~.services.ServicesListener` it installs; registrations made
318
+ before are published at :meth:`start`.
319
+
320
+ ``on_event`` receives each import as the event
321
+ :func:`lan_service_event` builds, on the event loop's thread. Removal is
322
+ not an event: the mesh has no removal signal either, and
323
+ :meth:`lan_services` is the current view.
324
+ """
325
+
326
+ def __init__(
327
+ self,
328
+ services: Services,
329
+ *,
330
+ on_event: Callable[[dict[str, Any]], None] | None = None,
331
+ publish: bool = True,
332
+ browse: bool = True,
333
+ ttl: float = DEFAULT_TTL,
334
+ resolve_timeout_ms: int = RESOLVE_TIMEOUT_MS,
335
+ backend: Any | None = None,
336
+ ) -> None:
337
+ if ttl <= 0:
338
+ raise ValueError("ttl must be positive")
339
+ self._services = services
340
+ self._on_event = on_event
341
+ self._publish = publish
342
+ self._browse = browse
343
+ self._ttl = float(ttl)
344
+ self._resolve_timeout_ms = int(resolve_timeout_ms)
345
+ self._backend_given = backend
346
+ self._backend: Any = None
347
+ self._loop: asyncio.AbstractEventLoop | None = None
348
+ self._address: str | None = None
349
+ self._port = 0
350
+ self._addresses: list[str] = []
351
+ self._published: dict[str, Any] = {}
352
+ # The listed set: what the application sees.
353
+ self._lan: dict[str, _LanEntry] = {}
354
+ # The browsed set: every name the browser reported and has not
355
+ # reported gone, by the time of its last resolve attempt. Kept apart
356
+ # from the listed set because a browser reports a name once, and
357
+ # again only when its own cache has forgotten it (75 minutes for the
358
+ # PTR): a bridge that stopped re-resolving a name when the name left
359
+ # the listed set would lose a neighbour that missed one resolve
360
+ # window for that long.
361
+ self._browsed: dict[str, float] = {}
362
+ self._tasks: set[asyncio.Task[Any]] = set()
363
+ self._sweeper: asyncio.Task[None] | None = None
364
+ self._running = False
365
+
366
+ # -- lifecycle ------------------------------------------------------------
367
+
368
+ @property
369
+ def running(self) -> bool:
370
+ return self._running
371
+
372
+ @property
373
+ def address(self) -> str | None:
374
+ return self._address
375
+
376
+ async def start(
377
+ self,
378
+ *,
379
+ address: str,
380
+ port: int | None = None,
381
+ listen_host: str = "0.0.0.0",
382
+ addresses: list[str] | None = None,
383
+ ) -> None:
384
+ """Publish and browse.
385
+
386
+ ``address`` is this node's canonical address, ``port`` its
387
+ peer-stream listening port when it has one (the record's SRV port,
388
+ 0 otherwise), and ``addresses`` the interface addresses to publish
389
+ (every non-loopback address of every interface, by default, as the
390
+ peer-stream record does).
391
+ """
392
+ if self._running:
393
+ return
394
+ if not address.startswith(ADDRESS_PREFIX):
395
+ raise ValueError(f"{address!r} is not a canonical address")
396
+ self._loop = asyncio.get_running_loop()
397
+ self._address = address
398
+ self._port = int(port or 0)
399
+ self._backend = self._backend_given if self._backend_given is not None else ZeroconfBackend()
400
+ if self._publish:
401
+ self._addresses = list(addresses) if addresses is not None else advertised_addresses(listen_host)
402
+ if not self._addresses:
403
+ await self._backend.close()
404
+ self._backend = None
405
+ raise RuntimeError("publishing found no interface address to put in the record")
406
+ self._running = True
407
+ self._services.add_listener(self)
408
+ try:
409
+ if self._publish:
410
+ for record in self._services.registered():
411
+ await self.publish(record)
412
+ if self._browse:
413
+ self._backend.browse(self._on_change)
414
+ self._sweeper = self._loop.create_task(self._sweep_forever())
415
+ except BaseException:
416
+ # A responder that refuses a registration (a name conflict, a
417
+ # closed socket) must not leave a bridge that is listening to
418
+ # the registry and holds an open responder while reporting
419
+ # itself stopped.
420
+ await self.stop()
421
+ raise
422
+
423
+ async def stop(self) -> None:
424
+ if not self._running:
425
+ return
426
+ self._running = False
427
+ self._services.remove_listener(self)
428
+ if self._sweeper is not None:
429
+ self._sweeper.cancel()
430
+ self._sweeper = None
431
+ for task in list(self._tasks):
432
+ task.cancel()
433
+ self._tasks.clear()
434
+ for service_id in list(self._published):
435
+ handle = self._published.pop(service_id)
436
+ try:
437
+ await self._backend.unregister(handle)
438
+ except Exception:
439
+ logger.exception("withdrawing %r from the LAN failed", service_id)
440
+ self._lan.clear()
441
+ self._browsed.clear()
442
+ try:
443
+ await self._backend.close()
444
+ finally:
445
+ self._backend = None
446
+
447
+ # -- publishing -----------------------------------------------------------
448
+
449
+ def published(self) -> list[str]:
450
+ """The service ids currently on the LAN."""
451
+ return list(self._published)
452
+
453
+ async def publish(self, record: ServiceRecord) -> bool:
454
+ """Publish one of this node's registrations. Returns ``False`` when
455
+ the descriptor does not fit the record (rule 3); the mesh
456
+ registration stands either way. A record that is not this node's
457
+ own is refused outright (rule 2)."""
458
+ if record.source != SOURCE_LOCAL:
459
+ raise ValueError("only this node's own registrations are published (dns-sd-mapping invariant 2)")
460
+ if not self._running or not self._publish or self._address is None:
461
+ return False
462
+ try:
463
+ txt = txt_record(record, self._address)
464
+ except RecordRefused as exc:
465
+ logger.warning("service %r not published on the LAN: %s", record.service_id, exc)
466
+ return False
467
+ previous = self._published.pop(record.service_id, None)
468
+ if previous is not None:
469
+ await self._backend.unregister(previous)
470
+ handle = await self._backend.register(
471
+ name=service_instance_name(self._address, record.service_id),
472
+ port=self._port,
473
+ txt=txt,
474
+ server=service_host_name(self._address),
475
+ addresses=self._addresses,
476
+ )
477
+ self._published[record.service_id] = handle
478
+ return True
479
+
480
+ async def withdraw(self, record: ServiceRecord) -> None:
481
+ handle = self._published.pop(record.service_id, None)
482
+ if handle is not None and self._backend is not None:
483
+ await self._backend.unregister(handle)
484
+
485
+ # ServicesListener: called on whatever thread changed the registry.
486
+ def on_registered(self, record: ServiceRecord) -> None:
487
+ self._later(
488
+ lambda: self.publish(record),
489
+ f"service {record.service_id!r} not published on the LAN",
490
+ )
491
+
492
+ def on_unregistered(self, record: ServiceRecord) -> None:
493
+ self._later(
494
+ lambda: self.withdraw(record),
495
+ f"service {record.service_id!r} not withdrawn from the LAN",
496
+ )
497
+
498
+ def _later(self, make: Callable[[], Any], what: str) -> None:
499
+ loop = self._loop
500
+ if loop is None or not self._running:
501
+ return
502
+ loop.call_soon_threadsafe(self._spawn, make, what)
503
+
504
+ def _spawn(self, make: Callable[[], Any], what: str) -> None:
505
+ if not self._running or self._loop is None:
506
+ return
507
+ task = self._loop.create_task(self._guarded(make, what))
508
+ self._tasks.add(task)
509
+ task.add_done_callback(self._tasks.discard)
510
+
511
+ @staticmethod
512
+ async def _guarded(make: Callable[[], Any], what: str) -> None:
513
+ """Run one scheduled step and log what it was when it fails. A task
514
+ nobody awaits otherwise reports "exception was never retrieved" at
515
+ collection, without the service id, or nothing at all."""
516
+ try:
517
+ await make()
518
+ except asyncio.CancelledError:
519
+ raise
520
+ except Exception as exc:
521
+ logger.warning("%s: %s", what, exc, exc_info=True)
522
+
523
+ # -- importing ------------------------------------------------------------
524
+
525
+ def lan_services(self) -> list[ServiceRecord]:
526
+ """What the LAN's neighbours currently claim to offer: the listed
527
+ set."""
528
+ return [entry.record for entry in self._lan.values()]
529
+
530
+ def browsed_names(self) -> list[str]:
531
+ """Every instance name the browser has reported and not yet reported
532
+ gone, listed or not: the browsed set, which the sweep re-resolves."""
533
+ return list(self._browsed)
534
+
535
+ def _on_change(self, name: str, removed: bool) -> None:
536
+ if removed:
537
+ self._browsed.pop(name, None)
538
+ self._lan.pop(name, None)
539
+ return
540
+ self._browsed[name] = time.monotonic()
541
+ self._spawn(
542
+ lambda: self._resolve_and_import(name),
543
+ f"instance {name!r} not resolved",
544
+ )
545
+
546
+ async def _resolve_and_import(self, name: str, now: float | None = None) -> None:
547
+ if self._backend is None:
548
+ return
549
+ raw = await self._backend.resolve(name, self._resolve_timeout_ms)
550
+ if name not in self._browsed:
551
+ # Reported gone while the resolve was in flight: an import now
552
+ # would list an instance the browser has already withdrawn.
553
+ return
554
+ if raw is not None:
555
+ self.import_txt(name, raw, now=now)
556
+
557
+ def import_txt(self, name: str, raw: bytes, now: float | None = None) -> bool:
558
+ """Take a resolved instance's TXT record into the LAN registry.
559
+ Returns whether an event was delivered: a new instance, one whose
560
+ record changed, or one that had expired from the listed set and
561
+ resolved again (delivery is at least once). A record the chapter
562
+ says to ignore removes any earlier import under that name; this
563
+ node's own record is ignored. A resolved name is a browsed name."""
564
+ seen_at = time.monotonic() if now is None else now
565
+ self._browsed[name] = seen_at
566
+ record = record_from_txt(raw)
567
+ if record is None:
568
+ self._lan.pop(name, None)
569
+ return False
570
+ if record.provider == self._address:
571
+ return False
572
+ previous = self._lan.get(name)
573
+ self._lan[name] = _LanEntry(record, seen_at)
574
+ if previous is not None and previous.record == record:
575
+ return False
576
+ self._emit(lan_service_event(record))
577
+ return True
578
+
579
+ async def sweep(self, now: float | None = None) -> None:
580
+ """Re-resolve every browsed name whose last resolve attempt is older
581
+ than half the time to live, listed or not, then drop every listed
582
+ entry still older than the whole of it. The periodic task calls
583
+ this; a test calls it with a clock of its own.
584
+
585
+ Resolve first. The sweep runs at half the time to live, so one
586
+ missed window puts the next attempt on the drop boundary; dropping
587
+ first would show the application an empty list during that resolve
588
+ and announce the same record a second time when it answers, where
589
+ an answer refreshes the entry and shows nothing."""
590
+ current = time.monotonic() if now is None else now
591
+ for name, attempted_at in list(self._browsed.items()):
592
+ if current - attempted_at < self._ttl / 2 or name not in self._browsed:
593
+ continue
594
+ self._browsed[name] = current
595
+ await self._resolve_and_import(name, now=current)
596
+ for name, entry in list(self._lan.items()):
597
+ if current - entry.seen_at >= self._ttl:
598
+ self._lan.pop(name, None)
599
+
600
+ async def _sweep_forever(self) -> None:
601
+ while self._running:
602
+ await asyncio.sleep(self._ttl / 2)
603
+ try:
604
+ await self.sweep()
605
+ except Exception:
606
+ logger.exception("the LAN sweep failed; the next one runs on schedule")
607
+
608
+ def _emit(self, event: dict[str, Any]) -> None:
609
+ if self._on_event is None:
610
+ return
611
+ try:
612
+ self._on_event(event)
613
+ except Exception:
614
+ logger.exception("event handler failed on %s", event.get("type"))