CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
client.py
Go to the documentation of this file.
1"""PsycloneClient: post into a Psyclone system by post name, receive its triggers by trigger name."""
2import itertools
3import os
4import threading
5import time
6from concurrent.futures import Future
7from concurrent.futures import TimeoutError as FutureTimeout
8
9from .datamessage import DataMessage, Layout
10from .stats import StatsCounters
11from .transports import TcpTransport, UdpTransport, WebSocketTransport
12
13POST = "PsyPost"
14TRIGGER = "PsyTrigger"
15DEVICE = "PsyDevice"
16REQUEST_ID = "PsyClientRequestID"
17TEXT = "Text"
18#: Keepalive entries (Psyclone 2.3.2+ services answer them; see PsycloneClient).
19KEEPALIVE = "PsyKeepAlive"
20KEEPALIVE_SENT = "PsyKeepAliveSent"
21KEEPALIVE_REPLY = "PsyKeepAliveReply"
22
23
25 """Which DataMessage wire form the client sends."""
26 #: Always the regular (full) form: every Psyclone and CMSDK program reads it.
27 FULL = "full"
28 #: Always the packed form (about 3x less overhead for small messages; Psyclone 2.3+).
29 PACKED = "packed"
30 #: The full form until the service shows it reads the packed form (its keepalive reply carries
31 #: ``PsyPacked=1``, Psyclone 2.3.2+, or it sends us a packed message), then packed. The default.
32 AUTO = "auto"
33
34
35def _is_packed(data):
36 return len(data) >= 8 and int.from_bytes(data[4:8], "little") == Layout.PACKEDDATAMESSAGEID
37
38
39class Options:
40 """Client settings (all optional keyword arguments of the factory functions).
41
42 packed_mode: PackedMode.AUTO (default), FULL or PACKED. packed: True = PACKED, False = FULL (kept from
43 2.3.1; prefer packed_mode). reconnect, reconnect_min, reconnect_max (seconds): TCP/WebSocket reconnect
44 backoff (UDP: reopening a socket), spread by +-reconnect_jitter (0..1, default 0.2).
45 keepalive_interval (s, default 15; 0 = none, AUTO still sends one keepalive after connecting to negotiate
46 the packed form), keepalive_miss_limit (default 3; once the service has answered keepalives, silence
47 for this many intervals = a dead connection; 0 = never).
48 connect_timeout (s), ping_interval (s, WebSocket keep-alive, 0 = none), headers (WebSocket upgrade),
49 ssl_context (wss:// and tls(); None = the system's trust store), local_port (UDP), max_message_bytes,
50 callback: a callable that runs handlers, e.g. ``loop.call_soon_threadsafe``; None = the reader thread.
51 """
52
53 def __init__(self, packed=None, reconnect=True, reconnect_min=0.5, reconnect_max=10.0, connect_timeout=5.0,
54 ping_interval=20.0, headers=None, ssl_context=None, local_port=0, max_message_bytes=64 << 20,
55 callback=None, packed_mode=None, reconnect_jitter=0.2, keepalive_interval=15.0,
56 keepalive_miss_limit=3):
57 if packed_mode is None:
58 packed_mode = PackedMode.AUTO if packed is None else (PackedMode.PACKED if packed else PackedMode.FULL)
59 if packed_mode not in (PackedMode.FULL, PackedMode.PACKED, PackedMode.AUTO):
60 raise ValueError("packed_mode must be PackedMode.FULL, PACKED or AUTO: %r" % (packed_mode,))
61 self.packed_mode = packed_mode
62 self.reconnect = reconnect
63 self.reconnect_min = reconnect_min
64 self.reconnect_max = reconnect_max
65 self.reconnect_jitter = reconnect_jitter
66 self.keepalive_interval = keepalive_interval
67 self.keepalive_miss_limit = keepalive_miss_limit
68 self.connect_timeout = connect_timeout
69 self.ping_interval = ping_interval
70 self.headers = dict(headers or {})
71 self.ssl_context = ssl_context
72 self.local_port = local_port
73 self.max_message_bytes = max_message_bytes
74 self.callback = callback
75
76 @property
77 def packed(self):
78 """True when the packed form is forced (PackedMode.PACKED)."""
79 return self.packed_mode == PackedMode.PACKED
80
81 @packed.setter
82 def packed(self, v):
83 self.packed_mode = PackedMode.PACKED if v else PackedMode.FULL
84
85
86class _Sink:
87 """What the transport calls (on its reader thread)."""
88 __slots__ = ("c",)
89
90 def __init__(self, client):
91 self.c = client
92
93 def on_bytes(self, data):
94 self.c._on_bytes(data)
95
96 def on_text(self, text):
97 self.c._on_text_frame(text)
98
99 def on_state(self, connected, error):
100 self.c._on_state(connected, error)
101
102
104 """A client for a Psyclone ``<service>``, over UDP, TCP or WebSocket.
105
106 ::
107
108 psy = PsycloneClient.websocket("wss://host:8443/phone", device="phone-1")
109 psy.on_trigger("Playout", lambda msg: play(msg.get_data("audio"))) # the system pushes to us
110 psy.post("AudioFrame", DataMessage().set_data("audio", opus)) # fire-and-forget into it
111 answer = psy.request("Question", DataMessage().set_string("Text", "hi")) # reply, or None
112 psy.close()
113
114 Every message sent names one of the service's posts in ``PsyPost`` (the service applies that post's
115 type; a client never sets a type) and carries ``PsyDevice`` when ``device`` is set. Every message
116 received carries ``PsyTrigger``. ``request()`` adds ``PsyClientRequestID`` and waits for the reply
117 carrying it back: a responder that copies the request (the built-in ``Simple`` crank) does; one that
118 builds a new message must copy ``PsyClientRequestID`` and ``PsyServiceConnection``.
119
120 Every ``keepalive_interval`` (and right after connecting) the client sends a keepalive
121 (``PsyPost=PsyKeepAlive``, ``PsyKeepAlive=<seq>``). A Psyclone 2.3.2+ service answers it without posting
122 anything (round-trip time, ``PsyPacked``, ``PsyVersion``; 2.3.2+ also ``PsyFeatures``); an older one
123 drops it after refreshing the peer's address, which still keeps a UDP path (NAT) open, and keeps a
124 2.3.2+ service from forgetting a silent UDP peer. Once a service has answered keepalives, a connection
125 that stays silent for ``keepalive_miss_limit`` intervals is treated as dead: TCP/WebSocket reconnect,
126 UDP reports the link down and opens a new socket.
127
128 Handlers run on the reader thread unless ``callback`` is given. TCP and WebSocket reconnect by
129 themselves, with a doubling, jittered back-off; nothing is queued while a pipe is down (``post()``
130 returns False). The service learns a UDP peer's address from its first datagram (the first keepalive
131 does this at once).
132 """
133
134 def __init__(self, transport, device, options):
135 self._transport = transport
136 self.device = device
137 self.options = options
138 self._handlers = {}
139 self._any = []
140 self._text = []
141 self._state = []
142 self._pending = {}
143 self._modules = [] # RemoteModule frame listeners (reader thread, before any handler)
144 self._lock = threading.Lock()
145 self._seq = itertools.count(1)
146 self._prefix = "r%x-" % (int.from_bytes(os.urandom(6), "little"))
147 self._closed = False
148 self.sent = 0
149 self.received = 0
150 self.bad = 0
152 self._stream = not isinstance(transport, UdpTransport)
153 self._ka_seq = itertools.count(1)
154 #: True while messages go out packed (forced, or negotiated by PackedMode.AUTO for this connection).
155 self.packed_active = options.packed_mode == PackedMode.PACKED
156 #: True once the service has answered a keepalive on this connection (Psyclone 2.3.2+).
158 self._link_dead = False # UDP: the service stopped answering keepalives
159 self._state_lock = threading.Lock()
160 self._last_up = False
161 self._wake = threading.Event() # ask the keepalive thread for a keepalive now
162 self._ka_thread = threading.Thread(target=self._keepalive_loop, name="psyclone-keepalive", daemon=True)
163 transport.start(_Sink(self))
164 self._ka_thread.start()
165
166 # ---- factories ------------------------------------------------------------------------------
167 @classmethod
168 def udp(cls, host, port, device=None, **options):
169 """UDP to an ``<interface ip="UDP" protocol="Message">``; keep messages under ~1200 bytes on mobile."""
170 o = Options(**options)
171 return cls(UdpTransport(host, port, o), device, o)
172
173 @classmethod
174 def tcp(cls, host, port, device=None, **options):
175 """TCP to an ``<interface protocol="Message">`` (CMSDK Message framing)."""
176 o = Options(**options)
177 return cls(TcpTransport(host, port, False, o), device, o)
178
179 @classmethod
180 def tls(cls, host, port, device=None, **options):
181 """TCP + TLS to an ``<interface protocol="Message">`` with encryption."""
182 o = Options(**options)
183 return cls(TcpTransport(host, port, True, o), device, o)
184
185 @classmethod
186 def websocket(cls, url, device=None, **options):
187 """WebSocket (``ws://`` or ``wss://``) to a service's HTTP interface; any path."""
188 o = Options(**options)
189 return cls(WebSocketTransport(url, o), device, o)
190
191 # ---- transport sink -------------------------------------------------------------------------
192 def _on_bytes(self, data):
193 self._heard(len(data))
194 try:
195 msg = DataMessage.from_bytes(data)
196 except (ValueError, UnicodeDecodeError, IndexError, KeyError):
197 self.bad += 1
198 return
199 if self.options.packed_mode == PackedMode.AUTO and not self.packed_active and _is_packed(data):
200 self.packed_active = True
201 if msg.has(KEEPALIVE): # never handed to the handlers; an echo of our own (no reply flag) is ignored
202 if msg.has(KEEPALIVE_REPLY):
203 self._keepalive_reply(msg)
204 return
205 self._receive(msg)
206
207 def _on_text_frame(self, text):
208 self._heard(len(text))
209 if self._text:
210 self.received += 1
211 self._dispatch([(h, text) for h in list(self._text)])
212 else:
213 self._receive(DataMessage().set_string(TEXT, text))
214
215 def _on_state(self, connected, error):
216 if self._closed:
217 return
218 if connected:
219 self._counters.last_receive = time.monotonic() # the dead-link clock starts now
220 self._link_dead = False
221 if self._stream: # a new connection may reach another server: negotiate again
222 self.server_answers_keepalive = False
223 self.packed_active = self.options.packed_mode == PackedMode.PACKED
224 self._state_changed(connected, error)
225 if connected:
226 self._wake.set()
227
228 def _heard(self, n):
229 """Count what arrived; a UDP link that was judged dead is up again."""
230 self._counters.add("bytes_received", n)
231 self._counters.last_receive = time.monotonic()
232 if self._link_dead:
233 self._link_dead = False
234 self._state_changed(self._transport.connected, None)
235
236 def _state_changed(self, transport_up, error):
237 notify = False
238 c = self._counters
239 with self._state_lock:
240 up = transport_up and not self._link_dead
241 if up and not self._last_up:
242 c.add("connects")
243 c.connected_since = time.time()
244 notify = True
245 elif not up and self._last_up:
246 c.add("disconnects")
247 c.connected_since = 0.0
248 notify = True
249 elif not up and error is not None:
250 c.add("connect_failures")
251 notify = True
252 self._last_up = up
253 c.error(error)
254 if notify and not self._closed:
255 self._dispatch([(lambda u=up, e=error, f=f: f(u, e), None) for f in list(self._state)], raw=True)
256
257 def _keepalive_reply(self, msg):
258 c = self._counters
259 c.add("keepalives_answered")
260 self.server_answers_keepalive = True
261 sent_us = msg.get_int(KEEPALIVE_SENT)
262 if sent_us is not None:
263 rtt_us = time.monotonic_ns() // 1000 - sent_us
264 if 0 <= rtt_us <= 600000000:
265 c.rtt(rtt_us / 1000.0)
266 v = msg.get_string("PsyVersion")
267 if v is not None:
268 c.server_version = v
269 f = msg.get_string("PsyFeatures")
270 if f is not None:
271 c.server_features = [x.strip() for x in f.split(",") if x.strip()]
272 if self.options.packed_mode == PackedMode.AUTO and msg.get_int("PsyPacked") == 1:
273 self.packed_active = True
274
276 """Every keepalive interval: judge the link, then send a keepalive (also at once after connecting)."""
277 interval = self.options.keepalive_interval
278 next_tick = time.monotonic() + interval if interval > 0 else None
279 while not self._closed:
280 timeout = None if next_tick is None else max(0.0, next_tick - time.monotonic())
281 woken = self._wake.wait(timeout)
282 if self._closed:
283 break
284 if woken:
285 self._wake.clear()
286 self._send_keepalive()
287 continue
288 next_tick = time.monotonic() + interval
289 try:
290 self._tick()
291 except Exception as e: # noqa: BLE001 - the keepalive thread must not die
292 self._counters.error(e)
293
294 def _tick(self):
295 limit = self.options.keepalive_miss_limit
296 if limit > 0 and self.server_answers_keepalive and self._transport.connected:
297 silent = time.monotonic() - self._counters.last_receive
298 if silent > self.options.keepalive_interval * limit:
299 why = TimeoutError("nothing received for %d ms (keepalives unanswered)" % int(silent * 1000))
300 self._counters.add("dead_link_drops")
301 self._counters.error(why)
302 if not self._stream and not self._link_dead:
303 self._link_dead = True
304 self._state_changed(self._transport.connected, why)
305 self._counters.last_receive = time.monotonic() # one drop per silent period
306 self._transport.drop(why)
307 self._send_keepalive()
308
310 if self._closed or not self._transport.connected:
311 return
312 m = DataMessage().set_string(POST, KEEPALIVE).set_int(KEEPALIVE, next(self._ka_seq)) \
313 .set_int(KEEPALIVE_SENT, time.monotonic_ns() // 1000)
314 if self.device is not None:
315 m.set_string(DEVICE, self.device)
316 data = m.to_packed_bytes() if self.packed_active else m.to_bytes()
317 if self._transport.send(data):
318 self._counters.add("keepalives_sent")
319 self._counters.add("bytes_sent", len(data))
320
321 def _receive(self, msg):
322 self.received += 1
323 rid = msg.get_string(REQUEST_ID)
324 if rid is not None:
325 with self._lock:
326 f = self._pending.pop(rid, None)
327 if f is not None:
328 f.set_result(msg)
329 return
330 # remote-module frames go to their RemoteModule on this (reader) thread, so one reply's frames keep their order
331 if self._modules and msg.has("PsyModule"):
332 for listener in list(self._modules):
333 if listener(msg):
334 return
335 trig = msg.get_string(TRIGGER)
336 calls = [(h, msg) for h in self._handlers.get(trig, ())] + [(h, msg) for h in self._any]
337 if calls:
338 self._dispatch(calls)
339
340 def _run_callback(self, fn):
341 """Run fn() where handlers run (the ``callback`` executor, or here)."""
342 self._dispatch([(fn, None)], raw=True)
343
344 def _dispatch(self, calls, raw=False):
345 def run():
346 for h, arg in calls:
347 try:
348 h() if raw else h(arg)
349 except Exception: # noqa: BLE001 - a handler's error must not stop the reader
350 import traceback
351 traceback.print_exc()
352 cb = self.options.callback
353 if cb is not None:
354 cb(run)
355 else:
356 run()
357
358 # ---- API ------------------------------------------------------------------------------------
359 @property
360 def transport(self):
361 """'udp', 'tcp', 'tls', 'ws' or 'wss'."""
362 return self._transport.name
363
364 @property
365 def connected(self):
366 """Stream transports: while the socket is up. UDP: while its socket is open and (once the service has
367 answered keepalives) the service keeps answering."""
368 return self._transport.connected and not self._link_dead
369
370 def stats(self):
371 """A ConnectionStats snapshot of this connection's counters, state and round-trip times."""
372 return self._counters.snapshot(self._transport.name, self.connected, self.packed_active, self.sent,
373 self.received, self.bad)
374
375 @property
377 """The service's PsyFeatures from its last keepalive reply (a list; empty before Psyclone 2.3.2)."""
378 return list(self._counters.server_features)
379
380 def on_trigger(self, trigger, handler):
381 """Call handler(msg) for every message the service trigger named ``trigger`` sends."""
382 self._handlers.setdefault(trigger, []).append(handler)
383 return self
384
385 def on_any_message(self, handler):
386 """Call handler(msg) for every message received (after trigger handlers), except request replies."""
387 self._any.append(handler)
388 return self
389
390 def on_text(self, handler):
391 """WebSocket text frames: handler(str). Without one they arrive as messages with a ``Text`` entry."""
392 self._text.append(handler)
393 return self
394
395 def on_state_changed(self, listener):
396 """listener(connected, error) when the connection comes up or goes down (error is None for a clean
397 change); failed reconnect attempts are reported as (False, error) too. UDP: up while its socket is
398 open and, once the service has answered a keepalive, while it keeps answering."""
399 self._state.append(listener)
400 return self
401
402 def remove_handler(self, handler):
403 """Remove ``handler`` from on_any_message and every on_trigger list."""
404 if handler in self._any:
405 self._any.remove(handler)
406 for lst in self._handlers.values():
407 while handler in lst:
408 lst.remove(handler)
409
410 def post(self, post, msg=None):
411 """Post ``msg`` (sets ``PsyPost`` and ``PsyDevice`` on it) as the service post named ``post``.
412 Returns False when the pipe is down (nothing is queued)."""
413 if self._closed:
414 raise RuntimeError("client closed")
415 if msg is None:
416 msg = DataMessage()
417 msg.set_string(POST, post)
418 if self.device is not None:
419 msg.set_string(DEVICE, self.device)
420 data = msg.to_packed_bytes() if self.packed_active else msg.to_bytes()
421 ok = self._transport.send(data)
422 if ok:
423 self.sent += 1
424 self._counters.add("bytes_sent", len(data))
425 else:
426 self._counters.add("send_failures")
427 return ok
428
429 def send_text(self, text):
430 """Send a WebSocket text frame (posted as a ``Text`` entry to the service's only post)."""
431 ok = self._transport.send_text(text)
432 if ok:
433 self.sent += 1
434 self._counters.add("bytes_sent", len(text))
435 else:
436 self._counters.add("send_failures")
437 return ok
438
439 def request_async(self, post, msg=None, timeout=5.0):
440 """Post and return a concurrent.futures.Future for the reply (TimeoutError after ``timeout`` s)."""
441 if msg is None:
442 msg = DataMessage()
443 rid = self._prefix + str(next(self._seq))
444 f = Future()
445 with self._lock:
446 self._pending[rid] = f
447 msg.set_string(REQUEST_ID, rid)
448 if not self.post(post, msg):
449 with self._lock:
450 self._pending.pop(rid, None)
451 f.set_exception(ConnectionError("not connected"))
452 return f
453 self._counters.add("requests_sent")
454
455 def expire():
456 with self._lock:
457 gone = self._pending.pop(rid, None)
458 if gone is not None and not gone.done():
459 self._counters.add("request_timeouts")
460 gone.set_exception(TimeoutError("no reply to %s within %.1f s" % (post, timeout)))
461 t = threading.Timer(timeout, expire)
462 t.daemon = True
463 t.start()
464 f.add_done_callback(lambda _f: t.cancel())
465 return f
466
467 def request(self, post, msg=None, timeout=5.0):
468 """Blocking request: the reply DataMessage, or None on timeout or when the pipe is down."""
469 try:
470 return self.request_async(post, msg, timeout).result(timeout + 1.0)
471 except (TimeoutError, FutureTimeout, ConnectionError):
472 return None
473
474 def wait_connected(self, timeout):
475 """Wait until connected (``connected``); True if it is."""
476 end = time.monotonic() + timeout
477 while not self.connected:
478 if self._closed or time.monotonic() > end:
479 return False
480 time.sleep(0.01)
481 return True
482
483 def wait_server(self, timeout):
484 """Wait until the service has answered a keepalive (a Psyclone 2.3.2+ service; AUTO has then
485 negotiated the packed form); True if it has."""
486 end = time.monotonic() + timeout
487 while not self.server_answers_keepalive:
488 if self._closed or time.monotonic() > end:
489 return False
490 time.sleep(0.01)
491 return True
492
493 def close(self):
494 if self._closed:
495 return
496 self._closed = True
497 self._wake.set()
498 self._transport.close()
499 with self._lock:
500 pending, self._pending = list(self._pending.values()), {}
501 for f in pending:
502 if not f.done():
503 f.set_exception(ConnectionError("client closed"))
504
505 def __enter__(self):
506 return self
507
508 def __exit__(self, *exc):
509 self.close()
__init__(self, client)
Definition client.py:90
on_state(self, connected, error)
Definition client.py:99
__init__(self, packed=None, reconnect=True, reconnect_min=0.5, reconnect_max=10.0, connect_timeout=5.0, ping_interval=20.0, headers=None, ssl_context=None, local_port=0, max_message_bytes=64<< 20, callback=None, packed_mode=None, reconnect_jitter=0.2, keepalive_interval=15.0, keepalive_miss_limit=3)
Definition client.py:56
_state_changed(self, transport_up, error)
Definition client.py:236
on_trigger(self, trigger, handler)
Definition client.py:380
_on_state(self, connected, error)
Definition client.py:215
request(self, post, msg=None, timeout=5.0)
Definition client.py:467
_dispatch(self, calls, raw=False)
Definition client.py:344
post(self, post, msg=None)
Definition client.py:410
tcp(cls, host, port, device=None, **options)
Definition client.py:174
websocket(cls, url, device=None, **options)
Definition client.py:186
tls(cls, host, port, device=None, **options)
Definition client.py:180
request_async(self, post, msg=None, timeout=5.0)
Definition client.py:439
__init__(self, transport, device, options)
Definition client.py:134
# a new connection may reach another server negotiate again _stream
Definition client.py:152
udp(cls, host, port, device=None, **options)
Definition client.py:168