1"""Remote modules (Psyclone 2.3.2+): this process *is* a module of a running Psyclone system.
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
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())
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
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::
28 ext = RemoteModule.attach(psy, "Ext.Logger")
29 ext.subscribe(Trigger("All", "Mimir.*").max_age(1000))
30 ext.declare_post("Note", "Ext.Logger.Note")
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).
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).
48from collections
import deque
50from .datamessage
import DataMessage
55__all__ = [
"RemoteModule",
"RemoteModuleError",
"Auth",
"Trigger",
"ATTACHED",
"STOPPED",
"DETACHED"]
57ATTACHED, STOPPED, DETACHED =
"attached",
"stopped",
"detached"
61 """The host refused an operation or did not answer. ``status`` is its PsyStatus (denied, unknown, busy,
62 invalid, timeout, failed, unsupported, incomplete)."""
65 super().
__init__(
"%s: %s" % (status, message))
70 """How the process proves it may attach (the host's ``<modules auth=...>``)."""
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)
85 """The host's shared ``<modules auth="token" token="...">``."""
86 return cls(
"token", token)
90 """``<modules auth="none">``: accepted only from the host's own machine."""
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()
102 """XML attribute value escaping for the fragments sent to the host."""
103 return (str(s).replace(
"&",
"&").replace(
"<",
"<").replace(
">",
">")
104 .replace(
'"',
""").replace(
"'",
"'"))
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)``."""
116 self.
_attrs = [(a, b)
for a, b
in self.
_attrs if a != k] + [(k, str(v))]
120 return self.
_set(
"from", component)
122 def to(self, component):
123 return self.
_set(
"to", component)
126 return self.
_set(
"tag", tag)
129 return self.
_set(
"maxage", int(ms))
132 return self.
_set(
"delay", int(ms))
135 """Also fire every ``ms`` milliseconds (an interval trigger; at least 10 ms)."""
136 return self.
_set(
"interval", int(ms))
139 self.
_filters.append((op, key, value))
143 return self.
filter(
"equals", key, value)
146 return self.
filter(
"notequals", key, value)
149 return self.
filter(
"greaterthan", key, value)
152 return self.
filter(
"lessthan", key, value)
155 return self.
filter(
"haskey", key)
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)
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>"
171 return [x.strip()
for x
in (s
or "").split(
",")
if x.strip()]
182 """One declared remote module, attached through ``client`` (one connection may carry several modules).
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.
219 self.
_prefix =
"m%x-" % int.from_bytes(os.urandom(6),
"little")
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)
233 if not client.wait_connected(timeout):
237 client._modules.remove(m._receive)
243 device = self.
client.device
or ""
244 m =
DataMessage().set_string(
"PsyOp",
"attach").set_string(MODULE, self.
name)
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":
251 nonce = hello.get_string(
"PsyNonce")
255 m.set_string(
"PsyAuthKey", key_id).set_string(
"PsyAuthNonce", nonce).set_string(
"PsyAuthProof", proof)
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")
264 if r.get_int(
"Resumed", 0) == 1:
277 by[entry] = by.get(entry,
"") + xml
278 for entry, xml
in by.items():
279 d.set_string(entry, xml)
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"):
292 self.
dynamic = r.get_int(
"Dynamic") == 1
293 if r.has(
"Changeable"):
294 self.
changeable = r.get_int(
"Changeable") == 1
297 for line
in (s
or "").split(
"\n"):
298 k, sep, v = line.partition(
"=")
318 except RemoteModuleError
as e:
319 if e.status
in (
"denied",
"unknown",
"busy"):
323 delay = min(delay * 2, 5.0)
327 threading.Thread(target=run, name=
"psyclone-module-%s-%s" % (self.
name, why), daemon=
True).start()
331 """Call handler(msg) for every message the module's trigger ``trigger`` delivers."""
332 self.
_handlers.setdefault(trigger, []).append(handler)
336 """Call handler(msg) for every trigger message of this module (after the named handlers)."""
337 self.
_any.append(handler)
341 """handler(reason): PsyProbe stopped the module (or the node shuts down); no triggers until on_start."""
342 self.
_stop.append(handler)
346 self.
_start.append(handler)
350 """handler(reason): the host ended the session (takeover, lease, shutdown)."""
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)."""
361 """handler(name, value): a parameter of the module was changed in PsyProbe."""
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
370 while not self.
_pull:
371 left = end - time.monotonic()
375 m = self.
_pull.popleft()
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."""
387 msg.set_string(MODULE, self.
name).set_string(
"PsySession", s)
391 """post() and wait for the host to confirm it (RemoteModuleError on a refusal or timeout)."""
396 msg.set_string(MODULE, self.
name).set_string(
"PsySession", s)
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)
404 m.set_int(
"MaxCount", max_count)
406 m.set_int(
"MaxAge", max_age_ms)
411 want = op.reply.get_int(
"PsyResultCount", 0)
412 got = sorted(op.frames, key=
lambda f: f.get_int(
"PsyResultIndex", 0))
414 raise RemoteModuleError(
"incomplete",
"retrieve %s: %d of %d results arrived" % (what, len(got), want))
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."""
421 msg.set_string(
"PsyOp",
"query").set_string(MODULE, self.
name).set_string(
"PsyQuery", query)
423 msg.set_string(
"PsySession", self.
session)
424 return self.
_request(MODULE, msg, timeout)
427 """What the host has for this module now (Posts, Triggers, PsyState, Contract; TriggerSpecs when changeable)."""
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)
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 "*")))
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))
453 x +=
' to="%s"' %
_xa(to)
455 x +=
' ttl="%d"' % ttl_ms
457 x +=
' guaranteed="no"'
458 return self.
_declare(name,
"Posts", x +
"/>")
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))
464 x +=
' type="%s"' %
_xa(type)
466 x +=
' maxcount="%d"' % max_count
468 x +=
' maxage="%d"' % max_age_ms
469 return self.
_declare(name,
"Retrieves", x +
"/>")
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)))
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)))
480 """Remove declared posts, retrieves or queries by name."""
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"))
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)):
504 m.set_string(k, str(v))
506 m.set_int(
"MaxCount", max_count)
508 m.set_int(
"MaxAge", max_age_ms)
512 """An ad-hoc catalog query: ``source`` (in <allow query>) gets ``msg``'s entries as the query."""
514 msg.set_string(
"PsyOp",
"query").set_string(MODULE, self.
name).set_string(
"Source", source)
516 msg.set_string(
"PsySession", self.
session)
517 return self.
_request(MODULE, msg, timeout)
520 """Tell the host this process has every trigger up to last_seq (it may trim its resume buffer); optional."""
525 """Leave cleanly: the host marks the module offline (Psyclone.RemoteModule.Offline, Reason=detach)."""
530 except RemoteModuleError:
535 """detach() and stop listening (the client stays open: close it separately)."""
555 m =
DataMessage().set_string(
"PsyOp", op).set_string(MODULE, self.
name)
557 m.set_string(
"PsySession", self.
session)
561 timeout = self.
timeout if timeout
is None else timeout
566 msg.set_string(
"PsyOpID", oid)
571 if not op.done.wait(timeout)
or op.reply
is 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")
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:
588 oid = msg.get_string(
"PsyOpID")
589 if oid
is not None and msg.get_int(
"PsyOpReply") == 1:
591 if msg.get_string(
"PsyOp") ==
"attach" and msg.get_string(
"PsyStatus") ==
"ok" and msg.get_int(
"Resumed", 0) != 1:
595 if op
is not None and msg.has(
"PsyStatus"):
598 if msg.has(
"PsyStatus"):
602 op.frames.append(msg)
604 op = msg.get_string(
"PsyOp")
606 n, f, why = msg.get_int(
"Count", 0), msg.get_int(
"FromSeq", 0), msg.get_string(
"Reason",
"")
610 self.
client._run_callback(
lambda: [h(n, f, why)
for h
in hs])
612 if op ==
"parameter":
613 name, value = msg.get_string(
"Name"), msg.get_string(
"Value",
"")
618 self.
client._run_callback(
lambda: [h(name, value)
for h
in hs])
620 if op
in (
"stop",
"start",
"detached"):
621 reason = msg.get_string(
"Reason",
"")
623 self.
state, handlers = STOPPED, list(self.
_stop)
633 self.
client._run_callback(
lambda: [h(reason)
for h
in handlers])
635 trigger = msg.get_string(TRIGGER)
638 seq = msg.get_int(
"PsySeq")
641 calls = list(self.
_handlers.get(trigger, ())) + list(self.
_any)
644 self.
_pull.append(msg)
647 self.
client._run_callback(
lambda: [h(msg)
for h
in calls])
__init__(self, mode, value="")
__init__(self, status, message)
_request(self, post, msg, timeout=None)
_state_changed(self, up, error)
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)
set_parameter(self, name, value)
declare_parameter(self, name, value)
_request_op(self, post, msg, timeout=None)
unsubscribe(self, *names)
on_dropped(self, handler)
post_confirmed(self, post, msg=None, timeout=None)
subscribe(self, *triggers)
post(self, post, msg=None)
_reattach_later(self, why)
on_trigger(self, trigger, handler)
on_parameter(self, handler)
attach(cls, client, name, auth=None, timeout=5.0)
_declare(self, name, entry, xml)
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)
declare_query(self, name, source)
retrieve(self, retrieve, max_count=0, max_age_ms=0, timeout=None)
on_detached(self, handler)
on_any_trigger(self, handler)
__init__(self, client, name, auth, timeout)
wait_for_new_message(self, timeout)
greater_than(self, key, value)
__init__(self, name, type)
less_than(self, key, value)
not_equal_to(self, key, value)
filter(self, op, key, value=None)
equal_to(self, key, value)
_proof(api_key, module, device, nonce)