@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,112 +0,0 @@
1
- // Package lifecycle manages ordered start/stop of services with graceful shutdown.
2
- package lifecycle
3
-
4
- import (
5
- "context"
6
- "errors"
7
- "net"
8
- "net/http"
9
- )
10
-
11
- // Service is a managed component with a start/stop lifecycle.
12
- // Services are started in registration order and stopped in reverse.
13
- type Service interface {
14
- String() string
15
- Start(ctx context.Context) error
16
- Stop(ctx context.Context) error
17
- }
18
-
19
- // fatalReporter is optionally implemented by services that can fail
20
- // asynchronously after Start (e.g. an HTTP server whose accept loop dies).
21
- type fatalReporter interface {
22
- Fatal() <-chan error
23
- }
24
-
25
- // --- Adapters ---
26
-
27
- // Closer creates a Service that only needs shutdown cleanup (no start phase).
28
- // Useful for resources like OTel TracerProviders.
29
- func Closer(name string, stop func(ctx context.Context) error) Service {
30
- return &closerSvc{name: name, stopFn: stop}
31
- }
32
-
33
- type closerSvc struct {
34
- name string
35
- stopFn func(ctx context.Context) error
36
- }
37
-
38
- func (c *closerSvc) String() string { return c.name }
39
- func (c *closerSvc) Start(context.Context) error { return nil }
40
- func (c *closerSvc) Stop(ctx context.Context) error { return c.stopFn(ctx) }
41
-
42
- // Worker creates a Service from a fire-and-forget start and a synchronous stop.
43
- // The start function receives the group's cancellable context.
44
- // Stop is bounded by the shutdown context's deadline.
45
- func Worker(name string, start func(ctx context.Context), stop func()) Service {
46
- return &workerSvc{name: name, startFn: start, stopFn: stop}
47
- }
48
-
49
- type workerSvc struct {
50
- name string
51
- startFn func(ctx context.Context)
52
- stopFn func()
53
- }
54
-
55
- func (w *workerSvc) String() string { return w.name }
56
-
57
- func (w *workerSvc) Start(ctx context.Context) error {
58
- w.startFn(ctx)
59
- return nil
60
- }
61
-
62
- func (w *workerSvc) Stop(ctx context.Context) error {
63
- done := make(chan struct{})
64
- go func() {
65
- w.stopFn()
66
- close(done)
67
- }()
68
- select {
69
- case <-done:
70
- return nil
71
- case <-ctx.Done():
72
- return ctx.Err()
73
- }
74
- }
75
-
76
- // ListenServer creates a Service that wraps an *http.Server.
77
- // Start launches ListenAndServe in a goroutine; Stop calls Shutdown.
78
- // It implements fatalReporter so the group can detect accept-loop failures.
79
- func ListenServer(name string, srv *http.Server) Service {
80
- return &listenSvc{name: name, srv: srv}
81
- }
82
-
83
- type listenSvc struct {
84
- name string
85
- srv *http.Server
86
- fatalCh chan error
87
- }
88
-
89
- func (l *listenSvc) String() string { return l.name }
90
-
91
- func (l *listenSvc) Start(ctx context.Context) error {
92
- // Detach so in-flight requests keep context values (logger, tracing)
93
- // but aren't canceled when the group's context is canceled during shutdown.
94
- // Requests finish naturally, bounded by Shutdown's graceful timeout.
95
- l.srv.BaseContext = func(_ net.Listener) context.Context {
96
- return context.WithoutCancel(ctx)
97
- }
98
- l.fatalCh = make(chan error, 1)
99
- go func() {
100
- defer close(l.fatalCh)
101
- if err := l.srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
102
- l.fatalCh <- err
103
- }
104
- }()
105
- return nil
106
- }
107
-
108
- func (l *listenSvc) Stop(ctx context.Context) error {
109
- return l.srv.Shutdown(ctx)
110
- }
111
-
112
- func (l *listenSvc) Fatal() <-chan error { return l.fatalCh }
@@ -1,89 +0,0 @@
1
- // Package netprobe validates outbound network reachability at startup.
2
- // Catches NetworkPolicy misconfigs before the pod accepts traffic.
3
- package netprobe
4
-
5
- import (
6
- "context"
7
- "errors"
8
- "fmt"
9
- "net"
10
- "strings"
11
- "time"
12
- )
13
-
14
- // Host is a TCP endpoint to probe.
15
- type Host struct {
16
- Name string // short label for logs (e.g. "openai")
17
- Addr string // host:port form (e.g. "api.openai.com:443")
18
- }
19
-
20
- // ParseHosts parses a comma-separated list of host:port entries.
21
- func ParseHosts(raw string) ([]Host, error) {
22
- raw = strings.TrimSpace(raw)
23
- if raw == "" {
24
- return nil, nil
25
- }
26
- parts := strings.Split(raw, ",")
27
- out := make([]Host, 0, len(parts))
28
- for _, p := range parts {
29
- p = strings.TrimSpace(p)
30
- if p == "" {
31
- continue
32
- }
33
- host, port, err := net.SplitHostPort(p)
34
- if err != nil {
35
- return nil, fmt.Errorf("netprobe: invalid host:port %q: %w", p, err)
36
- }
37
- if host == "" || port == "" {
38
- return nil, fmt.Errorf("netprobe: invalid host:port %q", p)
39
- }
40
- name := host
41
- if i := strings.IndexByte(host, '.'); i > 0 {
42
- name = host[:i]
43
- }
44
- out = append(out, Host{Name: name, Addr: net.JoinHostPort(host, port)})
45
- }
46
- return out, nil
47
- }
48
-
49
- // Prober runs reachability checks.
50
- type Prober struct {
51
- Dialer *net.Dialer
52
- PerHostTimeout time.Duration // default 2s
53
- }
54
-
55
- // Probe checks each host sequentially. Returns the first failure.
56
- func (p *Prober) Probe(ctx context.Context, hosts []Host) error {
57
- if len(hosts) == 0 {
58
- return nil
59
- }
60
- dialer := p.Dialer
61
- if dialer == nil {
62
- dialer = &net.Dialer{}
63
- }
64
- timeout := p.PerHostTimeout
65
- if timeout <= 0 {
66
- timeout = 2 * time.Second
67
- }
68
- for _, h := range hosts {
69
- if err := probeOne(ctx, dialer, h, timeout); err != nil {
70
- return fmt.Errorf("netprobe %s (%s): %w", h.Name, h.Addr, err)
71
- }
72
- }
73
- return nil
74
- }
75
-
76
- func probeOne(ctx context.Context, dialer *net.Dialer, h Host, timeout time.Duration) error {
77
- cctx, cancel := context.WithTimeout(ctx, timeout)
78
- defer cancel()
79
- conn, err := dialer.DialContext(cctx, "tcp", h.Addr)
80
- if err != nil {
81
- var dnsErr *net.DNSError
82
- if errors.As(err, &dnsErr) {
83
- return fmt.Errorf("dns resolution failed: %w", err)
84
- }
85
- return fmt.Errorf("tcp dial failed: %w", err)
86
- }
87
- _ = conn.Close()
88
- return nil
89
- }
@@ -1,55 +0,0 @@
1
- package netprobe
2
-
3
- import (
4
- "testing"
5
-
6
- "github.com/stretchr/testify/assert"
7
- "github.com/stretchr/testify/require"
8
- )
9
-
10
- func TestParseHosts(t *testing.T) {
11
- tests := []struct {
12
- name string
13
- input string
14
- want []Host
15
- }{
16
- {
17
- name: "single host",
18
- input: "api.openai.com:443",
19
- want: []Host{{Name: "api", Addr: "api.openai.com:443"}},
20
- },
21
- {
22
- name: "multiple hosts",
23
- input: "api.openai.com:443, redis.local:6379",
24
- want: []Host{
25
- {Name: "api", Addr: "api.openai.com:443"},
26
- {Name: "redis", Addr: "redis.local:6379"},
27
- },
28
- },
29
- {
30
- name: "host without dot uses full name",
31
- input: "localhost:8080",
32
- want: []Host{{Name: "localhost", Addr: "localhost:8080"}},
33
- },
34
- }
35
-
36
- for _, tc := range tests {
37
- t.Run(tc.name, func(t *testing.T) {
38
- hosts, err := ParseHosts(tc.input)
39
- require.NoError(t, err)
40
- assert.Equal(t, tc.want, hosts)
41
- })
42
- }
43
- }
44
-
45
- func TestParseHosts_Empty(t *testing.T) {
46
- hosts, err := ParseHosts("")
47
- require.NoError(t, err)
48
- assert.Nil(t, hosts)
49
- }
50
-
51
- func TestParseHosts_Invalid(t *testing.T) {
52
- _, err := ParseHosts("not-a-host-port")
53
- require.Error(t, err)
54
- assert.Contains(t, err.Error(), "invalid host:port")
55
- }
@@ -1,226 +0,0 @@
1
- // Package otelsetup provides a generic OpenTelemetry bootstrap for any service.
2
- // It configures tracing (and in future, metrics), registers globals, and returns
3
- // a Provider whose Shutdown method flushes all pending telemetry.
4
- //
5
- // Service name, version, and environment are read from the context's ServiceInfo
6
- // (see pkg/contexts). Override with Options fields if needed.
7
- package otelsetup
8
-
9
- import (
10
- "context"
11
- "strings"
12
- "sync"
13
- "sync/atomic"
14
- "time"
15
-
16
- otelapi "go.opentelemetry.io/otel"
17
- "go.opentelemetry.io/otel/attribute"
18
- "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
19
- "go.opentelemetry.io/otel/propagation"
20
- "go.opentelemetry.io/otel/sdk/resource"
21
- sdktrace "go.opentelemetry.io/otel/sdk/trace"
22
- semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
23
-
24
- "github.com/langwatch/langwatch/pkg/contexts"
25
- )
26
-
27
- // startupErrorHandler silences OTLP export errors during the first few
28
- // seconds of startup. The gateway commonly races its OTel exporter
29
- // against control-plane readiness — the first few batches hit 401/503
30
- // while auth is still being minted — and the default handler logs each
31
- // batch as a WARN. Once we've seen a single successful export (signaled
32
- // by `markHealthy`), the filter unlocks and every error flows through
33
- // normally again.
34
- type startupErrorHandler struct {
35
- delegate otelapi.ErrorHandler
36
- until time.Time
37
- healthy atomic.Bool
38
- once sync.Once
39
- }
40
-
41
- func newStartupErrorHandler(delegate otelapi.ErrorHandler, graceWindow time.Duration) *startupErrorHandler {
42
- return &startupErrorHandler{
43
- delegate: delegate,
44
- until: time.Now().Add(graceWindow),
45
- }
46
- }
47
-
48
- func (h *startupErrorHandler) Handle(err error) {
49
- if err == nil {
50
- return
51
- }
52
- if h.healthy.Load() {
53
- h.delegate.Handle(err)
54
- return
55
- }
56
- if time.Now().Before(h.until) && isTransportAuthError(err) {
57
- // Swallow: grace-window auth/transport noise.
58
- return
59
- }
60
- h.delegate.Handle(err)
61
- }
62
-
63
- // markHealthy is called by a SpanProcessor wrapper after the first
64
- // successful export batch. Flips the filter off for the rest of the
65
- // process lifetime.
66
- func (h *startupErrorHandler) markHealthy() {
67
- h.once.Do(func() { h.healthy.Store(true) })
68
- }
69
-
70
- func isTransportAuthError(err error) bool {
71
- s := err.Error()
72
- return strings.Contains(s, "401") ||
73
- strings.Contains(s, "403") ||
74
- strings.Contains(s, "unauthorized") ||
75
- strings.Contains(s, "Unauthorized") ||
76
- strings.Contains(s, "connection refused") ||
77
- strings.Contains(s, "no such host")
78
- }
79
-
80
- // Options configures the telemetry provider. Fields left empty are filled from
81
- // the context's ServiceInfo when available.
82
- type Options struct {
83
- NodeID string
84
- OTLPEndpoint string // OTLP HTTP endpoint (empty = noop)
85
- OTLPHeaders map[string]string // auth headers for the collector
86
- BatchTimeout time.Duration
87
- MaxQueueSize int
88
- // SampleRatio controls the fraction of traces sampled (0.0–1.0).
89
- // 0 means "use default" (AlwaysSample). Set explicitly via config.
90
- SampleRatio float64
91
- }
92
-
93
- // Provider holds the configured OTel SDK providers.
94
- type Provider struct {
95
- tp *sdktrace.TracerProvider
96
- }
97
-
98
- // New creates the telemetry provider. If TraceEndpoint is empty, a noop
99
- // provider is registered globally. Globals (TracerProvider, Propagator) are
100
- // set before returning.
101
- func New(ctx context.Context, opts Options) (*Provider, error) {
102
- info := contexts.GetServiceInfo(ctx)
103
-
104
- serviceName := "langwatch-service"
105
- serviceVersion := "dev"
106
- environment := ""
107
- if info != nil {
108
- if info.Service != "" {
109
- serviceName = info.Service
110
- }
111
- if info.Version != "" {
112
- serviceVersion = info.Version
113
- }
114
- environment = info.Environment
115
- }
116
-
117
- prop := propagation.NewCompositeTextMapPropagator(
118
- propagation.TraceContext{},
119
- propagation.Baggage{},
120
- )
121
- otelapi.SetTextMapPropagator(prop)
122
-
123
- if opts.OTLPEndpoint == "" {
124
- return &Provider{}, nil
125
- }
126
-
127
- exporterOpts := []otlptracehttp.Option{
128
- otlptracehttp.WithEndpointURL(opts.OTLPEndpoint),
129
- }
130
- if len(opts.OTLPHeaders) > 0 {
131
- exporterOpts = append(exporterOpts, otlptracehttp.WithHeaders(opts.OTLPHeaders))
132
- }
133
- exp, err := otlptracehttp.New(ctx, exporterOpts...)
134
- if err != nil {
135
- return nil, err
136
- }
137
-
138
- // Suppress startup-race auth/transport noise from the OTLP exporter —
139
- // the default handler emits WARN for every batch, which floods logs
140
- // for ~5s until the control-plane mints auth. The filter auto-disables
141
- // once the healthyExporter wrapper sees a successful export, or after
142
- // the 30s grace window elapses (whichever comes first).
143
- startupFilter := newStartupErrorHandler(
144
- otelapi.GetErrorHandler(),
145
- 30*time.Second,
146
- )
147
- otelapi.SetErrorHandler(startupFilter)
148
- wrappedExp := healthyExporterWrap(exp, startupFilter.markHealthy)
149
-
150
- attrs := []attribute.KeyValue{
151
- semconv.ServiceName(serviceName),
152
- semconv.ServiceVersion(serviceVersion),
153
- }
154
- if environment != "" {
155
- attrs = append(attrs, attribute.String("deployment.environment.name", environment))
156
- }
157
- if opts.NodeID != "" {
158
- attrs = append(attrs, attribute.String("node.id", opts.NodeID))
159
- }
160
-
161
- res, _ := resource.Merge(
162
- resource.Default(),
163
- resource.NewWithAttributes(semconv.SchemaURL, attrs...),
164
- )
165
-
166
- batchTimeout := opts.BatchTimeout
167
- if batchTimeout == 0 {
168
- batchTimeout = 5 * time.Second
169
- }
170
- queueSize := opts.MaxQueueSize
171
- if queueSize == 0 {
172
- queueSize = 8192
173
- }
174
-
175
- var rootSampler sdktrace.Sampler
176
- if opts.SampleRatio > 0 && opts.SampleRatio < 1.0 {
177
- rootSampler = sdktrace.TraceIDRatioBased(opts.SampleRatio)
178
- } else {
179
- rootSampler = sdktrace.AlwaysSample()
180
- }
181
-
182
- tp := sdktrace.NewTracerProvider(
183
- sdktrace.WithResource(res),
184
- sdktrace.WithBatcher(wrappedExp,
185
- sdktrace.WithBatchTimeout(batchTimeout),
186
- sdktrace.WithMaxQueueSize(queueSize),
187
- ),
188
- sdktrace.WithSampler(sdktrace.ParentBased(rootSampler)),
189
- )
190
- otelapi.SetTracerProvider(tp)
191
-
192
- return &Provider{tp: tp}, nil
193
- }
194
-
195
- // Shutdown flushes pending telemetry. Safe to call on a noop provider.
196
- func (p *Provider) Shutdown(ctx context.Context) error {
197
- if p.tp != nil {
198
- return p.tp.Shutdown(ctx)
199
- }
200
- return nil
201
- }
202
-
203
- // healthyExporter wraps a SpanExporter, invoking `onHealthy` the first
204
- // time ExportSpans returns nil. Used to flip the startupErrorHandler
205
- // filter off once the collector is actually answering.
206
- type healthyExporter struct {
207
- inner sdktrace.SpanExporter
208
- onHealthy func()
209
- once sync.Once
210
- }
211
-
212
- func healthyExporterWrap(inner sdktrace.SpanExporter, onHealthy func()) sdktrace.SpanExporter {
213
- return &healthyExporter{inner: inner, onHealthy: onHealthy}
214
- }
215
-
216
- func (h *healthyExporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error {
217
- err := h.inner.ExportSpans(ctx, spans)
218
- if err == nil {
219
- h.once.Do(h.onHealthy)
220
- }
221
- return err
222
- }
223
-
224
- func (h *healthyExporter) Shutdown(ctx context.Context) error {
225
- return h.inner.Shutdown(ctx)
226
- }
@@ -1,130 +0,0 @@
1
- package otelsetup
2
-
3
- import (
4
- "context"
5
- "errors"
6
- "sync/atomic"
7
- "testing"
8
- "time"
9
-
10
- sdktrace "go.opentelemetry.io/otel/sdk/trace"
11
- )
12
-
13
- // capturingHandler records every error it receives so tests can assert
14
- // the startupErrorHandler's filter is actually gating what reaches the
15
- // delegate logger.
16
- type capturingHandler struct {
17
- errs []error
18
- }
19
-
20
- func (c *capturingHandler) Handle(err error) { c.errs = append(c.errs, err) }
21
-
22
- func TestStartupErrorHandler_SuppressesTransportAuthErrorsInGraceWindow(t *testing.T) {
23
- captured := &capturingHandler{}
24
- h := newStartupErrorHandler(captured, 10*time.Second)
25
-
26
- // All of these should be suppressed: the gateway races its OTLP
27
- // exporter against the control-plane coming up, and the default
28
- // handler emits a WARN for each one — floods logs for seconds.
29
- h.Handle(errors.New(`exporter POST http://cp/v1/traces returned 401 Unauthorized`))
30
- h.Handle(errors.New(`net/http: dial tcp 127.0.0.1:5560: connection refused`))
31
- h.Handle(errors.New(`no such host: langwatch-saas.internal`))
32
- h.Handle(errors.New(`exporter returned 403`))
33
-
34
- if len(captured.errs) != 0 {
35
- t.Fatalf("expected all startup-noise errors to be suppressed, got %d: %v", len(captured.errs), captured.errs)
36
- }
37
- }
38
-
39
- func TestStartupErrorHandler_PassesRealErrorsThroughEvenInGraceWindow(t *testing.T) {
40
- captured := &capturingHandler{}
41
- h := newStartupErrorHandler(captured, 10*time.Second)
42
-
43
- // Non-transport errors are always surfaced — an OTLP protocol-level
44
- // issue isn't startup noise, it's a real bug that needs to page.
45
- realErr := errors.New("sdk/trace: span exporter returned nil context")
46
- h.Handle(realErr)
47
-
48
- if len(captured.errs) != 1 || !errors.Is(captured.errs[0], realErr) {
49
- t.Fatalf("expected real error to propagate, got: %v", captured.errs)
50
- }
51
- }
52
-
53
- func TestStartupErrorHandler_PassesAuthErrorsAfterGraceWindowElapses(t *testing.T) {
54
- captured := &capturingHandler{}
55
- h := newStartupErrorHandler(captured, 10*time.Millisecond)
56
-
57
- // After the grace window lapses, 401s become real and must surface —
58
- // they likely mean credentials rotated / got revoked at runtime.
59
- time.Sleep(20 * time.Millisecond)
60
- authErr := errors.New(`POST /v1/traces returned 401 Unauthorized`)
61
- h.Handle(authErr)
62
-
63
- if len(captured.errs) != 1 || !errors.Is(captured.errs[0], authErr) {
64
- t.Fatalf("expected post-grace auth error to surface, got: %v", captured.errs)
65
- }
66
- }
67
-
68
- func TestStartupErrorHandler_MarkHealthyFlipsFilterOff(t *testing.T) {
69
- captured := &capturingHandler{}
70
- h := newStartupErrorHandler(captured, 1*time.Hour) // effectively never expires
71
-
72
- h.Handle(errors.New(`POST /v1/traces returned 401 Unauthorized`))
73
- if len(captured.errs) != 0 {
74
- t.Fatalf("expected 401 to be swallowed before markHealthy, got: %v", captured.errs)
75
- }
76
-
77
- h.markHealthy()
78
-
79
- // Second 401 after the exporter has succeeded once should flow through —
80
- // something new is wrong, not just startup race.
81
- newAuthErr := errors.New(`POST /v1/traces returned 401 Unauthorized`)
82
- h.Handle(newAuthErr)
83
- if len(captured.errs) != 1 || !errors.Is(captured.errs[0], newAuthErr) {
84
- t.Fatalf("expected post-healthy 401 to surface, got: %v", captured.errs)
85
- }
86
- }
87
-
88
- func TestHealthyExporterWrap_CallsOnHealthyOnFirstSuccessfulExport(t *testing.T) {
89
- inner := &fakeExporter{}
90
- var called atomic.Int32
91
- wrap := healthyExporterWrap(inner, func() { called.Add(1) })
92
-
93
- // First export returns success → onHealthy should be invoked once.
94
- if err := wrap.ExportSpans(context.Background(), nil); err != nil {
95
- t.Fatalf("unexpected export error: %v", err)
96
- }
97
- if got := called.Load(); got != 1 {
98
- t.Fatalf("expected onHealthy called once, got %d", got)
99
- }
100
-
101
- // Subsequent successful exports must NOT re-fire — sync.Once guards it.
102
- if err := wrap.ExportSpans(context.Background(), nil); err != nil {
103
- t.Fatalf("unexpected export error: %v", err)
104
- }
105
- if got := called.Load(); got != 1 {
106
- t.Fatalf("expected onHealthy to remain at 1 after second success, got %d", got)
107
- }
108
- }
109
-
110
- func TestHealthyExporterWrap_DoesNotCallOnHealthyOnErrors(t *testing.T) {
111
- inner := &fakeExporter{err: errors.New("transport failure")}
112
- var called atomic.Int32
113
- wrap := healthyExporterWrap(inner, func() { called.Add(1) })
114
-
115
- for i := 0; i < 3; i++ {
116
- if err := wrap.ExportSpans(context.Background(), nil); err == nil {
117
- t.Fatalf("expected wrapped error on call %d", i)
118
- }
119
- }
120
- if got := called.Load(); got != 0 {
121
- t.Fatalf("expected onHealthy never called when exports fail, got %d", got)
122
- }
123
- }
124
-
125
- type fakeExporter struct {
126
- err error
127
- }
128
-
129
- func (f *fakeExporter) ExportSpans(_ context.Context, _ []sdktrace.ReadOnlySpan) error { return f.err }
130
- func (f *fakeExporter) Shutdown(_ context.Context) error { return nil }
package/pkg/ptr/LICENSE DELETED
@@ -1,26 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2022-2024 Mojo Men Ltd
4
- Copyright (c) 2026 Reasoning Engine B.V.
5
-
6
- Permission is hereby granted, free of charge, to any person obtaining a copy
7
- of this software and associated documentation files (the "Software"), to deal
8
- in the Software without restriction, including without limitation the rights
9
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- copies of the Software, and to permit persons to whom the Software is
11
- furnished to do so, subject to the following conditions:
12
-
13
- The above copyright notice and this permission notice shall be included in all
14
- copies or substantial portions of the Software.
15
-
16
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- SOFTWARE.
23
-
24
- ---
25
-
26
- This package is derived from https://github.com/wearemojo/mojo-public-go/tree/main/lib/ptr
package/pkg/ptr/ptr.go DELETED
@@ -1,34 +0,0 @@
1
- package ptr
2
-
3
- // P returns a pointer to v.
4
- func P[T any](v T) *T {
5
- return &v
6
- }
7
-
8
- // ValueOrNil returns a pointer to v if non-zero, otherwise nil.
9
- func ValueOrNil[T comparable](v T) *T {
10
- var zero T
11
- if v == zero {
12
- return nil
13
- }
14
- return &v
15
- }
16
-
17
- // ValueOrZero dereferences a pointer, returning the zero value if nil.
18
- func ValueOrZero[T any](v *T) T {
19
- if v == nil {
20
- var zero T
21
- return zero
22
- }
23
- return *v
24
- }
25
-
26
- // ShallowCopy returns a pointer to a shallow copy of the pointed-to value.
27
- func ShallowCopy[T any](v *T) *T {
28
- if v == nil {
29
- return nil
30
- }
31
- cpy := new(T)
32
- *cpy = *v
33
- return cpy
34
- }