flowhawk-sdk 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flowhawk_sdk/__init__.py +220 -0
- flowhawk_sdk/app_metrics.py +98 -0
- flowhawk_sdk/config.py +216 -0
- flowhawk_sdk/control.py +146 -0
- flowhawk_sdk/llm.py +145 -0
- flowhawk_sdk/logger.py +147 -0
- flowhawk_sdk/match.py +111 -0
- flowhawk_sdk/runtime.py +75 -0
- flowhawk_sdk/sentry.py +49 -0
- flowhawk_sdk/sqlcomment.py +104 -0
- flowhawk_sdk/state.py +87 -0
- flowhawk_sdk/tagging.py +226 -0
- flowhawk_sdk/tail.py +235 -0
- flowhawk_sdk-0.1.0.dist-info/METADATA +74 -0
- flowhawk_sdk-0.1.0.dist-info/RECORD +17 -0
- flowhawk_sdk-0.1.0.dist-info/WHEEL +4 -0
- flowhawk_sdk-0.1.0.dist-info/licenses/LICENSE +201 -0
flowhawk_sdk/__init__.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
# flowhawk-sdk: the OpenTelemetry Python SDK plus business-flow tagging and remote-controlled
|
|
2
|
+
# collection; the Python twin of @flowhawk/sdk-node. Usage, before the web framework is imported:
|
|
3
|
+
# import flowhawk_sdk; flowhawk_sdk.init(service="recommendations")
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import atexit
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import socket
|
|
10
|
+
import threading
|
|
11
|
+
from contextlib import contextmanager
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import Any, Iterator, Optional
|
|
14
|
+
|
|
15
|
+
from opentelemetry import _logs, metrics, trace
|
|
16
|
+
from opentelemetry.context import Context
|
|
17
|
+
from opentelemetry.propagate import set_global_textmap
|
|
18
|
+
from opentelemetry.propagators.composite import CompositePropagator
|
|
19
|
+
from opentelemetry.sdk.resources import Resource
|
|
20
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
21
|
+
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
|
22
|
+
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
|
23
|
+
|
|
24
|
+
from .control import SDK_ID, ControlClient, auth_headers
|
|
25
|
+
from .llm import LlmCall, LlmResult, trace_llm
|
|
26
|
+
from .logger import _set_logger, logger, logging_handler
|
|
27
|
+
from .app_metrics import count, gauge, histogram, up_down
|
|
28
|
+
from .runtime import start_runtime_metrics
|
|
29
|
+
from .state import get_applied
|
|
30
|
+
from .tagging import ENTRY, FLOW, STEP, BusinessBaggagePropagator, FlowTagger, set_code_skip
|
|
31
|
+
from .tail import TailSampler
|
|
32
|
+
from .sentry import SentryTracePropagator
|
|
33
|
+
from .sqlcomment import instrument_psycopg, instrument_sqlalchemy, set_sql_comments, sql_comment, tag_sql
|
|
34
|
+
|
|
35
|
+
__all__ = ["init", "shutdown", "current_config", "with_step", "logger", "trace_llm", "LlmCall", "LlmResult", "SDK_ID", "count", "histogram", "up_down", "gauge", "tag_sql", "sql_comment"]
|
|
36
|
+
|
|
37
|
+
# Fine buckets so the platform's p95 from this histogram is close to the true one (same as the Node SDK).
|
|
38
|
+
STEP_BUCKETS = [2, 5, 10, 15, 25, 40, 60, 80, 100, 150, 200, 300, 400, 500, 750, 1000, 1500, 2000, 3000, 4000, 5000, 7500, 10000, 20000, 30000, 60000, 120000, 300000, 600000, 1800000, 3600000, 7200000, 14400000, 43200000, 86400000]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class _Instruments:
|
|
43
|
+
duration: Any
|
|
44
|
+
requests: Any
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
_lock = threading.Lock()
|
|
48
|
+
_started = False
|
|
49
|
+
_parts: dict[str, Any] = {}
|
|
50
|
+
_instruments: Optional[_Instruments] = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _delta_temporality() -> dict:
|
|
54
|
+
# Delta temporality: each export carries only its interval, so the platform's rollups can sum
|
|
55
|
+
# rows (what OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta selects).
|
|
56
|
+
from opentelemetry.sdk.metrics import Counter, Histogram, ObservableCounter, ObservableGauge, ObservableUpDownCounter, UpDownCounter
|
|
57
|
+
from opentelemetry.sdk.metrics.export import AggregationTemporality as T
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
Counter: T.DELTA,
|
|
61
|
+
Histogram: T.DELTA,
|
|
62
|
+
ObservableCounter: T.DELTA,
|
|
63
|
+
UpDownCounter: T.CUMULATIVE,
|
|
64
|
+
ObservableUpDownCounter: T.CUMULATIVE,
|
|
65
|
+
ObservableGauge: T.CUMULATIVE,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _make_instruments(meter: Any) -> _Instruments:
|
|
70
|
+
return _Instruments(
|
|
71
|
+
duration=meter.create_histogram(
|
|
72
|
+
"business.step.duration",
|
|
73
|
+
unit="ms",
|
|
74
|
+
description="Duration of business step entries",
|
|
75
|
+
explicit_bucket_boundaries_advisory=STEP_BUCKETS,
|
|
76
|
+
),
|
|
77
|
+
requests=meter.create_counter("business.step.requests", description="Business step entries"),
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def init(
|
|
82
|
+
service: str,
|
|
83
|
+
version: Optional[str] = None,
|
|
84
|
+
environment: Optional[str] = None,
|
|
85
|
+
endpoint: Optional[str] = None,
|
|
86
|
+
control_url: Optional[str] = None,
|
|
87
|
+
instrument: bool = True,
|
|
88
|
+
api_key: Optional[str] = None,
|
|
89
|
+
code_skip: Optional[list[str]] = None,
|
|
90
|
+
sql_comments: Optional[bool] = None,
|
|
91
|
+
) -> None:
|
|
92
|
+
"""Starts tracing, metrics, logs and remote control. Call once, before importing Flask.
|
|
93
|
+
|
|
94
|
+
code_skip: path fragments of your own query helpers, skipped when recording where a query is
|
|
95
|
+
called; default FLOWHAWK_CODE_SKIP (comma separated).
|
|
96
|
+
sql_comments: SQL comment tags (flow, step, service, and traceparent on sampled traces) on queries
|
|
97
|
+
sent through psycopg 3 or SQLAlchemy, and from tag_sql(); default on, FLOWHAWK_SQL_COMMENTS=off
|
|
98
|
+
turns them off.
|
|
99
|
+
"""
|
|
100
|
+
global _started, _instruments
|
|
101
|
+
with _lock:
|
|
102
|
+
if _started:
|
|
103
|
+
return
|
|
104
|
+
_started = True
|
|
105
|
+
set_code_skip(code_skip if code_skip is not None else os.environ.get("FLOWHAWK_CODE_SKIP", "").split(","))
|
|
106
|
+
|
|
107
|
+
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
|
108
|
+
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
|
109
|
+
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
|
110
|
+
from opentelemetry.sdk._logs import LoggerProvider
|
|
111
|
+
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
|
112
|
+
from opentelemetry.sdk.metrics import MeterProvider
|
|
113
|
+
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
|
114
|
+
|
|
115
|
+
version = version or os.environ.get("FLOWHAWK_SERVICE_VERSION") or "0.0.0"
|
|
116
|
+
environment = environment or os.environ.get("FLOWHAWK_ENVIRONMENT") or os.environ.get("NODE_ENV") or "development"
|
|
117
|
+
endpoint = (endpoint or os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") or "http://localhost:4318").rstrip("/")
|
|
118
|
+
# host.name as the Node SDK's host detector sets it (OTEL_RESOURCE_ATTRIBUTES still wins): host metrics reach
|
|
119
|
+
# the services on a host by it.
|
|
120
|
+
resource = Resource({"host.name": socket.gethostname()}).merge(
|
|
121
|
+
Resource.create({"service.name": service, "service.version": version, "deployment.environment": environment})
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
api_key = api_key or os.environ.get("FLOWHAWK_API_KEY") or None
|
|
125
|
+
headers = auth_headers(api_key)
|
|
126
|
+
|
|
127
|
+
tp = TracerProvider(resource=resource)
|
|
128
|
+
# Tagging runs first so the tail decision sees business.flow.
|
|
129
|
+
tp.add_span_processor(FlowTagger(service, lambda: _instruments))
|
|
130
|
+
tp.add_span_processor(TailSampler(BatchSpanProcessor(OTLPSpanExporter(endpoint=f"{endpoint}/v1/traces", headers=headers))))
|
|
131
|
+
trace.set_tracer_provider(tp)
|
|
132
|
+
|
|
133
|
+
reader = PeriodicExportingMetricReader(
|
|
134
|
+
OTLPMetricExporter(endpoint=f"{endpoint}/v1/metrics", headers=headers, preferred_temporality=_delta_temporality()),
|
|
135
|
+
export_interval_millis=15_000,
|
|
136
|
+
)
|
|
137
|
+
mp = MeterProvider(resource=resource, metric_readers=[reader])
|
|
138
|
+
metrics.set_meter_provider(mp)
|
|
139
|
+
|
|
140
|
+
lp = LoggerProvider(resource=resource)
|
|
141
|
+
lp.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter(endpoint=f"{endpoint}/v1/logs", headers=headers)))
|
|
142
|
+
_logs.set_logger_provider(lp)
|
|
143
|
+
_set_logger(service, lp)
|
|
144
|
+
handler = logging_handler(lp)
|
|
145
|
+
logging.getLogger().addHandler(handler)
|
|
146
|
+
|
|
147
|
+
# Sentry first, so a traceparent sent too wins (mobile apps send sentry-trace).
|
|
148
|
+
set_global_textmap(CompositePropagator([SentryTracePropagator(), TraceContextTextMapPropagator(), BusinessBaggagePropagator()]))
|
|
149
|
+
|
|
150
|
+
_instruments = _make_instruments(mp.get_meter("flowhawk-sdk"))
|
|
151
|
+
start_runtime_metrics(service)
|
|
152
|
+
|
|
153
|
+
if instrument:
|
|
154
|
+
_instrument()
|
|
155
|
+
if sql_comments is None:
|
|
156
|
+
sql_comments = os.environ.get("FLOWHAWK_SQL_COMMENTS") != "off"
|
|
157
|
+
set_sql_comments(sql_comments, service)
|
|
158
|
+
if sql_comments:
|
|
159
|
+
instrument_psycopg()
|
|
160
|
+
instrument_sqlalchemy()
|
|
161
|
+
|
|
162
|
+
control = ControlClient(
|
|
163
|
+
control_url or os.environ.get("FLOWHAWK_CONTROL_URL") or "http://localhost:4000",
|
|
164
|
+
service,
|
|
165
|
+
version,
|
|
166
|
+
api_key,
|
|
167
|
+
)
|
|
168
|
+
control.start()
|
|
169
|
+
_parts.update(tp=tp, mp=mp, lp=lp, handler=handler, control=control)
|
|
170
|
+
atexit.register(shutdown)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _instrument() -> None:
|
|
174
|
+
# Each framework is optional: a missing one is skipped, never fatal.
|
|
175
|
+
try:
|
|
176
|
+
from opentelemetry.instrumentation.flask import FlaskInstrumentor
|
|
177
|
+
|
|
178
|
+
FlaskInstrumentor().instrument()
|
|
179
|
+
except Exception:
|
|
180
|
+
pass
|
|
181
|
+
try:
|
|
182
|
+
from opentelemetry.instrumentation.requests import RequestsInstrumentor
|
|
183
|
+
|
|
184
|
+
RequestsInstrumentor().instrument()
|
|
185
|
+
except Exception:
|
|
186
|
+
pass
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def shutdown() -> None:
|
|
190
|
+
"""Flushes and stops telemetry. Safe to call more than once."""
|
|
191
|
+
global _instruments
|
|
192
|
+
parts = dict(_parts)
|
|
193
|
+
_parts.clear()
|
|
194
|
+
_instruments = None
|
|
195
|
+
if not parts:
|
|
196
|
+
return
|
|
197
|
+
parts["control"].stop()
|
|
198
|
+
logging.getLogger().removeHandler(parts["handler"])
|
|
199
|
+
for k in ("tp", "mp", "lp"):
|
|
200
|
+
try:
|
|
201
|
+
parts[k].shutdown()
|
|
202
|
+
except Exception:
|
|
203
|
+
pass
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def current_config() -> Optional[dict]:
|
|
207
|
+
"""The remote config currently applied as {"hash", "config"}, or None before the first one arrives."""
|
|
208
|
+
a = get_applied()
|
|
209
|
+
return {"hash": a.hash, "config": a.config} if a else None
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@contextmanager
|
|
213
|
+
def with_step(flow: str, step: str, span_name: Optional[str] = None) -> Iterator[Any]:
|
|
214
|
+
"""
|
|
215
|
+
Runs a background job as a business step entry: a new root span with business.* set.
|
|
216
|
+
An exception marks the span as an error and propagates.
|
|
217
|
+
"""
|
|
218
|
+
tracer = trace.get_tracer("flowhawk-sdk")
|
|
219
|
+
with tracer.start_as_current_span(span_name or step, context=Context(), attributes={FLOW: flow, STEP: step, ENTRY: "true"}) as span:
|
|
220
|
+
yield span
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# App metrics (named app_metrics so it does not shadow opentelemetry.metrics in the package) with flow context: count(), histogram(), up_down() and gauge() over the OpenTelemetry Meter API;
|
|
2
|
+
# the Python twin of metrics.ts in @flowhawk/sdk-node. Recorded inside a request, a point gets business.flow and
|
|
3
|
+
# business.step from the active span. The catalog's label allowlist (metrics/*.yaml) is applied before recording,
|
|
4
|
+
# so labels nobody declared never create series.
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import threading
|
|
8
|
+
from typing import Any, Callable, Iterable, Optional, Union
|
|
9
|
+
|
|
10
|
+
from opentelemetry import metrics
|
|
11
|
+
|
|
12
|
+
from .state import _UNSET, _cfg, policy_for
|
|
13
|
+
from .match import FlowStep
|
|
14
|
+
from .tagging import FLOW, STEP, flow_of_context
|
|
15
|
+
|
|
16
|
+
Labels = dict[str, Union[str, int, float, bool]]
|
|
17
|
+
|
|
18
|
+
_lock = threading.Lock()
|
|
19
|
+
_instruments: dict[tuple[str, str], Any] = {}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def point_labels(name: str, labels: Optional[Labels], flow: Optional[FlowStep], cfg: Any = _UNSET) -> Optional[dict]:
|
|
23
|
+
"""The labels a point is recorded with, or None when the metric is turned off in the catalog or the flow's
|
|
24
|
+
policy has custom metrics off."""
|
|
25
|
+
c = _cfg(cfg)
|
|
26
|
+
if name in (((c or {}).get("metrics") or {}).get("drop") or []):
|
|
27
|
+
return None
|
|
28
|
+
labels = labels or {}
|
|
29
|
+
fs = FlowStep(str(labels[FLOW]), str(labels.get(STEP, ""))) if labels.get(FLOW) is not None else flow
|
|
30
|
+
if fs:
|
|
31
|
+
p = policy_for(fs.flow, c)
|
|
32
|
+
if p and p.get("metrics", {}).get("custom") is False:
|
|
33
|
+
return None
|
|
34
|
+
keep = ((c or {}).get("metrics") or {}).get("keep", {}).get(name)
|
|
35
|
+
out = {k: v for k, v in labels.items() if k not in (FLOW, STEP) and (keep is None or k in keep)}
|
|
36
|
+
if fs:
|
|
37
|
+
out[FLOW] = fs.flow
|
|
38
|
+
if fs.step:
|
|
39
|
+
out[STEP] = fs.step
|
|
40
|
+
return out
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _instrument(kind: str, name: str, unit: str, description: str) -> Any:
|
|
44
|
+
key = (kind, name)
|
|
45
|
+
with _lock:
|
|
46
|
+
inst = _instruments.get(key)
|
|
47
|
+
if inst is None:
|
|
48
|
+
meter = metrics.get_meter("flowhawk-app")
|
|
49
|
+
make = {"counter": meter.create_counter, "histogram": meter.create_histogram, "updown": meter.create_up_down_counter}[kind]
|
|
50
|
+
inst = _instruments[key] = make(name, unit=unit, description=description)
|
|
51
|
+
return inst
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def count(name: str, value: float = 1, labels: Optional[Labels] = None, unit: str = "", description: str = "") -> None:
|
|
55
|
+
"""Adds to a counter (orders placed, emails sent). Inside a request it carries the request's flow and step."""
|
|
56
|
+
attrs = point_labels(name, labels, flow_of_context())
|
|
57
|
+
if attrs is not None:
|
|
58
|
+
_instrument("counter", name, unit, description).add(value, attrs)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def histogram(name: str, value: float, labels: Optional[Labels] = None, unit: str = "", description: str = "") -> None:
|
|
62
|
+
"""Records a distribution (render time, basket size)."""
|
|
63
|
+
attrs = point_labels(name, labels, flow_of_context())
|
|
64
|
+
if attrs is not None:
|
|
65
|
+
_instrument("histogram", name, unit, description).record(value, attrs)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def up_down(name: str, delta: float, labels: Optional[Labels] = None, unit: str = "", description: str = "") -> None:
|
|
69
|
+
"""Moves a value up or down (items in a queue, open connections)."""
|
|
70
|
+
attrs = point_labels(name, labels, flow_of_context())
|
|
71
|
+
if attrs is not None:
|
|
72
|
+
_instrument("updown", name, unit, description).add(delta, attrs)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
Reading = Union[float, Iterable[tuple[float, Labels]]]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def gauge(name: str, read: Callable[[], Reading], labels: Optional[Labels] = None, unit: str = "", description: str = "") -> Any:
|
|
79
|
+
"""
|
|
80
|
+
Reports a value read on each export (queue depth, pool usage): a number, or (value, labels) pairs. Read outside
|
|
81
|
+
any request, so it reaches flows through the service unless the labels name a flow. Returns the instrument.
|
|
82
|
+
"""
|
|
83
|
+
from opentelemetry.metrics import CallbackOptions, Observation
|
|
84
|
+
|
|
85
|
+
def cb(_: CallbackOptions) -> Iterable[Observation]:
|
|
86
|
+
try:
|
|
87
|
+
r = read()
|
|
88
|
+
except Exception:
|
|
89
|
+
return []
|
|
90
|
+
points = [(r, labels or {})] if isinstance(r, (int, float)) else [(v, {**(labels or {}), **pl}) for v, pl in r]
|
|
91
|
+
out = []
|
|
92
|
+
for v, pl in points:
|
|
93
|
+
attrs = point_labels(name, pl, None)
|
|
94
|
+
if attrs is not None:
|
|
95
|
+
out.append(Observation(v, attrs))
|
|
96
|
+
return out
|
|
97
|
+
|
|
98
|
+
return metrics.get_meter("flowhawk-app").create_observable_gauge(name, callbacks=[cb], unit=unit, description=description)
|
flowhawk_sdk/config.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
# Validation of the remote config (SdkRemoteConfig in packages/schema/src/api.ts) with the same
|
|
2
|
+
# rules and defaults as the zod schemas BusinessMap and CollectionPolicy in config.ts.
|
|
3
|
+
# Configs stay plain dicts with the JSON (camelCase) keys.
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
from typing import Any, Optional
|
|
9
|
+
|
|
10
|
+
_ID = re.compile(r"^[a-z0-9][a-z0-9-]*$")
|
|
11
|
+
_CRITICALITY = ("critical", "important", "background")
|
|
12
|
+
_LEVELS = ("debug", "info", "warn", "error")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ConfigError(ValueError):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _obj(v: Any, where: str) -> dict:
|
|
20
|
+
if not isinstance(v, dict):
|
|
21
|
+
raise ConfigError(f"{where}: expected object")
|
|
22
|
+
return v
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _str(v: Any, where: str) -> str:
|
|
26
|
+
if not isinstance(v, str):
|
|
27
|
+
raise ConfigError(f"{where}: expected string")
|
|
28
|
+
return v
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _opt_str(o: dict, k: str, where: str) -> str | None:
|
|
32
|
+
v = o.get(k)
|
|
33
|
+
return None if v is None else _str(v, f"{where}.{k}")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _bool(o: dict, k: str, where: str, default: bool) -> bool:
|
|
37
|
+
v = o.get(k)
|
|
38
|
+
if v is None:
|
|
39
|
+
return default
|
|
40
|
+
if not isinstance(v, bool):
|
|
41
|
+
raise ConfigError(f"{where}.{k}: expected boolean")
|
|
42
|
+
return v
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _num(v: Any, where: str) -> float:
|
|
46
|
+
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v):
|
|
47
|
+
raise ConfigError(f"{where}: expected number")
|
|
48
|
+
return v
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _id(v: Any, where: str) -> str:
|
|
52
|
+
s = _str(v, where)
|
|
53
|
+
if not _ID.match(s):
|
|
54
|
+
raise ConfigError(f"{where}: ids are lowercase letters, digits and dashes")
|
|
55
|
+
return s
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _str_list(o: dict, k: str, where: str) -> list[str]:
|
|
59
|
+
v = o.get(k)
|
|
60
|
+
if v is None:
|
|
61
|
+
return []
|
|
62
|
+
if not isinstance(v, list):
|
|
63
|
+
raise ConfigError(f"{where}.{k}: expected array")
|
|
64
|
+
return [_str(x, f"{where}.{k}[{i}]") for i, x in enumerate(v)]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def parse_policy(raw: Any, where: str = "policy") -> dict:
|
|
68
|
+
p = _obj(raw, where)
|
|
69
|
+
t = _obj(p.get("traces"), f"{where}.traces")
|
|
70
|
+
rate = _num(t.get("sampleRate"), f"{where}.traces.sampleRate")
|
|
71
|
+
if not 0 <= rate <= 1:
|
|
72
|
+
raise ConfigError(f"{where}.traces.sampleRate: must be in 0..1")
|
|
73
|
+
traces: dict[str, Any] = {
|
|
74
|
+
"enabled": _bool(t, "enabled", f"{where}.traces", True),
|
|
75
|
+
"sampleRate": rate,
|
|
76
|
+
"keepErrors": _bool(t, "keepErrors", f"{where}.traces", True),
|
|
77
|
+
}
|
|
78
|
+
if t.get("keepSlowerThanMs") is not None:
|
|
79
|
+
slow = _num(t["keepSlowerThanMs"], f"{where}.traces.keepSlowerThanMs")
|
|
80
|
+
if slow <= 0:
|
|
81
|
+
raise ConfigError(f"{where}.traces.keepSlowerThanMs: must be positive")
|
|
82
|
+
traces["keepSlowerThanMs"] = slow
|
|
83
|
+
lg = _obj(p.get("logs"), f"{where}.logs")
|
|
84
|
+
level = lg.get("level", "info")
|
|
85
|
+
if level not in _LEVELS:
|
|
86
|
+
raise ConfigError(f"{where}.logs.level: expected one of {', '.join(_LEVELS)}")
|
|
87
|
+
m = _obj(p.get("metrics", {"enabled": True}), f"{where}.metrics")
|
|
88
|
+
a = _obj(p.get("attributes", {}), f"{where}.attributes")
|
|
89
|
+
llm = _obj(p.get("llm", {}), f"{where}.llm")
|
|
90
|
+
r = _obj(p.get("replay", {}), f"{where}.replay")
|
|
91
|
+
replay_rate = _num(r.get("sampleRate", 0.25), f"{where}.replay.sampleRate")
|
|
92
|
+
if not 0 <= replay_rate <= 1:
|
|
93
|
+
raise ConfigError(f"{where}.replay.sampleRate: must be in 0..1")
|
|
94
|
+
return {
|
|
95
|
+
"flow": _id(p.get("flow"), f"{where}.flow"),
|
|
96
|
+
"traces": traces,
|
|
97
|
+
"logs": {"enabled": _bool(lg, "enabled", f"{where}.logs", True), "level": level},
|
|
98
|
+
"metrics": {"enabled": _bool(m, "enabled", f"{where}.metrics", True), "custom": _bool(m, "custom", f"{where}.metrics", True)},
|
|
99
|
+
"attributes": {"drop": _str_list(a, "drop", f"{where}.attributes"), "redact": _str_list(a, "redact", f"{where}.attributes")},
|
|
100
|
+
"llm": {"capturePrompts": _bool(llm, "capturePrompts", f"{where}.llm", False)},
|
|
101
|
+
"replay": {
|
|
102
|
+
"enabled": _bool(r, "enabled", f"{where}.replay", True),
|
|
103
|
+
"maskInputs": _bool(r, "maskInputs", f"{where}.replay", True),
|
|
104
|
+
"maskText": _bool(r, "maskText", f"{where}.replay", True),
|
|
105
|
+
"sampleRate": replay_rate,
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _parse_match(raw: Any, where: str) -> dict:
|
|
111
|
+
o = _obj(raw, where)
|
|
112
|
+
m = {k: v for k in ("service", "route", "spanName", "queue") if (v := _opt_str(o, k, where)) is not None}
|
|
113
|
+
if not (m.get("route") or m.get("spanName") or m.get("queue")):
|
|
114
|
+
raise ConfigError(f"{where}: a match needs a route, spanName or queue")
|
|
115
|
+
return m
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _parse_step(raw: Any, where: str) -> dict:
|
|
119
|
+
o = _obj(raw, where)
|
|
120
|
+
match = o.get("match")
|
|
121
|
+
if not isinstance(match, list) or not match:
|
|
122
|
+
raise ConfigError(f"{where}.match: expected a non-empty array")
|
|
123
|
+
return {
|
|
124
|
+
"id": _id(o.get("id"), f"{where}.id"),
|
|
125
|
+
"name": _str(o.get("name"), f"{where}.name"),
|
|
126
|
+
"match": [_parse_match(x, f"{where}.match[{i}]") for i, x in enumerate(match)],
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _parse_flow(raw: Any, where: str) -> dict:
|
|
131
|
+
o = _obj(raw, where)
|
|
132
|
+
crit = o.get("criticality")
|
|
133
|
+
if crit not in _CRITICALITY:
|
|
134
|
+
raise ConfigError(f"{where}.criticality: expected one of {', '.join(_CRITICALITY)}")
|
|
135
|
+
steps = o.get("steps")
|
|
136
|
+
if not isinstance(steps, list) or not steps:
|
|
137
|
+
raise ConfigError(f"{where}.steps: expected a non-empty array")
|
|
138
|
+
flow: dict[str, Any] = {"id": _id(o.get("id"), f"{where}.id"), "name": _str(o.get("name"), f"{where}.name")}
|
|
139
|
+
if (d := _opt_str(o, "description", where)) is not None:
|
|
140
|
+
flow["description"] = d
|
|
141
|
+
flow["criticality"] = crit
|
|
142
|
+
if o.get("slo") is not None:
|
|
143
|
+
s = _obj(o["slo"], f"{where}.slo")
|
|
144
|
+
slo: dict[str, float] = {}
|
|
145
|
+
if s.get("availability") is not None:
|
|
146
|
+
av = _num(s["availability"], f"{where}.slo.availability")
|
|
147
|
+
if not 50 <= av <= 100:
|
|
148
|
+
raise ConfigError(f"{where}.slo.availability: must be in 50..100")
|
|
149
|
+
slo["availability"] = av
|
|
150
|
+
if s.get("latencyP95Ms") is not None:
|
|
151
|
+
lat = _num(s["latencyP95Ms"], f"{where}.slo.latencyP95Ms")
|
|
152
|
+
if lat <= 0:
|
|
153
|
+
raise ConfigError(f"{where}.slo.latencyP95Ms: must be positive")
|
|
154
|
+
slo["latencyP95Ms"] = lat
|
|
155
|
+
flow["slo"] = slo
|
|
156
|
+
flow["steps"] = [_parse_step(x, f"{where}.steps[{i}]") for i, x in enumerate(steps)]
|
|
157
|
+
return flow
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def parse_map(raw: Any) -> dict:
|
|
161
|
+
o = _obj(raw, "map")
|
|
162
|
+
flows = o.get("flows")
|
|
163
|
+
if not isinstance(flows, list):
|
|
164
|
+
raise ConfigError("map.flows: expected array")
|
|
165
|
+
parsed = [_parse_flow(f, f"map.flows[{i}]") for i, f in enumerate(flows)]
|
|
166
|
+
seen: set[str] = set()
|
|
167
|
+
for f in parsed:
|
|
168
|
+
if f["id"] in seen:
|
|
169
|
+
raise ConfigError(f"duplicate flow id {f['id']}")
|
|
170
|
+
seen.add(f["id"])
|
|
171
|
+
steps: set[str] = set()
|
|
172
|
+
for s in f["steps"]:
|
|
173
|
+
if s["id"] in steps:
|
|
174
|
+
raise ConfigError(f"duplicate step {f['id']}.{s['id']}")
|
|
175
|
+
steps.add(s["id"])
|
|
176
|
+
return {"flows": parsed}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def parse_remote_config(raw: Any) -> dict:
|
|
180
|
+
"""Validates a received config and fills schema defaults; raises ConfigError on an invalid one."""
|
|
181
|
+
o = _obj(raw, "config")
|
|
182
|
+
policies = {flow: parse_policy(p, f"policies.{flow}") for flow, p in _obj(o.get("policies") or {}, "policies").items()}
|
|
183
|
+
return {
|
|
184
|
+
"map": parse_map(o.get("map")),
|
|
185
|
+
"policies": policies,
|
|
186
|
+
"defaultPolicy": parse_policy(o.get("defaultPolicy"), "defaultPolicy"),
|
|
187
|
+
"boosts": o.get("boosts") or {},
|
|
188
|
+
"metrics": parse_metrics(o.get("metrics")),
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
_METRIC_LEVELS = ("off", "standard", "full")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _level(o: dict, k: str, where: str) -> Optional[str]:
|
|
196
|
+
v = o.get(k)
|
|
197
|
+
if v is None:
|
|
198
|
+
return None
|
|
199
|
+
if v not in _METRIC_LEVELS:
|
|
200
|
+
raise ConfigError(f"{where}.{k}: expected one of {', '.join(_METRIC_LEVELS)}")
|
|
201
|
+
return v
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def parse_metrics(raw: Any) -> dict:
|
|
205
|
+
"""The metrics block (optional: older servers send none): runtime level, per-service overrides, label allowlists."""
|
|
206
|
+
if raw is None:
|
|
207
|
+
return {"runtime": "standard", "services": {}, "keep": {}, "drop": []}
|
|
208
|
+
o = _obj(raw, "metrics")
|
|
209
|
+
services = {}
|
|
210
|
+
for name, s in _obj(o.get("services") or {}, "metrics.services").items():
|
|
211
|
+
so = _obj(s, f"metrics.services.{name}")
|
|
212
|
+
level = _level(so, "runtime", f"metrics.services.{name}")
|
|
213
|
+
services[name] = {"runtime": level} if level else {}
|
|
214
|
+
keep = {name: _str_list({"k": v}, "k", f"metrics.keep.{name}") for name, v in _obj(o.get("keep") or {}, "metrics.keep").items()}
|
|
215
|
+
drop = _str_list(o, "drop", "metrics")
|
|
216
|
+
return {"runtime": _level(o, "runtime", "metrics") or "standard", "services": services, "keep": keep, "drop": drop}
|
flowhawk_sdk/control.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# Remote-control client: polls the control plane's OpAMP endpoint (JSON over HTTP) and
|
|
2
|
+
# applies the returned config. Never raises into the host app; until a config arrives the
|
|
3
|
+
# SDK keeps everything and tags nothing, but still applies the default redaction.
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.parse
|
|
13
|
+
import urllib.request
|
|
14
|
+
import uuid
|
|
15
|
+
from typing import Any, Optional
|
|
16
|
+
|
|
17
|
+
from .config import parse_remote_config
|
|
18
|
+
from .state import Applied, get_applied, set_applied, stats
|
|
19
|
+
|
|
20
|
+
SDK_ID = "flowhawk-python/0.1.0"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def auth_headers(api_key: Optional[str]) -> dict:
|
|
24
|
+
"""The ingest key as the bearer token, for /v1/opamp and the OTLP exports; nothing without a key (local dev mode)."""
|
|
25
|
+
return {"authorization": f"Bearer {api_key}"} if api_key else {}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def insecure_control_url(url: str, api_key: Optional[str], allow: Optional[bool] = None) -> Optional[str]:
|
|
29
|
+
"""Why the ingest key must not go to this control URL, or None when it may: plain http sends it in the
|
|
30
|
+
clear, so it is allowed only to this machine (localhost, 127.x, ::1) or with
|
|
31
|
+
FLOWHAWK_ALLOW_INSECURE_CONTROL_URL=true (a private network). Without a key nothing secret is sent."""
|
|
32
|
+
if allow is None:
|
|
33
|
+
allow = os.environ.get("FLOWHAWK_ALLOW_INSECURE_CONTROL_URL") == "true"
|
|
34
|
+
if not api_key or allow:
|
|
35
|
+
return None
|
|
36
|
+
u = urllib.parse.urlsplit(url)
|
|
37
|
+
if u.scheme == "https":
|
|
38
|
+
return None
|
|
39
|
+
host = (u.hostname or "").strip("[]")
|
|
40
|
+
if u.scheme == "http" and (host == "localhost" or host.endswith(".localhost") or host == "::1" or host.startswith("127.")):
|
|
41
|
+
return None
|
|
42
|
+
origin = f"{u.scheme}://{u.netloc}" if u.scheme else url
|
|
43
|
+
return (
|
|
44
|
+
f"refusing to send the ingest key to {origin} over plain http: use https, "
|
|
45
|
+
"or set FLOWHAWK_ALLOW_INSECURE_CONTROL_URL=true on a private network"
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _suppressed() -> Any:
|
|
50
|
+
# The SDK's own traffic must not be traced (urllib is not instrumented, but be safe).
|
|
51
|
+
try:
|
|
52
|
+
from opentelemetry.instrumentation.utils import suppress_instrumentation
|
|
53
|
+
|
|
54
|
+
return suppress_instrumentation()
|
|
55
|
+
except Exception:
|
|
56
|
+
import contextlib
|
|
57
|
+
|
|
58
|
+
return contextlib.nullcontext()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class ControlClient:
|
|
62
|
+
def __init__(self, url: str, service: str, version: Optional[str] = None, api_key: Optional[str] = None) -> None:
|
|
63
|
+
self._url = url.rstrip("/")
|
|
64
|
+
self._api_key = api_key
|
|
65
|
+
self._service = service
|
|
66
|
+
self._version = version
|
|
67
|
+
self._uid = str(uuid.uuid4())
|
|
68
|
+
self._seq = 0
|
|
69
|
+
self._stop = threading.Event()
|
|
70
|
+
self._last_warn = 0.0
|
|
71
|
+
self._failures = 0
|
|
72
|
+
self._status: Optional[dict] = None
|
|
73
|
+
self._thread: Optional[threading.Thread] = None
|
|
74
|
+
|
|
75
|
+
def start(self) -> None:
|
|
76
|
+
insecure = insecure_control_url(self._url, self._api_key)
|
|
77
|
+
if insecure:
|
|
78
|
+
self._warn(f"{insecure}; remote config is off")
|
|
79
|
+
return
|
|
80
|
+
self._thread = threading.Thread(target=self._run, name="flowhawk-control", daemon=True)
|
|
81
|
+
self._thread.start()
|
|
82
|
+
|
|
83
|
+
def stop(self) -> None:
|
|
84
|
+
self._stop.set()
|
|
85
|
+
|
|
86
|
+
def _run(self) -> None:
|
|
87
|
+
while not self._stop.is_set():
|
|
88
|
+
nxt: float = 5
|
|
89
|
+
try:
|
|
90
|
+
nxt = self.poll() or nxt
|
|
91
|
+
self._failures = 0
|
|
92
|
+
except Exception as e: # noqa: BLE001 - nothing may escape into the host app
|
|
93
|
+
# Server gone: the last config stays applied (its redaction with it) until it returns. Dropping it would
|
|
94
|
+
# export what the workspace's own redact and drop rules remove; only the defaults apply without a config.
|
|
95
|
+
self._failures += 1
|
|
96
|
+
self._warn(f"control plane unreachable at {self._url}: {e}")
|
|
97
|
+
self._stop.wait(max(1, nxt))
|
|
98
|
+
|
|
99
|
+
def poll(self) -> Optional[float]:
|
|
100
|
+
self._seq += 1
|
|
101
|
+
description: dict[str, Any] = {"service": self._service, "sdk": SDK_ID}
|
|
102
|
+
if self._version is not None:
|
|
103
|
+
description["version"] = self._version
|
|
104
|
+
body: dict[str, Any] = {
|
|
105
|
+
"instance_uid": self._uid,
|
|
106
|
+
"sequence_num": self._seq,
|
|
107
|
+
"agent_description": description,
|
|
108
|
+
"health": {"healthy": True, "spans_exported": stats.kept, "spans_dropped": stats.dropped},
|
|
109
|
+
}
|
|
110
|
+
if self._status is not None:
|
|
111
|
+
body["remote_config_status"] = self._status
|
|
112
|
+
headers = {"content-type": "application/json", **auth_headers(self._api_key)}
|
|
113
|
+
req = urllib.request.Request(f"{self._url}/v1/opamp", data=json.dumps(body).encode(), headers=headers, method="POST")
|
|
114
|
+
# urlopen raises HTTPError on a non-2xx answer.
|
|
115
|
+
try:
|
|
116
|
+
with _suppressed(), urllib.request.urlopen(req, timeout=3) as res:
|
|
117
|
+
msg = json.loads(res.read() or b"{}")
|
|
118
|
+
except urllib.error.HTTPError as e:
|
|
119
|
+
if e.code == 401:
|
|
120
|
+
hint = "the ingest key was rejected" if self._api_key else "set FLOWHAWK_API_KEY to a workspace ingest key"
|
|
121
|
+
raise RuntimeError(f"HTTP 401: {hint}") from None
|
|
122
|
+
raise
|
|
123
|
+
rc = msg.get("remote_config")
|
|
124
|
+
cur = get_applied()
|
|
125
|
+
if rc and rc.get("config_hash") != (cur.hash if cur else None):
|
|
126
|
+
h = rc["config_hash"]
|
|
127
|
+
try:
|
|
128
|
+
set_applied(Applied(h, parse_remote_config(rc.get("config"))))
|
|
129
|
+
self._status = {"last_remote_config_hash": h, "status": "APPLIED"}
|
|
130
|
+
except Exception as e: # noqa: BLE001
|
|
131
|
+
# Keep the previous config; report the failure on the next poll.
|
|
132
|
+
self._status = {"last_remote_config_hash": h, "status": "FAILED", "error_message": str(e)[:500]}
|
|
133
|
+
self._warn(f"rejected remote config {h}: {e}")
|
|
134
|
+
interval = msg.get("poll_interval_s")
|
|
135
|
+
return interval if isinstance(interval, (int, float)) and not isinstance(interval, bool) else None
|
|
136
|
+
|
|
137
|
+
def _warn(self, text: str) -> None:
|
|
138
|
+
"""At most one warning per minute."""
|
|
139
|
+
now = time.monotonic()
|
|
140
|
+
if self._last_warn and now - self._last_warn < 60:
|
|
141
|
+
return
|
|
142
|
+
self._last_warn = now
|
|
143
|
+
try:
|
|
144
|
+
print(f"[flowhawk-sdk] {text}", file=sys.stderr)
|
|
145
|
+
except Exception:
|
|
146
|
+
pass
|