@langwatch/server 3.1.0-beta.7 → 3.1.0-beta.9

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.
Files changed (144) hide show
  1. package/package.json +1 -6
  2. package/packages/server/dist/cli.cjs +23 -17
  3. package/cmd/service/main.go +0 -68
  4. package/go.mod +0 -117
  5. package/go.sum +0 -299
  6. package/pkg/breaker/breaker.go +0 -157
  7. package/pkg/breaker/breaker_test.go +0 -131
  8. package/pkg/clog/LICENSE +0 -26
  9. package/pkg/clog/clog.go +0 -90
  10. package/pkg/clog/clog_test.go +0 -56
  11. package/pkg/clog/panic.go +0 -39
  12. package/pkg/config/LICENSE +0 -26
  13. package/pkg/config/config.go +0 -86
  14. package/pkg/config/config_test.go +0 -70
  15. package/pkg/config/otel.go +0 -50
  16. package/pkg/config/server.go +0 -61
  17. package/pkg/config/validate.go +0 -80
  18. package/pkg/config/validate_test.go +0 -74
  19. package/pkg/contexts/contexts_test.go +0 -34
  20. package/pkg/contexts/request_id.go +0 -1
  21. package/pkg/contexts/service_info.go +0 -33
  22. package/pkg/errfuncs/errfuncs.go +0 -9
  23. package/pkg/errfuncs/errfuncs_test.go +0 -28
  24. package/pkg/forkedcontext/forkedcontext.go +0 -57
  25. package/pkg/health/health.go +0 -123
  26. package/pkg/health/health_test.go +0 -84
  27. package/pkg/herr/LICENSE +0 -26
  28. package/pkg/herr/code.go +0 -14
  29. package/pkg/herr/herr.go +0 -112
  30. package/pkg/herr/herr_test.go +0 -78
  31. package/pkg/herr/http.go +0 -133
  32. package/pkg/herr/http_test.go +0 -103
  33. package/pkg/herr/validate.go +0 -72
  34. package/pkg/herr/validate_test.go +0 -75
  35. package/pkg/httpmiddleware/bearer.go +0 -47
  36. package/pkg/httpmiddleware/httputil_test.go +0 -167
  37. package/pkg/httpmiddleware/inflight.go +0 -23
  38. package/pkg/httpmiddleware/maxbody.go +0 -30
  39. package/pkg/httpmiddleware/recover.go +0 -38
  40. package/pkg/httpmiddleware/requestid.go +0 -40
  41. package/pkg/httpmiddleware/telemetry.go +0 -96
  42. package/pkg/httpmiddleware/version.go +0 -16
  43. package/pkg/jwtverify/verifier.go +0 -72
  44. package/pkg/jwtverify/verifier_test.go +0 -134
  45. package/pkg/ksuid/LICENSE +0 -26
  46. package/pkg/ksuid/ksuid.go +0 -157
  47. package/pkg/ksuid/ksuid_test.go +0 -107
  48. package/pkg/ksuid/resources.go +0 -13
  49. package/pkg/lifecycle/group.go +0 -175
  50. package/pkg/lifecycle/group_test.go +0 -236
  51. package/pkg/lifecycle/service.go +0 -112
  52. package/pkg/netprobe/netprobe.go +0 -89
  53. package/pkg/netprobe/netprobe_test.go +0 -55
  54. package/pkg/otelsetup/otelsetup.go +0 -226
  55. package/pkg/otelsetup/otelsetup_test.go +0 -130
  56. package/pkg/ptr/LICENSE +0 -26
  57. package/pkg/ptr/ptr.go +0 -34
  58. package/pkg/ptr/ptr_test.go +0 -66
  59. package/pkg/retry/bench_test.go +0 -67
  60. package/pkg/retry/retry.go +0 -188
  61. package/pkg/retry/retry_test.go +0 -222
  62. package/pkg/slicefuncs/LICENSE +0 -26
  63. package/pkg/slicefuncs/slicefuncs.go +0 -10
  64. package/pkg/slicefuncs/slicefuncs_test.go +0 -29
  65. package/pkg/stacktrace/LICENSE +0 -26
  66. package/pkg/stacktrace/frames.go +0 -77
  67. package/pkg/stacktrace/frames_test.go +0 -73
  68. package/services/aigateway/BENCHMARKS.md +0 -110
  69. package/services/aigateway/README.md +0 -156
  70. package/services/aigateway/adapters/authresolver/bench_test.go +0 -13
  71. package/services/aigateway/adapters/authresolver/redis.go +0 -61
  72. package/services/aigateway/adapters/authresolver/service.go +0 -442
  73. package/services/aigateway/adapters/authresolver/service_test.go +0 -435
  74. package/services/aigateway/adapters/budget/bench_test.go +0 -50
  75. package/services/aigateway/adapters/budget/budget.go +0 -59
  76. package/services/aigateway/adapters/cacherules/evaluator.go +0 -134
  77. package/services/aigateway/adapters/cacherules/evaluator_test.go +0 -207
  78. package/services/aigateway/adapters/controlplane/bench_test.go +0 -40
  79. package/services/aigateway/adapters/controlplane/client.go +0 -213
  80. package/services/aigateway/adapters/controlplane/client_test.go +0 -73
  81. package/services/aigateway/adapters/controlplane/config_wire.go +0 -310
  82. package/services/aigateway/adapters/controlplane/guardrails.go +0 -88
  83. package/services/aigateway/adapters/controlplane/signer.go +0 -95
  84. package/services/aigateway/adapters/controlplane/signer_test.go +0 -64
  85. package/services/aigateway/adapters/customertracebridge/context.go +0 -48
  86. package/services/aigateway/adapters/customertracebridge/context_test.go +0 -24
  87. package/services/aigateway/adapters/customertracebridge/emitter.go +0 -329
  88. package/services/aigateway/adapters/customertracebridge/emitter_test.go +0 -93
  89. package/services/aigateway/adapters/customertracebridge/registry.go +0 -82
  90. package/services/aigateway/adapters/customertracebridge/transport.go +0 -122
  91. package/services/aigateway/adapters/gatewaytracer/attrs.go +0 -28
  92. package/services/aigateway/adapters/gatewaytracer/attrs_genai.go +0 -24
  93. package/services/aigateway/adapters/gatewaytracer/headers.go +0 -8
  94. package/services/aigateway/adapters/gatewaytracer/tracer.go +0 -101
  95. package/services/aigateway/adapters/httpapi/bench_test.go +0 -83
  96. package/services/aigateway/adapters/httpapi/middleware.go +0 -123
  97. package/services/aigateway/adapters/httpapi/router.go +0 -635
  98. package/services/aigateway/adapters/httpapi/router_test.go +0 -633
  99. package/services/aigateway/adapters/modelresolver/resolver.go +0 -107
  100. package/services/aigateway/adapters/modelresolver/resolver_test.go +0 -140
  101. package/services/aigateway/adapters/policy/matcher.go +0 -250
  102. package/services/aigateway/adapters/policy/matcher_test.go +0 -124
  103. package/services/aigateway/adapters/providers/bifrost.go +0 -798
  104. package/services/aigateway/adapters/providers/bifrost_parser.go +0 -201
  105. package/services/aigateway/adapters/providers/bifrost_test.go +0 -181
  106. package/services/aigateway/adapters/ratelimit/limiter.go +0 -122
  107. package/services/aigateway/adapters/ratelimit/limiter_test.go +0 -81
  108. package/services/aigateway/app/app.go +0 -104
  109. package/services/aigateway/app/dispatch.go +0 -89
  110. package/services/aigateway/app/dispatch_test.go +0 -475
  111. package/services/aigateway/app/handlers.go +0 -79
  112. package/services/aigateway/app/peek_bench_test.go +0 -21
  113. package/services/aigateway/app/pipeline/bench_test.go +0 -34
  114. package/services/aigateway/app/pipeline/budget.go +0 -55
  115. package/services/aigateway/app/pipeline/cache.go +0 -34
  116. package/services/aigateway/app/pipeline/cachecontrol.go +0 -86
  117. package/services/aigateway/app/pipeline/cachecontrol_test.go +0 -110
  118. package/services/aigateway/app/pipeline/guardrail.go +0 -121
  119. package/services/aigateway/app/pipeline/pipeline.go +0 -159
  120. package/services/aigateway/app/pipeline/policy.go +0 -23
  121. package/services/aigateway/app/pipeline/ratelimit.go +0 -21
  122. package/services/aigateway/app/pipeline/rawframing_test.go +0 -67
  123. package/services/aigateway/app/pipeline/resolve.go +0 -44
  124. package/services/aigateway/app/pipeline/trace.go +0 -129
  125. package/services/aigateway/app/ports.go +0 -61
  126. package/services/aigateway/cmd/root.go +0 -42
  127. package/services/aigateway/config.go +0 -86
  128. package/services/aigateway/deps.go +0 -177
  129. package/services/aigateway/domain/bundle.go +0 -203
  130. package/services/aigateway/domain/errors.go +0 -23
  131. package/services/aigateway/domain/model.go +0 -24
  132. package/services/aigateway/domain/provider.go +0 -38
  133. package/services/aigateway/domain/request.go +0 -65
  134. package/services/aigateway/domain/response.go +0 -56
  135. package/services/aigateway/domain/verdict.go +0 -55
  136. package/services/aigateway/serve.go +0 -45
  137. package/services/aigateway/tests/matrix/README.md +0 -71
  138. package/services/aigateway/tests/matrix/anthropic_test.go +0 -61
  139. package/services/aigateway/tests/matrix/azure_test.go +0 -52
  140. package/services/aigateway/tests/matrix/bedrock_test.go +0 -69
  141. package/services/aigateway/tests/matrix/gemini_test.go +0 -117
  142. package/services/aigateway/tests/matrix/matrix_test.go +0 -601
  143. package/services/aigateway/tests/matrix/openai_test.go +0 -66
  144. package/services/aigateway/tests/matrix/vertex_test.go +0 -160
