-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnexus.go
More file actions
270 lines (219 loc) · 7.12 KB
/
nexus.go
File metadata and controls
270 lines (219 loc) · 7.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
// Package nexus is a composable AI gateway library for Go.
// Route, cache, guard, and observe LLM traffic at scale.
//
// Nexus is a library, not a SaaS. Import it, compose your AI gateway,
// and own your infrastructure.
//
// gw := nexus.New(
// nexus.WithProvider(openai.New("sk-...")),
// nexus.WithProvider(anthropic.New("sk-ant-...")),
// nexus.WithRouter(router.NewCostOptimized()),
// nexus.WithCache(cache.NewRedis(redisClient)),
// nexus.WithGuard(guard.NewPII(guard.ActionRedact)),
// )
// gw.Initialize(ctx)
// gw.Mount(router, "/ai")
package nexus
import (
"context"
"net/http"
"time"
"github.com/xraph/nexus/auth"
"github.com/xraph/nexus/cache"
"github.com/xraph/nexus/guard"
"github.com/xraph/nexus/key"
"github.com/xraph/nexus/model"
"github.com/xraph/nexus/observability"
"github.com/xraph/nexus/pipeline"
"github.com/xraph/nexus/pipeline/middlewares"
"github.com/xraph/nexus/plugin"
"github.com/xraph/nexus/provider"
"github.com/xraph/nexus/router"
"github.com/xraph/nexus/router/strategies"
"github.com/xraph/nexus/store"
"github.com/xraph/nexus/tenant"
"github.com/xraph/nexus/transform"
"github.com/xraph/nexus/usage"
)
// Gateway is the root Nexus instance.
// It can be used standalone or mounted into a Forge application.
type Gateway struct {
config *Config
engine *Engine
store store.Store
auth auth.Provider
logger Logger
// Core services (all interface-based)
providers provider.Registry
router router.Service
pipeline pipeline.Service
cache cache.Service
guard guard.Service
tenant tenant.Service
key key.Service
usage usage.Service
model model.Service
// Model alias registry
aliasRegistry model.AliasRegistry
// Extension registry — audit_hook, observability, relay_hook, etc.
extensions *plugin.Registry
// Observability
tracer observability.Tracer
transforms *transform.Registry
healthTrack provider.HealthTracker
// Custom middleware to add to the pipeline
customMiddleware []pipeline.Middleware
initialized bool
}
// New creates a new Nexus Gateway with the given options.
func New(opts ...Option) *Gateway {
gw := &Gateway{
config: DefaultConfig(),
providers: provider.NewRegistry(),
extensions: plugin.NewRegistry(),
}
for _, opt := range opts {
opt(gw)
}
return gw
}
// Initialize sets up all services and validates configuration.
func (gw *Gateway) Initialize(_ context.Context) error {
if gw.initialized {
return nil
}
// Set defaults for unset services
if gw.auth == nil {
gw.auth = auth.NewNoop()
}
if gw.store == nil {
gw.store = store.NewMemory()
}
if gw.logger == nil {
gw.logger = NewNoopLogger()
}
// Initialize model service
if gw.model == nil {
gw.model = model.NewService(gw.aliasRegistry, gw.providers)
}
// Default router: priority strategy (registration order)
if gw.router == nil {
gw.router = router.NewService(strategies.NewPriority())
}
// Initialize engine
gw.engine = newEngine(gw)
// Build default pipeline if not set
if gw.pipeline == nil {
gw.pipeline = gw.buildDefaultPipeline()
}
gw.initialized = true
gw.logger.Info("nexus gateway initialized",
"providers", gw.providers.Count(),
"extensions", gw.extensions.Count(),
"base_path", gw.config.BasePath,
)
return nil
}
// buildDefaultPipeline creates the standard middleware chain.
// Middleware is sorted by priority (lower = earlier), so the order
// of b.Use() calls here doesn't matter — priority determines execution order.
func (gw *Gateway) buildDefaultPipeline() pipeline.Service {
b := pipeline.NewBuilder()
// Priority 10: Tracing (if configured)
if gw.tracer != nil {
b.Use(observability.NewTracingMiddleware(gw.tracer))
}
// Priority 20: Timeout (if configured)
if gw.config.DefaultTimeout > 0 {
b.Use(middlewares.NewTimeout(gw.config.DefaultTimeout))
}
// Priority 150: Input guardrails (if configured)
if gw.guard != nil {
b.Use(middlewares.NewGuardrail(gw.guard))
}
// Priority 200: Transforms (if configured)
if gw.transforms != nil {
b.Use(middlewares.NewTransform(gw.transforms))
}
// Priority 250: Alias resolution (if configured)
if gw.aliasRegistry != nil {
b.Use(middlewares.NewAlias(gw.aliasRegistry))
}
// Priority 280: Cache (if configured)
if gw.cache != nil {
b.Use(middlewares.NewCache(gw.cache))
}
// Priority 340: Retry (if resilience configured)
if gw.config.DefaultMaxRetries > 0 {
b.Use(middlewares.NewRetry(gw.config.DefaultMaxRetries, 500*time.Millisecond, 2.0))
}
// Priority 350: Core provider call (always present)
b.Use(middlewares.NewProviderCall(gw.router, gw.providers))
// Priority 500: Response headers
b.Use(middlewares.NewHeaders("nexus"))
// Priority 550: Usage tracking (if store available)
if gw.usage != nil {
b.Use(middlewares.NewUsage(gw.usage))
}
// Custom middleware (user-provided, any priority)
for _, m := range gw.customMiddleware {
b.Use(m)
}
return b.Build()
}
// Mount registers Nexus HTTP handlers on the given router.
func (gw *Gateway) Mount(mux Router, basePath ...string) {
path := gw.config.BasePath
if len(basePath) > 0 {
path = basePath[0]
}
mountHandlers(gw, mux, path)
}
// Engine returns the core engine for programmatic usage.
func (gw *Gateway) Engine() *Engine { return gw.engine }
// Config returns the gateway configuration.
func (gw *Gateway) Config() *Config { return gw.config }
// Store returns the persistence store.
func (gw *Gateway) Store() store.Store { return gw.store }
// Service Accessors
// Providers returns the provider registry.
func (gw *Gateway) Providers() provider.Registry { return gw.providers }
// RouterService returns the routing service.
func (gw *Gateway) RouterService() router.Service { return gw.router }
// Cache returns the cache service.
func (gw *Gateway) Cache() cache.Service { return gw.cache }
// Guard returns the guard service.
func (gw *Gateway) Guard() guard.Service { return gw.guard }
// Tenants returns the tenant service.
func (gw *Gateway) Tenants() tenant.Service { return gw.tenant }
// Keys returns the API key service.
func (gw *Gateway) Keys() key.Service { return gw.key }
// Usage returns the usage service.
func (gw *Gateway) Usage() usage.Service { return gw.usage }
// Models returns the model service.
func (gw *Gateway) Models() model.Service { return gw.model }
// Extensions returns the extension registry.
func (gw *Gateway) Extensions() *plugin.Registry { return gw.extensions }
// Pipeline returns the pipeline service.
func (gw *Gateway) Pipeline() pipeline.Service { return gw.pipeline }
// Logger returns the gateway logger.
func (gw *Gateway) Logger() Logger { return gw.logger }
// Health checks the health of the Gateway.
func (gw *Gateway) Health(_ context.Context) error {
return nil
}
// Shutdown gracefully stops all services.
func (gw *Gateway) Shutdown(_ context.Context) error {
gw.logger.Info("nexus gateway shutting down")
if gw.store != nil {
return gw.store.Close()
}
return nil
}
// Router is a minimal interface for HTTP routing.
// Compatible with chi.Router, forge.Router, http.ServeMux, etc.
type Router interface {
http.Handler
Handle(pattern string, handler http.Handler)
HandleFunc(pattern string, handler http.HandlerFunc)
}