traceforge-observability 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,203 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ https://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ https://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.4
2
+ Name: traceforge-observability
3
+ Version: 0.1.0
4
+ Summary: TraceForge zero-code OpenTelemetry instrumentation for Python
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Repository, https://github.com/KeshavKandoi/TraceForge
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: python-dotenv<2,>=1.0
11
+ Requires-Dist: opentelemetry-sdk==1.34.1
12
+ Requires-Dist: opentelemetry-exporter-otlp-proto-common==1.34.1
13
+ Requires-Dist: opentelemetry-instrumentation-fastapi==0.55b1
14
+ Requires-Dist: opentelemetry-instrumentation-flask==0.55b1
15
+ Requires-Dist: opentelemetry-instrumentation-django==0.55b1
16
+ Requires-Dist: opentelemetry-instrumentation-requests==0.55b1
17
+ Requires-Dist: opentelemetry-instrumentation-httpx==0.55b1
18
+ Requires-Dist: opentelemetry-instrumentation-sqlalchemy==0.55b1
19
+ Requires-Dist: opentelemetry-instrumentation-psycopg==0.55b1
20
+ Requires-Dist: opentelemetry-instrumentation-psycopg2==0.55b1
21
+ Requires-Dist: opentelemetry-instrumentation-redis==0.55b1
22
+ Dynamic: license-file
23
+
24
+ # TraceForge for Python
25
+
26
+ Python 3.10+ instrumentation using the official OpenTelemetry SDK. Install the
27
+ distribution and configure the server environment with the workspace
28
+ `TRACEFORGE_DSN` and optionally `OTEL_SERVICE_NAME`. Start an existing application
29
+ with `traceforge-run uvicorn main:app` or `traceforge-run python app.py`.
30
+
31
+ The launcher reads `.env` from the working directory and preserves settings
32
+ provided by your host. It loads instrumentation before application imports.
33
+ Install the framework or database drivers your application normally uses.
34
+ For Django, set `DJANGO_SETTINGS_MODULE` before startup. Isolated Python modes
35
+ that skip site initialization cannot load the runtime.
36
+
37
+ The exporter retains trace relationships, timing, status, and allowlisted HTTP
38
+ metadata. It omits URLs, headers, query strings, SQL, Redis commands, payloads,
39
+ and exception messages. Set `TRACEFORGE_LOG_EXPORTS=1` to check storage receipts.
40
+
41
+ Framework and database version support follows the bundled OpenTelemetry
42
+ instrumentors. For example, the bundled SQLAlchemy instrumentor supports
43
+ SQLAlchemy before 2.1. The app can still run when an optional instrumentor
44
+ reports an incompatible dependency.
@@ -0,0 +1,21 @@
1
+ # TraceForge for Python
2
+
3
+ Python 3.10+ instrumentation using the official OpenTelemetry SDK. Install the
4
+ distribution and configure the server environment with the workspace
5
+ `TRACEFORGE_DSN` and optionally `OTEL_SERVICE_NAME`. Start an existing application
6
+ with `traceforge-run uvicorn main:app` or `traceforge-run python app.py`.
7
+
8
+ The launcher reads `.env` from the working directory and preserves settings
9
+ provided by your host. It loads instrumentation before application imports.
10
+ Install the framework or database drivers your application normally uses.
11
+ For Django, set `DJANGO_SETTINGS_MODULE` before startup. Isolated Python modes
12
+ that skip site initialization cannot load the runtime.
13
+
14
+ The exporter retains trace relationships, timing, status, and allowlisted HTTP
15
+ metadata. It omits URLs, headers, query strings, SQL, Redis commands, payloads,
16
+ and exception messages. Set `TRACEFORGE_LOG_EXPORTS=1` to check storage receipts.
17
+
18
+ Framework and database version support follows the bundled OpenTelemetry
19
+ instrumentors. For example, the bundled SQLAlchemy instrumentor supports
20
+ SQLAlchemy before 2.1. The app can still run when an optional instrumentor
21
+ reports an incompatible dependency.
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "traceforge-observability"
7
+ version = "0.1.0"
8
+ description = "TraceForge zero-code OpenTelemetry instrumentation for Python"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ dependencies = [
13
+ "python-dotenv>=1.0,<2",
14
+ "opentelemetry-sdk==1.34.1",
15
+ "opentelemetry-exporter-otlp-proto-common==1.34.1",
16
+ "opentelemetry-instrumentation-fastapi==0.55b1",
17
+ "opentelemetry-instrumentation-flask==0.55b1",
18
+ "opentelemetry-instrumentation-django==0.55b1",
19
+ "opentelemetry-instrumentation-requests==0.55b1",
20
+ "opentelemetry-instrumentation-httpx==0.55b1",
21
+ "opentelemetry-instrumentation-sqlalchemy==0.55b1",
22
+ "opentelemetry-instrumentation-psycopg==0.55b1",
23
+ "opentelemetry-instrumentation-psycopg2==0.55b1",
24
+ "opentelemetry-instrumentation-redis==0.55b1",
25
+ ]
26
+
27
+ [project.urls]
28
+ Repository = "https://github.com/KeshavKandoi/TraceForge"
29
+
30
+ [project.scripts]
31
+ traceforge-run = "traceforge_observability.cli:main"
32
+
33
+ [tool.setuptools.packages.find]
34
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,10 @@
1
+ """Python startup hook enabled by traceforge-run."""
2
+ import sys
3
+
4
+ try:
5
+ from traceforge_observability.runtime import start
6
+
7
+ start()
8
+ except Exception:
9
+ print("[TraceForge] tracing disabled: invalid configuration or initialization failure",
10
+ file=sys.stderr)
@@ -0,0 +1,33 @@
1
+ """Launch a Python command with instrumentation loaded before application imports."""
2
+ import argparse
3
+ import os
4
+ import shutil
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from dotenv import load_dotenv
9
+
10
+
11
+ def main():
12
+ parser = argparse.ArgumentParser(description=__doc__)
13
+ parser.add_argument("--env-file", type=Path, default=Path(".env"))
14
+ parser.add_argument("command", nargs=argparse.REMAINDER)
15
+ options = parser.parse_args()
16
+ command = options.command
17
+ if command[:1] == ["--"]:
18
+ command = command[1:]
19
+ if not command:
20
+ parser.error("provide a Python command, such as uvicorn main:app")
21
+ if options.env_file.is_file():
22
+ # An injected environment takes precedence. Do not expand variables into secrets.
23
+ load_dotenv(options.env_file, override=False, interpolate=False)
24
+ bootstrap = str(Path(__file__).with_name("_bootstrap"))
25
+ inherited = os.environ.get("PYTHONPATH")
26
+ if os.environ.get("TRACEFORGE_DSN"):
27
+ os.environ["PYTHONPATH"] = os.pathsep.join(filter(None, (bootstrap, os.getcwd(), inherited)))
28
+ if command[0] in {"python", "python3"}:
29
+ command[0] = sys.executable
30
+ executable = shutil.which(command[0])
31
+ if executable is None:
32
+ parser.error("application command was not found on PATH")
33
+ os.execv(executable, command)
@@ -0,0 +1,203 @@
1
+ """Configure the official OTel SDK and export only bounded, allowlisted metadata."""
2
+ import importlib.util
3
+ import os
4
+ import random
5
+ import re
6
+ import signal
7
+ import sys
8
+ import time
9
+ from urllib.error import HTTPError, URLError
10
+ from urllib.parse import unquote, urlsplit
11
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
12
+
13
+ from opentelemetry import propagate, trace
14
+ from opentelemetry.exporter.otlp.proto.common.trace_encoder import encode_spans
15
+ from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceResponse
16
+ from opentelemetry.sdk.resources import Resource
17
+ from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor, TracerProvider
18
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor, SpanExporter, SpanExportResult
19
+ from opentelemetry.sdk.util.instrumentation import InstrumentationScope
20
+ from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
21
+
22
+ INSTRUMENTATION = (
23
+ ("fastapi", "fastapi", "FastAPIInstrumentor"),
24
+ ("flask", "flask", "FlaskInstrumentor"),
25
+ ("django", "django", "DjangoInstrumentor"),
26
+ ("requests", "requests", "RequestsInstrumentor"),
27
+ ("httpx", "httpx", "HTTPXClientInstrumentor"),
28
+ ("sqlalchemy", "sqlalchemy", "SQLAlchemyInstrumentor"),
29
+ ("psycopg", "psycopg", "PsycopgInstrumentor"),
30
+ ("psycopg2", "psycopg2", "Psycopg2Instrumentor"),
31
+ ("redis", "redis", "RedisInstrumentor"),
32
+ )
33
+
34
+
35
+ def connection(dsn):
36
+ source = urlsplit(dsn)
37
+ key = unquote(source.fragment)
38
+ endpoint = source._replace(fragment="").geturl()
39
+ if (not source.hostname or source.username is not None or source.query or source.path != "/v1/traces"
40
+ or (source.scheme != "https" and endpoint != "http://127.0.0.1:8000/v1/traces")
41
+ or not re.fullmatch(r"[A-Za-z0-9._~-]{32,256}", key)):
42
+ raise ValueError("Invalid workspace DSN")
43
+ return endpoint, key
44
+
45
+
46
+ def safe_context(context):
47
+ if context is None:
48
+ return None
49
+ return trace.SpanContext(context.trace_id, context.span_id, context.is_remote, context.trace_flags)
50
+
51
+
52
+ class Sanitize(SpanProcessor):
53
+ def __init__(self, processor, resource):
54
+ self.processor = processor
55
+ self.resource = resource
56
+
57
+ def on_end(self, span):
58
+ attributes = {}
59
+ for key in ("http.method", "http.request.method", "http.status_code", "http.response.status_code"):
60
+ value = (span.attributes or {}).get(key)
61
+ if type(value) is int and 100 <= value <= 599:
62
+ attributes[key] = value
63
+ elif isinstance(value, str) and re.fullmatch(r"[A-Z]{1,16}", value):
64
+ attributes[key] = value
65
+ method = attributes.get("http.request.method", attributes.get("http.method"))
66
+ scope_name = span.instrumentation_scope.name if span.instrumentation_scope else ""
67
+ product = scope_name.rsplit(".", 1)[-1]
68
+ approved = {module for _, module, _ in INSTRUMENTATION}
69
+ product = product if product in approved else "application"
70
+ safe = ReadableSpan(
71
+ "HTTP " + method if isinstance(method, str) else product + " operation",
72
+ context=safe_context(span.context), parent=safe_context(span.parent),
73
+ resource=self.resource, attributes=attributes, events=(), links=(),
74
+ kind=span.kind, status=trace.Status(span.status.status_code),
75
+ start_time=span.start_time, end_time=span.end_time,
76
+ instrumentation_scope=InstrumentationScope(f"traceforge.{product}"),
77
+ )
78
+ self.processor.on_end(safe)
79
+
80
+ def force_flush(self, timeout_millis=30000):
81
+ return self.processor.force_flush(timeout_millis)
82
+
83
+ def shutdown(self):
84
+ self.processor.shutdown()
85
+
86
+
87
+ class NoRedirect(HTTPRedirectHandler):
88
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
89
+ return None
90
+
91
+
92
+ class Exporter(SpanExporter):
93
+ def __init__(self, endpoint, key, timeout):
94
+ self.endpoint = endpoint
95
+ self.key = key
96
+ self.timeout = timeout
97
+ self.opener = build_opener(NoRedirect())
98
+
99
+ def export(self, spans):
100
+ try:
101
+ self.deliver(spans)
102
+ except Exception as failure:
103
+ reason = str(failure) if isinstance(failure, ExportFailure) else "transport or serialization error"
104
+ print(f"[TraceForge] OTLP export failed: {reason}; {len(spans)} span(s)", file=sys.stderr)
105
+ return SpanExportResult.FAILURE
106
+ return SpanExportResult.SUCCESS
107
+
108
+ def deliver(self, spans):
109
+ payload = encode_spans(spans).SerializeToString()
110
+ if not payload or len(payload) > 4 * 1024 * 1024:
111
+ raise ExportFailure("invalid OTLP batch size")
112
+ request = Request(self.endpoint, data=payload, headers={
113
+ "Authorization": f"Bearer {self.key}", "Content-Type": "application/x-protobuf",
114
+ })
115
+ deadline = time.monotonic() + self.timeout
116
+ for attempt in range(3):
117
+ remaining = deadline - time.monotonic()
118
+ if remaining <= 0:
119
+ raise ExportFailure("request timed out")
120
+ retry_after = ""
121
+ try:
122
+ with self.opener.open(request, timeout=remaining) as response:
123
+ check_receipt(response, len(spans))
124
+ return
125
+ except HTTPError as error:
126
+ with error:
127
+ if error.code not in {429, 502, 503, 504} or attempt == 2:
128
+ raise ExportFailure(f"HTTP {error.code}") from None
129
+ retry_after = error.headers.get("Retry-After", "")
130
+ except (TimeoutError, URLError, OSError):
131
+ if attempt == 2:
132
+ raise ExportFailure("transport unavailable") from None
133
+ delay = int(retry_after) if re.fullmatch(r"[0-9]{1,5}", retry_after) else 0.25 * 2**attempt + random.random() * 0.15
134
+ if time.monotonic() + delay >= deadline:
135
+ raise ExportFailure("retry budget exhausted")
136
+ time.sleep(delay)
137
+
138
+
139
+ class ExportFailure(Exception):
140
+ pass
141
+
142
+
143
+ def check_receipt(response, count):
144
+ if response.status != 200 or response.headers.get_content_type() != "application/x-protobuf":
145
+ raise ExportFailure("unexpected OTLP acknowledgement")
146
+ body = response.read(65537)
147
+ if len(body) > 65536:
148
+ raise ExportFailure("OTLP response exceeded limit")
149
+ receipt = ExportTraceServiceResponse.FromString(body)
150
+ if receipt.partial_success.rejected_spans:
151
+ raise ExportFailure("OTLP partial rejection")
152
+ result = "storage unverified"
153
+ if response.headers.get("X-TraceForge-Ingestion-Mode") == "lite":
154
+ decoded = response.headers.get("X-TraceForge-Decoded-Spans")
155
+ stored = response.headers.get("X-TraceForge-Stored-Spans", "")
156
+ if decoded != str(count) or not re.fullmatch(r"[0-9]{1,4}", stored) or int(stored) > count:
157
+ raise ExportFailure("inconsistent Lite ingestion receipt")
158
+ result = f"storage acknowledged for {int(stored)} span(s)" if int(stored) else "zero spans retained"
159
+ if result == "zero spans retained" or os.getenv("TRACEFORGE_LOG_EXPORTS") == "1":
160
+ print(f"[TraceForge] OTLP export acknowledged: {count} span(s); {result}", file=sys.stderr)
161
+
162
+
163
+ def timeout(name, default):
164
+ value = int(os.getenv(name, default))
165
+ if not 1000 <= value <= 300_000:
166
+ raise ValueError("Invalid timeout")
167
+ return value
168
+
169
+
170
+ def start():
171
+ value = os.getenv("TRACEFORGE_DSN")
172
+ if not value:
173
+ return
174
+ endpoint, key = connection(value)
175
+ export_timeout = timeout("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", 60000)
176
+ batch_timeout = timeout("OTEL_BSP_EXPORT_TIMEOUT", export_timeout + 5000)
177
+ if batch_timeout <= export_timeout:
178
+ raise ValueError("Batch timeout must exceed transport timeout")
179
+ service = os.getenv("OTEL_SERVICE_NAME") or os.path.basename(os.getcwd()) or "python-app"
180
+ resource = Resource({"service.name": service[:256]})
181
+ provider = TracerProvider(resource=resource)
182
+ provider.add_span_processor(Sanitize(BatchSpanProcessor(
183
+ Exporter(endpoint, key, export_timeout / 1000), max_queue_size=2048,
184
+ max_export_batch_size=256, schedule_delay_millis=1000, export_timeout_millis=batch_timeout,
185
+ ), resource))
186
+ trace.set_tracer_provider(provider)
187
+ propagate.set_global_textmap(TraceContextTextMapPropagator())
188
+ for dependency, module, name in INSTRUMENTATION:
189
+ if importlib.util.find_spec(dependency) is None:
190
+ continue
191
+ try:
192
+ instrumentor = getattr(importlib.import_module(f"opentelemetry.instrumentation.{module}"), name)
193
+ instrumentor().instrument(tracer_provider=provider)
194
+ except Exception:
195
+ print(f"[TraceForge] {module} instrumentation unavailable", file=sys.stderr)
196
+ def flush_on_term(signum, frame):
197
+ signal.signal(signum, signal.SIG_DFL)
198
+ provider.shutdown()
199
+ os.kill(os.getpid(), signum)
200
+
201
+ if signal.getsignal(signal.SIGTERM) == signal.SIG_DFL:
202
+ signal.signal(signal.SIGTERM, flush_on_term)
203
+ print("[TraceForge] Python tracing enabled", file=sys.stderr)
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.4
2
+ Name: traceforge-observability
3
+ Version: 0.1.0
4
+ Summary: TraceForge zero-code OpenTelemetry instrumentation for Python
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Repository, https://github.com/KeshavKandoi/TraceForge
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: python-dotenv<2,>=1.0
11
+ Requires-Dist: opentelemetry-sdk==1.34.1
12
+ Requires-Dist: opentelemetry-exporter-otlp-proto-common==1.34.1
13
+ Requires-Dist: opentelemetry-instrumentation-fastapi==0.55b1
14
+ Requires-Dist: opentelemetry-instrumentation-flask==0.55b1
15
+ Requires-Dist: opentelemetry-instrumentation-django==0.55b1
16
+ Requires-Dist: opentelemetry-instrumentation-requests==0.55b1
17
+ Requires-Dist: opentelemetry-instrumentation-httpx==0.55b1
18
+ Requires-Dist: opentelemetry-instrumentation-sqlalchemy==0.55b1
19
+ Requires-Dist: opentelemetry-instrumentation-psycopg==0.55b1
20
+ Requires-Dist: opentelemetry-instrumentation-psycopg2==0.55b1
21
+ Requires-Dist: opentelemetry-instrumentation-redis==0.55b1
22
+ Dynamic: license-file
23
+
24
+ # TraceForge for Python
25
+
26
+ Python 3.10+ instrumentation using the official OpenTelemetry SDK. Install the
27
+ distribution and configure the server environment with the workspace
28
+ `TRACEFORGE_DSN` and optionally `OTEL_SERVICE_NAME`. Start an existing application
29
+ with `traceforge-run uvicorn main:app` or `traceforge-run python app.py`.
30
+
31
+ The launcher reads `.env` from the working directory and preserves settings
32
+ provided by your host. It loads instrumentation before application imports.
33
+ Install the framework or database drivers your application normally uses.
34
+ For Django, set `DJANGO_SETTINGS_MODULE` before startup. Isolated Python modes
35
+ that skip site initialization cannot load the runtime.
36
+
37
+ The exporter retains trace relationships, timing, status, and allowlisted HTTP
38
+ metadata. It omits URLs, headers, query strings, SQL, Redis commands, payloads,
39
+ and exception messages. Set `TRACEFORGE_LOG_EXPORTS=1` to check storage receipts.
40
+
41
+ Framework and database version support follows the bundled OpenTelemetry
42
+ instrumentors. For example, the bundled SQLAlchemy instrumentor supports
43
+ SQLAlchemy before 2.1. The app can still run when an optional instrumentor
44
+ reports an incompatible dependency.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/traceforge_observability/__init__.py
5
+ src/traceforge_observability/cli.py
6
+ src/traceforge_observability/runtime.py
7
+ src/traceforge_observability.egg-info/PKG-INFO
8
+ src/traceforge_observability.egg-info/SOURCES.txt
9
+ src/traceforge_observability.egg-info/dependency_links.txt
10
+ src/traceforge_observability.egg-info/entry_points.txt
11
+ src/traceforge_observability.egg-info/requires.txt
12
+ src/traceforge_observability.egg-info/top_level.txt
13
+ src/traceforge_observability/_bootstrap/sitecustomize.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ traceforge-run = traceforge_observability.cli:main
@@ -0,0 +1,12 @@
1
+ python-dotenv<2,>=1.0
2
+ opentelemetry-sdk==1.34.1
3
+ opentelemetry-exporter-otlp-proto-common==1.34.1
4
+ opentelemetry-instrumentation-fastapi==0.55b1
5
+ opentelemetry-instrumentation-flask==0.55b1
6
+ opentelemetry-instrumentation-django==0.55b1
7
+ opentelemetry-instrumentation-requests==0.55b1
8
+ opentelemetry-instrumentation-httpx==0.55b1
9
+ opentelemetry-instrumentation-sqlalchemy==0.55b1
10
+ opentelemetry-instrumentation-psycopg==0.55b1
11
+ opentelemetry-instrumentation-psycopg2==0.55b1
12
+ opentelemetry-instrumentation-redis==0.55b1