flowhawk-sdk 0.1.0__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.
@@ -0,0 +1,4 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ .pytest_cache/
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.5
2
+ Name: flowhawk-sdk
3
+ Version: 0.1.0
4
+ Summary: OpenTelemetry Python SDK distribution with business-flow tagging and remote-controlled collection
5
+ Project-URL: Homepage, https://flowhawk.dev
6
+ Project-URL: Documentation, https://flowhawk.dev/docs/sending-data
7
+ Author-email: Flowhawk <hello@flowhawk.dev>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: flowhawk,observability,opentelemetry,tracing
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: System :: Monitoring
14
+ Requires-Python: >=3.10
15
+ Requires-Dist: opentelemetry-api<2,>=1.45
16
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http<2,>=1.45
17
+ Requires-Dist: opentelemetry-instrumentation-flask>=0.66b0
18
+ Requires-Dist: opentelemetry-instrumentation-requests>=0.66b0
19
+ Requires-Dist: opentelemetry-sdk<2,>=1.45
20
+ Provides-Extra: test
21
+ Requires-Dist: flask>=3; extra == 'test'
22
+ Requires-Dist: pytest>=8; extra == 'test'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # flowhawk-sdk (Python)
26
+
27
+ The Flowhawk SDK for Python: a thin OpenTelemetry distribution that tags every span, log and metric with the business flow and step it belongs to, samples whole traces by the flow's collection policy, redacts attributes, and takes new settings from the Flowhawk control plane without a redeploy. It behaves the same as the Node SDK (`@flowhawk/sdk-node`).
28
+
29
+ ```bash
30
+ pip install flowhawk-sdk
31
+ ```
32
+
33
+ Python 3.10 or later. Docs: [flowhawk.dev/docs/sending-data](https://flowhawk.dev/docs/sending-data).
34
+
35
+ ## Set up
36
+
37
+ Call `init` once, before importing Flask:
38
+
39
+ ```python
40
+ import flowhawk_sdk
41
+ flowhawk_sdk.init(service="recommendations")
42
+ ```
43
+
44
+ Options: `service`, `version`, `environment`, `endpoint` (OTLP HTTP, default `OTEL_EXPORTER_OTLP_ENDPOINT` or `http://localhost:4318`), `control_url` (default `FLOWHAWK_CONTROL_URL` or `http://localhost:4000`), `api_key` (default `FLOWHAWK_API_KEY`; not needed in local dev mode), `code_skip` (default `FLOWHAWK_CODE_SKIP`) and `instrument=False` to skip the Flask and requests instrumentation. Records from the standard `logging` module are exported with their trace, span, flow and step.
45
+
46
+ ## API
47
+
48
+ ```python
49
+ # A job or queue consumer that no route matches
50
+ with flowhawk_sdk.with_step("payouts", "settle"):
51
+ settle(batch)
52
+
53
+ flowhawk_sdk.logger.info("payout settled")
54
+
55
+ # App metrics: flow and step come from the active request
56
+ flowhawk_sdk.count("orders.placed", 1, {"plan": "team"})
57
+ flowhawk_sdk.histogram("pdf.render_ms", ms)
58
+ flowhawk_sdk.gauge("queue.depth", lambda: queue.qsize(), {"queue": "emails"})
59
+
60
+ # An LLM call as a gen_ai span
61
+ with flowhawk_sdk.trace_llm(system="anthropic", model="claude-haiku-5-5", input=prompt) as call:
62
+ reply = client.messages.create(...)
63
+ call.record(output=text, input_tokens=reply.usage.input_tokens, output_tokens=reply.usage.output_tokens)
64
+ ```
65
+
66
+ `shutdown()` flushes before exit; `current_config()` returns the config the control plane last sent.
67
+
68
+ ## Tests
69
+
70
+ ```bash
71
+ cd packages/sdk-python
72
+ pip install -e ".[test]"
73
+ pytest
74
+ ```
@@ -0,0 +1,50 @@
1
+ # flowhawk-sdk (Python)
2
+
3
+ The Flowhawk SDK for Python: a thin OpenTelemetry distribution that tags every span, log and metric with the business flow and step it belongs to, samples whole traces by the flow's collection policy, redacts attributes, and takes new settings from the Flowhawk control plane without a redeploy. It behaves the same as the Node SDK (`@flowhawk/sdk-node`).
4
+
5
+ ```bash
6
+ pip install flowhawk-sdk
7
+ ```
8
+
9
+ Python 3.10 or later. Docs: [flowhawk.dev/docs/sending-data](https://flowhawk.dev/docs/sending-data).
10
+
11
+ ## Set up
12
+
13
+ Call `init` once, before importing Flask:
14
+
15
+ ```python
16
+ import flowhawk_sdk
17
+ flowhawk_sdk.init(service="recommendations")
18
+ ```
19
+
20
+ Options: `service`, `version`, `environment`, `endpoint` (OTLP HTTP, default `OTEL_EXPORTER_OTLP_ENDPOINT` or `http://localhost:4318`), `control_url` (default `FLOWHAWK_CONTROL_URL` or `http://localhost:4000`), `api_key` (default `FLOWHAWK_API_KEY`; not needed in local dev mode), `code_skip` (default `FLOWHAWK_CODE_SKIP`) and `instrument=False` to skip the Flask and requests instrumentation. Records from the standard `logging` module are exported with their trace, span, flow and step.
21
+
22
+ ## API
23
+
24
+ ```python
25
+ # A job or queue consumer that no route matches
26
+ with flowhawk_sdk.with_step("payouts", "settle"):
27
+ settle(batch)
28
+
29
+ flowhawk_sdk.logger.info("payout settled")
30
+
31
+ # App metrics: flow and step come from the active request
32
+ flowhawk_sdk.count("orders.placed", 1, {"plan": "team"})
33
+ flowhawk_sdk.histogram("pdf.render_ms", ms)
34
+ flowhawk_sdk.gauge("queue.depth", lambda: queue.qsize(), {"queue": "emails"})
35
+
36
+ # An LLM call as a gen_ai span
37
+ with flowhawk_sdk.trace_llm(system="anthropic", model="claude-haiku-5-5", input=prompt) as call:
38
+ reply = client.messages.create(...)
39
+ call.record(output=text, input_tokens=reply.usage.input_tokens, output_tokens=reply.usage.output_tokens)
40
+ ```
41
+
42
+ `shutdown()` flushes before exit; `current_config()` returns the config the control plane last sent.
43
+
44
+ ## Tests
45
+
46
+ ```bash
47
+ cd packages/sdk-python
48
+ pip install -e ".[test]"
49
+ pytest
50
+ ```
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "flowhawk-sdk"
7
+ version = "0.1.0"
8
+ description = "OpenTelemetry Python SDK distribution with business-flow tagging and remote-controlled collection"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Flowhawk", email = "hello@flowhawk.dev" }]
13
+ keywords = ["observability", "opentelemetry", "tracing", "flowhawk"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: System :: Monitoring",
17
+ "Development Status :: 4 - Beta",
18
+ ]
19
+ requires-python = ">=3.10"
20
+ dependencies = [
21
+ "opentelemetry-api>=1.45,<2",
22
+ "opentelemetry-sdk>=1.45,<2",
23
+ "opentelemetry-exporter-otlp-proto-http>=1.45,<2",
24
+ "opentelemetry-instrumentation-flask>=0.66b0",
25
+ "opentelemetry-instrumentation-requests>=0.66b0",
26
+ ]
27
+
28
+ [project.urls]
29
+ Homepage = "https://flowhawk.dev"
30
+ Documentation = "https://flowhawk.dev/docs/sending-data"
31
+
32
+ [project.optional-dependencies]
33
+ test = ["pytest>=8", "flask>=3"]
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ packages = ["src/flowhawk_sdk"]
37
+
38
+ [tool.pytest.ini_options]
39
+ testpaths = ["tests"]
@@ -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