@langwatch/server 3.1.0-beta.8 → 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.
- package/package.json +1 -6
- package/packages/server/dist/cli.cjs +19 -16
- package/cmd/service/main.go +0 -68
- package/go.mod +0 -117
- package/go.sum +0 -299
- package/pkg/breaker/breaker.go +0 -157
- package/pkg/breaker/breaker_test.go +0 -131
- package/pkg/clog/LICENSE +0 -26
- package/pkg/clog/clog.go +0 -90
- package/pkg/clog/clog_test.go +0 -56
- package/pkg/clog/panic.go +0 -39
- package/pkg/config/LICENSE +0 -26
- package/pkg/config/config.go +0 -86
- package/pkg/config/config_test.go +0 -70
- package/pkg/config/otel.go +0 -50
- package/pkg/config/server.go +0 -61
- package/pkg/config/validate.go +0 -80
- package/pkg/config/validate_test.go +0 -74
- package/pkg/contexts/contexts_test.go +0 -34
- package/pkg/contexts/request_id.go +0 -1
- package/pkg/contexts/service_info.go +0 -33
- package/pkg/errfuncs/errfuncs.go +0 -9
- package/pkg/errfuncs/errfuncs_test.go +0 -28
- package/pkg/forkedcontext/forkedcontext.go +0 -57
- package/pkg/health/health.go +0 -123
- package/pkg/health/health_test.go +0 -84
- package/pkg/herr/LICENSE +0 -26
- package/pkg/herr/code.go +0 -14
- package/pkg/herr/herr.go +0 -112
- package/pkg/herr/herr_test.go +0 -78
- package/pkg/herr/http.go +0 -133
- package/pkg/herr/http_test.go +0 -103
- package/pkg/herr/validate.go +0 -72
- package/pkg/herr/validate_test.go +0 -75
- package/pkg/httpmiddleware/bearer.go +0 -47
- package/pkg/httpmiddleware/httputil_test.go +0 -167
- package/pkg/httpmiddleware/inflight.go +0 -23
- package/pkg/httpmiddleware/maxbody.go +0 -30
- package/pkg/httpmiddleware/recover.go +0 -38
- package/pkg/httpmiddleware/requestid.go +0 -40
- package/pkg/httpmiddleware/telemetry.go +0 -96
- package/pkg/httpmiddleware/version.go +0 -16
- package/pkg/jwtverify/verifier.go +0 -72
- package/pkg/jwtverify/verifier_test.go +0 -134
- package/pkg/ksuid/LICENSE +0 -26
- package/pkg/ksuid/ksuid.go +0 -157
- package/pkg/ksuid/ksuid_test.go +0 -107
- package/pkg/ksuid/resources.go +0 -13
- package/pkg/lifecycle/group.go +0 -175
- package/pkg/lifecycle/group_test.go +0 -236
- package/pkg/lifecycle/service.go +0 -112
- package/pkg/netprobe/netprobe.go +0 -89
- package/pkg/netprobe/netprobe_test.go +0 -55
- package/pkg/otelsetup/otelsetup.go +0 -226
- package/pkg/otelsetup/otelsetup_test.go +0 -130
- package/pkg/ptr/LICENSE +0 -26
- package/pkg/ptr/ptr.go +0 -34
- package/pkg/ptr/ptr_test.go +0 -66
- package/pkg/retry/bench_test.go +0 -67
- package/pkg/retry/retry.go +0 -188
- package/pkg/retry/retry_test.go +0 -222
- package/pkg/slicefuncs/LICENSE +0 -26
- package/pkg/slicefuncs/slicefuncs.go +0 -10
- package/pkg/slicefuncs/slicefuncs_test.go +0 -29
- package/pkg/stacktrace/LICENSE +0 -26
- package/pkg/stacktrace/frames.go +0 -77
- package/pkg/stacktrace/frames_test.go +0 -73
- package/services/aigateway/BENCHMARKS.md +0 -110
- package/services/aigateway/README.md +0 -156
- package/services/aigateway/adapters/authresolver/bench_test.go +0 -13
- package/services/aigateway/adapters/authresolver/redis.go +0 -61
- package/services/aigateway/adapters/authresolver/service.go +0 -442
- package/services/aigateway/adapters/authresolver/service_test.go +0 -435
- package/services/aigateway/adapters/budget/bench_test.go +0 -50
- package/services/aigateway/adapters/budget/budget.go +0 -59
- package/services/aigateway/adapters/cacherules/evaluator.go +0 -134
- package/services/aigateway/adapters/cacherules/evaluator_test.go +0 -207
- package/services/aigateway/adapters/controlplane/bench_test.go +0 -40
- package/services/aigateway/adapters/controlplane/client.go +0 -213
- package/services/aigateway/adapters/controlplane/client_test.go +0 -73
- package/services/aigateway/adapters/controlplane/config_wire.go +0 -310
- package/services/aigateway/adapters/controlplane/guardrails.go +0 -88
- package/services/aigateway/adapters/controlplane/signer.go +0 -95
- package/services/aigateway/adapters/controlplane/signer_test.go +0 -64
- package/services/aigateway/adapters/customertracebridge/context.go +0 -48
- package/services/aigateway/adapters/customertracebridge/context_test.go +0 -24
- package/services/aigateway/adapters/customertracebridge/emitter.go +0 -329
- package/services/aigateway/adapters/customertracebridge/emitter_test.go +0 -93
- package/services/aigateway/adapters/customertracebridge/registry.go +0 -82
- package/services/aigateway/adapters/customertracebridge/transport.go +0 -122
- package/services/aigateway/adapters/gatewaytracer/attrs.go +0 -28
- package/services/aigateway/adapters/gatewaytracer/attrs_genai.go +0 -24
- package/services/aigateway/adapters/gatewaytracer/headers.go +0 -8
- package/services/aigateway/adapters/gatewaytracer/tracer.go +0 -101
- package/services/aigateway/adapters/httpapi/bench_test.go +0 -83
- package/services/aigateway/adapters/httpapi/middleware.go +0 -123
- package/services/aigateway/adapters/httpapi/router.go +0 -635
- package/services/aigateway/adapters/httpapi/router_test.go +0 -633
- package/services/aigateway/adapters/modelresolver/resolver.go +0 -107
- package/services/aigateway/adapters/modelresolver/resolver_test.go +0 -140
- package/services/aigateway/adapters/policy/matcher.go +0 -250
- package/services/aigateway/adapters/policy/matcher_test.go +0 -124
- package/services/aigateway/adapters/providers/bifrost.go +0 -798
- package/services/aigateway/adapters/providers/bifrost_parser.go +0 -201
- package/services/aigateway/adapters/providers/bifrost_test.go +0 -181
- package/services/aigateway/adapters/ratelimit/limiter.go +0 -122
- package/services/aigateway/adapters/ratelimit/limiter_test.go +0 -81
- package/services/aigateway/app/app.go +0 -104
- package/services/aigateway/app/dispatch.go +0 -89
- package/services/aigateway/app/dispatch_test.go +0 -475
- package/services/aigateway/app/handlers.go +0 -79
- package/services/aigateway/app/peek_bench_test.go +0 -21
- package/services/aigateway/app/pipeline/bench_test.go +0 -34
- package/services/aigateway/app/pipeline/budget.go +0 -55
- package/services/aigateway/app/pipeline/cache.go +0 -34
- package/services/aigateway/app/pipeline/cachecontrol.go +0 -86
- package/services/aigateway/app/pipeline/cachecontrol_test.go +0 -110
- package/services/aigateway/app/pipeline/guardrail.go +0 -121
- package/services/aigateway/app/pipeline/pipeline.go +0 -159
- package/services/aigateway/app/pipeline/policy.go +0 -23
- package/services/aigateway/app/pipeline/ratelimit.go +0 -21
- package/services/aigateway/app/pipeline/rawframing_test.go +0 -67
- package/services/aigateway/app/pipeline/resolve.go +0 -44
- package/services/aigateway/app/pipeline/trace.go +0 -129
- package/services/aigateway/app/ports.go +0 -61
- package/services/aigateway/cmd/root.go +0 -42
- package/services/aigateway/config.go +0 -86
- package/services/aigateway/deps.go +0 -177
- package/services/aigateway/domain/bundle.go +0 -203
- package/services/aigateway/domain/errors.go +0 -23
- package/services/aigateway/domain/model.go +0 -24
- package/services/aigateway/domain/provider.go +0 -38
- package/services/aigateway/domain/request.go +0 -65
- package/services/aigateway/domain/response.go +0 -56
- package/services/aigateway/domain/verdict.go +0 -55
- package/services/aigateway/serve.go +0 -45
- package/services/aigateway/tests/matrix/README.md +0 -71
- package/services/aigateway/tests/matrix/anthropic_test.go +0 -61
- package/services/aigateway/tests/matrix/azure_test.go +0 -52
- package/services/aigateway/tests/matrix/bedrock_test.go +0 -69
- package/services/aigateway/tests/matrix/gemini_test.go +0 -117
- package/services/aigateway/tests/matrix/matrix_test.go +0 -601
- package/services/aigateway/tests/matrix/openai_test.go +0 -66
- package/services/aigateway/tests/matrix/vertex_test.go +0 -160
|
@@ -1,442 +0,0 @@
|
|
|
1
|
-
// Package authresolver resolves virtual-key bearer tokens into domain.Bundle
|
|
2
|
-
// via a three-tier cache (L1 in-memory LRU → L2 optional store → L3 upstream resolver).
|
|
3
|
-
//
|
|
4
|
-
// Stale-while-error: when a cached L1 entry crosses its natural JWT expiry
|
|
5
|
-
// AND the upstream refresh fails for transport reasons (network error, dial
|
|
6
|
-
// timeout, 5xx, connection refused, malformed response, JWT verify failure),
|
|
7
|
-
// the entry's soft expiry is bumped by SoftBump and the cached bundle keeps
|
|
8
|
-
// serving, up to a hard cap (JWT exp + HardGrace). Any auth-class rejection
|
|
9
|
-
// (401/403/404) evicts immediately — bad credentials get no grace window.
|
|
10
|
-
// See specs/ai-gateway/auth-cache.feature, Rule "Cached JWT serves
|
|
11
|
-
// stale-while-error past natural expiry on transport failure".
|
|
12
|
-
package authresolver
|
|
13
|
-
|
|
14
|
-
import (
|
|
15
|
-
"context"
|
|
16
|
-
"crypto/sha256"
|
|
17
|
-
"encoding/hex"
|
|
18
|
-
"errors"
|
|
19
|
-
"sync"
|
|
20
|
-
"time"
|
|
21
|
-
|
|
22
|
-
lru "github.com/hashicorp/golang-lru/v2"
|
|
23
|
-
"go.uber.org/zap"
|
|
24
|
-
|
|
25
|
-
"github.com/langwatch/langwatch/pkg/herr"
|
|
26
|
-
"github.com/langwatch/langwatch/services/aigateway/domain"
|
|
27
|
-
)
|
|
28
|
-
|
|
29
|
-
// L2Store is an optional second-level cache (e.g., Redis).
|
|
30
|
-
type L2Store interface {
|
|
31
|
-
Get(ctx context.Context, hash string) (*domain.Bundle, error)
|
|
32
|
-
Set(ctx context.Context, hash string, bundle *domain.Bundle)
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// KeyResolver resolves a raw API key into a Bundle via an upstream source.
|
|
36
|
-
type KeyResolver interface {
|
|
37
|
-
ResolveKey(ctx context.Context, rawKey string) (*domain.Bundle, error)
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// ConfigFetcher retrieves configuration for a virtual key.
|
|
41
|
-
type ConfigFetcher interface {
|
|
42
|
-
FetchConfig(ctx context.Context, vkID string) (domain.BundleConfig, error)
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
// Service is the three-tier auth resolver.
|
|
46
|
-
type Service struct {
|
|
47
|
-
l1 *lru.Cache[[64]byte, *entry]
|
|
48
|
-
l2 L2Store
|
|
49
|
-
resolver KeyResolver
|
|
50
|
-
configFetcher ConfigFetcher
|
|
51
|
-
logger *zap.Logger
|
|
52
|
-
|
|
53
|
-
refreshThreshold time.Duration
|
|
54
|
-
softBump time.Duration
|
|
55
|
-
hardGrace time.Duration
|
|
56
|
-
|
|
57
|
-
stopCh chan struct{}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// entry tracks both the natural JWT exp ("soft" expiry, bumpable on
|
|
61
|
-
// transport failure) and the absolute hard cap. softExpiresAt is mutable;
|
|
62
|
-
// hardExpiresAt is set once at insert time and never changes.
|
|
63
|
-
type entry struct {
|
|
64
|
-
mu sync.Mutex
|
|
65
|
-
bundle *domain.Bundle
|
|
66
|
-
softExpiresAt time.Time
|
|
67
|
-
hardExpiresAt time.Time
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
func (e *entry) softExpired() bool {
|
|
71
|
-
e.mu.Lock()
|
|
72
|
-
defer e.mu.Unlock()
|
|
73
|
-
return time.Now().After(e.softExpiresAt)
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
func (e *entry) hardExpired() bool {
|
|
77
|
-
e.mu.Lock()
|
|
78
|
-
defer e.mu.Unlock()
|
|
79
|
-
return time.Now().After(e.hardExpiresAt)
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
func (e *entry) nearSoftExpiry(threshold time.Duration) bool {
|
|
83
|
-
e.mu.Lock()
|
|
84
|
-
defer e.mu.Unlock()
|
|
85
|
-
return time.Until(e.softExpiresAt) < threshold
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// bumpSoft pushes softExpiresAt forward by amount, capped at hardExpiresAt.
|
|
89
|
-
// Returns the new soft expiry and whether any bump applied (false when
|
|
90
|
-
// the entry was already at or past the hard cap).
|
|
91
|
-
func (e *entry) bumpSoft(amount time.Duration) (time.Time, bool) {
|
|
92
|
-
e.mu.Lock()
|
|
93
|
-
defer e.mu.Unlock()
|
|
94
|
-
target := time.Now().Add(amount)
|
|
95
|
-
if target.After(e.hardExpiresAt) {
|
|
96
|
-
target = e.hardExpiresAt
|
|
97
|
-
}
|
|
98
|
-
if !target.After(e.softExpiresAt) {
|
|
99
|
-
return e.softExpiresAt, false
|
|
100
|
-
}
|
|
101
|
-
e.softExpiresAt = target
|
|
102
|
-
return e.softExpiresAt, true
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
func (e *entry) snapshot() (bundle *domain.Bundle, soft, hard time.Time) {
|
|
106
|
-
e.mu.Lock()
|
|
107
|
-
defer e.mu.Unlock()
|
|
108
|
-
return e.bundle, e.softExpiresAt, e.hardExpiresAt
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
// refreshErrorClass maps an upstream resolver error to an action policy.
|
|
112
|
-
// AuthRejection means the control plane explicitly said "this key is not
|
|
113
|
-
// valid"; the cached entry must be evicted. TransportFailure means the
|
|
114
|
-
// control plane could not give us a useful answer (network, 5xx, parse);
|
|
115
|
-
// the cached entry should be preserved and its soft expiry bumped.
|
|
116
|
-
type refreshErrorClass int
|
|
117
|
-
|
|
118
|
-
const (
|
|
119
|
-
classNone refreshErrorClass = iota
|
|
120
|
-
classAuthRejection
|
|
121
|
-
classTransportFailure
|
|
122
|
-
)
|
|
123
|
-
|
|
124
|
-
func (c refreshErrorClass) String() string {
|
|
125
|
-
switch c {
|
|
126
|
-
case classNone:
|
|
127
|
-
return "none"
|
|
128
|
-
case classAuthRejection:
|
|
129
|
-
return "auth_rejection"
|
|
130
|
-
case classTransportFailure:
|
|
131
|
-
return "transport"
|
|
132
|
-
default:
|
|
133
|
-
return "unknown"
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// classifyRefreshError maps an upstream resolver error to a class.
|
|
138
|
-
// Conservative on unknown shapes: anything that isn't an explicit
|
|
139
|
-
// AuthRejection is treated as transport — we'd rather serve stale on a
|
|
140
|
-
// surprising error than evict a good key the operator can't easily
|
|
141
|
-
// re-create.
|
|
142
|
-
func classifyRefreshError(err error) refreshErrorClass {
|
|
143
|
-
if err == nil {
|
|
144
|
-
return classNone
|
|
145
|
-
}
|
|
146
|
-
if errors.Is(err, domain.ErrInvalidAPIKey) || errors.Is(err, domain.ErrKeyRevoked) {
|
|
147
|
-
return classAuthRejection
|
|
148
|
-
}
|
|
149
|
-
return classTransportFailure
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
// Options configures the auth service.
|
|
153
|
-
type Options struct {
|
|
154
|
-
LRUSize int
|
|
155
|
-
RefreshThreshold time.Duration
|
|
156
|
-
// SoftBump is how much to extend a stale entry's soft expiry on each
|
|
157
|
-
// transport-class refresh failure. Default 5m.
|
|
158
|
-
SoftBump time.Duration
|
|
159
|
-
// HardGrace is the absolute cap on extending a stale entry beyond its
|
|
160
|
-
// natural JWT exp. Default 6h. Setting 0 disables stale-while-error
|
|
161
|
-
// entirely (legacy behavior: hard-fail at JWT exp).
|
|
162
|
-
HardGrace time.Duration
|
|
163
|
-
Logger *zap.Logger
|
|
164
|
-
L2 L2Store // optional, nil = skip L2
|
|
165
|
-
Resolver KeyResolver
|
|
166
|
-
ConfigFetcher ConfigFetcher
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
// New creates the auth service.
|
|
170
|
-
func New(opts Options) (*Service, error) {
|
|
171
|
-
if opts.LRUSize <= 0 {
|
|
172
|
-
opts.LRUSize = 10_000
|
|
173
|
-
}
|
|
174
|
-
if opts.RefreshThreshold == 0 {
|
|
175
|
-
opts.RefreshThreshold = 5 * time.Minute
|
|
176
|
-
}
|
|
177
|
-
if opts.SoftBump == 0 {
|
|
178
|
-
opts.SoftBump = 5 * time.Minute
|
|
179
|
-
}
|
|
180
|
-
// HardGrace == 0 is a documented opt-out (disables stale-while-error).
|
|
181
|
-
// Only fill in the default when the field was unset entirely.
|
|
182
|
-
if opts.HardGrace == 0 {
|
|
183
|
-
opts.HardGrace = 6 * time.Hour
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
l1, err := lru.New[[64]byte, *entry](opts.LRUSize)
|
|
187
|
-
if err != nil {
|
|
188
|
-
return nil, err
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
logger := opts.Logger
|
|
192
|
-
if logger == nil {
|
|
193
|
-
logger = zap.NewNop()
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
return &Service{
|
|
197
|
-
l1: l1,
|
|
198
|
-
l2: opts.L2,
|
|
199
|
-
resolver: opts.Resolver,
|
|
200
|
-
configFetcher: opts.ConfigFetcher,
|
|
201
|
-
logger: logger,
|
|
202
|
-
refreshThreshold: opts.RefreshThreshold,
|
|
203
|
-
softBump: opts.SoftBump,
|
|
204
|
-
hardGrace: opts.HardGrace,
|
|
205
|
-
stopCh: make(chan struct{}),
|
|
206
|
-
}, nil
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
// Resolve returns a Bundle for the raw bearer token.
|
|
210
|
-
// Checks L1 → L2 → upstream resolver, caching at each tier.
|
|
211
|
-
//
|
|
212
|
-
// On L1 hit past softExpiresAt but within hardExpiresAt, attempts a
|
|
213
|
-
// foreground refresh; on transport-class failure serves the stale bundle
|
|
214
|
-
// and bumps soft expiry. On auth-class failure evicts and rejects.
|
|
215
|
-
func (s *Service) Resolve(ctx context.Context, rawKey string) (*domain.Bundle, error) {
|
|
216
|
-
if rawKey == "" {
|
|
217
|
-
return nil, herr.New(ctx, domain.ErrInvalidAPIKey, nil)
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
h := hashKey(rawKey)
|
|
221
|
-
|
|
222
|
-
// L1: in-memory
|
|
223
|
-
if e, ok := s.l1.Get(h); ok {
|
|
224
|
-
switch {
|
|
225
|
-
case !e.softExpired():
|
|
226
|
-
// Fresh: serve, maybe trigger background refresh on near-expiry.
|
|
227
|
-
if e.nearSoftExpiry(s.refreshThreshold) {
|
|
228
|
-
go s.refreshBackground(rawKey, h) //nolint:gosec // G118: intentional fire-and-forget refresh detached from request
|
|
229
|
-
}
|
|
230
|
-
return e.bundle, nil
|
|
231
|
-
|
|
232
|
-
case !e.hardExpired():
|
|
233
|
-
// Soft-expired but within hard grace. Try foreground refresh;
|
|
234
|
-
// stale-while-error on transport failure.
|
|
235
|
-
return s.refreshOrServeStale(ctx, rawKey, h, e)
|
|
236
|
-
|
|
237
|
-
default:
|
|
238
|
-
// Past hard cap: evict, fall through to fresh resolve.
|
|
239
|
-
s.l1.Remove(h)
|
|
240
|
-
s.logger.Error("auth_cache_hard_evict",
|
|
241
|
-
zap.String("vk_id", e.bundle.VirtualKeyID),
|
|
242
|
-
zap.String("reason", "hard_cap_exceeded_on_lookup"),
|
|
243
|
-
)
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
// L2: optional store
|
|
248
|
-
if s.l2 != nil {
|
|
249
|
-
hStr := string(h[:])
|
|
250
|
-
if bundle, err := s.l2.Get(ctx, hStr); err == nil && bundle != nil {
|
|
251
|
-
s.storeL1(h, bundle)
|
|
252
|
-
return bundle, nil
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
// L3: upstream resolver
|
|
257
|
-
return s.resolveFresh(ctx, rawKey, h)
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
// resolveFresh calls the upstream resolver and caches the result.
|
|
261
|
-
// Used for cold L1+L2 misses; not on stale-entry refresh paths (those
|
|
262
|
-
// use refreshOrServeStale for the served-stale fallback).
|
|
263
|
-
func (s *Service) resolveFresh(ctx context.Context, rawKey string, h [64]byte) (*domain.Bundle, error) {
|
|
264
|
-
bundle, err := s.resolver.ResolveKey(ctx, rawKey)
|
|
265
|
-
if err != nil {
|
|
266
|
-
return nil, err
|
|
267
|
-
}
|
|
268
|
-
s.populateConfig(ctx, bundle)
|
|
269
|
-
s.storeL1(h, bundle)
|
|
270
|
-
if s.l2 != nil {
|
|
271
|
-
s.l2.Set(ctx, string(h[:]), bundle)
|
|
272
|
-
}
|
|
273
|
-
return bundle, nil
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
// refreshOrServeStale tries to resolve fresh against the control plane.
|
|
277
|
-
// On success replaces the L1 entry. On transport-class failure bumps the
|
|
278
|
-
// stale entry's soft expiry by SoftBump and serves the stale bundle. On
|
|
279
|
-
// auth-class failure evicts the entry and returns the rejection.
|
|
280
|
-
func (s *Service) refreshOrServeStale(ctx context.Context, rawKey string, h [64]byte, stale *entry) (*domain.Bundle, error) {
|
|
281
|
-
bundle, err := s.resolver.ResolveKey(ctx, rawKey)
|
|
282
|
-
cls := classifyRefreshError(err)
|
|
283
|
-
|
|
284
|
-
staleBundle, _, hardExpiresAt := stale.snapshot()
|
|
285
|
-
vkID := staleBundle.VirtualKeyID
|
|
286
|
-
|
|
287
|
-
switch cls {
|
|
288
|
-
case classNone:
|
|
289
|
-
s.populateConfig(ctx, bundle)
|
|
290
|
-
s.storeL1(h, bundle)
|
|
291
|
-
if s.l2 != nil {
|
|
292
|
-
s.l2.Set(ctx, string(h[:]), bundle)
|
|
293
|
-
}
|
|
294
|
-
return bundle, nil
|
|
295
|
-
|
|
296
|
-
case classAuthRejection:
|
|
297
|
-
s.l1.Remove(h)
|
|
298
|
-
s.logger.Error("auth_cache_hard_evict",
|
|
299
|
-
zap.String("vk_id", vkID),
|
|
300
|
-
zap.String("reason", "auth_rejection"),
|
|
301
|
-
zap.Error(err),
|
|
302
|
-
)
|
|
303
|
-
return nil, err
|
|
304
|
-
|
|
305
|
-
default:
|
|
306
|
-
newSoft, bumped := stale.bumpSoft(s.softBump)
|
|
307
|
-
if !bumped {
|
|
308
|
-
s.l1.Remove(h)
|
|
309
|
-
s.logger.Error("auth_cache_hard_evict",
|
|
310
|
-
zap.String("vk_id", vkID),
|
|
311
|
-
zap.String("reason", "hard_cap_exceeded"),
|
|
312
|
-
zap.Error(err),
|
|
313
|
-
)
|
|
314
|
-
return nil, err
|
|
315
|
-
}
|
|
316
|
-
s.logger.Warn("auth_cache_refresh_transport_failure",
|
|
317
|
-
zap.String("vk_id", vkID),
|
|
318
|
-
zap.Time("new_soft_expires_at", newSoft),
|
|
319
|
-
zap.Duration("hard_grace_remaining", time.Until(hardExpiresAt)),
|
|
320
|
-
zap.Error(err),
|
|
321
|
-
)
|
|
322
|
-
s.logger.Info("auth_cache_serve_stale",
|
|
323
|
-
zap.String("vk_id", vkID),
|
|
324
|
-
zap.Duration("stale_for", time.Since(staleBundle.ExpiresAt)),
|
|
325
|
-
zap.Duration("hard_grace_remaining", time.Until(hardExpiresAt)),
|
|
326
|
-
zap.String("refresh_error_class", cls.String()),
|
|
327
|
-
)
|
|
328
|
-
return staleBundle, nil
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
// populateConfig eagerly fetches the bundle's config and merges it into the
|
|
333
|
-
// bundle. Failure here is non-fatal — the bundle still serves with empty
|
|
334
|
-
// config.Credentials, and downstream resolution will surface its own error.
|
|
335
|
-
func (s *Service) populateConfig(ctx context.Context, bundle *domain.Bundle) {
|
|
336
|
-
if bundle == nil {
|
|
337
|
-
return
|
|
338
|
-
}
|
|
339
|
-
cfg, err := s.configFetcher.FetchConfig(ctx, bundle.VirtualKeyID)
|
|
340
|
-
if err != nil {
|
|
341
|
-
s.logger.Warn("config_fetch_failed", zap.String("vk_id", bundle.VirtualKeyID), zap.Error(err))
|
|
342
|
-
return
|
|
343
|
-
}
|
|
344
|
-
bundle.Config = cfg
|
|
345
|
-
bundle.Credentials = cfg.Credentials
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
// Start launches the background refresh loop.
|
|
349
|
-
func (s *Service) Start(ctx context.Context) {
|
|
350
|
-
go s.loop(ctx)
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
// Stop signals background goroutines to exit.
|
|
354
|
-
func (s *Service) Stop() {
|
|
355
|
-
select {
|
|
356
|
-
case <-s.stopCh:
|
|
357
|
-
default:
|
|
358
|
-
close(s.stopCh)
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
// --- Internal ---
|
|
363
|
-
|
|
364
|
-
func (s *Service) storeL1(h [64]byte, bundle *domain.Bundle) {
|
|
365
|
-
s.l1.Add(h, &entry{
|
|
366
|
-
bundle: bundle,
|
|
367
|
-
softExpiresAt: bundle.ExpiresAt,
|
|
368
|
-
hardExpiresAt: bundle.ExpiresAt.Add(s.hardGrace),
|
|
369
|
-
})
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
// refreshBackground is the near-soft-expiry proactive refresh: fires
|
|
373
|
-
// fire-and-forget when the entry has less than RefreshThreshold left
|
|
374
|
-
// before softExpiresAt. Same classification as foreground:
|
|
375
|
-
// AuthRejection evicts; TransportFailure bumps the existing entry.
|
|
376
|
-
func (s *Service) refreshBackground(rawKey string, h [64]byte) {
|
|
377
|
-
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
|
378
|
-
defer cancel()
|
|
379
|
-
bundle, err := s.resolver.ResolveKey(ctx, rawKey)
|
|
380
|
-
cls := classifyRefreshError(err)
|
|
381
|
-
|
|
382
|
-
switch cls {
|
|
383
|
-
case classNone:
|
|
384
|
-
s.populateConfig(ctx, bundle)
|
|
385
|
-
s.storeL1(h, bundle)
|
|
386
|
-
if s.l2 != nil {
|
|
387
|
-
s.l2.Set(ctx, string(h[:]), bundle)
|
|
388
|
-
}
|
|
389
|
-
s.logger.Debug("auth_cache_refresh_success", zap.String("vk_id", bundle.VirtualKeyID))
|
|
390
|
-
|
|
391
|
-
case classAuthRejection:
|
|
392
|
-
var vkID string
|
|
393
|
-
if e, ok := s.l1.Get(h); ok {
|
|
394
|
-
vkID = e.bundle.VirtualKeyID
|
|
395
|
-
}
|
|
396
|
-
s.l1.Remove(h)
|
|
397
|
-
s.logger.Error("auth_cache_hard_evict",
|
|
398
|
-
zap.String("vk_id", vkID),
|
|
399
|
-
zap.String("reason", "auth_rejection_async"),
|
|
400
|
-
zap.Error(err),
|
|
401
|
-
)
|
|
402
|
-
|
|
403
|
-
default:
|
|
404
|
-
e, ok := s.l1.Get(h)
|
|
405
|
-
if !ok {
|
|
406
|
-
return
|
|
407
|
-
}
|
|
408
|
-
newSoft, bumped := e.bumpSoft(s.softBump)
|
|
409
|
-
if !bumped {
|
|
410
|
-
return
|
|
411
|
-
}
|
|
412
|
-
_, _, hardExpiresAt := e.snapshot()
|
|
413
|
-
s.logger.Warn("auth_cache_refresh_transport_failure",
|
|
414
|
-
zap.String("vk_id", e.bundle.VirtualKeyID),
|
|
415
|
-
zap.Time("new_soft_expires_at", newSoft),
|
|
416
|
-
zap.Duration("hard_grace_remaining", time.Until(hardExpiresAt)),
|
|
417
|
-
zap.Error(err),
|
|
418
|
-
)
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
func (s *Service) loop(ctx context.Context) {
|
|
423
|
-
t := time.NewTicker(60 * time.Second)
|
|
424
|
-
defer t.Stop()
|
|
425
|
-
for {
|
|
426
|
-
select {
|
|
427
|
-
case <-ctx.Done():
|
|
428
|
-
return
|
|
429
|
-
case <-s.stopCh:
|
|
430
|
-
return
|
|
431
|
-
case <-t.C:
|
|
432
|
-
// Entries near expiry refresh on next request hit
|
|
433
|
-
}
|
|
434
|
-
}
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
func hashKey(raw string) [64]byte {
|
|
438
|
-
sum := sha256.Sum256([]byte(raw))
|
|
439
|
-
var dst [64]byte
|
|
440
|
-
hex.Encode(dst[:], sum[:])
|
|
441
|
-
return dst
|
|
442
|
-
}
|