pmx-io 9.35.1__tar.gz
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.
- pmx_io-9.35.1/MANIFEST.in +4 -0
- pmx_io-9.35.1/PKG-INFO +12 -0
- pmx_io-9.35.1/boot/pmx_io/__init__.py +106 -0
- pmx_io-9.35.1/boot/pmx_io/__main__.py +6 -0
- pmx_io-9.35.1/boot/pmx_io/_actions.py +310 -0
- pmx_io-9.35.1/boot/pmx_io/_activate.py +208 -0
- pmx_io-9.35.1/boot/pmx_io/_aio.py +188 -0
- pmx_io-9.35.1/boot/pmx_io/_amqp.py +478 -0
- pmx_io-9.35.1/boot/pmx_io/_api.py +509 -0
- pmx_io-9.35.1/boot/pmx_io/_application.py +128 -0
- pmx_io-9.35.1/boot/pmx_io/_batch.py +101 -0
- pmx_io-9.35.1/boot/pmx_io/_callmap.py +338 -0
- pmx_io-9.35.1/boot/pmx_io/_capture.py +290 -0
- pmx_io-9.35.1/boot/pmx_io/_config.py +958 -0
- pmx_io-9.35.1/boot/pmx_io/_container.py +1119 -0
- pmx_io-9.35.1/boot/pmx_io/_core.py +1464 -0
- pmx_io-9.35.1/boot/pmx_io/_db.py +1280 -0
- pmx_io-9.35.1/boot/pmx_io/_dbcomment.py +196 -0
- pmx_io-9.35.1/boot/pmx_io/_defaults.py +314 -0
- pmx_io-9.35.1/boot/pmx_io/_envname.py +94 -0
- pmx_io-9.35.1/boot/pmx_io/_errors.py +299 -0
- pmx_io-9.35.1/boot/pmx_io/_http.py +1162 -0
- pmx_io-9.35.1/boot/pmx_io/_hub.py +370 -0
- pmx_io-9.35.1/boot/pmx_io/_importhook.py +128 -0
- pmx_io-9.35.1/boot/pmx_io/_kafka.py +462 -0
- pmx_io-9.35.1/boot/pmx_io/_launcher.py +99 -0
- pmx_io-9.35.1/boot/pmx_io/_listen.py +254 -0
- pmx_io-9.35.1/boot/pmx_io/_logs.py +114 -0
- pmx_io-9.35.1/boot/pmx_io/_metrics.py +636 -0
- pmx_io-9.35.1/boot/pmx_io/_mongo.py +484 -0
- pmx_io-9.35.1/boot/pmx_io/_msg.py +497 -0
- pmx_io-9.35.1/boot/pmx_io/_mysql.py +378 -0
- pmx_io-9.35.1/boot/pmx_io/_nats.py +364 -0
- pmx_io-9.35.1/boot/pmx_io/_otel.py +1760 -0
- pmx_io-9.35.1/boot/pmx_io/_otel_env.py +117 -0
- pmx_io-9.35.1/boot/pmx_io/_procrastinate.py +240 -0
- pmx_io-9.35.1/boot/pmx_io/_prodman.py +1691 -0
- pmx_io-9.35.1/boot/pmx_io/_profiling.py +810 -0
- pmx_io-9.35.1/boot/pmx_io/_redis.py +598 -0
- pmx_io-9.35.1/boot/pmx_io/_rq.py +160 -0
- pmx_io-9.35.1/boot/pmx_io/_signals.py +227 -0
- pmx_io-9.35.1/boot/pmx_io/_sql.py +320 -0
- pmx_io-9.35.1/boot/pmx_io/_standalone.py +295 -0
- pmx_io-9.35.1/boot/pmx_io/_tracing.py +1355 -0
- pmx_io-9.35.1/boot/pmx_io/_transport.py +419 -0
- pmx_io-9.35.1/boot/pmx_io/_util.py +206 -0
- pmx_io-9.35.1/boot/pmx_io/_version.py +4 -0
- pmx_io-9.35.1/boot/pmx_io/_ws.py +634 -0
- pmx_io-9.35.1/boot/pmx_io/py.typed +0 -0
- pmx_io-9.35.1/boot/pmx_io.egg-info/PKG-INFO +12 -0
- pmx_io-9.35.1/boot/pmx_io.egg-info/SOURCES.txt +89 -0
- pmx_io-9.35.1/boot/pmx_io.egg-info/dependency_links.txt +1 -0
- pmx_io-9.35.1/boot/pmx_io.egg-info/entry_points.txt +2 -0
- pmx_io-9.35.1/boot/pmx_io.egg-info/top_level.txt +1 -0
- pmx_io-9.35.1/boot/pmx_io_boot-9.35.1.dist-info/METADATA +4 -0
- pmx_io-9.35.1/boot/pmx_io_boot-9.35.1.dist-info/entry_points.txt +2 -0
- pmx_io-9.35.1/boot/pmx_io_boot.py +27 -0
- pmx_io-9.35.1/boot/sitecustomize.py +175 -0
- pmx_io-9.35.1/pyproject.toml +54 -0
- pmx_io-9.35.1/setup.cfg +4 -0
- pmx_io-9.35.1/setup.py +46 -0
- pmx_io-9.35.1/tests/test_application_unit.py +120 -0
- pmx_io-9.35.1/tests/test_boot.py +209 -0
- pmx_io-9.35.1/tests/test_callmap.py +326 -0
- pmx_io-9.35.1/tests/test_callmap_unit.py +727 -0
- pmx_io-9.35.1/tests/test_db.py +419 -0
- pmx_io-9.35.1/tests/test_db_comment.py +562 -0
- pmx_io-9.35.1/tests/test_envname_unit.py +81 -0
- pmx_io-9.35.1/tests/test_exit.py +96 -0
- pmx_io-9.35.1/tests/test_frameworks.py +464 -0
- pmx_io-9.35.1/tests/test_ipc.py +945 -0
- pmx_io-9.35.1/tests/test_itg_amqp.py +250 -0
- pmx_io-9.35.1/tests/test_itg_db.py +589 -0
- pmx_io-9.35.1/tests/test_itg_kafka.py +192 -0
- pmx_io-9.35.1/tests/test_itg_misc.py +257 -0
- pmx_io-9.35.1/tests/test_itg_nats.py +215 -0
- pmx_io-9.35.1/tests/test_itg_pgqueue.py +108 -0
- pmx_io-9.35.1/tests/test_itg_redis.py +349 -0
- pmx_io-9.35.1/tests/test_otel.py +825 -0
- pmx_io-9.35.1/tests/test_otel_e2e.py +484 -0
- pmx_io-9.35.1/tests/test_otel_unit.py +1248 -0
- pmx_io-9.35.1/tests/test_standalone.py +1378 -0
- pmx_io-9.35.1/tests/test_standalone_unit.py +1409 -0
- pmx_io-9.35.1/tests/test_startup.py +237 -0
- pmx_io-9.35.1/tests/test_tracing.py +674 -0
- pmx_io-9.35.1/tests/test_tracing_control.py +220 -0
- pmx_io-9.35.1/tests/test_tracing_unit.py +733 -0
- pmx_io-9.35.1/tests/test_unit.py +509 -0
- pmx_io-9.35.1/tests/test_v94.py +558 -0
- pmx_io-9.35.1/tests/test_v94_unit.py +660 -0
- pmx_io-9.35.1/tests/test_wheel.py +107 -0
pmx_io-9.35.1/PKG-INFO
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pmx-io
|
|
3
|
+
Version: 9.35.1
|
|
4
|
+
Summary: pmx in-process instrumentation for Python apps (metrics, actions, exceptions, profiling, tracing)
|
|
5
|
+
Author: Mike Warriner
|
|
6
|
+
License: Proprietary
|
|
7
|
+
Classifier: License :: Other/Proprietary License
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
|
+
Classifier: Operating System :: POSIX
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Python: >=3.8
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mike Warriner. All rights reserved. Proprietary — see LICENSE.
|
|
2
|
+
"""pmx-io — in-process instrumentation for Python apps run by pmx (specs/80 Part C).
|
|
3
|
+
|
|
4
|
+
The module object is the API (a process-wide singleton). Under pmx it is activated by the
|
|
5
|
+
daemon's ``sitecustomize`` before the app starts; outside pmx every function works and does
|
|
6
|
+
nothing externally (metrics still compute locally; actions are registered but never triggered).
|
|
7
|
+
|
|
8
|
+
Example::
|
|
9
|
+
|
|
10
|
+
import pmx_io
|
|
11
|
+
|
|
12
|
+
jobs = pmx_io.counter("Jobs")
|
|
13
|
+
jobs.inc()
|
|
14
|
+
|
|
15
|
+
@pmx_io.action("ping")
|
|
16
|
+
def ping():
|
|
17
|
+
return {"pong": True}
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from ._api import (
|
|
21
|
+
action,
|
|
22
|
+
baggage,
|
|
23
|
+
consumer_span,
|
|
24
|
+
counter,
|
|
25
|
+
destroy,
|
|
26
|
+
emit,
|
|
27
|
+
extract,
|
|
28
|
+
gauge,
|
|
29
|
+
get_baggage,
|
|
30
|
+
get_config,
|
|
31
|
+
get_tracer,
|
|
32
|
+
histogram,
|
|
33
|
+
init,
|
|
34
|
+
inject,
|
|
35
|
+
is_active,
|
|
36
|
+
listen_fds,
|
|
37
|
+
meter,
|
|
38
|
+
metric,
|
|
39
|
+
metrics,
|
|
40
|
+
notify_error,
|
|
41
|
+
on_exit,
|
|
42
|
+
on_message,
|
|
43
|
+
ready,
|
|
44
|
+
scoped_action,
|
|
45
|
+
send,
|
|
46
|
+
structlog_processor,
|
|
47
|
+
trace_context,
|
|
48
|
+
wrap,
|
|
49
|
+
)
|
|
50
|
+
from ._metrics import Counter, Gauge, Histogram, Meter
|
|
51
|
+
from ._version import __version__
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def __getattr__(name: str): # type: ignore[no-untyped-def] # PEP 562
|
|
55
|
+
# The tracer module loads on first use (start-up cost, PYI-105).
|
|
56
|
+
if name in ("NEW_TRACE", "SpanContext"):
|
|
57
|
+
from . import _tracing
|
|
58
|
+
|
|
59
|
+
return getattr(_tracing, name)
|
|
60
|
+
# TraceContextFilter subclasses logging.Filter: built on first access so that importing
|
|
61
|
+
# pmx_io does not import logging (startup cost, PYI-102).
|
|
62
|
+
if name == "TraceContextFilter":
|
|
63
|
+
from ._logs import trace_context_filter_class
|
|
64
|
+
|
|
65
|
+
return trace_context_filter_class()
|
|
66
|
+
raise AttributeError("module 'pmx_io' has no attribute %r" % (name,))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
__all__ = [
|
|
70
|
+
"__version__",
|
|
71
|
+
"init",
|
|
72
|
+
"destroy",
|
|
73
|
+
"get_config",
|
|
74
|
+
"metric",
|
|
75
|
+
"gauge",
|
|
76
|
+
"counter",
|
|
77
|
+
"meter",
|
|
78
|
+
"histogram",
|
|
79
|
+
"metrics",
|
|
80
|
+
"action",
|
|
81
|
+
"scoped_action",
|
|
82
|
+
"notify_error",
|
|
83
|
+
"emit",
|
|
84
|
+
"on_exit",
|
|
85
|
+
"ready",
|
|
86
|
+
"send",
|
|
87
|
+
"on_message",
|
|
88
|
+
"get_tracer",
|
|
89
|
+
"SpanContext",
|
|
90
|
+
"NEW_TRACE",
|
|
91
|
+
"consumer_span",
|
|
92
|
+
"inject",
|
|
93
|
+
"extract",
|
|
94
|
+
"baggage",
|
|
95
|
+
"get_baggage",
|
|
96
|
+
"wrap",
|
|
97
|
+
"trace_context",
|
|
98
|
+
"TraceContextFilter",
|
|
99
|
+
"structlog_processor",
|
|
100
|
+
"listen_fds",
|
|
101
|
+
"is_active",
|
|
102
|
+
"Counter",
|
|
103
|
+
"Gauge",
|
|
104
|
+
"Histogram",
|
|
105
|
+
"Meter",
|
|
106
|
+
]
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mike Warriner. All rights reserved. Proprietary — see LICENSE.
|
|
2
|
+
"""Actions (80 C.6.1, A.8.1, A.8.2, 40 §8.3)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import collections
|
|
7
|
+
import threading
|
|
8
|
+
|
|
9
|
+
TYPE_CHECKING = False
|
|
10
|
+
if TYPE_CHECKING: # typing is not imported at run time (startup cost, PYI-102)
|
|
11
|
+
from typing import Any, Callable, Deque, Dict, Optional, Tuple
|
|
12
|
+
|
|
13
|
+
from ._util import debug, now_ms
|
|
14
|
+
|
|
15
|
+
MAX_WORKERS = 4
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def action_type(name: str) -> str:
|
|
19
|
+
return "internal" if name.startswith("km:") or name.startswith("internal:") else "custom"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def positional_params(fn: Callable[..., Any]) -> int:
|
|
23
|
+
"""Declared positional parameter count (VAR_POSITIONAL counts as 2)."""
|
|
24
|
+
import inspect
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
sig = inspect.signature(fn)
|
|
28
|
+
except (TypeError, ValueError):
|
|
29
|
+
return 2
|
|
30
|
+
n = 0
|
|
31
|
+
for p in sig.parameters.values():
|
|
32
|
+
if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD):
|
|
33
|
+
n += 1
|
|
34
|
+
elif p.kind == p.VAR_POSITIONAL:
|
|
35
|
+
return max(n, 2)
|
|
36
|
+
return n
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def is_coroutine_function(fn: Any) -> bool:
|
|
40
|
+
import inspect
|
|
41
|
+
|
|
42
|
+
return inspect.iscoroutinefunction(fn) or inspect.iscoroutinefunction(getattr(fn, "__call__", None))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class WorkerPool:
|
|
46
|
+
"""Up to ``MAX_WORKERS`` daemon threads named ``pmx-io-action-N`` (never the receiver)."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, size: int = MAX_WORKERS) -> None:
|
|
49
|
+
self._size = size
|
|
50
|
+
self._q: Deque[Callable[[], None]] = collections.deque()
|
|
51
|
+
self._cv = threading.Condition(threading.Lock())
|
|
52
|
+
self._threads = 0
|
|
53
|
+
self._idle = 0
|
|
54
|
+
self._next_index = 1
|
|
55
|
+
|
|
56
|
+
def submit(self, fn: Callable[[], None]) -> None:
|
|
57
|
+
with self._cv:
|
|
58
|
+
self._q.append(fn)
|
|
59
|
+
if self._idle == 0 and self._threads < self._size:
|
|
60
|
+
idx = self._next_index
|
|
61
|
+
self._next_index += 1
|
|
62
|
+
self._threads += 1
|
|
63
|
+
t = threading.Thread(target=self._loop, name="pmx-io-action-%d" % idx, daemon=True)
|
|
64
|
+
t.start()
|
|
65
|
+
else:
|
|
66
|
+
self._cv.notify()
|
|
67
|
+
|
|
68
|
+
def _loop(self) -> None:
|
|
69
|
+
while True:
|
|
70
|
+
with self._cv:
|
|
71
|
+
while not self._q:
|
|
72
|
+
self._idle += 1
|
|
73
|
+
self._cv.wait()
|
|
74
|
+
self._idle -= 1
|
|
75
|
+
fn = self._q.popleft()
|
|
76
|
+
try:
|
|
77
|
+
fn()
|
|
78
|
+
except Exception as exc: # pragma: no cover - handlers are wrapped
|
|
79
|
+
debug("axm:actions", "worker error: %r", exc)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class AsyncRunner:
|
|
83
|
+
"""Runs coroutines on the probed main-thread loop if running, else on a private loop
|
|
84
|
+
thread (``pmx-io-asyncio``)."""
|
|
85
|
+
|
|
86
|
+
def __init__(self, main_loop_getter: Callable[[], Any]) -> None:
|
|
87
|
+
self._get_main = main_loop_getter
|
|
88
|
+
self._loop: Any = None
|
|
89
|
+
self._lock = threading.Lock()
|
|
90
|
+
|
|
91
|
+
def _private_loop(self) -> Any:
|
|
92
|
+
import asyncio
|
|
93
|
+
|
|
94
|
+
with self._lock:
|
|
95
|
+
if self._loop is None:
|
|
96
|
+
loop = asyncio.new_event_loop()
|
|
97
|
+
ready = threading.Event()
|
|
98
|
+
|
|
99
|
+
def run() -> None:
|
|
100
|
+
asyncio.set_event_loop(loop)
|
|
101
|
+
ready.set()
|
|
102
|
+
loop.run_forever()
|
|
103
|
+
|
|
104
|
+
threading.Thread(target=run, name="pmx-io-asyncio", daemon=True).start()
|
|
105
|
+
ready.wait(5)
|
|
106
|
+
self._loop = loop
|
|
107
|
+
return self._loop
|
|
108
|
+
|
|
109
|
+
def run(self, coro: Any, done: Callable[[Any, Optional[BaseException]], None]) -> None:
|
|
110
|
+
import asyncio
|
|
111
|
+
|
|
112
|
+
loop = self._get_main()
|
|
113
|
+
if loop is None or not loop.is_running() or loop.is_closed():
|
|
114
|
+
loop = self._private_loop()
|
|
115
|
+
|
|
116
|
+
async def wrapper() -> None:
|
|
117
|
+
try:
|
|
118
|
+
result = await coro
|
|
119
|
+
except BaseException as exc: # noqa: BLE001
|
|
120
|
+
done(None, exc)
|
|
121
|
+
if not isinstance(exc, Exception):
|
|
122
|
+
raise
|
|
123
|
+
return
|
|
124
|
+
done(result, None)
|
|
125
|
+
|
|
126
|
+
asyncio.run_coroutine_threadsafe(wrapper(), loop)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class Action:
|
|
130
|
+
__slots__ = ("name", "handler", "opts", "scoped", "nparams", "arity", "is_coro")
|
|
131
|
+
|
|
132
|
+
def __init__(
|
|
133
|
+
self,
|
|
134
|
+
name: str,
|
|
135
|
+
handler: Callable[..., Any],
|
|
136
|
+
opts: Any = None,
|
|
137
|
+
scoped: bool = False,
|
|
138
|
+
nparams: Optional[int] = None,
|
|
139
|
+
) -> None:
|
|
140
|
+
self.name = name
|
|
141
|
+
self.handler = handler
|
|
142
|
+
self.opts = opts
|
|
143
|
+
self.scoped = scoped
|
|
144
|
+
self.nparams = positional_params(handler) if nparams is None else nparams
|
|
145
|
+
self.arity = 2 if scoped or self.nparams >= 1 else 1
|
|
146
|
+
self.is_coro = False if nparams is not None else is_coroutine_function(handler)
|
|
147
|
+
|
|
148
|
+
def registration(self) -> Dict[str, Any]:
|
|
149
|
+
if self.scoped:
|
|
150
|
+
return {"action_name": self.name, "action_type": "scoped", "arity": 2, "opts": None}
|
|
151
|
+
data: Dict[str, Any] = {"action_name": self.name, "action_type": action_type(self.name), "arity": self.arity}
|
|
152
|
+
if self.opts is not None:
|
|
153
|
+
data["opts"] = self.opts
|
|
154
|
+
return data
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class ScopedStream:
|
|
158
|
+
"""``stream.send/error/end(data)`` → ``axm:scoped_action:stream|error|end`` (A.8.2)."""
|
|
159
|
+
|
|
160
|
+
def __init__(self, send: Callable[[Dict[str, Any]], Any], name: str, uuid: Any) -> None:
|
|
161
|
+
self._send = send
|
|
162
|
+
self._name = name
|
|
163
|
+
self._uuid = uuid
|
|
164
|
+
|
|
165
|
+
def _emit(self, kind: str, data: Any) -> None:
|
|
166
|
+
self._send(
|
|
167
|
+
{
|
|
168
|
+
"type": "axm:scoped_action:%s" % kind,
|
|
169
|
+
"data": {"data": data, "uuid": self._uuid, "action_name": self._name},
|
|
170
|
+
}
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
def send(self, data: Any = None) -> None:
|
|
174
|
+
self._emit("stream", data)
|
|
175
|
+
|
|
176
|
+
def error(self, data: Any = None) -> None:
|
|
177
|
+
self._emit("error", data)
|
|
178
|
+
|
|
179
|
+
def end(self, data: Any = None) -> None:
|
|
180
|
+
self._emit("end", data)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def parse_trigger(msg: Any) -> Optional[Tuple[str, Any, Any, bool]]:
|
|
184
|
+
"""→ (name, opts, uuid, is_object) per 40 §8.3 dispatch rules."""
|
|
185
|
+
if isinstance(msg, str):
|
|
186
|
+
return msg, None, None, False
|
|
187
|
+
if isinstance(msg, dict):
|
|
188
|
+
name = msg.get("msg")
|
|
189
|
+
if not isinstance(name, str):
|
|
190
|
+
name = msg.get("action_name")
|
|
191
|
+
if not isinstance(name, str):
|
|
192
|
+
return None
|
|
193
|
+
return name, msg.get("opts"), msg.get("uuid"), True
|
|
194
|
+
return None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class ActionRegistry:
|
|
198
|
+
def __init__(
|
|
199
|
+
self,
|
|
200
|
+
send: Callable[[Dict[str, Any]], Any],
|
|
201
|
+
report_error: Callable[[BaseException], None],
|
|
202
|
+
main_loop_getter: Callable[[], Any],
|
|
203
|
+
) -> None:
|
|
204
|
+
self._send = send
|
|
205
|
+
self._report = report_error
|
|
206
|
+
self._lock = threading.Lock()
|
|
207
|
+
self.actions: Dict[str, Action] = {}
|
|
208
|
+
self.pool = WorkerPool()
|
|
209
|
+
self.runner = AsyncRunner(main_loop_getter)
|
|
210
|
+
|
|
211
|
+
def register(self, act: Action) -> None:
|
|
212
|
+
with self._lock:
|
|
213
|
+
self.actions[act.name] = act
|
|
214
|
+
self._send({"type": "axm:action", "data": act.registration()})
|
|
215
|
+
|
|
216
|
+
def resend_all(self, exclude_internal: bool = False) -> None:
|
|
217
|
+
with self._lock:
|
|
218
|
+
acts = list(self.actions.values())
|
|
219
|
+
for a in acts:
|
|
220
|
+
if exclude_internal and a.name.startswith("km:"):
|
|
221
|
+
continue
|
|
222
|
+
self._send({"type": "axm:action", "data": a.registration()})
|
|
223
|
+
|
|
224
|
+
def unregister(self, name: str) -> None:
|
|
225
|
+
with self._lock:
|
|
226
|
+
self.actions.pop(name, None)
|
|
227
|
+
|
|
228
|
+
def _reply(self, name: str, data: Any) -> None:
|
|
229
|
+
self._send({"type": "axm:reply", "data": {"at": now_ms(), "action_name": name, "return": data}})
|
|
230
|
+
|
|
231
|
+
def dispatch(self, msg: Any) -> bool:
|
|
232
|
+
parsed = parse_trigger(msg)
|
|
233
|
+
if parsed is None:
|
|
234
|
+
return False
|
|
235
|
+
name, opts, uuid, is_obj = parsed
|
|
236
|
+
with self._lock:
|
|
237
|
+
act = self.actions.get(name)
|
|
238
|
+
if act is None:
|
|
239
|
+
return False # unknown triggers are ignored silently
|
|
240
|
+
if act.scoped:
|
|
241
|
+
if uuid is None:
|
|
242
|
+
return False
|
|
243
|
+
params = opts if opts else {}
|
|
244
|
+
stream = ScopedStream(self._send, name, uuid)
|
|
245
|
+
self.pool.submit(lambda: self._invoke(act, (params, stream), scoped_stream=stream))
|
|
246
|
+
return True
|
|
247
|
+
params = opts if opts is not None else {}
|
|
248
|
+
self.pool.submit(lambda: self._run_action(act, params))
|
|
249
|
+
return True
|
|
250
|
+
|
|
251
|
+
def _error_reply(self, act: Action, exc: BaseException) -> None:
|
|
252
|
+
try:
|
|
253
|
+
self._report(exc)
|
|
254
|
+
except Exception:
|
|
255
|
+
pass
|
|
256
|
+
self._reply(act.name, {"success": False, "err": "%s: %s" % (type(exc).__name__, exc)})
|
|
257
|
+
|
|
258
|
+
def _run_action(self, act: Action, params: Any) -> None:
|
|
259
|
+
reply = lambda data=None: self._reply(act.name, data) # noqa: E731
|
|
260
|
+
if act.nparams == 0:
|
|
261
|
+
args: Tuple[Any, ...] = ()
|
|
262
|
+
elif act.nparams == 1:
|
|
263
|
+
args = (params,)
|
|
264
|
+
else:
|
|
265
|
+
args = (params, reply)
|
|
266
|
+
explicit_reply = act.nparams >= 2
|
|
267
|
+
self._invoke(act, args, explicit_reply=explicit_reply)
|
|
268
|
+
|
|
269
|
+
def _invoke(
|
|
270
|
+
self, act: Action, args: Tuple[Any, ...], explicit_reply: bool = False, scoped_stream: Any = None
|
|
271
|
+
) -> None:
|
|
272
|
+
def finish(result: Any, exc: Optional[BaseException]) -> None:
|
|
273
|
+
if exc is not None:
|
|
274
|
+
if isinstance(exc, Exception):
|
|
275
|
+
if scoped_stream is not None:
|
|
276
|
+
try:
|
|
277
|
+
self._report(exc)
|
|
278
|
+
except Exception:
|
|
279
|
+
pass
|
|
280
|
+
scoped_stream.error("%s: %s" % (type(exc).__name__, exc))
|
|
281
|
+
else:
|
|
282
|
+
self._error_reply(act, exc)
|
|
283
|
+
return
|
|
284
|
+
if scoped_stream is None and not explicit_reply:
|
|
285
|
+
self._reply(act.name, result)
|
|
286
|
+
|
|
287
|
+
try:
|
|
288
|
+
result = act.handler(*args)
|
|
289
|
+
except Exception as exc:
|
|
290
|
+
finish(None, exc)
|
|
291
|
+
return
|
|
292
|
+
if _is_awaitable(result):
|
|
293
|
+
try:
|
|
294
|
+
self.runner.run(_as_coro(result), finish)
|
|
295
|
+
except Exception as exc:
|
|
296
|
+
finish(None, exc)
|
|
297
|
+
return
|
|
298
|
+
finish(result, None)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _is_awaitable(obj: Any) -> bool:
|
|
302
|
+
if obj is None or isinstance(obj, (str, bytes, int, float, dict, list, tuple, bool)):
|
|
303
|
+
return False
|
|
304
|
+
import inspect
|
|
305
|
+
|
|
306
|
+
return inspect.isawaitable(obj)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
async def _as_coro(awaitable: Any) -> Any:
|
|
310
|
+
return await awaitable
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mike Warriner. All rights reserved. Proprietary — see LICENSE.
|
|
2
|
+
"""Activation under pmx (80 PYI-020, PYI-013), called by the boot ``sitecustomize``."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
TYPE_CHECKING = False
|
|
10
|
+
if TYPE_CHECKING: # typing is not imported at run time (startup cost, PYI-102)
|
|
11
|
+
from typing import MutableMapping, Optional
|
|
12
|
+
|
|
13
|
+
from ._core import CORE
|
|
14
|
+
from ._transport import fd_is_socket, socket_from_fd
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _same_dir(a: str, b: str) -> bool:
|
|
18
|
+
try:
|
|
19
|
+
return os.path.realpath(os.path.abspath(a or os.curdir)) == os.path.realpath(b)
|
|
20
|
+
except Exception:
|
|
21
|
+
return False
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _strip_pythonpath(boot_dir: Optional[str], env: MutableMapping[str, str]) -> None:
|
|
25
|
+
if not boot_dir:
|
|
26
|
+
return
|
|
27
|
+
pp = env.get("PYTHONPATH")
|
|
28
|
+
if pp is None:
|
|
29
|
+
return
|
|
30
|
+
parts = [p for p in pp.split(os.pathsep) if p and not _same_dir(p, boot_dir)]
|
|
31
|
+
if parts:
|
|
32
|
+
env["PYTHONPATH"] = os.pathsep.join(parts)
|
|
33
|
+
else:
|
|
34
|
+
del env["PYTHONPATH"]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def ensure_on_pythonpath(boot_dir: Optional[str], env: MutableMapping[str, str]) -> None:
|
|
38
|
+
"""Put ``boot_dir`` first on PYTHONPATH unless it is already there (C.16, PYI-153)."""
|
|
39
|
+
if not boot_dir:
|
|
40
|
+
return
|
|
41
|
+
parts = [p for p in (env.get("PYTHONPATH") or "").split(os.pathsep) if p]
|
|
42
|
+
if any(_same_dir(p, boot_dir) for p in parts):
|
|
43
|
+
return
|
|
44
|
+
env["PYTHONPATH"] = os.pathsep.join([boot_dir] + parts)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def conditions_hold(env: Optional[MutableMapping[str, str]] = None) -> Optional[int]:
|
|
48
|
+
"""PYI-020: return the channel fd when pmx-io must activate, else None."""
|
|
49
|
+
if env is None:
|
|
50
|
+
env = os.environ
|
|
51
|
+
if sys.version_info < (3, 8):
|
|
52
|
+
return None
|
|
53
|
+
if env.get("PMX_IO") != "1":
|
|
54
|
+
return None
|
|
55
|
+
if env.get("pmx") == "false" or env.get("automation") == "false":
|
|
56
|
+
return None
|
|
57
|
+
raw = env.get("PMX_IPC_FD")
|
|
58
|
+
if not raw:
|
|
59
|
+
return None
|
|
60
|
+
try:
|
|
61
|
+
fd = int(raw)
|
|
62
|
+
except ValueError:
|
|
63
|
+
return None
|
|
64
|
+
if fd < 0 or not fd_is_socket(fd):
|
|
65
|
+
return None
|
|
66
|
+
if CORE.role is not None:
|
|
67
|
+
return None
|
|
68
|
+
return fd
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def daemon_relay_wanted(env: Optional[MutableMapping[str, str]] = None) -> bool:
|
|
72
|
+
"""80 PYI-172: a descendant of a daemon-mode root (hub variables, no ``PMX_IO``, not
|
|
73
|
+
standalone)."""
|
|
74
|
+
if env is None:
|
|
75
|
+
env = os.environ
|
|
76
|
+
return bool(
|
|
77
|
+
sys.version_info >= (3, 8)
|
|
78
|
+
and not env.get("PMX_IO")
|
|
79
|
+
and env.get("PMX_IO_HUB")
|
|
80
|
+
and env.get("PMX_IO_HUB_TOKEN")
|
|
81
|
+
and not env.get("PMX_IO_STANDALONE")
|
|
82
|
+
and env.get("pmx") != "false"
|
|
83
|
+
and env.get("automation") != "false"
|
|
84
|
+
and CORE.role is None
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def activate_daemon_relay() -> bool:
|
|
89
|
+
"""Connect to the root's hub and relay through it like a forked child (PYI-172); stay inert
|
|
90
|
+
and silent when the hub cannot be reached."""
|
|
91
|
+
from . import _hub
|
|
92
|
+
from ._util import debug
|
|
93
|
+
|
|
94
|
+
env = os.environ
|
|
95
|
+
sock = _hub.connect(env.get("PMX_IO_HUB") or "", env.get("PMX_IO_HUB_TOKEN") or "", ns="axm:relay")
|
|
96
|
+
if sock is None:
|
|
97
|
+
debug("axm:relay", "root pid %s not reachable, not instrumented", env.get("PMX_IO_ROOT_PID"))
|
|
98
|
+
return False
|
|
99
|
+
CORE.activate_relay(sock, None, standalone=False)
|
|
100
|
+
debug("axm:relay", "relay %d connected to the hub", os.getpid())
|
|
101
|
+
return True
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
OTEL_LAUNCHER = "opentelemetry-instrument"
|
|
105
|
+
OTEL_HOOK_MISSING = '[pmx-io] not active under opentelemetry-instrument %s; add "import pmx_io" to the app or upgrade\n'
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def otel_launcher(argv: Optional[list] = None) -> bool:
|
|
109
|
+
"""85 OTX-040: this interpreter runs OpenTelemetry's launcher, which ``exec``s the app with
|
|
110
|
+
its own ``sitecustomize`` first on ``PYTHONPATH``."""
|
|
111
|
+
if argv is None:
|
|
112
|
+
argv = getattr(sys, "argv", None)
|
|
113
|
+
if not argv or not isinstance(argv[0], str):
|
|
114
|
+
return False
|
|
115
|
+
return os.path.basename(argv[0]) == OTEL_LAUNCHER
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def otel_hook_support(paths: Optional[list] = None) -> "tuple":
|
|
119
|
+
"""→ (instrumentation version or 'unknown', whether its auto-instrumentation calls the
|
|
120
|
+
``opentelemetry_pre_instrument`` entry points). Reads the installed sources without
|
|
121
|
+
importing them."""
|
|
122
|
+
version = "unknown"
|
|
123
|
+
supported = False
|
|
124
|
+
for p in sys.path if paths is None else paths:
|
|
125
|
+
base = os.path.join(p or os.curdir, "opentelemetry", "instrumentation")
|
|
126
|
+
auto = os.path.join(base, "auto_instrumentation")
|
|
127
|
+
if not os.path.isdir(auto):
|
|
128
|
+
continue
|
|
129
|
+
try:
|
|
130
|
+
with open(os.path.join(base, "version.py"), encoding="utf-8") as f:
|
|
131
|
+
for line in f:
|
|
132
|
+
if line.startswith("__version__"):
|
|
133
|
+
version = line.split("=", 1)[1].strip().strip("\"'")
|
|
134
|
+
break
|
|
135
|
+
except OSError:
|
|
136
|
+
pass
|
|
137
|
+
for name in ("_load.py", "__init__.py", "sitecustomize.py"):
|
|
138
|
+
try:
|
|
139
|
+
with open(os.path.join(auto, name), encoding="utf-8") as f:
|
|
140
|
+
if "opentelemetry_pre_instrument" in f.read():
|
|
141
|
+
supported = True
|
|
142
|
+
break
|
|
143
|
+
except OSError:
|
|
144
|
+
continue
|
|
145
|
+
break
|
|
146
|
+
return version, supported
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _defer_to_otel_hook() -> bool:
|
|
150
|
+
"""In the launcher itself nothing activates and the environment stays intact (the channel
|
|
151
|
+
fd stays inheritable): the exec'd app activates through the entry point (OTX-040)."""
|
|
152
|
+
version, supported = otel_hook_support()
|
|
153
|
+
if not supported:
|
|
154
|
+
try:
|
|
155
|
+
sys.stderr.write(OTEL_HOOK_MISSING % version)
|
|
156
|
+
except Exception:
|
|
157
|
+
pass
|
|
158
|
+
return False
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def activate_from_otel_hook(boot_dir: Optional[str]) -> bool:
|
|
162
|
+
"""``opentelemetry_pre_instrument`` entry point (``pmx_io_boot.activate``, OTX-040):
|
|
163
|
+
activate as the bootstrap would; idempotent."""
|
|
164
|
+
if CORE.role is not None:
|
|
165
|
+
return True
|
|
166
|
+
ok = activate_from_boot(boot_dir, _hook=True)
|
|
167
|
+
if boot_dir: # as the bootstrap does once it has run (PYI-012)
|
|
168
|
+
sys.path[:] = [p for p in sys.path if not _same_dir(p, boot_dir)]
|
|
169
|
+
return ok
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def activate_from_boot(boot_dir: Optional[str] = None, _hook: bool = False) -> bool:
|
|
173
|
+
"""Activate pmx-io in this interpreter (the *root* process, PYI-021)."""
|
|
174
|
+
env = os.environ
|
|
175
|
+
if not _hook and otel_launcher():
|
|
176
|
+
return _defer_to_otel_hook()
|
|
177
|
+
fd = conditions_hold(env)
|
|
178
|
+
if fd is None:
|
|
179
|
+
# 80 PYI-150 (b): standalone mode through the bootstrap (set by ``pmx-io run``, or
|
|
180
|
+
# inherited from a standalone root by its descendants)
|
|
181
|
+
if env.get("PMX_IO_STANDALONE") == "1" and CORE.role is None:
|
|
182
|
+
from . import _standalone
|
|
183
|
+
|
|
184
|
+
return _standalone.activate("boot", None, None)
|
|
185
|
+
if daemon_relay_wanted(env):
|
|
186
|
+
return activate_daemon_relay()
|
|
187
|
+
return False
|
|
188
|
+
# PYI-013: the daemon channel is never inherited; with ``children`` on (C.16) descendants
|
|
189
|
+
# report through this process's hub instead (the boot directory stays on PYTHONPATH).
|
|
190
|
+
raw_fd = env.pop("PMX_IPC_FD", None)
|
|
191
|
+
env.pop("PMX_IO", None)
|
|
192
|
+
caps = [c.strip() for c in (env.pop("PMX_IO_CAPS", None) or "").split(",") if c.strip()] # INJ-024
|
|
193
|
+
if env.get("NODE_CHANNEL_FD") == raw_fd:
|
|
194
|
+
env.pop("NODE_CHANNEL_FD", None)
|
|
195
|
+
env.pop("NODE_CHANNEL_SERIALIZATION_MODE", None)
|
|
196
|
+
for k in ("PMX_IO_HUB", "PMX_IO_HUB_TOKEN", "PMX_IO_ROOT_PID"):
|
|
197
|
+
env.pop(k, None) # never another tree's hub
|
|
198
|
+
os.set_inheritable(fd, False)
|
|
199
|
+
sock = socket_from_fd(fd)
|
|
200
|
+
CORE.activate_root(sock, caps, boot_dir) # strips PYTHONPATH or starts the hub (PYI-171)
|
|
201
|
+
return True
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def after_site_chain() -> None:
|
|
205
|
+
"""Called by the boot ``sitecustomize`` after it chained to the next one (PYI-012): keep
|
|
206
|
+
pmx-io's exception hooks in front of any the chained module installed."""
|
|
207
|
+
if CORE.initialised:
|
|
208
|
+
CORE.hooks.reassert()
|