-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdoc.go
More file actions
393 lines (392 loc) · 15.8 KB
/
doc.go
File metadata and controls
393 lines (392 loc) · 15.8 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
// 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 provides a batteries-included, cloud-native web framework built on top
// of the Rivaas router. It features high-performance routing, comprehensive request
// binding & validation, automatic OpenAPI generation, and OpenTelemetry-native observability,
// along with lifecycle management and sensible defaults for building production-ready web applications.
//
// # Overview
//
// The app package wraps the router package with additional features:
//
// - Integrated observability (metrics, tracing, logging)
// - Lifecycle hooks (OnStart, OnReady, OnShutdown, OnStop)
// - Graceful shutdown handling
// - Server configuration management
// - Request binding and validation
// - OpenAPI/Swagger documentation with ETag-based caching
// - Health check endpoints
// - Development and production modes
//
// # When to Use
//
// Use the app package when:
//
// - Building a complete web application with batteries included
// - You want integrated observability configured out of the box
// - You need development with sensible defaults
// - Building REST APIs with common middleware patterns
// - You prefer convention over configuration
//
// Use the router package directly when:
//
// - Building a library or framework that needs full control
// - You have custom observability setup already configured
// - You need complete flexibility without any opinions
// - Integrating into existing systems with established patterns
//
// # Constructor Pattern
//
// The app package follows the functional options pattern used throughout Rivaas:
//
// - Options apply to an internal config struct (not the App type directly)
//
// - New() validates the config and builds the App from the validated config
//
// - New() returns (*App, error) because app initialization can fail.
// The app initializes external resources (metrics, tracing, logging) that may fail
// to connect to backends, validate configurations, or allocate resources.
//
// - MustNew() is provided as a convenience wrapper that panics on error.
// This follows the standard Go idiom (like regexp.MustCompile, template.Must)
// and is useful for initialization in main() functions where errors should abort startup.
//
// - All configuration options use the "With" prefix for consistency.
//
// - Grouping options (e.g., WithServer, WithRouter) accept sub-options
// to organize related settings and reduce API surface.
//
// # Option Validation
//
// Options must not be nil. Passing a nil option to New(), MustNew(), or methods
// that accept options (e.g., Test) returns a validation error, not a panic.
// This applies to both top-level options (e.g., WithServer) and nested options
// (e.g., WithReadTimeout inside WithServer).
//
// # Quick Start
//
// Simple application with defaults:
//
// app, err := app.New()
// if err != nil {
// log.Fatal(err)
// }
//
// app.GET("/", func(c *app.Context) {
// c.JSON(http.StatusOK, map[string]string{"message": "Hello"})
// })
//
// if err := app.Start(context.Background()); err != nil {
// log.Fatal(err)
// }
//
// Full-featured application with observability, health, and debug endpoints:
//
// app, err := app.New(
// app.WithServiceName("my-api"),
// app.WithServiceVersion("v1.0.0"),
// app.WithEnvironment("production"),
// // Observability: all three pillars in one place
// app.WithObservability(
// app.WithLogging(logging.WithJSONHandler()),
// app.WithMetrics(), // Prometheus is default
// app.WithTracing(tracing.WithOTLP("localhost:4317")),
// ),
// // Health endpoints: /livez and /readyz
// app.WithHealthEndpoints(
// app.WithLivenessCheck("process", func(ctx context.Context) error {
// return nil
// }),
// app.WithReadinessCheck("database", func(ctx context.Context) error {
// return db.PingContext(ctx)
// }),
// ),
// // Debug endpoints: /debug/pprof/* (conditionally enabled)
// app.WithDebugEndpoints(
// app.WithPprofIf(os.Getenv("PPROF_ENABLED") == "true"),
// ),
// app.WithServer(
// app.WithReadTimeout(15 * time.Second),
// app.WithWriteTimeout(15 * time.Second),
// ),
// )
// if err != nil {
// log.Fatal(err)
// }
//
// Or using MustNew for initialization that panics on error:
//
// app := app.MustNew(
// app.WithServiceName("my-service"),
// app.WithObservability(
// app.WithMetrics(), // Prometheus is default
// ),
// )
//
// # Observability
//
// The app package integrates three pillars of observability:
//
// - Metrics: Prometheus-compatible metrics with automatic HTTP request instrumentation
// - Tracing: OpenTelemetry tracing with request context propagation
// - Logging: Structured logging with slog, including request-scoped fields
//
// Request spans use the same semantics as the tracing package: W3C trace context
// extraction, sampling (e.g. WithSampleRate), and standard HTTP attributes
// (http.method, http.url, http.route, http.status_code, service.name, etc.).
//
// From handlers, use [Context.SetSpanAttribute] and [Context.AddSpanEvent] on the
// current span. For child spans (e.g. "db-query", "call-service"), use
// [Context.StartSpan] and [Context.FinishSpan] for success, or [Context.FinishSpanWithHTTPStatus]
// when you have an HTTP status, or [Context.FinishSpanWithError] when the span fails.
// Use [Context.RecordError] to record an error on the request span without ending it.
// Use [Context.CopyTraceContext] to get a context for goroutines that share the same trace.
// Use [Context.WithSpan] to run a function under a span that is finished from the returned error:
//
// ctx, span := c.StartSpan("db-query")
// defer c.FinishSpan(span)
// // or: defer func() { if err != nil { c.FinishSpanWithError(span, err) } else { c.FinishSpan(span) } }()
// // or: err := c.WithSpan("fetch-user", func(ctx context.Context) error { ... })
//
// Use [Context.Tracer] only when you need to pass the tracer to another library
// (e.g. DB driver, HTTP client) or use tracer-specific options (inject/extract).
//
// For custom metrics from handlers, use [Context.RecordHistogram],
// [Context.IncrementCounter], [Context.AddCounter], and [Context.SetGauge]:
//
// c.IncrementCounter("requests_total")
// c.AddCounter("bytes_processed", 1024, attribute.String("type", "upload"))
// c.RecordHistogram("duration_seconds", 0.5)
// c.SetGauge("queue_size", 10)
//
// All observability features are optional and can be enabled independently:
//
// app.New(
// app.WithObservability(
// app.WithMetrics(), // Prometheus is default; use metrics.WithOTLP() for OTLP
// app.WithTracing(tracing.WithOTLP("localhost:4317")),
// app.WithLogging(logging.WithJSONHandler()),
// ),
// )
//
// # Lifecycle Hooks
//
// The app provides lifecycle hooks for application events:
//
// - OnStart: Called before server starts (sequential, stops on first error)
// - OnReady: Called when server is ready to accept connections (async, non-blocking)
// - OnShutdown: Called during graceful shutdown (LIFO order)
// - OnStop: Called after shutdown completes (best-effort)
//
// Example:
//
// if err := app.OnStart(func(ctx context.Context) error {
// return db.Connect(ctx)
// }); err != nil {
// log.Fatal(err)
// }
//
// if err := app.OnReady(func() {
// log.Println("Server is ready!")
// }); err != nil {
// log.Fatal(err)
// }
//
// if err := app.OnShutdown(func(ctx context.Context) {
// db.Close()
// }); err != nil {
// log.Fatal(err)
// }
//
// # Request Handling
//
// Handlers receive an app.Context that extends router.Context with app-level features:
//
// - Request binding (JSON, form, query parameters)
// - Request validation
// - Access to observability (metrics, tracing, logging)
//
// The app package defines its own handler type, [HandlerFunc] (func(*[Context])), rather
// than using [router.HandlerFunc] directly. This is a deliberate design trade-off:
// [Context] extends [router.Context] with binding, validation, and observability helpers
// that cannot be provided through [router.Context] alone. The conversion surface is
// bounded to a single method — [App.WrapHandler] — which adapts an app.HandlerFunc to a
// [router.HandlerFunc] with context pooling. Middleware written at the router level
// (using [router.HandlerFunc]) works without wrapping; app.HandlerFunc is only needed
// when handlers require [Context] features.
//
// Example:
//
// app.POST("/users", func(c *app.Context) {
// var req CreateUserRequest
// if err := c.Bind(&req); err != nil {
// c.Fail(err)
// return
// }
//
// // Process request...
// c.JSON(http.StatusCreated, user)
// })
//
// Or using the type-safe generic API:
//
// app.POST("/users", func(c *app.Context) {
// req, ok := app.MustBind[CreateUserRequest](c)
// if !ok {
// return // Error already written
// }
//
// // Process request...
// c.JSON(http.StatusCreated, user)
// })
//
// # Request Binding and Validation
//
// The app package provides a unified API for binding and validation:
//
// - [Context.Bind]: Binds and validates request data (default behavior)
// - [Context.MustBind]: Bind and validate, write error on failure
// - [Context.BindOnly]: Bind without validation (for advanced use)
// - [Context.Validate]: Validate only (after BindOnly); accepts [ValidateOption] for app-scoped options
//
// Generic type-safe variants:
//
// - [Bind]: Type-safe binding with generics
// - [MustBind]: Type-safe Must pattern
// - [BindOnly]: Bind without validation (for advanced use)
//
// Options for customization. Bind and Validate options must not be nil; passing a nil option returns an error.
//
// - [WithStrict]: Reject unknown JSON fields (Bind)
// - [WithPartial]: Partial validation for PATCH requests (Bind)
// - [WithoutValidation]: Skip validation step
// - [WithBindingOptions]: Pass options to binding package
// - [WithValidationOptions]: Pass options to validation package (Bind)
// - [WithValidatePartial], [WithValidateStrict], [WithValidateOptions]: Options for [Context.Validate]
// - [WithValidationEngine]: Use a custom validation engine for Bind/Validate (e.g. for redaction or test isolation)
//
// Example with options:
//
// app.PATCH("/users/:id", func(c *app.Context) {
// req, ok := app.MustBind[UpdateUserRequest](c, app.WithPartial())
// if !ok {
// return
// }
// // Only provided fields are validated
// })
//
// # Server Configuration
//
// Configure server address and timeouts using functional options:
//
// app.New(
// app.WithPort(3000), // Listen on port 3000
// app.WithHost("127.0.0.1"), // Bind to localhost only
// app.WithServer(
// app.WithReadTimeout(10 * time.Second),
// app.WithWriteTimeout(10 * time.Second),
// app.WithIdleTimeout(60 * time.Second),
// app.WithShutdownTimeout(30 * time.Second),
// ),
// )
//
// For HTTPS use WithTLS(certFile, keyFile); for mTLS use WithMTLS(serverCert, ...MTLSOption). Then call Start(ctx).
// Default port is 8080 for HTTP and 8443 for TLS/mTLS; override with WithPort or RIVAAS_PORT.
// Configuration is automatically validated to catch common misconfigurations.
//
// # Environment Variables
//
// The app package supports configuration via environment variables using [WithEnv]:
//
// app.New(
// app.WithServiceName("orders-api"),
// app.WithEnv(), // Enable RIVAAS_* environment variable overrides
// )
//
// Environment variables override programmatic configuration. Supported variables:
//
// Core:
// RIVAAS_ENV - Environment mode: "development" or "production"
// RIVAAS_SERVICE_NAME - Service name for observability
// RIVAAS_SERVICE_VERSION - Service version
//
// Server:
// RIVAAS_PORT - Server port (default 8080 for HTTP, 8443 for TLS/mTLS; e.g., "8080", "443")
// RIVAAS_HOST - HTTP server host/interface (e.g., "127.0.0.1")
// RIVAAS_READ_TIMEOUT - Request read timeout (e.g., "10s")
// RIVAAS_WRITE_TIMEOUT - Response write timeout (e.g., "10s")
// RIVAAS_SHUTDOWN_TIMEOUT - Graceful shutdown timeout (e.g., "30s")
//
// Logging:
// RIVAAS_LOG_LEVEL - Log level: "debug", "info", "warn", "error"
// RIVAAS_LOG_FORMAT - Log format: "json", "text", or "console"
//
// Observability:
// RIVAAS_METRICS_EXPORTER - Metrics exporter: "prometheus", "otlp", or "stdout"
// RIVAAS_METRICS_ADDR - Prometheus address (default: ":9090")
// RIVAAS_METRICS_PATH - Prometheus path (default: "/metrics")
// RIVAAS_METRICS_ENDPOINT - OTLP metrics endpoint (e.g., "http://localhost:4318")
// RIVAAS_TRACING_EXPORTER - Tracing exporter: "otlp", "otlp-http", or "stdout"
// RIVAAS_TRACING_ENDPOINT - OTLP tracing endpoint (e.g., "localhost:4317")
//
// Debug:
// RIVAAS_PPROF_ENABLED - Enable pprof: "true" or "false"
//
// Use [WithEnvPrefix] for a custom prefix:
//
// app.New(
// app.WithEnvPrefix("MYAPP_"), // Use MYAPP_* instead of RIVAAS_*
// )
//
// Invalid environment values cause [New] to return an error (fail-fast).
//
// # Examples
//
// See the examples directory for complete working examples:
//
// - examples/01-quick-start: Minimal setup to get started (basic routing, JSON responses)
// - examples/02-blog: Real-world blog API with configuration, validation, OpenAPI docs, observability, and testing
//
// # Architecture
//
// The app package is built on top of the router package:
//
// ┌─────────────────────────────────────────┐
// │ Application Layer │
// │ (app package - this package) │
// │ │
// │ • Configuration Management │
// │ • Lifecycle Hooks │
// │ • Observability Integration │
// │ • Server Management │
// │ • Request Binding/Validation │
// └──────────────┬──────────────────────────┘
// │
// ▼
// ┌─────────────────────────────────────────┐
// │ Router Layer │
// │ (router package) │
// │ │
// │ • HTTP Routing │
// │ • Middleware Chain │
// │ • Request Context │
// │ • Path Parameters │
// └──────────────┬──────────────────────────┘
// │
// ▼
// ┌─────────────────────────────────────────┐
// │ Standard Library │
// │ (net/http) │
// └─────────────────────────────────────────┘
package app