-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.go
More file actions
446 lines (383 loc) · 15 KB
/
server.go
File metadata and controls
446 lines (383 loc) · 15 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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// Copyright 2025 The Rivaas Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"rivaas.dev/router"
"rivaas.dev/router/route"
)
// serverStartFunc defines the function type for starting a server.
type serverStartFunc func() error
// logLifecycleEvent logs a lifecycle event using the base logger.
func (a *App) logLifecycleEvent(ctx context.Context, level slog.Level, msg string, args ...any) {
logger := a.BaseLogger()
if logger.Enabled(ctx, level) {
logger.Log(ctx, level, msg, args...)
}
}
// flushStartupLogs flushes any buffered startup logs.
// This is called after the banner is printed to ensure clean terminal output.
func (a *App) flushStartupLogs() {
if a.logging != nil {
//nolint:errcheck // Best-effort flush; failure here doesn't affect server startup
a.logging.FlushBuffer()
}
}
// logStartupInfo logs startup information including address, environment, and observability.
func (a *App) logStartupInfo(ctx context.Context, addr, protocol string) {
attrs := []any{
"address", addr,
"environment", a.config.environment,
"protocol", protocol,
}
if a.metrics != nil {
attrs = append(attrs, "metrics_enabled", true, "metrics_address", a.metrics.ServerAddress())
}
a.logLifecycleEvent(ctx, slog.LevelInfo, "server starting", attrs...)
if a.tracing != nil {
a.logLifecycleEvent(ctx, slog.LevelInfo, "tracing enabled")
}
}
// startObservability starts observability components (metrics, tracing) with the given context.
// The context is used for network connections and server lifecycle.
func (a *App) startObservability(ctx context.Context) error {
// Start a metrics server if configured
if a.metrics != nil {
if err := a.metrics.Start(ctx); err != nil {
return fmt.Errorf("failed to start metrics server: %w", err)
}
}
// Start tracing if configured (initializes OTLP exporters)
if a.tracing != nil {
if err := a.tracing.Start(ctx); err != nil {
return fmt.Errorf("failed to start tracing: %w", err)
}
}
return nil
}
func (a *App) shutdownObservability(ctx context.Context) {
// Shutdown metrics if running
if a.metrics != nil {
if err := a.metrics.Shutdown(ctx); err != nil {
a.logLifecycleEvent(ctx, slog.LevelWarn, "metrics shutdown failed", "error", err)
}
}
// Shutdown tracing if running
if a.tracing != nil {
if err := a.tracing.Shutdown(ctx); err != nil {
a.logLifecycleEvent(ctx, slog.LevelWarn, "tracing shutdown failed", "error", err)
}
}
}
// runServer handles the common lifecycle for starting and shutting down an HTTP server.
// It is used by [App.Start], [App.StartTLS], and [App.StartMTLS].
//
// The server listens for OS signals (SIGINT/SIGTERM) internally — no signal setup is
// required from the caller. The context can still be used for programmatic shutdown
// (e.g. in tests or admin endpoints), but callers no longer need signal.NotifyContext.
//
// Shutdown sequence on first signal or context cancellation:
// 1. OnShutdown hooks execute (LIFO order)
// 2. In-flight requests drain (up to shutdown timeout)
// 3. Observability components shut down
// 4. OnStop hooks execute
//
// A second signal during the shutdown window triggers an immediate os.Exit(1).
func (a *App) runServer(ctx context.Context, server *http.Server, startFunc serverStartFunc, protocol string) error {
// Framework-owned shutdown signal channel. Handles SIGINT and SIGTERM so callers
// don't need to set up signal.NotifyContext themselves.
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, shutdownSignals...)
defer signal.Stop(sigCh)
// Start a server in a goroutine
serverErr := make(chan error, 1)
serverReady := make(chan struct{})
go func() {
a.printStartupBanner(server.Addr, protocol)
// Flush any buffered startup logs after the banner is printed.
// This ensures all initialization logs appear after the banner for cleaner DX.
a.flushStartupLogs()
a.logStartupInfo(ctx, server.Addr, protocol)
// Signal that the server is ready to accept connections
close(serverReady)
if err := startFunc(); err != nil && !errors.Is(err, http.ErrServerClosed) {
serverErr <- fmt.Errorf("%s server failed to start: %w", protocol, err)
}
}()
// Wait for the server to be ready, then execute OnReady hooks
<-serverReady
a.executeReadyHooks(ctx)
// Set up SIGHUP: handle reload when hooks exist, otherwise ignore so the process isn't killed
var sighupCh <-chan os.Signal
if a.hasReloadHooks() {
ch, cleanup := setupReloadSignal()
defer cleanup()
sighupCh = ch
} else {
ignoreReloadSignal() // Unix: SIGHUP ignored so the process isn't killed
}
// Event loop: wait for shutdown signal, context cancellation, reload, or server error.
// When sighupCh is nil (no reload hooks registered), that case blocks forever with zero overhead.
for {
select {
case err := <-serverErr:
return err
case <-sighupCh:
a.logLifecycleEvent(ctx, slog.LevelInfo, "reload signal received", "signal", "SIGHUP")
if err := a.Reload(ctx); err != nil {
// Error already logged inside Reload(), continue serving
_ = err
}
case sig := <-sigCh:
a.logLifecycleEvent(ctx, slog.LevelInfo, "shutdown signal received", "signal", sig)
goto shutdown
case <-ctx.Done():
a.logLifecycleEvent(ctx, slog.LevelInfo, "context canceled, shutting down", "protocol", protocol, "reason", ctx.Err())
goto shutdown
}
}
shutdown:
// Inform the user that a second signal will force-terminate immediately.
a.logLifecycleEvent(ctx, slog.LevelInfo,
"shutting down gracefully, press Ctrl+C again to force")
// Force-shutdown listener: a second signal during graceful shutdown exits immediately.
// sigCh is still registered — the second signal arrives on the same channel.
go func() {
<-sigCh
a.logLifecycleEvent(ctx, slog.LevelWarn,
"force shutdown: second signal received, terminating immediately")
// Best-effort log flush before exit so the warning above is visible.
if a.logging != nil {
_ = a.logging.FlushBuffer() //nolint:errcheck // Best-effort flush before force exit; failure here is acceptable
}
a.forceExit(1)
}()
// Create a deadline for shutdown.
// We use context.WithoutCancel() to preserve context values (tracing, logging) while ignoring
// the parent's cancellation. The parent ctx may already be canceled (signal path leaves it live,
// but context-cancel path does not), so we derive a fresh timeout from a non-canceled base.
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), a.config.server.shutdownTimeout)
defer cancel()
// Execute OnShutdown hooks (LIFO order)
a.executeShutdownHooks(shutdownCtx)
// Shutdown the server
if err := server.Shutdown(shutdownCtx); err != nil {
return fmt.Errorf("%s server forced to shutdown: %w", protocol, err)
}
// Shutdown observability components (metrics and tracing)
a.shutdownObservability(shutdownCtx)
// Execute OnStop hooks (best-effort)
a.executeStopHooks(shutdownCtx)
a.logLifecycleEvent(shutdownCtx, slog.LevelInfo, "server exited", "protocol", protocol)
return nil
}
// registerOpenAPIEndpoints registers OpenAPI spec and UI endpoints.
// registerOpenAPIEndpoints is the integration between router and openapi packages.
func (a *App) registerOpenAPIEndpoints() {
if a.openapi == nil {
return
}
// Register spec endpoint
a.router.GET(a.openapi.SpecPath(), func(c *router.Context) {
specJSON, etag, err := a.openapi.GenerateSpec(c.Request.Context())
if err != nil {
if writeErr := c.Stringf(http.StatusInternalServerError, "Failed to generate OpenAPI specification: %v", err); writeErr != nil {
slog.ErrorContext(c.RequestContext(), "failed to write error response", "err", writeErr)
}
return
}
// Check If-None-Match header for caching
if match := c.Request.Header.Get("If-None-Match"); match != "" && match == etag {
c.Status(http.StatusNotModified)
return
}
c.Response.Header().Set("ETag", etag)
c.Response.Header().Set("Cache-Control", "public, max-age=3600")
c.Response.Header().Set("Content-Type", "application/json")
if _, err = c.Response.Write(specJSON); err != nil { //nolint:gosec // G705: specJSON is server-generated OpenAPI spec, not user input
slog.ErrorContext(c.RequestContext(), "failed to write spec response", "err", err)
}
})
// Update route info to show the builtin handler name
a.router.UpdateRouteInfo("GET", a.openapi.SpecPath(), "", func(info *route.Info) {
info.HandlerName = "[builtin] openapi-spec"
})
// Register UI endpoint if enabled
if a.openapi.ServeUI() {
a.router.GET(a.openapi.UIPath(), func(c *router.Context) {
ui := a.openapi.UIConfig()
configJSON, err := ui.ToJSON(a.openapi.SpecPath())
if err != nil {
// Fallback to basic config
configJSON = `{"url":"` + a.openapi.SpecPath() + `","dom_id":"#swagger-ui"}`
}
html := `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="API Documentation" />
<title>API Documentation</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.32.0/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@5.32.0/swagger-ui-bundle.js" crossorigin></script>
<script>
window.onload = () => {
window.ui = SwaggerUIBundle(` + configJSON + `);
};
</script>
</body>
</html>`
if htmlErr := c.HTML(http.StatusOK, html); htmlErr != nil {
slog.ErrorContext(c.RequestContext(), "failed to write HTML response", "err", htmlErr)
}
})
// Update route info to show the builtin handler name
a.router.UpdateRouteInfo("GET", a.openapi.UIPath(), "", func(info *route.Info) {
info.HandlerName = "[builtin] openapi-ui"
})
}
}
// Start starts the server with graceful shutdown.
// Start automatically freezes the router before starting, making routes immutable.
// The server runs HTTP, HTTPS, or mTLS depending on configuration: use [WithTLS] or
// [WithMTLS] at construction to serve over TLS; otherwise plain HTTP is used.
//
// The server listens on the address configured via [WithPort] and [WithHost].
// Default is :8080 for HTTP and :8443 when using [WithTLS] or [WithMTLS], overridable by
// [WithPort] and by RIVAAS_PORT and RIVAAS_HOST when [WithEnv] is used.
//
// Signal handling is built in — no signal.NotifyContext setup is needed. Start listens
// for SIGINT (Ctrl+C) and SIGTERM internally and initiates graceful shutdown automatically.
// A second signal during the shutdown window calls os.Exit(1) immediately.
//
// The context parameter is still useful for programmatic shutdown (tests, admin endpoints).
// Canceling it triggers the same graceful shutdown sequence as a signal.
//
// Shutdown sequence:
// 1. OnShutdown hooks execute (LIFO order, within shutdown timeout)
// 2. In-flight requests drain (up to shutdown timeout)
// 3. Observability components shut down (metrics, tracing)
// 4. OnStop hooks execute (best-effort)
//
// Example:
//
// app := app.MustNew(
// app.WithServiceName("my-service"),
// app.WithPort(3000),
// )
// if err := app.Start(context.Background()); err != nil {
// log.Fatal(err)
// }
//
// HTTPS example (default port 8443):
//
// app := app.MustNew(
// app.WithServiceName("my-service"),
// app.WithTLS("server.crt", "server.key"),
// )
// if err := app.Start(context.Background()); err != nil { ... }
func (a *App) Start(ctx context.Context) error {
addr := a.config.server.ListenAddr()
// Validate route options before any startup side effects.
if err := a.ValidateRoutes(); err != nil {
return fmt.Errorf("route validation failed: %w", err)
}
// Start observability servers (metrics, etc.)
if err := a.startObservability(ctx); err != nil {
return fmt.Errorf("failed to start observability: %w", err)
}
// Execute OnStart hooks sequentially, stopping on first error
if err := a.executeStartHooks(ctx); err != nil {
return fmt.Errorf("startup failed: %w", err)
}
// Register OpenAPI endpoints before freezing
//nolint:contextcheck // Handler registration - context comes from request at runtime
a.registerOpenAPIEndpoints()
// Freeze router before starting (point of no return)
a.router.Freeze()
server := &http.Server{
Addr: addr,
Handler: a.router,
ReadTimeout: a.config.server.readTimeout,
WriteTimeout: a.config.server.writeTimeout,
IdleTimeout: a.config.server.idleTimeout,
ReadHeaderTimeout: a.config.server.readHeaderTimeout,
MaxHeaderBytes: a.config.server.maxHeaderBytes,
}
// Branch on transport: TLS (HTTPS), mTLS, or plain HTTP
if a.config.server.tlsCertFile != "" {
return a.runServer(ctx, server, func() error {
return server.ListenAndServeTLS(a.config.server.tlsCertFile, a.config.server.tlsKeyFile)
}, "HTTPS")
}
if len(a.config.server.mtlsServerCert.Certificate) > 0 {
return a.startMTLS(ctx, server, addr)
}
return a.runServer(ctx, server, server.ListenAndServe, "HTTP")
}
// startMTLS runs the server with mTLS using config from a.config.server.
func (a *App) startMTLS(ctx context.Context, server *http.Server, addr string) error {
cfg := newMTLSConfig(a.config.server.mtlsServerCert, a.config.server.mtlsOpts...)
tlsConfig := cfg.buildTLSConfig()
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", addr)
if err != nil {
return fmt.Errorf("failed to listen on %s: %w", addr, err)
}
tlsListener := tls.NewListener(listener, tlsConfig)
server.TLSConfig = tlsConfig
originalConnState := server.ConnState
server.ConnState = func(conn net.Conn, state http.ConnState) {
if state == http.StateActive && !authorizeMTLSConnection(conn, cfg) {
if closeErr := conn.Close(); closeErr != nil {
a.logLifecycleEvent(ctx, slog.LevelError, "failed to close unauthorized mTLS connection", "error", closeErr)
}
return
}
if originalConnState != nil {
originalConnState(conn, state)
}
}
return a.runServer(ctx, server, func() error {
return server.Serve(tlsListener)
}, "mTLS")
}
// authorizeMTLSConnection checks if the TLS connection is authorized.
// Returns true if authorized (or no authorization required), false if denied.
func authorizeMTLSConnection(conn net.Conn, cfg *mtlsConfig) bool {
// No authorized callback means all connections are allowed
if cfg.authorize == nil {
return true
}
tlsConn, ok := conn.(*tls.Conn)
if !ok {
return true // Not a TLS connection, skip authorization
}
connState := tlsConn.ConnectionState()
if len(connState.PeerCertificates) == 0 {
return true // No peer certificate, skip authorization
}
_, allowed := cfg.authorize(connState.PeerCertificates[0])
return allowed
}