juvera-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,175 @@
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 made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other transformations
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submit" means any form of electronic, verbal, or
51
+ written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of reporting and
55
+ discussing improvements to the Work, but excluding communication that is
56
+ conspicuously marked or designated in writing by the copyright owner as
57
+ "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those Contributions necessary to
76
+ make, have made, use, offer to sell, sell, import, and transfer said
77
+ Contributions. Notwithstanding the above, no patent license is granted
78
+ to any organization or individual for claims that are provable only by
79
+ reference to the patented article or process used in, transferred, or
80
+ incorporated into the Work.
81
+
82
+ 4. Redistribution. You may reproduce and distribute copies of the
83
+ Work or Derivative Works thereof in any medium, with or without
84
+ modifications, and in Source or Object form, provided that You
85
+ meet the following conditions:
86
+
87
+ (a) You must give any other recipients of the Work or Derivative Works
88
+ a copy of this License; and
89
+
90
+ (b) You must cause any modified files to carry prominent notices
91
+ stating that You changed the files; and
92
+
93
+ (c) You must retain, in the Source form of any Derivative Works
94
+ that You distribute, all copyright, patent, trademark, and
95
+ attribution notices from the Source form of the Work,
96
+ excluding those notices that do not pertain to any part of
97
+ the Derivative Works; and
98
+
99
+ (d) If the Work includes a "NOTICE" text file, as part of your
100
+ distribution, you must include a readable copy of the attribution
101
+ notices contained within such NOTICE file, in at least one of
102
+ the following places: within a text file distributed as part of
103
+ the Derivative Works; within the Source form or documentation,
104
+ if provided along with the Derivative Works; or, within a display
105
+ generated by the Derivative Works, if and wherever such
106
+ third-party notices normally appear. The contents of the NOTICE
107
+ file are for informational purposes only and do not modify the
108
+ License. You may add Your own attribution notices within Derivative
109
+ Works that You distribute, alongside or as an addendum to the NOTICE
110
+ text from the Work, provided that such additional attribution notices
111
+ cannot be construed as modifying the License.
112
+
113
+ You may add Your own license statement for Your modifications and may
114
+ provide additional grant of rights to use, copy, modify, merge, publish,
115
+ distribute, sublicense, and/or sell copies of the Work, and to permit
116
+ persons to whom the Work is provided to do so, subject to the following
117
+ conditions:
118
+
119
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
120
+ any Contribution intentionally submitted for inclusion in the Work
121
+ by You to the Licensor shall be under the terms and conditions of
122
+ this License, without any additional terms or conditions.
123
+ Notwithstanding the above, nothing herein shall supersede or modify
124
+ the terms of any separate license agreement you may have executed
125
+ with Licensor regarding such Contributions.
126
+
127
+ 6. Trademarks. This License does not grant permission to use the trade
128
+ names, trademarks, service marks, or product names of the Licensor,
129
+ except as required for reasonable and customary use in describing the
130
+ origin of the Work and reproducing the content of the NOTICE file.
131
+
132
+ 7. Disclaimer of Warranty. Unless required by applicable law or
133
+ agreed to in writing, Licensor provides the Work (and each
134
+ Contributor provides its Contributions) on an "AS IS" BASIS,
135
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
136
+ implied, including, without limitation, any conditions of title,
137
+ non-infringement, merchantability, or fitness for a particular purpose.
138
+ You are solely responsible for determining the appropriateness of using
139
+ or reproducing the Work and assume any risks associated with Your
140
+ exercise of permissions under this License.
141
+
142
+ 8. Limitation of Liability. In no event and under no legal theory,
143
+ whether in tort (including negligence), contract, or otherwise,
144
+ unless required by applicable law (such as deliberate and grossly
145
+ negligent acts) or agreed to in writing, shall any Contributor be
146
+ liable to You for damages, including any direct, indirect, special,
147
+ incidental, or exemplary damages of any character arising as a
148
+ result of this License or out of the use or inability to use the
149
+ Work (including but not limited to damages for loss of goodwill,
150
+ work stoppage, computer failure or malfunction, or all other
151
+ commercial damages or losses), even if such Contributor has been
152
+ advised of the possibility of such damages.
153
+
154
+ 9. Accepting Warranty or Additional Liability. While redistributing
155
+ the Work or Derivative Works thereof, You may choose to offer,
156
+ and charge a fee for, acceptance of support, warranty, indemnity,
157
+ or other liability obligations and/or rights consistent with this
158
+ License. However, in accepting such obligations, You may offer only
159
+ conditions consistent with this License.
160
+
161
+ END OF TERMS AND CONDITIONS
162
+
163
+ Copyright 2026 Juvera AI, Inc.
164
+
165
+ Licensed under the Apache License, Version 2.0 (the "License");
166
+ you may not use this file except in compliance with the License.
167
+ You may obtain a copy of the License at
168
+
169
+ http://www.apache.org/licenses/LICENSE-2.0
170
+
171
+ Unless required by applicable law or agreed to in writing, software
172
+ distributed under the License is distributed on an "AS IS" BASIS,
173
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
174
+ See the License for the specific language governing permissions and
175
+ limitations under the License.
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.4
2
+ Name: juvera-sdk
3
+ Version: 0.1.0
4
+ Summary: Open instrumentation SDK for Juvera — emit agent telemetry and business-impact signals
5
+ License: Apache-2.0
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: opentelemetry-sdk<2.0,>=1.20
10
+ Requires-Dist: pydantic<3.0,>=2.0
11
+ Requires-Dist: httpx<1.0,>=0.27
12
+ Requires-Dist: jsonschema<5.0,>=4.0
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest>=8.0; extra == "dev"
15
+ Requires-Dist: respx>=0.21; extra == "dev"
16
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ # juvera-python
20
+
21
+ Open instrumentation SDK for AI agent business-impact events.
22
+
23
+ ```bash
24
+ pip install juvera-sdk
25
+ ```
26
+
27
+ ---
28
+
29
+ ## What it is
30
+
31
+ `juvera-sdk` lets you instrument AI agents to emit **OTel-compatible traces** and **business-impact signals** to the Juvera ingest gateway. It answers one question: *how do I emit good data?* Nothing more.
32
+
33
+ ---
34
+
35
+ ## Quickstart
36
+
37
+ ```python
38
+ import juvera_sdk as j
39
+
40
+ j.init(
41
+ api_key="jvr_your_key",
42
+ org_id="org_your_org",
43
+ service_name="support-agent",
44
+ domain="support", # support | marketing | sales | custom
45
+ )
46
+
47
+ with j.agent_span(agent_id="agent_01", work_item_id="wi_ZD98765") as span:
48
+ span.set_model("claude-sonnet-4-6", provider="anthropic")
49
+ span.set_tokens(input=420, output=180)
50
+ span.add_tool_call("lookup_order_status", status="success")
51
+ # ... your agent logic ...
52
+
53
+ j.record_impact_signal(
54
+ impact_type="cost_reduction",
55
+ value=180.0,
56
+ impact_category="ticket_deflection",
57
+ source_system="zendesk",
58
+ )
59
+
60
+ j.flush()
61
+ ```
62
+
63
+ **Debug mode** — no network calls, prints to stdout:
64
+
65
+ ```python
66
+ j.init(api_key="any", org_id="org_test", endpoint="local")
67
+ ```
68
+
69
+ ---
70
+
71
+ ## What Juvera Cloud computes from this data
72
+
73
+ Once traces and signals reach the ingest gateway, the Juvera platform handles:
74
+
75
+ - **ROI attribution** — which agent actions drove which business outcomes
76
+ - **Benchmarking** — agent performance over time, by domain and workflow type
77
+ - **Compliance scoring** — policy adherence, human-in-the-loop rate, escalation patterns
78
+ - **Root cause analysis** — why deflection rates dropped, which tool failures cost the most
79
+
80
+ None of this logic is in this package. It runs server-side.
81
+
82
+ ---
83
+
84
+ ## What this SDK does not include
85
+
86
+ - Attribution engine
87
+ - Benchmarking or evaluation
88
+ - Compliance rules or scoring
89
+ - Dashboard or analytics
90
+ - Any API beyond `/v1/traces` and `/v1/impact-signals`
91
+
92
+ This package has no dependency on any closed Juvera service. `endpoint="local"` works fully offline.
93
+
94
+ ---
95
+
96
+ ## API reference
97
+
98
+ | Call | Description |
99
+ |------|-------------|
100
+ | `j.init(api_key, org_id, ...)` | Configure once at startup |
101
+ | `j.agent_span(agent_id, work_item_id, ...)` | Context manager for one unit of work. Yields `AgentSpan`. |
102
+ | `span.set_model(model, provider)` | Record which LLM was used |
103
+ | `span.set_tokens(input, output)` | Record token consumption |
104
+ | `span.add_tool_call(name, status)` | Record a tool/function call |
105
+ | `span.set_error(exception)` | Mark span as errored |
106
+ | `j.record_impact_signal(impact_type, value, ...)` | Emit a business outcome event |
107
+ | `j.record_handoff(reason, reviewer_role)` | Record a human-in-the-loop handoff |
108
+ | `j.flush()` | Force-export buffered spans before process exit |
109
+ | `j.shutdown()` | Release resources |
110
+
111
+ ### `work_item_id`
112
+
113
+ Every `agent_span()` is tied to a `work_item_id` — the unique identifier for one unit of agent work (e.g. a Zendesk ticket ID, a document ID, a task ID). This links spans to impact signals so Juvera can attribute outcomes to specific work items.
114
+
115
+ If you omit it, a UUID is generated automatically. Pass your own system's ID to enable cross-system attribution.
116
+
117
+ ---
118
+
119
+ ## Examples
120
+
121
+ - [`examples/01_manual_instrumentation.py`](examples/01_manual_instrumentation.py) — core loop
122
+ - [`examples/02_openai_assistant.py`](examples/02_openai_assistant.py) — wrapping an OpenAI call
123
+ - [`examples/03_langchain_agent.py`](examples/03_langchain_agent.py) — LangChain agent pattern
124
+
125
+ ---
126
+
127
+ ## License
128
+
129
+ Apache 2.0 — see [LICENSE](LICENSE).
130
+
131
+ Built by [Juvera](https://juvera.ai).
@@ -0,0 +1,113 @@
1
+ # juvera-python
2
+
3
+ Open instrumentation SDK for AI agent business-impact events.
4
+
5
+ ```bash
6
+ pip install juvera-sdk
7
+ ```
8
+
9
+ ---
10
+
11
+ ## What it is
12
+
13
+ `juvera-sdk` lets you instrument AI agents to emit **OTel-compatible traces** and **business-impact signals** to the Juvera ingest gateway. It answers one question: *how do I emit good data?* Nothing more.
14
+
15
+ ---
16
+
17
+ ## Quickstart
18
+
19
+ ```python
20
+ import juvera_sdk as j
21
+
22
+ j.init(
23
+ api_key="jvr_your_key",
24
+ org_id="org_your_org",
25
+ service_name="support-agent",
26
+ domain="support", # support | marketing | sales | custom
27
+ )
28
+
29
+ with j.agent_span(agent_id="agent_01", work_item_id="wi_ZD98765") as span:
30
+ span.set_model("claude-sonnet-4-6", provider="anthropic")
31
+ span.set_tokens(input=420, output=180)
32
+ span.add_tool_call("lookup_order_status", status="success")
33
+ # ... your agent logic ...
34
+
35
+ j.record_impact_signal(
36
+ impact_type="cost_reduction",
37
+ value=180.0,
38
+ impact_category="ticket_deflection",
39
+ source_system="zendesk",
40
+ )
41
+
42
+ j.flush()
43
+ ```
44
+
45
+ **Debug mode** — no network calls, prints to stdout:
46
+
47
+ ```python
48
+ j.init(api_key="any", org_id="org_test", endpoint="local")
49
+ ```
50
+
51
+ ---
52
+
53
+ ## What Juvera Cloud computes from this data
54
+
55
+ Once traces and signals reach the ingest gateway, the Juvera platform handles:
56
+
57
+ - **ROI attribution** — which agent actions drove which business outcomes
58
+ - **Benchmarking** — agent performance over time, by domain and workflow type
59
+ - **Compliance scoring** — policy adherence, human-in-the-loop rate, escalation patterns
60
+ - **Root cause analysis** — why deflection rates dropped, which tool failures cost the most
61
+
62
+ None of this logic is in this package. It runs server-side.
63
+
64
+ ---
65
+
66
+ ## What this SDK does not include
67
+
68
+ - Attribution engine
69
+ - Benchmarking or evaluation
70
+ - Compliance rules or scoring
71
+ - Dashboard or analytics
72
+ - Any API beyond `/v1/traces` and `/v1/impact-signals`
73
+
74
+ This package has no dependency on any closed Juvera service. `endpoint="local"` works fully offline.
75
+
76
+ ---
77
+
78
+ ## API reference
79
+
80
+ | Call | Description |
81
+ |------|-------------|
82
+ | `j.init(api_key, org_id, ...)` | Configure once at startup |
83
+ | `j.agent_span(agent_id, work_item_id, ...)` | Context manager for one unit of work. Yields `AgentSpan`. |
84
+ | `span.set_model(model, provider)` | Record which LLM was used |
85
+ | `span.set_tokens(input, output)` | Record token consumption |
86
+ | `span.add_tool_call(name, status)` | Record a tool/function call |
87
+ | `span.set_error(exception)` | Mark span as errored |
88
+ | `j.record_impact_signal(impact_type, value, ...)` | Emit a business outcome event |
89
+ | `j.record_handoff(reason, reviewer_role)` | Record a human-in-the-loop handoff |
90
+ | `j.flush()` | Force-export buffered spans before process exit |
91
+ | `j.shutdown()` | Release resources |
92
+
93
+ ### `work_item_id`
94
+
95
+ Every `agent_span()` is tied to a `work_item_id` — the unique identifier for one unit of agent work (e.g. a Zendesk ticket ID, a document ID, a task ID). This links spans to impact signals so Juvera can attribute outcomes to specific work items.
96
+
97
+ If you omit it, a UUID is generated automatically. Pass your own system's ID to enable cross-system attribution.
98
+
99
+ ---
100
+
101
+ ## Examples
102
+
103
+ - [`examples/01_manual_instrumentation.py`](examples/01_manual_instrumentation.py) — core loop
104
+ - [`examples/02_openai_assistant.py`](examples/02_openai_assistant.py) — wrapping an OpenAI call
105
+ - [`examples/03_langchain_agent.py`](examples/03_langchain_agent.py) — LangChain agent pattern
106
+
107
+ ---
108
+
109
+ ## License
110
+
111
+ Apache 2.0 — see [LICENSE](LICENSE).
112
+
113
+ Built by [Juvera](https://juvera.ai).
@@ -0,0 +1,51 @@
1
+ """Juvera SDK — open instrumentation for AI agents."""
2
+ from __future__ import annotations
3
+ from juvera_sdk.config import JuveraConfig
4
+ import juvera_sdk.tracer as _tracer
5
+
6
+ _config: JuveraConfig | None = None
7
+
8
+
9
+ def init(
10
+ api_key: str,
11
+ org_id: str,
12
+ endpoint: str = "https://ingest.juvera.ai",
13
+ service_name: str = "juvera-agent",
14
+ domain: str | None = None,
15
+ agent_id: str | None = None,
16
+ debug: bool = False,
17
+ _exporter=None, # test hook
18
+ ) -> None:
19
+ """Configure the SDK. Call once at startup before any spans."""
20
+ global _config
21
+ _config = JuveraConfig(
22
+ api_key=api_key, org_id=org_id, endpoint=endpoint,
23
+ service_name=service_name, domain=domain, agent_id=agent_id, debug=debug,
24
+ )
25
+ _tracer.setup_provider(_config, exporter=_exporter)
26
+
27
+
28
+ def _get_config() -> JuveraConfig:
29
+ if _config is None:
30
+ raise RuntimeError("juvera.init() must be called before using the SDK")
31
+ return _config
32
+
33
+
34
+ def flush() -> None:
35
+ _tracer.flush()
36
+
37
+
38
+ def shutdown() -> None:
39
+ global _config
40
+ _tracer.shutdown()
41
+ _config = None
42
+
43
+
44
+ from juvera_sdk.span import agent_span # noqa: E402
45
+ from juvera_sdk.signals import record_impact_signal # noqa: E402
46
+ from juvera_sdk.handoff import record_handoff # noqa: E402
47
+
48
+ __all__ = [
49
+ "init", "agent_span", "record_impact_signal",
50
+ "record_handoff", "flush", "shutdown",
51
+ ]
@@ -0,0 +1,32 @@
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass, field
3
+
4
+
5
+ @dataclass(frozen=True)
6
+ class JuveraConfig:
7
+ api_key: str
8
+ org_id: str
9
+ endpoint: str = "https://ingest.juvera.ai"
10
+ service_name: str = "juvera-agent"
11
+ domain: str | None = None
12
+ agent_id: str | None = None
13
+ debug: bool = False
14
+ human_reviewer_cost_per_hour_usd: float = 50.0
15
+
16
+ def __post_init__(self):
17
+ if not self.api_key:
18
+ raise ValueError("api_key is required")
19
+ if not self.org_id:
20
+ raise ValueError("org_id is required")
21
+
22
+ @property
23
+ def is_local(self) -> bool:
24
+ return self.endpoint == "local"
25
+
26
+ @property
27
+ def traces_url(self) -> str:
28
+ return f"{self.endpoint.rstrip('/')}/v1/traces"
29
+
30
+ @property
31
+ def signals_url(self) -> str:
32
+ return f"{self.endpoint.rstrip('/')}/v1/impact-signals"
@@ -0,0 +1,13 @@
1
+ """Context variable storage for work items and request-scoped data."""
2
+ from __future__ import annotations
3
+ from contextvars import ContextVar
4
+
5
+ _work_item_id: ContextVar[str | None] = ContextVar("juvera_work_item_id", default=None)
6
+
7
+
8
+ def get_work_item_id() -> str | None:
9
+ return _work_item_id.get()
10
+
11
+
12
+ def set_work_item_id(value: str | None):
13
+ return _work_item_id.set(value)
@@ -0,0 +1,17 @@
1
+ # juvera_sdk/costs.py
2
+
3
+ MODEL_COSTS_USD_PER_TOKEN: dict[str, dict[str, float]] = {
4
+ "claude-sonnet-4-6": {"input": 3.00 / 1e6, "output": 15.00 / 1e6},
5
+ "claude-opus-4-6": {"input": 15.00 / 1e6, "output": 75.00 / 1e6},
6
+ "claude-haiku-4-5-20251001": {"input": 0.25 / 1e6, "output": 1.25 / 1e6},
7
+ "gpt-4o": {"input": 2.50 / 1e6, "output": 10.00 / 1e6},
8
+ "gpt-4o-mini": {"input": 0.15 / 1e6, "output": 0.60 / 1e6},
9
+ "gemini-1.5-pro": {"input": 3.50 / 1e6, "output": 10.50 / 1e6},
10
+ "gemini-1.5-flash": {"input": 0.075 / 1e6, "output": 0.30 / 1e6},
11
+ }
12
+
13
+
14
+ def compute_token_cost_usd(model: str, input_tokens: int, output_tokens: int) -> float:
15
+ costs = MODEL_COSTS_USD_PER_TOKEN.get(model, {})
16
+ return (input_tokens * costs.get("input", 0.0) +
17
+ output_tokens * costs.get("output", 0.0))
File without changes
@@ -0,0 +1,22 @@
1
+ """Debug exporter for local development."""
2
+ from __future__ import annotations
3
+ import json
4
+ from opentelemetry.sdk.trace import ReadableSpan
5
+ from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
6
+
7
+
8
+ class DebugExporter(SpanExporter):
9
+ """Prints spans to stdout. Activated by endpoint='local'."""
10
+
11
+ def export(self, spans: list[ReadableSpan]) -> SpanExportResult:
12
+ for span in spans:
13
+ attrs = dict(span.attributes or {})
14
+ print(f"[juvera-debug] SPAN name={span.name!r} "
15
+ f"trace_id={format(span.context.trace_id, '032x')} "
16
+ f"agent_id={attrs.get('juvera.agent_id')} "
17
+ f"work_item_id={attrs.get('juvera.work_item_id')} "
18
+ f"attrs={json.dumps(attrs, default=str)}")
19
+ return SpanExportResult.SUCCESS
20
+
21
+ def shutdown(self) -> None:
22
+ pass
@@ -0,0 +1,83 @@
1
+ """HTTP exporter for Juvera SDK."""
2
+ from __future__ import annotations
3
+ import httpx
4
+ from opentelemetry.sdk.trace import ReadableSpan
5
+ from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
6
+ from juvera_sdk.config import JuveraConfig
7
+
8
+
9
+ def _otel_value(v) -> dict:
10
+ """Convert a Python value to OTel attribute value format."""
11
+ if isinstance(v, bool):
12
+ return {"boolValue": v}
13
+ if isinstance(v, int):
14
+ return {"intValue": v}
15
+ if isinstance(v, float):
16
+ return {"doubleValue": v}
17
+ return {"stringValue": str(v)}
18
+
19
+
20
+ def _attrs_list(attrs: dict | None) -> list[dict]:
21
+ if not attrs:
22
+ return []
23
+ return [{"key": k, "value": _otel_value(v)} for k, v in attrs.items()]
24
+
25
+
26
+ class JuveraSpanExporter(SpanExporter):
27
+ """
28
+ Exports OTel spans to the Juvera ingest gateway as TraceIngestEnvelope JSON.
29
+ One HTTP POST per export() call (batch).
30
+ """
31
+
32
+ def __init__(self, config: JuveraConfig):
33
+ self._config = config
34
+
35
+ def export(self, spans: list[ReadableSpan]) -> SpanExportResult:
36
+ if not spans:
37
+ return SpanExportResult.SUCCESS
38
+
39
+ # Build resourceSpans grouped by trace_id (simple: one resource block)
40
+ # Resource attrs come from the first span's resource
41
+ resource = spans[0].resource
42
+ resource_attrs = _attrs_list(dict(resource.attributes or {}))
43
+
44
+ otel_spans = []
45
+ for span in spans:
46
+ attrs = _attrs_list(dict(span.attributes or {}))
47
+ otel_spans.append({
48
+ "traceId": format(span.context.trace_id, "032x"),
49
+ "spanId": format(span.context.span_id, "016x"),
50
+ "name": span.name,
51
+ "startTimeUnixNano": str(span.start_time),
52
+ "endTimeUnixNano": str(span.end_time or span.start_time),
53
+ "attributes": attrs,
54
+ })
55
+
56
+ envelope = {
57
+ "resourceSpans": [{
58
+ "resource": {"attributes": resource_attrs},
59
+ "scopeSpans": [{
60
+ "scope": {"name": "juvera-sdk"},
61
+ "spans": otel_spans,
62
+ }],
63
+ }]
64
+ }
65
+
66
+ try:
67
+ resp = httpx.post(
68
+ self._config.traces_url,
69
+ json=envelope,
70
+ headers={
71
+ "X-API-Key": self._config.api_key,
72
+ "Content-Type": "application/json",
73
+ },
74
+ timeout=10.0,
75
+ )
76
+ resp.raise_for_status()
77
+ return SpanExportResult.SUCCESS
78
+ except Exception as exc:
79
+ print(f"[juvera-sdk] export failed: {exc}")
80
+ return SpanExportResult.FAILURE
81
+
82
+ def shutdown(self) -> None:
83
+ pass
@@ -0,0 +1,30 @@
1
+ """Mock exporter for testing."""
2
+ from __future__ import annotations
3
+ from opentelemetry.sdk.trace import ReadableSpan
4
+ from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
5
+
6
+
7
+ class MockExporter(SpanExporter):
8
+ """Captures spans in memory. Use in tests — no network calls."""
9
+
10
+ def __init__(self):
11
+ self._spans: list[ReadableSpan] = []
12
+
13
+ def export(self, spans: list[ReadableSpan]) -> SpanExportResult:
14
+ self._spans.extend(spans)
15
+ return SpanExportResult.SUCCESS
16
+
17
+ def shutdown(self) -> None:
18
+ pass
19
+
20
+ def span_count(self) -> int:
21
+ return len(self._spans)
22
+
23
+ def last_span(self) -> ReadableSpan | None:
24
+ return self._spans[-1] if self._spans else None
25
+
26
+ def all_spans(self) -> list[ReadableSpan]:
27
+ return list(self._spans)
28
+
29
+ def clear(self) -> None:
30
+ self._spans.clear()