@@ -1,329 +0,0 @@
1
- package customertracebridge
2
-
3
- import (
4
- "context"
5
- "encoding/hex"
6
- "fmt"
7
- "strings"
8
- "time"
9
-
10
- "github.com/tidwall/gjson"
11
- "go.opentelemetry.io/otel/attribute"
12
- "go.opentelemetry.io/otel/propagation"
13
- "go.opentelemetry.io/otel/sdk/resource"
14
- sdktrace "go.opentelemetry.io/otel/sdk/trace"
15
- semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
16
- "go.opentelemetry.io/otel/trace"
17
-
18
- "github.com/langwatch/langwatch/pkg/contexts"
19
- "github.com/langwatch/langwatch/services/aigateway/adapters/gatewaytracer"
20
- "github.com/langwatch/langwatch/services/aigateway/domain"
21
- )
22
-
23
- const (
24
- attrProjectID = attribute.Key("langwatch.project_id")
25
- attrTotalUsage = attribute.Key("gen_ai.usage.total_tokens")
26
- attrCost = attribute.Key("gen_ai.usage.cost")
27
- attrInputMessages = attribute.Key("gen_ai.input.messages")
28
- attrOutputMessages = attribute.Key("gen_ai.output.messages")
29
- )
30
-
31
- // Emitter uses a private (non-global) OTel TracerProvider to construct spans
32
- // and export them to the customer's OTLP endpoint. The TP has an empty Resource
33
- // so customers only see the instrumentation scope, not the gateway's service identity.
34
- type Emitter struct {
35
- tp *sdktrace.TracerProvider
36
- tracer trace.Tracer
37
- propagator propagation.TextMapPropagator
38
- }
39
-
40
- // EmitterOptions configures the Emitter.
41
- type EmitterOptions struct {
42
- Registry *Registry
43
- BatchTimeout time.Duration
44
- MaxQueueSize int
45
- }
46
-
47
- // NewEmitter creates a customer trace bridge backed by a private TracerProvider.
48
- func NewEmitter(ctx context.Context, opts EmitterOptions) (*Emitter, error) {
49
- if opts.Registry == nil {
50
- opts.Registry = NewRegistry()
51
- }
52
-
53
- router := newRouterExporter(opts.Registry)
54
-
55
- batchTimeout := opts.BatchTimeout
56
- if batchTimeout == 0 {
57
- batchTimeout = 5 * time.Second
58
- }
59
- queueSize := opts.MaxQueueSize
60
- if queueSize == 0 {
61
- queueSize = 8192
62
- }
63
-
64
- // Empty resource — customers see instrumentation scope only.
65
- // AlwaysSample: the gateway never drops customer spans regardless of
66
- // the gateway's own sample ratio setting.
67
- tp := sdktrace.NewTracerProvider(
68
- sdktrace.WithResource(resource.Empty()),
69
- sdktrace.WithBatcher(router,
70
- sdktrace.WithBatchTimeout(batchTimeout),
71
- sdktrace.WithMaxQueueSize(queueSize),
72
- ),
73
- sdktrace.WithSampler(sdktrace.AlwaysSample()),
74
- )
75
-
76
- svcCtx := contexts.MustGetServiceInfo(ctx)
77
-
78
- return &Emitter{
79
- tp: tp,
80
- tracer: tp.Tracer(fmt.Sprintf("langwatch-%s", svcCtx.Service), trace.WithInstrumentationVersion(svcCtx.Version)),
81
- propagator: propagation.TraceContext{},
82
- }, nil
83
- }
84
-
85
- // BeginSpan starts a customer-facing span that nests under the customer's
86
- // inbound traceparent. It returns an enriched context (carrying the open span)
87
- // and a W3C traceparent string representing the new span.
88
- func (e *Emitter) BeginSpan(ctx context.Context, projectID string, reqType domain.RequestType) (context.Context, string) {
89
- tp := TraceParent(ctx)
90
- spanCtx := e.customerSpanContext(tp)
91
-
92
- //nolint:spancheck // span lifecycle is split across BeginSpan/EndSpan via activeSpan context key by design.
93
- spanCtx, span := e.tracer.Start(spanCtx, "gen_ai."+string(reqType),
94
- trace.WithSpanKind(trace.SpanKindClient),
95
- trace.WithAttributes(
96
- attrProjectID.String(projectID),
97
- semconv.GenAIOperationNameKey.String(string(reqType)),
98
- ),
99
- )
100
-
101
- // Store the span in request context so EndSpan can retrieve it.
102
- ctx = withActiveSpan(ctx, span)
103
-
104
- // Format the span's context as a W3C traceparent for the response header.
105
- sc := span.SpanContext()
106
- traceparent := formatTraceparent(sc)
107
-
108
- _ = spanCtx // span lifecycle managed via activeSpan context key
109
- //nolint:spancheck // span ends in EndSpan, retrieved via activeSpan context key.
110
- return ctx, traceparent
111
- }
112
-
113
- // EndSpan retrieves the span started by BeginSpan, sets final attributes, and
114
- // ends it. If no span is found in context this is a no-op.
115
- func (e *Emitter) EndSpan(ctx context.Context, params domain.AITraceParams) {
116
- span := activeSpanFrom(ctx)
117
- if span == nil {
118
- return
119
- }
120
-
121
- attrs := []attribute.KeyValue{
122
- semconv.GenAIProviderNameKey.String(string(params.ProviderID)),
123
- semconv.GenAIRequestModelKey.String(params.Model),
124
- semconv.GenAIUsageInputTokensKey.Int(params.Usage.PromptTokens),
125
- semconv.GenAIUsageOutputTokensKey.Int(params.Usage.CompletionTokens),
126
- attrTotalUsage.Int(params.Usage.TotalTokens),
127
- attrCost.Int64(params.Usage.CostMicroUSD),
128
- }
129
- // VK id + request id let the control plane's trace-processing pipeline
130
- // identify gateway traces and fold idempotent budget debits into ClickHouse.
131
- // See specs/ai-gateway/_shared/contract.md §4.5.
132
- if params.VirtualKeyID != "" {
133
- attrs = append(attrs, attribute.String(gatewaytracer.AttrVirtualKeyID, params.VirtualKeyID))
134
- }
135
- if params.GatewayRequestID != "" {
136
- attrs = append(attrs, attribute.String(gatewaytracer.AttrGatewayReqID, params.GatewayRequestID))
137
- }
138
- span.SetAttributes(attrs...)
139
-
140
- if input := extractInputMessages(params.RequestBody, params.RequestType); input != "" {
141
- span.SetAttributes(attrInputMessages.String(input))
142
- }
143
- if output := extractOutputMessages(params.ResponseBody, params.RequestType); output != "" {
144
- span.SetAttributes(attrOutputMessages.String(output))
145
- }
146
-
147
- span.End()
148
- }
149
-
150
- // Shutdown flushes pending spans to customer endpoints.
151
- func (e *Emitter) Shutdown(ctx context.Context) error {
152
- if e.tp != nil {
153
- return e.tp.Shutdown(ctx)
154
- }
155
- return nil
156
- }
157
-
158
- // customerSpanContext builds a context with the customer's trace/span IDs as
159
- // the parent, using a fresh context.Background() — never the request context.
160
- func (e *Emitter) customerSpanContext(traceparent string) context.Context {
161
- if traceparent == "" {
162
- // No customer traceparent — span will be a new root trace.
163
- return context.Background()
164
- }
165
-
166
- // Use the W3C propagator to extract into a clean context.
167
- carrier := propagation.MapCarrier{"traceparent": traceparent}
168
- return e.propagator.Extract(context.Background(), carrier)
169
- }
170
-
171
- // formatTraceparent formats a SpanContext as a W3C traceparent header value.
172
- func formatTraceparent(sc trace.SpanContext) string {
173
- if !sc.IsValid() {
174
- return ""
175
- }
176
- flags := "00"
177
- if sc.IsSampled() {
178
- flags = "01"
179
- }
180
- return fmt.Sprintf("00-%s-%s-%s", sc.TraceID().String(), sc.SpanID().String(), flags)
181
- }
182
-
183
- // parseTraceparent extracts trace ID and parent span ID from a W3C traceparent
184
- // header: "00-<traceID>-<spanID>-<flags>"
185
- func parseTraceparent(tp string) (traceID []byte, spanID []byte) {
186
- if tp == "" {
187
- return nil, nil
188
- }
189
- parts := strings.Split(tp, "-")
190
- if len(parts) < 4 {
191
- return nil, nil
192
- }
193
- tid, err := hex.DecodeString(parts[1])
194
- if err != nil || len(tid) != 16 {
195
- return nil, nil
196
- }
197
- sid, err := hex.DecodeString(parts[2])
198
- if err != nil || len(sid) != 8 {
199
- return nil, nil
200
- }
201
- return tid, sid
202
- }
203
-
204
- // extractInputMessages returns the JSON-encoded messages array from the request body.
205
- func extractInputMessages(body []byte, reqType domain.RequestType) string {
206
- if len(body) == 0 {
207
- return ""
208
- }
209
- // Gemini-native /v1beta passthrough bodies carry `contents` not
210
- // `messages`. Convert to a synthetic chat-completion `messages`
211
- // shape so the LangWatch trace viewer renders the conversation
212
- // the same way it does for the OpenAI / Anthropic surfaces.
213
- if reqType == domain.RequestTypePassthrough {
214
- return geminiContentsAsMessages(body)
215
- }
216
- r := gjson.GetBytes(body, "messages")
217
- if !r.Exists() {
218
- return ""
219
- }
220
- return r.Raw
221
- }
222
-
223
- // geminiContentsAsMessages flattens Gemini's `systemInstruction` +
224
- // `contents[]` into a chat-style `[{role, content}, …]` array. Gemini's
225
- // roles are "user" / "model"; the latter maps to "assistant" so the
226
- // downstream trace viewer doesn't render an unknown role badge.
227
- func geminiContentsAsMessages(body []byte) string {
228
- var msgs []string
229
- if sys := gjson.GetBytes(body, "systemInstruction"); sys.Exists() {
230
- text := joinGeminiPartsText(sys.Get("parts"))
231
- if text != "" {
232
- msgs = append(msgs, fmt.Sprintf(`{"role":"system","content":%q}`, text))
233
- }
234
- }
235
- contents := gjson.GetBytes(body, "contents")
236
- if !contents.Exists() {
237
- if len(msgs) == 0 {
238
- return ""
239
- }
240
- return "[" + strings.Join(msgs, ",") + "]"
241
- }
242
- contents.ForEach(func(_, v gjson.Result) bool {
243
- role := v.Get("role").String()
244
- if role == "model" {
245
- role = "assistant"
246
- }
247
- if role == "" {
248
- role = "user"
249
- }
250
- text := joinGeminiPartsText(v.Get("parts"))
251
- if text == "" {
252
- return true
253
- }
254
- msgs = append(msgs, fmt.Sprintf(`{"role":%q,"content":%q}`, role, text))
255
- return true
256
- })
257
- if len(msgs) == 0 {
258
- return ""
259
- }
260
- return "[" + strings.Join(msgs, ",") + "]"
261
- }
262
-
263
- // joinGeminiPartsText concatenates all `parts[].text` fields, ignoring
264
- // non-text part types (functionCall / functionResponse / inlineData) for
265
- // the trace-viewer string rendering.
266
- func joinGeminiPartsText(parts gjson.Result) string {
267
- if !parts.Exists() || !parts.IsArray() {
268
- return ""
269
- }
270
- var out strings.Builder
271
- parts.ForEach(func(_, p gjson.Result) bool {
272
- if t := p.Get("text"); t.Exists() {
273
- if out.Len() > 0 {
274
- out.WriteByte('\n')
275
- }
276
- out.WriteString(t.String())
277
- }
278
- return true
279
- })
280
- return out.String()
281
- }
282
-
283
- // extractOutputMessages returns the JSON-encoded assistant message(s) from the response body.
284
- func extractOutputMessages(body []byte, reqType domain.RequestType) string {
285
- if len(body) == 0 {
286
- return ""
287
- }
288
- switch reqType {
289
- case domain.RequestTypeChat:
290
- // OpenAI: choices[].message
291
- choices := gjson.GetBytes(body, "choices")
292
- if !choices.Exists() {
293
- return ""
294
- }
295
- var msgs []string
296
- choices.ForEach(func(_, v gjson.Result) bool {
297
- msg := v.Get("message")
298
- if msg.Exists() {
299
- msgs = append(msgs, msg.Raw)
300
- }
301
- return true
302
- })
303
- if len(msgs) == 0 {
304
- return ""
305
- }
306
- return "[" + strings.Join(msgs, ",") + "]"
307
- case domain.RequestTypeMessages:
308
- // Anthropic: content array is the output, wrap as assistant message
309
- content := gjson.GetBytes(body, "content")
310
- if !content.Exists() {
311
- return ""
312
- }
313
- return `[{"role":"assistant","content":` + content.Raw + `}]`
314
- case domain.RequestTypePassthrough:
315
- // Gemini-native: candidates[].content.parts[].text. The bytes here
316
- // are either a single :generateContent JSON or the concatenated
317
- // SSE chunks from streamGenerateContent (the trace wrapper now
318
- // stamps the LAST chunk's body); both use the same nested shape.
319
- text := joinGeminiPartsText(
320
- gjson.GetBytes(body, "candidates.0.content.parts"),
321
- )
322
- if text == "" {
323
- return ""
324
- }
325
- return fmt.Sprintf(`[{"role":"assistant","content":%q}]`, text)
326
- default:
327
- return ""
328
- }
329
- }
@@ -1,93 +0,0 @@
1
- package customertracebridge
2
-
3
- import (
4
- "testing"
5
-
6
- "github.com/stretchr/testify/assert"
7
- )
8
-
9
- func TestParseTraceparent_valid(t *testing.T) {
10
- tp := "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
11
- traceID, spanID := parseTraceparent(tp)
12
- assert.Len(t, traceID, 16)
13
- assert.Len(t, spanID, 8)
14
- assert.Equal(t, "4bf92f3577b34da6a3ce929d0e0e4736", hexEncode(traceID))
15
- assert.Equal(t, "00f067aa0ba902b7", hexEncode(spanID))
16
- }
17
-
18
- func TestParseTraceparent_empty(t *testing.T) {
19
- traceID, spanID := parseTraceparent("")
20
- assert.Nil(t, traceID)
21
- assert.Nil(t, spanID)
22
- }
23
-
24
- func TestParseTraceparent_malformed(t *testing.T) {
25
- tests := []string{
26
- "not-a-traceparent",
27
- "00-short-00f067aa0ba902b7-01",
28
- "00-4bf92f3577b34da6a3ce929d0e0e4736-short-01",
29
- }
30
- for _, tp := range tests {
31
- traceID, spanID := parseTraceparent(tp)
32
- assert.Nil(t, traceID, "traceparent: %s", tp)
33
- assert.Nil(t, spanID, "traceparent: %s", tp)
34
- }
35
- }
36
-
37
- func TestRegistry_Set_ValidatesScheme(t *testing.T) {
38
- tests := []struct {
39
- name string
40
- endpoint string
41
- wantErr bool
42
- }{
43
- {name: "https allowed", endpoint: "https://otel.internal:4318", wantErr: false},
44
- {name: "http allowed", endpoint: "http://localhost:4318", wantErr: false},
45
- {name: "empty clears entry", endpoint: "", wantErr: false},
46
- {name: "ftp rejected", endpoint: "ftp://evil.com/exfil", wantErr: true},
47
- {name: "file rejected", endpoint: "file:///etc/passwd", wantErr: true},
48
- {name: "javascript rejected", endpoint: "javascript:alert(1)", wantErr: true},
49
- {name: "no scheme rejected", endpoint: "evil.com:4318", wantErr: true},
50
- {name: "data uri rejected", endpoint: "data:text/plain,hello", wantErr: true},
51
- }
52
-
53
- for _, tt := range tests {
54
- t.Run(tt.name, func(t *testing.T) {
55
- r := NewRegistry()
56
- err := r.Set("proj-1", tt.endpoint, nil)
57
- if tt.wantErr {
58
- assert.ErrorIs(t, err, ErrInvalidEndpoint)
59
- } else {
60
- assert.NoError(t, err)
61
- }
62
- })
63
- }
64
- }
65
-
66
- func TestRegistry_Lookup(t *testing.T) {
67
- r := NewRegistry()
68
- _ = r.Set("proj-1", "https://otel.internal:4318/v1/traces", map[string]string{"X-Auth-Token": "tok"})
69
-
70
- endpoint, headers, ok := r.Lookup("proj-1")
71
- assert.True(t, ok)
72
- assert.Equal(t, "https://otel.internal:4318/v1/traces", endpoint)
73
- assert.Equal(t, "tok", headers["X-Auth-Token"])
74
- }
75
-
76
- func TestRegistry_Set_ClearsWithEmpty(t *testing.T) {
77
- r := NewRegistry()
78
- _ = r.Set("proj-1", "https://otel.internal:4318", nil)
79
- _ = r.Set("proj-1", "", nil)
80
-
81
- _, _, ok := r.Lookup("proj-1")
82
- assert.False(t, ok)
83
- }
84
-
85
- func hexEncode(b []byte) string {
86
- const hexChars = "0123456789abcdef"
87
- out := make([]byte, len(b)*2)
88
- for i, v := range b {
89
- out[i*2] = hexChars[v>>4]
90
- out[i*2+1] = hexChars[v&0x0f]
91
- }
92
- return string(out)
93
- }
@@ -1,82 +0,0 @@
1
- package customertracebridge
2
-
3
- import (
4
- "errors"
5
- "net/url"
6
-
7
- lru "github.com/hashicorp/golang-lru/v2"
8
- )
9
-
10
- const defaultRegistrySize = 10_000
11
-
12
- // Registry maps project ID → OTLP endpoint + auth headers, bounded by an LRU.
13
- type Registry struct {
14
- cache *lru.Cache[string, registryEntry]
15
- }
16
-
17
- type registryEntry struct {
18
- endpoint string
19
- headers map[string]string
20
- }
21
-
22
- // NewRegistry creates a bounded registry. Size defaults to 10,000 entries.
23
- func NewRegistry() *Registry {
24
- return NewRegistryWithSize(defaultRegistrySize)
25
- }
26
-
27
- // NewRegistryWithSize creates a registry with a custom capacity.
28
- func NewRegistryWithSize(size int) *Registry {
29
- c, _ := lru.New[string, registryEntry](size)
30
- return &Registry{cache: c}
31
- }
32
-
33
- // ErrInvalidEndpoint is returned when an OTLP endpoint has a disallowed scheme.
34
- var ErrInvalidEndpoint = errors.New("otlp endpoint must use http or https scheme")
35
-
36
- // Set records an endpoint for a project. Empty endpoint clears the entry.
37
- // Returns an error if the endpoint scheme is not http/https.
38
- func (r *Registry) Set(projectID, endpoint string, headers map[string]string) error {
39
- if projectID == "" {
40
- return nil
41
- }
42
- if endpoint == "" {
43
- r.cache.Remove(projectID)
44
- return nil
45
- }
46
- if err := validateEndpointScheme(endpoint); err != nil {
47
- return err
48
- }
49
- r.cache.Add(projectID, registryEntry{endpoint: endpoint, headers: headers})
50
- return nil
51
- }
52
-
53
- // SetFromBundle registers the project's OTLP endpoint from a resolved bundle.
54
- // No-op if any required field is empty.
55
- func (r *Registry) SetFromBundle(projectID, otlpToken, defaultEndpoint string) error {
56
- if projectID == "" || otlpToken == "" || defaultEndpoint == "" {
57
- return nil
58
- }
59
- return r.Set(projectID, defaultEndpoint, map[string]string{"X-Auth-Token": otlpToken})
60
- }
61
-
62
- // Lookup returns the endpoint for a project.
63
- func (r *Registry) Lookup(projectID string) (string, map[string]string, bool) {
64
- e, ok := r.cache.Get(projectID)
65
- if !ok {
66
- return "", nil, false
67
- }
68
- return e.endpoint, e.headers, true
69
- }
70
-
71
- func validateEndpointScheme(endpoint string) error {
72
- u, err := url.Parse(endpoint)
73
- if err != nil {
74
- return ErrInvalidEndpoint
75
- }
76
- switch u.Scheme {
77
- case "http", "https":
78
- return nil
79
- default:
80
- return ErrInvalidEndpoint
81
- }
82
- }
@@ -1,122 +0,0 @@
1
- package customertracebridge
2
-
3
- import (
4
- "context"
5
- "strings"
6
- "sync"
7
- "time"
8
-
9
- lru "github.com/hashicorp/golang-lru/v2"
10
- "go.opentelemetry.io/otel/exporters/otlp/otlptrace"
11
- "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
12
- sdktrace "go.opentelemetry.io/otel/sdk/trace"
13
- )
14
-
15
- const defaultExporterCacheSize = 10_000
16
-
17
- // routerExporter is an OTel SpanExporter that routes spans to per-project OTLP
18
- // endpoints based on the langwatch.project_id attribute. Exporters are cached
19
- // in a bounded LRU; evicted exporters are shut down gracefully.
20
- type routerExporter struct {
21
- registry *Registry
22
- mu sync.Mutex
23
- byProject *lru.Cache[string, *otlptrace.Exporter]
24
- }
25
-
26
- func newRouterExporter(registry *Registry) *routerExporter {
27
- r := &routerExporter{registry: registry}
28
- cache, _ := lru.NewWithEvict[string, *otlptrace.Exporter](
29
- defaultExporterCacheSize,
30
- func(_ string, exp *otlptrace.Exporter) {
31
- // Best-effort shutdown on eviction.
32
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
33
- defer cancel()
34
- _ = exp.Shutdown(ctx)
35
- },
36
- )
37
- r.byProject = cache
38
- return r
39
- }
40
-
41
- func (r *routerExporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error {
42
- buckets := make(map[string][]sdktrace.ReadOnlySpan)
43
- for _, s := range spans {
44
- pid := readAttr(s, string(attrProjectID))
45
- if pid == "" {
46
- continue
47
- }
48
- buckets[pid] = append(buckets[pid], s)
49
- }
50
-
51
- for pid, batch := range buckets {
52
- exp := r.exporterFor(ctx, pid)
53
- if exp == nil {
54
- continue
55
- }
56
- _ = exp.ExportSpans(ctx, batch)
57
- }
58
- return nil
59
- }
60
-
61
- func (r *routerExporter) Shutdown(ctx context.Context) error {
62
- r.mu.Lock()
63
- defer r.mu.Unlock()
64
- keys := r.byProject.Keys()
65
- for _, k := range keys {
66
- if exp, ok := r.byProject.Get(k); ok {
67
- _ = exp.Shutdown(ctx)
68
- }
69
- }
70
- r.byProject.Purge()
71
- return nil
72
- }
73
-
74
- func (r *routerExporter) exporterFor(ctx context.Context, projectID string) *otlptrace.Exporter {
75
- // Fast path: already cached (LRU Get promotes to front).
76
- if exp, ok := r.byProject.Get(projectID); ok {
77
- return exp
78
- }
79
-
80
- endpoint, headers, ok := r.registry.Lookup(projectID)
81
- if !ok || endpoint == "" {
82
- return nil
83
- }
84
-
85
- r.mu.Lock()
86
- defer r.mu.Unlock()
87
- // Double-check after lock.
88
- if exp, ok := r.byProject.Get(projectID); ok {
89
- return exp
90
- }
91
-
92
- copts := []otlptracehttp.Option{
93
- otlptracehttp.WithEndpointURL(normalizeEndpoint(endpoint)),
94
- otlptracehttp.WithTimeout(5 * time.Second),
95
- }
96
- if len(headers) > 0 {
97
- copts = append(copts, otlptracehttp.WithHeaders(headers))
98
- }
99
- exp, err := otlptracehttp.New(ctx, copts...)
100
- if err != nil {
101
- return nil
102
- }
103
- r.byProject.Add(projectID, exp)
104
- return exp
105
- }
106
-
107
- func readAttr(s sdktrace.ReadOnlySpan, key string) string {
108
- for _, kv := range s.Attributes() {
109
- if string(kv.Key) == key {
110
- return kv.Value.AsString()
111
- }
112
- }
113
- return ""
114
- }
115
-
116
- func normalizeEndpoint(endpoint string) string {
117
- trimmed := strings.TrimRight(endpoint, "/")
118
- if strings.HasSuffix(trimmed, "/v1/traces") {
119
- return trimmed
120
- }
121
- return trimmed + "/v1/traces"
122
- }
@@ -1,28 +0,0 @@
1
- package gatewaytracer
2
-
3
- const (
4
- AttrOrigin = "langwatch.origin"
5
- OriginGateway = "gateway"
6
- AttrVirtualKeyID = "langwatch.virtual_key_id"
7
- AttrProjectID = "langwatch.project_id"
8
- AttrTeamID = "langwatch.team_id"
9
- AttrOrgID = "langwatch.organization_id"
10
- AttrPrincipalID = "langwatch.principal_id"
11
- AttrGatewayReqID = "langwatch.gateway_request_id"
12
- AttrModel = "langwatch.model"
13
- AttrProvider = "langwatch.provider"
14
- AttrModelSource = "langwatch.model_source"
15
- AttrStreaming = "langwatch.streaming"
16
- AttrCostUSD = "langwatch.cost_usd"
17
- AttrDurationMS = "langwatch.duration_ms"
18
- AttrStatus = "langwatch.status"
19
- AttrDecision = "langwatch.budget.decision"
20
- AttrGuardrailVerdict = "langwatch.guardrail.verdict"
21
- AttrCacheRuleID = "langwatch.cache.rule_id"
22
- AttrCacheRulePriority = "langwatch.cache.rule_priority"
23
- AttrCacheModeApplied = "langwatch.cache.mode_applied"
24
- AttrFallbackAttemptsCount = "langwatch.fallback.attempts_count"
25
- AttrFallbackWinningProvider = "langwatch.fallback.winning_provider"
26
- AttrFallbackWinningCredential = "langwatch.fallback.winning_credential"
27
- AttrThreadID = "langwatch.thread_id"
28
- )
@@ -1,24 +0,0 @@
1
- package gatewaytracer
2
-
3
- const (
4
- AttrGenAIOperationName = "gen_ai.operation.name"
5
- AttrGenAISystem = "gen_ai.system"
6
- AttrGenAIRequestModel = "gen_ai.request.model"
7
- AttrGenAIRequestTemp = "gen_ai.request.temperature"
8
- AttrGenAIRequestMaxTokens = "gen_ai.request.max_tokens"
9
- AttrGenAIRequestTopP = "gen_ai.request.top_p"
10
- AttrGenAIRequestFreqPen = "gen_ai.request.frequency_penalty"
11
- AttrGenAIRequestPresPen = "gen_ai.request.presence_penalty"
12
- AttrGenAIRequestStopSeqs = "gen_ai.request.stop_sequences"
13
- AttrGenAIResponseID = "gen_ai.response.id"
14
- AttrGenAIResponseModel = "gen_ai.response.model"
15
- AttrGenAIResponseFinish = "gen_ai.response.finish_reasons"
16
- AttrGenAIInputMessages = "gen_ai.input.messages"
17
- AttrGenAIOutputMessages = "gen_ai.output.messages"
18
- AttrGenAISystemInstructions = "gen_ai.system_instructions"
19
- AttrGenAIUsageIn = "gen_ai.usage.input_tokens"
20
- AttrGenAIUsageOut = "gen_ai.usage.output_tokens"
21
- AttrGenAIUsageTotal = "gen_ai.usage.total_tokens"
22
- AttrGenAIUsageCacheRead = "gen_ai.usage.cache_read.input_tokens"
23
- AttrGenAIUsageCacheCreate = "gen_ai.usage.cache_creation.input_tokens"
24
- )
@@ -1,8 +0,0 @@
1
- package gatewaytracer
2
-
3
- const (
4
- HeaderTraceID = "X-LangWatch-Trace-Id"
5
- HeaderSpanID = "X-LangWatch-Span-Id"
6
- HeaderPrincipal = "X-LangWatch-Principal"
7
- HeaderThreadID = "X-LangWatch-Thread-Id"
8
- )