CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
remote_module.py
Go to the documentation of this file.
1"""Remote modules (Psyclone 2.3.2+): this process *is* a module of a running Psyclone system.
2
3The PsySpec declares the module (``<module name="Asr" type="remote" service="Modules">`` with its triggers,
4posts, retrieves and queries) and a ``<service>`` with a ``<modules>`` element hosts it. The process attaches
5over any PsycloneClient transport (TCP, TLS, WebSocket; UDP only where the host allows it) and then receives
6the module's triggers, posts by post name, retrieves from whiteboards and queries catalogs by the names the
7spec gave them::
8
9 psy = PsycloneClient.tcp("host", 18700, device="asr-box-1")
10 asr = RemoteModule.attach(psy, "Asr", Auth.key(api_key)) # the contract comes from the server
11 asr.on_trigger("Audio", lambda m: asr.post("Text", DataMessage().set_string("Text", recognise(m))))
12 recent = asr.retrieve("Recent", max_count=5) # list of DataMessage
13 asr.on_stop(lambda reason: pause())
14
15Protocol ("Remote Module Protocol 1", Psyclone User Guide, "Remote modules"): control frames carry
16``PsyPost=PsyModule`` and ``PsyOp``; every frame about a module carries ``PsyModule`` and, after attach, the
17server-issued ``PsySession``. Replies echo ``PsyOpID`` and carry ``PsyOpReply=1`` and ``PsyStatus``. Trigger
18frames carry ``PsyTrigger``, ``PsySeq``, ``PsyTypeName`` and ``PsyFromName``. With ``Auth.key`` the API key's
19secret never travels: the client proves it with ``HMAC-SHA256(sha256hex(secret), "module|device|nonce")`` on a
20nonce from ``hello``.
21
22Dynamic modules (2.3.2 phase 2): a host with ``<modules allowdynamic="yes">`` lets a process attach a name the
23spec does not declare (inside ``<allow names>``) and build its contract at run time: ``subscribe(Trigger(...))``,
24``declare_post``, ``declare_retrieve``, ``declare_query``, ``declare_parameter``; every type is checked against the
25host's ``<allow>`` (a refusal raises ``denied``). Ad-hoc ``retrieve_from`` / ``query_catalog`` name a whiteboard or
26catalog the policy allows::
27
28 ext = RemoteModule.attach(psy, "Ext.Logger")
29 ext.subscribe(Trigger("All", "Mimir.*").max_age(1000))
30 ext.declare_post("Note", "Ext.Logger.Note")
31
32After a reconnect the module attaches again with ``Resume`` = its session and ``LastSeq`` = ``last_seq``: while
33the session lives the host replays the triggers this process missed (its resume buffer, by default 256 messages /
345 s) and reports what it could not keep through ``on_dropped``. When the session had ended, a changeable module's
35subscriptions and declarations are sent again (the desired set).
36
37Handlers run where the client runs its handlers (the reader thread, or the client's ``callback``). A handler
38may ``post()`` at once; the blocking calls (``retrieve``, ``query``, ``post_confirmed``, ``describe``) wait for
39a reply that arrives on the reader thread, so call them from a handler only when the client has a
40``callback`` that runs handlers elsewhere (or from another thread).
41"""
42import hashlib
43import hmac
44import itertools
45import os
46import threading
47import time
48from collections import deque
49
50from .datamessage import DataMessage
51
52MODULE = "PsyModule"
53TRIGGER = "PsyTrigger"
54
55__all__ = ["RemoteModule", "RemoteModuleError", "Auth", "Trigger", "ATTACHED", "STOPPED", "DETACHED"]
56
57ATTACHED, STOPPED, DETACHED = "attached", "stopped", "detached"
58
59
60class RemoteModuleError(Exception):
61 """The host refused an operation or did not answer. ``status`` is its PsyStatus (denied, unknown, busy,
62 invalid, timeout, failed, unsupported, incomplete)."""
63
64 def __init__(self, status, message):
65 super().__init__("%s: %s" % (status, message))
66 self.status = status
67
68
69class Auth:
70 """How the process proves it may attach (the host's ``<modules auth=...>``)."""
71
72 def __init__(self, mode, value=""):
73 self.mode = mode
74 self.value = value
75
76 @classmethod
77 def key(cls, api_key):
78 """A PsyProbe 2 API key ``psy_<id>_<secret>`` of an account with permission ``modules.attach.<Module>``."""
79 if not api_key.startswith("psy_") or api_key.find("_", 4) <= 4:
80 raise ValueError("an API key looks like psy_<id>_<secret>")
81 return cls("key", api_key)
82
83 @classmethod
84 def token(cls, token):
85 """The host's shared ``<modules auth="token" token="...">``."""
86 return cls("token", token)
87
88 @classmethod
89 def none(cls):
90 """``<modules auth="none">``: accepted only from the host's own machine."""
91 return cls("none")
92
93
94def _proof(api_key, module, device, nonce):
95 us = api_key.find("_", 4)
96 key_id, secret = api_key[4:us], api_key[us + 1:]
97 k = hashlib.sha256(secret.encode("utf-8")).hexdigest().encode("utf-8")
98 return key_id, hmac.new(k, ("%s|%s|%s" % (module, device, nonce)).encode("utf-8"), hashlib.sha256).hexdigest()
99
100
101def _xa(s):
102 """XML attribute value escaping for the fragments sent to the host."""
103 return (str(s).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
104 .replace('"', "&quot;").replace("'", "&apos;"))
105
106
108 """A trigger for ``subscribe``, written as the PsySpec ``<trigger>`` it becomes on the host (type wildcards,
109 from/to, tag, maxage, delay, interval, filters): ``Trigger("Audio", "Mimir.Audio.Frame").max_age(500)``."""
110
111 def __init__(self, name, type):
112 self.name, self.type = name, type
113 self._attrs, self._filters = [], []
114
115 def _set(self, k, v):
116 self._attrs = [(a, b) for a, b in self._attrs if a != k] + [(k, str(v))]
117 return self
118
119 def from_(self, component):
120 return self._set("from", component)
121
122 def to(self, component):
123 return self._set("to", component)
124
125 def tag(self, tag):
126 return self._set("tag", tag)
127
128 def max_age(self, ms):
129 return self._set("maxage", int(ms))
130
131 def delay(self, ms):
132 return self._set("delay", int(ms))
133
134 def interval(self, ms):
135 """Also fire every ``ms`` milliseconds (an interval trigger; at least 10 ms)."""
136 return self._set("interval", int(ms))
137
138 def filter(self, op, key, value=None):
139 self._filters.append((op, key, value))
140 return self
141
142 def equal_to(self, key, value):
143 return self.filter("equals", key, value)
144
145 def not_equal_to(self, key, value):
146 return self.filter("notequals", key, value)
147
148 def greater_than(self, key, value):
149 return self.filter("greaterthan", key, value)
150
151 def less_than(self, key, value):
152 return self.filter("lessthan", key, value)
153
154 def has_key(self, key):
155 return self.filter("haskey", key)
156
157 def to_xml(self):
158 s = '<trigger name="%s" type="%s"' % (_xa(self.name), _xa(self.type))
159 s += "".join(' %s="%s"' % (k, _xa(v)) for k, v in self._attrs)
160 if not self._filters:
161 return s + "/>"
162 s += ">"
163 for op, k, v in self._filters:
164 s += '<filter type="%s" key="%s"%s/>' % (_xa(op), _xa(k), (' value="%s"' % _xa(v)) if v is not None else "")
165 return s + "</trigger>"
166
167 __str__ = to_xml
168
169
170def _split(s):
171 return [x.strip() for x in (s or "").split(",") if x.strip()]
172
173
174class _Op:
175 def __init__(self):
176 self.frames = []
177 self.reply = None
178 self.done = threading.Event()
179
180
182 """One declared remote module, attached through ``client`` (one connection may carry several modules).
183
184 After a reconnect, or when the host reports that the lease ran out, the module attaches again with its
185 old session as ``Resume`` and ``last_seq`` as ``LastSeq`` (``auto_reattach``); the host replays what it kept.
186 """
187
188 def __init__(self, client, name, auth, timeout):
189 self.client = client
190 self.name = name
191 self._auth = auth
192 self.timeout = timeout
193 self.state = DETACHED
194 self.session = None
195 self.posts, self.triggers, self.retrieves, self.queries = [], {}, [], []
196 self.contract_xml = ""
197 self.lease_ms = 0
198 self.last_seq = 0
199 self.auto_reattach = True
200 self.attaches = 0
201 self.resumes = 0 # re-attaches that resumed the session (the host replayed what was missed)
202 self.dropped_reported = 0 # trigger messages the host reported dropped (on_dropped)
203 self.dynamic = False # made by this attach, not declared in the spec
204 self.changeable = False # may subscribe/declare (dynamic, or declared with dynamic="yes")
205 self.parameters = {} # name -> current value (attach, parameter frames)
206 self._desired_triggers = {} # the desired set, re-sent after a re-attach that could not resume
207 self._desired_decl = {} # name -> (entry, xml)
208 self._dropped_h, self._param_h = [], []
210 self._handlers = {}
211 self._any = []
212 self._stop, self._start, self._detached = [], [], []
213 self._pull = deque(maxlen=1024)
214 self._pull_ready = threading.Condition()
215 self._pending = {}
216 self._lock = threading.Lock()
217 self._attach_lock = threading.Lock()
218 self._seq = itertools.count(1)
219 self._prefix = "m%x-" % int.from_bytes(os.urandom(6), "little")
220 self._closed = False
221 self._reattaching = False
222
223 # ---- attach ---------------------------------------------------------------------------------
224 @classmethod
225 def attach(cls, client, name, auth=None, timeout=5.0):
226 """Attach this process to the declared module ``name`` over ``client`` (waits for it to connect).
227 Raises RemoteModuleError when the host refuses or does not answer (an older Psyclone, or a
228 service without ``<modules>``)."""
229 m = cls(client, name, auth or Auth.none(), timeout)
230 client._modules.append(m._receive)
231 client.on_state_changed(m._state_changed)
232 try:
233 if not client.wait_connected(timeout):
234 raise RemoteModuleError("timeout", "not connected (%s)" % client.transport)
235 m._do_attach(None)
236 except Exception:
237 client._modules.remove(m._receive)
238 raise
239 return m
240
241 def _do_attach(self, resume):
242 with self._attach_lock:
243 device = self.client.device or ""
244 m = DataMessage().set_string("PsyOp", "attach").set_string(MODULE, self.name)
245 if resume:
246 m.set_string("Resume", resume).set_int("LastSeq", self.last_seq)
247 if self._auth.mode == "token":
248 m.set_string("PsyAuthToken", self._auth.value)
249 elif self._auth.mode == "key":
250 hello = self._request(MODULE, DataMessage().set_string("PsyOp", "hello").set_string(MODULE, self.name))
251 nonce = hello.get_string("PsyNonce")
252 if not nonce:
253 raise RemoteModuleError("failed", 'the host sent no nonce (is its auth "key"?)')
254 key_id, proof = _proof(self._auth.value, self.name, device, nonce)
255 m.set_string("PsyAuthKey", key_id).set_string("PsyAuthNonce", nonce).set_string("PsyAuthProof", proof)
256 r = self._request(MODULE, m)
257 self._contract(r)
258 self.contract_xml = r.get_string("Contract", "")
259 self.lease_ms = r.get_int("Lease", 0)
260 self._params(r.get_string("Parameters"))
261 self.state = STOPPED if r.get_string("PsyState") == "stopped" else ATTACHED
262 self.session = r.get_string("PsySession")
263 self.attaches += 1
264 if r.get_int("Resumed", 0) == 1:
265 self.resumes += 1
266 elif self.changeable:
267 self._converge() # a new session: the host starts from the spec (declared) or empty (dynamic)
268
269 def _converge(self):
270 tx = "".join(self._desired_triggers.values())
271 if tx:
272 self._contract(self._request(MODULE, self._control("subscribe").set_string("Triggers", tx)))
273 if self._desired_decl:
274 d = self._control("declare")
275 by = {}
276 for entry, xml in list(self._desired_decl.values()):
277 by[entry] = by.get(entry, "") + xml
278 for entry, xml in by.items():
279 d.set_string(entry, xml)
280 self._contract(self._request(MODULE, d))
281
282 def _contract(self, r):
283 if r.has("Posts"):
284 self.posts = _split(r.get_string("Posts"))
285 if r.has("Triggers"):
286 self.triggers = dict((t.split("=", 1) + [""])[:2] for t in _split(r.get_string("Triggers")))
287 if r.has("Retrieves"):
288 self.retrieves = _split(r.get_string("Retrieves"))
289 if r.has("Queries"):
290 self.queries = _split(r.get_string("Queries"))
291 if r.has("Dynamic"):
292 self.dynamic = r.get_int("Dynamic") == 1
293 if r.has("Changeable"):
294 self.changeable = r.get_int("Changeable") == 1
295
296 def _params(self, s):
297 for line in (s or "").split("\n"):
298 k, sep, v = line.partition("=")
299 if sep and k:
300 self.parameters[k] = v
301
302 def _state_changed(self, up, error):
303 if up and not self._closed and self.auto_reattach and self.session is not None:
304 self._reattach_later("reconnect")
305
306 def _reattach_later(self, why):
307 if self._reattaching or self._closed:
308 return
309 self._reattaching = True
310
311 def run():
312 try:
313 delay = 0.2
314 while not self._closed and self.auto_reattach:
315 try:
316 self._do_attach(self.session)
317 break
318 except RemoteModuleError as e:
319 if e.status in ("denied", "unknown", "busy"):
320 self.session, self.state = None, DETACHED
321 break
322 time.sleep(delay)
323 delay = min(delay * 2, 5.0)
324 finally:
325 self._reattaching = False
326
327 threading.Thread(target=run, name="psyclone-module-%s-%s" % (self.name, why), daemon=True).start()
328
329 # ---- handlers -------------------------------------------------------------------------------
330 def on_trigger(self, trigger, handler):
331 """Call handler(msg) for every message the module's trigger ``trigger`` delivers."""
332 self._handlers.setdefault(trigger, []).append(handler)
333 return self
334
335 def on_any_trigger(self, handler):
336 """Call handler(msg) for every trigger message of this module (after the named handlers)."""
337 self._any.append(handler)
338 return self
339
340 def on_stop(self, handler):
341 """handler(reason): PsyProbe stopped the module (or the node shuts down); no triggers until on_start."""
342 self._stop.append(handler)
343 return self
344
345 def on_start(self, handler):
346 self._start.append(handler)
347 return self
348
349 def on_detached(self, handler):
350 """handler(reason): the host ended the session (takeover, lease, shutdown)."""
351 self._detached.append(handler)
352 return self
353
354 def on_dropped(self, handler):
355 """handler(count, from_seq, reason): the host dropped trigger messages (queue: this process read too
356 slowly; buffer: more was missed during an outage than the resume buffer keeps; size: too big for UDP)."""
357 self._dropped_h.append(handler)
358 return self
359
360 def on_parameter(self, handler):
361 """handler(name, value): a parameter of the module was changed in PsyProbe."""
362 self._param_h.append(handler)
363 return self
364
365 def wait_for_new_message(self, timeout):
366 """Crank-style pull: the next trigger message no handler took, or None after ``timeout`` seconds;
367 ``current_trigger_name`` names its trigger."""
368 end = time.monotonic() + timeout
369 with self._pull_ready:
370 while not self._pull:
371 left = end - time.monotonic()
372 if left <= 0:
373 return None
374 self._pull_ready.wait(left)
375 m = self._pull.popleft()
376 self.current_trigger_name = m.get_string(TRIGGER)
377 return m
378
379 # ---- operations -----------------------------------------------------------------------------
380 def post(self, post, msg=None):
381 """Post ``msg`` as the module's post named ``post`` (the spec decides its type). False when the pipe
382 is down or the module is not attached."""
383 s = self.session
384 if s is None:
385 return False
386 msg = msg if msg is not None else DataMessage()
387 msg.set_string(MODULE, self.name).set_string("PsySession", s)
388 return self.client.post(post, msg)
389
390 def post_confirmed(self, post, msg=None, timeout=None):
391 """post() and wait for the host to confirm it (RemoteModuleError on a refusal or timeout)."""
392 s = self.session
393 if s is None:
394 raise RemoteModuleError("denied", "not attached")
395 msg = msg if msg is not None else DataMessage()
396 msg.set_string(MODULE, self.name).set_string("PsySession", s)
397 self._request(post, msg, timeout)
398
399 def retrieve(self, retrieve, max_count=0, max_age_ms=0, timeout=None):
400 """The module's named whiteboard retrieve (its ``<retrieve name=...>``), optionally with a smaller
401 ``max_count`` or ``max_age_ms``; the host caps a remote retrieve (``<modules maxretrieve>``, 100)."""
402 m = self._control("retrieve").set_string("Retrieve", retrieve)
403 if max_count > 0:
404 m.set_int("MaxCount", max_count)
405 if max_age_ms > 0:
406 m.set_int("MaxAge", max_age_ms)
407 return self._results(self._request_op(MODULE, m, timeout), retrieve)
408
409 @staticmethod
410 def _results(op, what):
411 want = op.reply.get_int("PsyResultCount", 0)
412 got = sorted(op.frames, key=lambda f: f.get_int("PsyResultIndex", 0))
413 if len(got) != want:
414 raise RemoteModuleError("incomplete", "retrieve %s: %d of %d results arrived" % (what, len(got), want))
415 return got
416
417 def query(self, query, msg=None, timeout=None):
418 """The module's named catalog query (its ``<query name=...>``); ``msg``'s entries are the query
419 (``Query``, ``List``, ...). Returns the catalog's reply."""
420 msg = msg if msg is not None else DataMessage()
421 msg.set_string("PsyOp", "query").set_string(MODULE, self.name).set_string("PsyQuery", query)
422 if self.session:
423 msg.set_string("PsySession", self.session)
424 return self._request(MODULE, msg, timeout)
425
426 def describe(self):
427 """What the host has for this module now (Posts, Triggers, PsyState, Contract; TriggerSpecs when changeable)."""
428 return self._request(MODULE, self._control("describe"))
429
430 # ---- dynamic contract -----------------------------------------------------------------------
431 def subscribe(self, *triggers):
432 """Add or replace (by name) these Trigger()s; re-sending the same trigger changes nothing."""
433 xml = "".join(t.to_xml() for t in triggers)
434 self._contract(self._request(MODULE, self._control("subscribe").set_string("Triggers", xml)))
435 for t in triggers:
436 self._desired_triggers[t.name] = t.to_xml()
437 return self
438
439 def unsubscribe(self, *names):
440 """Remove triggers by name (no names: all of them)."""
441 self._contract(self._request(MODULE, self._control("unsubscribe").set_string("Names", ",".join(names) if names else "*")))
442 if names:
443 for n in names:
444 self._desired_triggers.pop(n, None)
445 else:
446 self._desired_triggers.clear()
447 return self
448
449 def declare_post(self, name, type, to=None, ttl_ms=0, guaranteed=True):
450 """Declare a post: post(name, ...) then sends messages of ``type`` (which <allow post> must cover)."""
451 x = '<post name="%s" type="%s"' % (_xa(name), _xa(type))
452 if to:
453 x += ' to="%s"' % _xa(to)
454 if ttl_ms:
455 x += ' ttl="%d"' % ttl_ms
456 if not guaranteed:
457 x += ' guaranteed="no"'
458 return self._declare(name, "Posts", x + "/>")
459
460 def declare_retrieve(self, name, source, type=None, max_count=0, max_age_ms=0):
461 """Declare a named whiteboard retrieve on ``source`` (in <allow retrieve>); use it with retrieve()."""
462 x = '<retrieve name="%s" source="%s"' % (_xa(name), _xa(source))
463 if type:
464 x += ' type="%s"' % _xa(type)
465 if max_count:
466 x += ' maxcount="%d"' % max_count
467 if max_age_ms:
468 x += ' maxage="%d"' % max_age_ms
469 return self._declare(name, "Retrieves", x + "/>")
470
471 def declare_query(self, name, source):
472 """Declare a named query of catalog ``source`` (in <allow query>); use it with query()."""
473 return self._declare(name, "Queries", '<query name="%s" source="%s"/>' % (_xa(name), _xa(source)))
474
475 def declare_parameter(self, name, value):
476 """Create (or set) a text parameter of the module: PsyProbe shows and edits it (on_parameter)."""
477 return self._declare(name, "Parameters", '<parameter name="%s" value="%s"/>' % (_xa(name), _xa(value)))
478
479 def undeclare(self, *names):
480 """Remove declared posts, retrieves or queries by name."""
481 if names:
482 self._contract(self._request(MODULE, self._control("declare").set_string("Remove", ",".join(names))))
483 for n in names:
484 self._desired_decl.pop(n, None)
485 return self
486
487 def _declare(self, name, entry, xml):
488 self._contract(self._request(MODULE, self._control("declare").set_string(entry, xml)))
489 self._desired_decl[name] = (entry, xml)
490 return self
491
492 def set_parameter(self, name, value):
493 """Set one of the module's parameters (declared in the spec or with declare_parameter)."""
494 r = self._request(MODULE, self._control("parameter").set_string("Name", name).set_string("Value", str(value)))
495 self._params(r.get_string("Parameters"))
496
497 def retrieve_from(self, source, type=None, max_count=0, max_age_ms=0, from_=None, to=None, key=None, key_type=None,
498 start=None, end=None, timeout=None):
499 """An ad-hoc whiteboard retrieve (dynamic modules, or a host with <modules adhoc="yes">): ``source`` must be
500 in <allow retrieve>; ``key``/``key_type`` (time, string, integer, float) with ``start``/``end`` select a range."""
501 m = self._control("retrieve").set_string("Source", source)
502 for k, v in (("Type", type), ("From", from_), ("To", to), ("Key", key), ("KeyType", key_type), ("Start", start), ("End", end)):
503 if v is not None:
504 m.set_string(k, str(v))
505 if max_count > 0:
506 m.set_int("MaxCount", max_count)
507 if max_age_ms > 0:
508 m.set_int("MaxAge", max_age_ms)
509 return self._results(self._request_op(MODULE, m, timeout), source)
510
511 def query_catalog(self, source, msg=None, timeout=None):
512 """An ad-hoc catalog query: ``source`` (in <allow query>) gets ``msg``'s entries as the query."""
513 msg = msg if msg is not None else DataMessage()
514 msg.set_string("PsyOp", "query").set_string(MODULE, self.name).set_string("Source", source)
515 if self.session:
516 msg.set_string("PsySession", self.session)
517 return self._request(MODULE, msg, timeout)
518
519 def ack(self):
520 """Tell the host this process has every trigger up to last_seq (it may trim its resume buffer); optional."""
521 if self.session:
522 self.client.post(MODULE, self._control("ack").set_int("Seq", self.last_seq))
523
524 def detach(self):
525 """Leave cleanly: the host marks the module offline (Psyclone.RemoteModule.Offline, Reason=detach)."""
526 self.auto_reattach = False
527 if self.session is not None:
528 try:
529 self._request(MODULE, self._control("detach"))
530 except RemoteModuleError:
531 pass
532 self.session, self.state = None, DETACHED
533
534 def close(self):
535 """detach() and stop listening (the client stays open: close it separately)."""
536 if self._closed:
537 return
538 self.detach()
539 self._closed = True
540 if self._receive in self.client._modules:
541 self.client._modules.remove(self._receive)
542 with self._lock:
543 ops, self._pending = list(self._pending.values()), {}
544 for op in ops:
545 op.done.set()
546
547 def __enter__(self):
548 return self
549
550 def __exit__(self, *exc):
551 self.close()
552
553 # ---- internals ------------------------------------------------------------------------------
554 def _control(self, op):
555 m = DataMessage().set_string("PsyOp", op).set_string(MODULE, self.name)
556 if self.session:
557 m.set_string("PsySession", self.session)
558 return m
559
560 def _request_op(self, post, msg, timeout=None):
561 timeout = self.timeout if timeout is None else timeout
562 oid = "%s%d" % (self._prefix, next(self._seq))
563 op = _Op()
564 with self._lock:
565 self._pending[oid] = op
566 msg.set_string("PsyOpID", oid)
567 if not self.client.post(post, msg):
568 with self._lock:
569 self._pending.pop(oid, None)
570 raise RemoteModuleError("failed", "not connected")
571 if not op.done.wait(timeout) or op.reply is None:
572 with self._lock:
573 self._pending.pop(oid, None)
574 hint = "" if "modules/1" in self.client.server_features else " (the service does not advertise remote modules)"
575 raise RemoteModuleError("timeout", "no reply to %s within %.1f s%s" % (msg.get_string("PsyOp") or post, timeout, hint))
576 status = op.reply.get_string("PsyStatus", "failed")
577 if status != "ok":
578 raise RemoteModuleError(status, op.reply.get_string("PsyError", status))
579 return op
580
581 def _request(self, post, msg, timeout=None):
582 return self._request_op(post, msg, timeout).reply
583
584 def _receive(self, msg):
585 """On the client's reader thread: this module's frames (replies in order; handlers via the callback)."""
586 if msg.get_string(MODULE) != self.name:
587 return False
588 oid = msg.get_string("PsyOpID")
589 if oid is not None and msg.get_int("PsyOpReply") == 1:
590 # an attach reply comes before the session's first (or replayed) trigger: reset the sequence here
591 if msg.get_string("PsyOp") == "attach" and msg.get_string("PsyStatus") == "ok" and msg.get_int("Resumed", 0) != 1:
592 self.last_seq = 0
593 with self._lock:
594 op = self._pending.get(oid)
595 if op is not None and msg.has("PsyStatus"):
596 del self._pending[oid]
597 if op is not None:
598 if msg.has("PsyStatus"):
599 op.reply = msg
600 op.done.set()
601 else:
602 op.frames.append(msg)
603 return True
604 op = msg.get_string("PsyOp")
605 if op == "dropped":
606 n, f, why = msg.get_int("Count", 0), msg.get_int("FromSeq", 0), msg.get_string("Reason", "")
607 self.dropped_reported += n
608 hs = list(self._dropped_h)
609 if hs:
610 self.client._run_callback(lambda: [h(n, f, why) for h in hs])
611 return True
612 if op == "parameter":
613 name, value = msg.get_string("Name"), msg.get_string("Value", "")
614 if name:
615 self.parameters[name] = value
616 hs = list(self._param_h)
617 if hs:
618 self.client._run_callback(lambda: [h(name, value) for h in hs])
619 return True
620 if op in ("stop", "start", "detached"):
621 reason = msg.get_string("Reason", "")
622 if op == "stop":
623 self.state, handlers = STOPPED, list(self._stop)
624 elif op == "start":
625 self.state, handlers = ATTACHED, list(self._start)
626 else:
627 had = self.session is not None
628 self.state, self.session, handlers = DETACHED, None, list(self._detached)
629 # a lease that ran out while this process lives (a network outage): attach again
630 if reason == "lease" and had and self.auto_reattach and not self._closed:
631 self._reattach_later("lease")
632 if handlers:
633 self.client._run_callback(lambda: [h(reason) for h in handlers])
634 return True
635 trigger = msg.get_string(TRIGGER)
636 if trigger is None:
637 return True
638 seq = msg.get_int("PsySeq")
639 if seq is not None:
640 self.last_seq = seq
641 calls = list(self._handlers.get(trigger, ())) + list(self._any)
642 if not calls:
643 with self._pull_ready:
644 self._pull.append(msg)
645 self._pull_ready.notify()
646 return True
647 self.client._run_callback(lambda: [h(msg) for h in calls])
648 return True
_request(self, post, msg, timeout=None)
declare_post(self, name, type, to=None, ttl_ms=0, guaranteed=True)
retrieve_from(self, source, type=None, max_count=0, max_age_ms=0, from_=None, to=None, key=None, key_type=None, start=None, end=None, timeout=None)
_request_op(self, post, msg, timeout=None)
post_confirmed(self, post, msg=None, timeout=None)
attach(cls, client, name, auth=None, timeout=5.0)
declare_retrieve(self, name, source, type=None, max_count=0, max_age_ms=0)
query_catalog(self, source, msg=None, timeout=None)
query(self, query, msg=None, timeout=None)
retrieve(self, retrieve, max_count=0, max_age_ms=0, timeout=None)
__init__(self, client, name, auth, timeout)
filter(self, op, key, value=None)
_proof(api_key, module, device, nonce)