@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,77 +0,0 @@
1
- package stacktrace
2
-
3
- import (
4
- "fmt"
5
- "runtime"
6
- "strings"
7
- )
8
-
9
- // Frame represents a single stack frame.
10
- type Frame struct {
11
- File string `json:"file"`
12
- Line int `json:"line"`
13
- Function string `json:"function"`
14
- }
15
-
16
- // GetCallerFrames returns stack frames starting at skip levels above the caller.
17
- // 0 = GetCallerFrames itself, 1 = caller of GetCallerFrames, etc.
18
- func GetCallerFrames(skip int) []Frame {
19
- stack := make([]uintptr, 100)
20
- length := runtime.Callers(skip+1, stack)
21
- stack = stack[:length]
22
-
23
- framesIter := runtime.CallersFrames(stack)
24
- frames := make([]Frame, 0, length)
25
-
26
- for {
27
- frame, more := framesIter.Next()
28
- frames = append(frames, Frame{
29
- File: frame.File,
30
- Line: frame.Line,
31
- Function: frame.Function,
32
- })
33
- if !more {
34
- break
35
- }
36
- }
37
-
38
- return frames
39
- }
40
-
41
- func (f Frame) String() string {
42
- return fmt.Sprintf("%s\n\t%s:%d", f.Function, f.File, f.Line)
43
- }
44
-
45
- // FormatFrames pretty-prints a slice of frames.
46
- func FormatFrames(frames []Frame) string {
47
- var sb strings.Builder
48
- for _, frame := range frames {
49
- sb.WriteString(frame.String())
50
- sb.WriteString("\n")
51
- }
52
- return sb.String()
53
- }
54
-
55
- // MergeStacks combines a root stack with a wrapped stack, deduplicating shared frames.
56
- func MergeStacks(root []Frame, wrapped []Frame) []Frame {
57
- if len(wrapped) == 0 {
58
- return root
59
- }
60
- if len(wrapped) == 1 {
61
- return append(root, wrapped[0])
62
- }
63
-
64
- for idx, f := range root {
65
- if f == wrapped[0] {
66
- return root
67
- }
68
- if f == wrapped[1] {
69
- return insert(root, wrapped[0], idx)
70
- }
71
- }
72
- return root
73
- }
74
-
75
- func insert(s []Frame, u Frame, at int) []Frame {
76
- return append(s[:at], append([]Frame{u}, s[at:]...)...)
77
- }
@@ -1,73 +0,0 @@
1
- package stacktrace
2
-
3
- import (
4
- "testing"
5
-
6
- "github.com/stretchr/testify/assert"
7
- "github.com/stretchr/testify/require"
8
- )
9
-
10
- func TestGetCallerFrames(t *testing.T) {
11
- frames := GetCallerFrames(1)
12
-
13
- require.NotEmpty(t, frames)
14
- // The first frame should be this test function.
15
- assert.Contains(t, frames[0].Function, "TestGetCallerFrames")
16
- assert.NotEmpty(t, frames[0].File)
17
- assert.Positive(t, frames[0].Line)
18
- }
19
-
20
- func TestFrame_String(t *testing.T) {
21
- f := Frame{
22
- Function: "github.com/langwatch/langwatch/pkg/stacktrace.TestFrame_String",
23
- File: "/src/frames_test.go",
24
- Line: 42,
25
- }
26
-
27
- s := f.String()
28
- assert.Contains(t, s, "TestFrame_String")
29
- assert.Contains(t, s, "/src/frames_test.go:42")
30
- assert.Contains(t, s, "\n\t", "format should be function\\n\\tfile:line")
31
- }
32
-
33
- func TestFormatFrames(t *testing.T) {
34
- frames := []Frame{
35
- {Function: "funcA", File: "a.go", Line: 1},
36
- {Function: "funcB", File: "b.go", Line: 2},
37
- }
38
-
39
- out := FormatFrames(frames)
40
-
41
- assert.Contains(t, out, "funcA")
42
- assert.Contains(t, out, "funcB")
43
- assert.Contains(t, out, "a.go:1")
44
- assert.Contains(t, out, "b.go:2")
45
- }
46
-
47
- func TestMergeStacks_EmptyWrapped(t *testing.T) {
48
- root := []Frame{
49
- {Function: "a", File: "a.go", Line: 1},
50
- {Function: "b", File: "b.go", Line: 2},
51
- }
52
-
53
- merged := MergeStacks(root, nil)
54
-
55
- assert.Equal(t, root, merged)
56
- }
57
-
58
- func TestMergeStacks_SingleWrapped(t *testing.T) {
59
- root := []Frame{
60
- {Function: "a", File: "a.go", Line: 1},
61
- {Function: "b", File: "b.go", Line: 2},
62
- }
63
- wrapped := []Frame{
64
- {Function: "extra", File: "extra.go", Line: 10},
65
- }
66
-
67
- merged := MergeStacks(root, wrapped)
68
-
69
- require.Len(t, merged, 3)
70
- assert.Equal(t, "a", merged[0].Function)
71
- assert.Equal(t, "b", merged[1].Function)
72
- assert.Equal(t, "extra", merged[2].Function)
73
- }
@@ -1,110 +0,0 @@
1
- # Gateway hot-path benchmarks
2
-
3
- Baseline numbers for the primitives that fire on every `/v1` request, measured on an Apple M3 Pro (`arm64`, Go 1.26.1). Reproduce with:
4
-
5
- ```bash
6
- go test -bench=. -benchmem -run=^$ \
7
- ./services/aigateway/adapters/controlplane/ \
8
- ./services/aigateway/adapters/authresolver/ \
9
- ./services/aigateway/adapters/budget/ \
10
- ./services/aigateway/adapters/httpapi/ \
11
- ./pkg/retry/
12
- ```
13
-
14
- ## Component benchmarks
15
-
16
- | Benchmark | ns/op | B/op | allocs | Notes |
17
- | ----------------------------- | ------: | -----: | -----: | -------------------------------------------------------------- |
18
- | `Router_ChatCompletions` | 4,836 | 12,870 | 75 | Full chi round-trip: auth + middleware + pipeline + JSON write |
19
- | `Sign` (POST w/ body) | 859.7 | 1,081 | 12 | HMAC-SHA256 canonical string — only on internal CP calls |
20
- | `Sign_EmptyBody` (GET) | 836.6 | 1,081 | 12 | Same cost; empty body still hashes |
21
- | `HashKey` | 83.8 | 48 | 1 | SHA-256 of raw VK for L1 cache lookup |
22
- | `Precheck` (3 scopes, cached) | **4.6** | 0 | 0 | Zero-alloc arithmetic on cached budget snapshot |
23
- | `Precheck_HardStop` | **1.5** | 0 | 0 | Early-exit on breached scope |
24
- | `NewULID` | 76.0 | 48 | 2 | Per-request idempotency key |
25
- | `Walk_PrimarySuccess` | 71.7 | 0 | 0 | Happy path: one slot, no fallback |
26
- | `Walk_FallsOver` | 128.2 | 0 | 0 | Primary 5xx → secondary serves |
27
- | `Walk_NonRetryableStops` | 86.3 | 0 | 0 | Fast exit on 4xx |
28
-
29
- ## Happy-path overhead budget
30
-
31
- Summing the primitives that fire on every successful non-streaming request
32
- (excluding the httptest recorder overhead in the Router benchmark):
33
-
34
- ```
35
- HashKey 83.8 ns (L1 cache lookup key)
36
- Precheck 4.6 ns (cached budget evaluation)
37
- Walk_PrimarySuccess 71.7 ns (retry engine — single slot)
38
- NewULID 76.0 ns (gateway_request_id)
39
- ─────────────────────────────
40
- total pre-dispatch ~ 236.1 ns ≈ 0.24 μs
41
- ```
42
-
43
- The full router benchmark (4.8 µs) includes chi routing, middleware stack,
44
- lazy body materialization, JSON model-peek, httptest recorder overhead,
45
- and response serialization. In production with connection reuse and kernel
46
- zero-copy, expect ~3–4 µs gateway-side overhead under load.
47
-
48
- HMAC signing (~0.9 μs) only fires on internal gateway→control-plane calls —
49
- never on the customer-facing hot path.
50
-
51
- ## Allocation profile
52
-
53
- Zero-allocation paths (great for GC pressure at high RPS):
54
-
55
- - `budget.Precheck` on allow/block
56
- - `retry.Walk` happy path (primary success / early-exit patterns)
57
- - All verdict evaluations (pure arithmetic)
58
-
59
- Allocating paths we accept:
60
-
61
- - `NewULID` — 2 allocs for the ULID buffer + string conversion
62
- - `HashKey` — 1 alloc for sha256 digest + hex encoding
63
- - `Router` — 75 allocs per request (chi context, headers, body read/lazy materialization, JSON write)
64
-
65
- ## Cache-override body mutation
66
-
67
- These benchmarks fire only when a guardrail/policy triggers a cache-control
68
- override — not on every request.
69
-
70
- | Benchmark | ns/op | B/op | allocs | Notes |
71
- | --------------------------------------- | -----: | ----: | -----: | ------------------------------------------------- |
72
- | `ApplyCacheOverride_RuleHitModeDisable` | 4,706 | 5,840 | 35 | Strip all `cache_control` keys via sjson |
73
- | `ApplyCacheOverride_RuleHitModeForce` | 2,252 | 2,800 | 18 | Inject ephemeral into last system + content block |
74
- | `ApplyCacheOverride_NoOp` | 2.2 | 0 | 0 | Respect mode — returns body unchanged |
75
-
76
- ## What's NOT benchmarked here
77
-
78
- - **Bifrost provider round-trip** — dominates wall time (50–2000 ms depending on
79
- model). Gateway overhead is noise relative to this.
80
- - **OTel span creation** — batched and async, not on critical path.
81
- - **Guardrails** — bound by control-plane RTT (5–50 ms), not a Go benchmark concern.
82
- - **L1 LRU hit** — `hashicorp/golang-lru` is well-benchmarked upstream; our overhead
83
- is the HashKey cost above.
84
- - **Streaming throughput** — measured end-to-end with the load test harness (see below).
85
-
86
- ## Load testing (vegeta)
87
-
88
- For p50/p99 latency under sustained RPS, use the vegeta harness:
89
-
90
- ```bash
91
- go run ./services/aigateway/loadtest \
92
- -rps=1000 -duration=30s \
93
- -target=http://localhost:5563/v1/chat/completions \
94
- -token=lw_vk_test_...
95
- ```
96
-
97
- See `services/aigateway/loadtest/` for the full harness and analysis scripts.
98
-
99
- ## Improvement opportunities
100
-
101
- See `services/aigateway/PERF-ROADMAP.md` for the prioritised list of optimisations.
102
-
103
- ## When to re-run
104
-
105
- Before cutting a release, after touching any file in:
106
- - `adapters/{authresolver,budget,controlplane,httpapi}/`
107
- - `app/pipeline/`
108
- - `pkg/retry/`
109
-
110
- Regressions > 2× should block the merge.
@@ -1,156 +0,0 @@
1
- # svc_aigateway
2
-
3
- ## Description
4
-
5
- AI Gateway is the data-plane proxy that sits between customers and LLM
6
- providers. It resolves virtual keys into provider credentials, enforces budgets,
7
- rate limits, guardrails, and policy rules, then dispatches requests via Bifrost.
8
- Per-tenant OTLP traces are emitted for every completion.
9
-
10
- ## Architecture
11
-
12
- Hexagonal (ports and adapters):
13
-
14
- ```
15
- cmd/root.go Entry point: LoadConfig → NewDeps → app.New → Serve
16
- config.go Environment-variable configuration
17
- deps.go Infrastructure adapter construction (DI root)
18
- serve.go HTTP server lifecycle (chi + lifecycle.Group)
19
-
20
- domain/ Pure types — no dependencies
21
- provider.go ProviderID enum, Credential, Provider interface
22
- request.go Request, RequestType, RequestMetadata
23
- response.go Response, StreamIterator, Usage
24
- bundle.go Bundle, BundleConfig, all sub-configs
25
- model.go ResolvedModel, ModelSource
26
- verdict.go BudgetVerdict, GuardrailVerdict, CacheDecision
27
- errors.go Domain error codes
28
-
29
- app/ Application layer — orchestration via interfaces
30
- app.go App struct, Option funcs, pipeline construction
31
- ports.go Port interfaces (AuthResolver, ProviderRouter, etc.)
32
- handlers.go HandleChat, HandleChatStream, HandleMessages, etc.
33
- pipeline/ Interceptor chain framework
34
- pipeline.go Build(), Call, Meta, Interceptor types
35
- ratelimit.go RPM/RPD gate
36
- policy.go Tool/MCP/URL deny/allow matching
37
- resolve.go Model alias/allowlist resolution
38
- cache.go Cache rule evaluation + body mutation
39
- cachecontrol.go Cache-control body rewriting
40
- budget.go Pre-check gate + post-dispatch debit
41
- guardrail.go Pre/post/chunk guardrail evaluation
42
- trace.go Customer trace span lifecycle
43
-
44
- adapters/ Infrastructure implementations
45
- httpapi/ chi router, auth + trace-registry middleware
46
- controlplane/ HMAC-signed HTTP client, JWT verify, guardrails RPC
47
- authresolver/ 3-tier cache (L1 LRU → L2 store → L3 upstream)
48
- providers/ Bifrost router (multi-provider dispatch)
49
- modelresolver/ Alias → explicit → implicit resolution
50
- ratelimit/ In-memory token bucket (per-VK LRU)
51
- budget/ Precheck + outbox worker for async debit
52
- cacherules/ Priority-sorted glob matching
53
- policy/ Regex deny/allow rule matcher
54
- customertracebridge/ Per-tenant OTLP span export
55
- gatewaytracer/ Gateway-side OTel instrumentation
56
- ```
57
-
58
- ## Base URL
59
-
60
- `http://localhost:5563/`
61
-
62
- ## HTTP transport
63
-
64
- ### Endpoints
65
-
66
- All `/v1/*` endpoints require a `Bearer` token (virtual key). The gateway
67
- resolves the token into a `Bundle` containing provider credentials, budget
68
- limits, rate limits, guardrails, policy rules, and model aliases.
69
-
70
- #### `POST /v1/chat/completions`
71
-
72
- OpenAI-compatible chat completion. Supports `stream: true` for SSE.
73
-
74
- #### `POST /v1/messages`
75
-
76
- Anthropic-compatible messages endpoint. Supports `stream: true` for SSE.
77
-
78
- #### `POST /v1/embeddings`
79
-
80
- OpenAI-compatible embedding generation.
81
-
82
- #### `GET /v1/models`
83
-
84
- Lists available models for the authenticated virtual key.
85
-
86
- ### Health
87
-
88
- | Endpoint | Purpose |
89
- |--------------|------------------------------------------------|
90
- | `/healthz` | Liveness probe (always 200) |
91
- | `/readyz` | Readiness probe (503 until auth cache warms) |
92
- | `/startupz` | Startup probe |
93
-
94
- ### Response headers
95
-
96
- Every proxied response includes:
97
-
98
- - `X-LangWatch-Gateway-Version` — build version of the running gateway.
99
- - `X-LangWatch-Gateway-Request-Id` — gateway-minted ID for debit idempotency.
100
- - `X-LangWatch-Budget-Warning` — present when budget thresholds are breached.
101
- - `X-LangWatch-Fallback-Count` — number of provider fallbacks attempted.
102
- - `X-LangWatch-Cache-Mode` — cache override decision (`respect`, `disable`, or `force`).
103
-
104
- ## Request pipeline
105
-
106
- Each request passes through an interceptor chain:
107
-
108
- ```
109
- Auth → RateLimit → Policy → Resolve → Cache → Budget → Guardrail → Dispatch → Trace
110
- ```
111
-
112
- All interceptors are defined as port interfaces in `app/ports.go`.
113
-
114
- ## Running locally
115
-
116
- ```bash
117
- make service svc=aigateway # run once
118
- make service-watch svc=aigateway # live reload via air
119
- ```
120
-
121
- This sources `langwatch/.env` in full — Go and the TS control-plane
122
- share the same file, so secrets like `LW_GATEWAY_INTERNAL_SECRET` live in
123
- exactly one place. Vars the Go service doesn't need are ignored by
124
- `config.Hydrate`. Required: `LW_GATEWAY_INTERNAL_SECRET`,
125
- `LW_GATEWAY_JWT_SECRET`, `LW_GATEWAY_BASE_URL` (see
126
- `langwatch/.env.example`).
127
-
128
- Logs emit as pretty-printed JSON locally (`LOG_FORMAT=pretty` is set by the
129
- Makefile target).
130
-
131
- ## Configuration
132
-
133
- All config is loaded from environment variables via `pkg/config.Hydrate` (nested
134
- struct tags chain with `_`). See `config.go` for the source of truth.
135
-
136
- | Variable | Required | Default | Description |
137
- |----------------------------------|----------|-----------------------|------------------------------------|
138
- | `ENVIRONMENT` | yes | | e.g. `local`, `production` |
139
- | `SERVER_ADDR` | no | `:5563` | Listen address |
140
- | `SERVER_GRACEFUL_SECONDS` | no | `10` | Shutdown grace period (seconds) |
141
- | `LOG_LEVEL` | no | `info` | Log level |
142
- | `LOG_FORMAT` | no | `json` | `json` or `pretty` |
143
- | `LW_GATEWAY_BASE_URL` | yes | `http://localhost:5560` | Control plane URL |
144
- | `LW_GATEWAY_INTERNAL_SECRET` | yes | | HMAC shared secret |
145
- | `LW_GATEWAY_JWT_SECRET` | yes | | JWT verification secret |
146
- | `LW_GATEWAY_JWT_SECRET_PREVIOUS`| no | | Previous JWT secret (rotation) |
147
- | `OTEL_GATEWAY_ENDPOINT` | no | | OTel collector for gateway traces |
148
- | `OTEL_GATEWAY_AUTH_TOKEN` | no | | Bearer token for OTel collector |
149
- | `OTEL_DEFAULT_EXPORT_ENDPOINT` | no | | Default customer OTLP endpoint |
150
- | `OTEL_DEFAULT_AUTH_TOKEN` | no | | Bearer token for default endpoint |
151
-
152
- ## Testing
153
-
154
- ```bash
155
- go test -race -count=1 ./services/aigateway/...
156
- ```
@@ -1,13 +0,0 @@
1
- package authresolver
2
-
3
- import "testing"
4
-
5
- // BenchmarkHashKey is the hot-path cache lookup hash. Fires on every
6
- // inbound request BEFORE we can serve from L1.
7
- func BenchmarkHashKey(b *testing.B) {
8
- raw := "lw_vk_live_01HZX0123456789ABCDEFGHIJ"
9
- b.ReportAllocs()
10
- for i := 0; i < b.N; i++ {
11
- _ = hashKey(raw)
12
- }
13
- }
@@ -1,61 +0,0 @@
1
- package authresolver
2
-
3
- import (
4
- "context"
5
- "encoding/json"
6
- "errors"
7
- "time"
8
-
9
- "github.com/redis/go-redis/v9"
10
-
11
- "github.com/langwatch/langwatch/services/aigateway/domain"
12
- )
13
-
14
- const keyPrefix = "gw:auth:"
15
- const minTTL = 30 * time.Second
16
-
17
- // RedisStore is the L2 cache backed by Redis. Implements L2Store.
18
- type RedisStore struct {
19
- client redis.UniversalClient
20
- }
21
-
22
- // NewRedisStore creates a Redis L2 store.
23
- func NewRedisStore(client redis.UniversalClient) *RedisStore {
24
- return &RedisStore{client: client}
25
- }
26
-
27
- // Get retrieves a bundle from Redis by key hash.
28
- func (s *RedisStore) Get(ctx context.Context, hash string) (*domain.Bundle, error) {
29
- raw, err := s.client.Get(ctx, keyPrefix+hash).Bytes()
30
- if err != nil {
31
- if errors.Is(err, redis.Nil) {
32
- return nil, nil
33
- }
34
- return nil, err
35
- }
36
- var bundle domain.Bundle
37
- if err := json.Unmarshal(raw, &bundle); err != nil {
38
- _ = s.client.Del(ctx, keyPrefix+hash).Err()
39
- return nil, nil //nolint:nilerr // corrupted cache entry — treat as miss
40
- }
41
- if time.Now().After(bundle.ExpiresAt) {
42
- return nil, nil
43
- }
44
- return &bundle, nil
45
- }
46
-
47
- // Set writes a bundle to Redis with TTL matching its expiry.
48
- func (s *RedisStore) Set(ctx context.Context, hash string, bundle *domain.Bundle) {
49
- if bundle == nil {
50
- return
51
- }
52
- ttl := time.Until(bundle.ExpiresAt)
53
- if ttl < minTTL {
54
- ttl = minTTL
55
- }
56
- raw, err := json.Marshal(bundle)
57
- if err != nil {
58
- return
59
- }
60
- _ = s.client.Set(ctx, keyPrefix+hash, raw, ttl).Err()
61
- }