-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathenv.go
More file actions
413 lines (358 loc) · 12.9 KB
/
env.go
File metadata and controls
413 lines (358 loc) · 12.9 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
// 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 (
"fmt"
"os"
"strconv"
"strings"
"time"
"rivaas.dev/logging"
"rivaas.dev/metrics"
"rivaas.dev/tracing"
)
// EnvPrefix is the environment variable prefix for Rivaas framework settings.
const EnvPrefix = "RIVAAS_"
// Environment variable names for framework configuration.
// These are used when [WithEnv] or [WithEnvPrefix] is called.
const (
// Core application settings
EnvMode = "ENV" // Environment mode: "development" or "production"
EnvServiceName = "SERVICE_NAME" // Service name for observability
EnvServiceVersion = "SERVICE_VERSION" // Service version
// Server settings
EnvPort = "PORT" // HTTP server port (e.g., "8080")
EnvHost = "HOST" // HTTP server host/interface (e.g., "127.0.0.1")
EnvReadTimeout = "READ_TIMEOUT" // Request read timeout (e.g., "10s")
EnvWriteTimeout = "WRITE_TIMEOUT" // Response write timeout (e.g., "10s")
EnvShutdownTimeout = "SHUTDOWN_TIMEOUT" // Graceful shutdown timeout (e.g., "30s")
// Logging settings
EnvLogLevel = "LOG_LEVEL" // Log level: "debug", "info", "warn", "error"
EnvLogFormat = "LOG_FORMAT" // Log format: "json", "text", or "console"
// Observability settings
EnvMetricsExporter = "METRICS_EXPORTER" // Metrics exporter: "prometheus", "otlp", or "stdout"
EnvMetricsAddr = "METRICS_ADDR" // Prometheus address (e.g., ":9090")
EnvMetricsPath = "METRICS_PATH" // Prometheus path (e.g., "/metrics")
EnvMetricsEndpoint = "METRICS_ENDPOINT" // OTLP endpoint (e.g., "http://localhost:4318")
EnvTracingExporter = "TRACING_EXPORTER" // Tracing exporter: "otlp", "otlp-http", or "stdout"
EnvTracingEndpoint = "TRACING_ENDPOINT" // OTLP endpoint (e.g., "localhost:4317")
// Debug settings
EnvPprofEnabled = "PPROF_ENABLED" // Enable pprof: "true" or "false"
)
// envConfig holds parsed environment variable values and any errors encountered.
type envConfig struct {
errors []error
}
// addError records a parsing error for later reporting.
func (e *envConfig) addError(envVar string, err error) {
e.errors = append(e.errors, fmt.Errorf("invalid environment variable %s: %w", envVar, err))
}
// WithEnv enables environment variable overrides for framework configuration.
// Environment variables use the RIVAAS_ prefix and take precedence over
// 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 - HTTP server port (e.g., "8080")
// 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"
//
// Example:
//
// export RIVAAS_ENV=production
// export RIVAAS_PORT=3000
// export RIVAAS_LOG_LEVEL=warn
//
// app := app.MustNew(
// app.WithServiceName("orders-api"),
// app.WithEnv(), // Applies environment overrides
// )
func WithEnv() Option {
return WithEnvPrefix(EnvPrefix)
}
// WithEnvPrefix enables environment variable overrides with a custom prefix.
// Use this when deploying multiple Rivaas services that need different configurations.
//
// The prefix is prepended to the standard variable names. For example, with prefix "ORDERS_":
// - ORDERS_ENV instead of RIVAAS_ENV
// - ORDERS_PORT instead of RIVAAS_PORT
//
// Example:
//
// // Service 1: uses ORDERS_ENV, ORDERS_PORT, etc.
// app.MustNew(
// app.WithServiceName("orders-api"),
// app.WithEnvPrefix("ORDERS_"),
// )
//
// // Service 2: uses PAYMENTS_ENV, PAYMENTS_PORT, etc.
// app.MustNew(
// app.WithServiceName("payments-api"),
// app.WithEnvPrefix("PAYMENTS_"),
// )
func WithEnvPrefix(prefix string) Option {
return func(c *config) {
env := &envConfig{}
applyEnvOverrides(c, prefix, env)
// Collect errors for validation phase
if len(env.errors) > 0 {
if c.envErrors == nil {
c.envErrors = make([]error, 0, len(env.errors))
}
c.envErrors = append(c.envErrors, env.errors...)
}
}
}
// applyEnvOverrides applies environment variable values to the configuration.
func applyEnvOverrides(c *config, prefix string, env *envConfig) {
// Core settings
applyEnvString(prefix, EnvMode, &c.environment)
applyEnvString(prefix, EnvServiceName, &c.serviceName)
applyEnvString(prefix, EnvServiceVersion, &c.serviceVersion)
// Server settings
applyEnvInt(prefix, EnvPort, &c.server.port, env)
applyEnvString(prefix, EnvHost, &c.server.host)
applyEnvDuration(prefix, EnvReadTimeout, &c.server.readTimeout, env)
applyEnvDuration(prefix, EnvWriteTimeout, &c.server.writeTimeout, env)
applyEnvDuration(prefix, EnvShutdownTimeout, &c.server.shutdownTimeout, env)
// Logging settings
applyEnvLogging(c, prefix, env)
// Observability settings
applyEnvObservability(c, prefix, env)
// Debug settings
applyEnvDebug(c, prefix, env)
}
// applyEnvString sets a string value from environment if present.
func applyEnvString(prefix, key string, target *string) {
if v := os.Getenv(prefix + key); v != "" {
*target = v
}
}
// applyEnvInt sets an int value from environment if present.
func applyEnvInt(prefix, key string, target *int, env *envConfig) {
fullKey := prefix + key
if v := os.Getenv(fullKey); v != "" {
parsed, err := strconv.Atoi(v)
if err != nil {
env.addError(fullKey, err)
return
}
*target = parsed
}
}
// applyEnvDuration sets a duration value from environment if present.
func applyEnvDuration(prefix, key string, target *time.Duration, env *envConfig) {
fullKey := prefix + key
if v := os.Getenv(fullKey); v != "" {
parsed, err := time.ParseDuration(v)
if err != nil {
env.addError(fullKey, err)
return
}
*target = parsed
}
}
// applyEnvBool parses a boolean value from environment.
func applyEnvBool(prefix, key string) (value, isSet bool) {
fullKey := prefix + key
v := os.Getenv(fullKey)
if v == "" {
return false, false
}
v = strings.ToLower(v)
return v == "true" || v == "1" || v == "yes", true
}
// applyEnvLogging configures logging from environment variables.
func applyEnvLogging(c *config, prefix string, env *envConfig) {
level := os.Getenv(prefix + EnvLogLevel)
format := os.Getenv(prefix + EnvLogFormat)
if level == "" && format == "" {
return
}
// Ensure observability settings exist
if c.observability == nil {
c.observability = defaultObservabilitySettings()
}
if c.observability.logging == nil {
c.observability.logging = &loggingConfig{enabled: true}
} else {
c.observability.logging.enabled = true
}
// Apply logging options
if level != "" {
switch strings.ToLower(level) {
case "debug":
c.observability.logging.options = append(c.observability.logging.options, logging.WithLevel(logging.LevelDebug))
case "info":
c.observability.logging.options = append(c.observability.logging.options, logging.WithLevel(logging.LevelInfo))
case "warn", "warning":
c.observability.logging.options = append(c.observability.logging.options, logging.WithLevel(logging.LevelWarn))
case "error":
c.observability.logging.options = append(c.observability.logging.options, logging.WithLevel(logging.LevelError))
default:
env.addError(prefix+EnvLogLevel, fmt.Errorf("unknown log level %q (valid: debug, info, warn, error)", level))
}
}
if format != "" {
switch strings.ToLower(format) {
case "json":
c.observability.logging.options = append(c.observability.logging.options, logging.WithJSONHandler())
case "text":
c.observability.logging.options = append(c.observability.logging.options, logging.WithTextHandler())
case "console":
c.observability.logging.options = append(c.observability.logging.options, logging.WithConsoleHandler())
default:
env.addError(prefix+EnvLogFormat, fmt.Errorf("unknown log format %q (valid: json, text, console)", format))
}
}
}
// applyEnvObservability configures metrics and tracing from environment variables.
func applyEnvObservability(c *config, prefix string, env *envConfig) {
metricsExporter := os.Getenv(prefix + EnvMetricsExporter)
tracingExporter := os.Getenv(prefix + EnvTracingExporter)
// No observability env vars set - nothing to do
if metricsExporter == "" && tracingExporter == "" {
return
}
// Ensure observability settings exist
if c.observability == nil {
c.observability = defaultObservabilitySettings()
}
// Configure metrics exporter
if metricsExporter != "" {
if err := applyMetricsExporter(c, prefix, metricsExporter, env); err != nil {
env.addError(prefix+EnvMetricsExporter, err)
}
}
// Configure tracing exporter
if tracingExporter != "" {
if err := applyTracingExporter(c, prefix, tracingExporter, env); err != nil {
env.addError(prefix+EnvTracingExporter, err)
}
}
}
// applyMetricsExporter configures metrics based on the exporter type.
func applyMetricsExporter(c *config, prefix, exporter string, env *envConfig) error {
exporterLower := strings.ToLower(exporter)
// Create new metrics config (env overrides code)
c.observability.metrics = &metricsConfig{
enabled: true,
options: []metrics.Option{},
}
switch exporterLower {
case "prometheus":
addr := os.Getenv(prefix + EnvMetricsAddr)
if addr == "" {
addr = ":9090" // Default Prometheus address
}
path := os.Getenv(prefix + EnvMetricsPath)
if path == "" {
path = "/metrics" // Default Prometheus path
}
c.observability.metrics.options = append(
c.observability.metrics.options,
metrics.WithPrometheus(addr, path),
)
case "otlp":
endpoint := os.Getenv(prefix + EnvMetricsEndpoint)
if endpoint == "" {
return fmt.Errorf("requires %s%s to be set", prefix, EnvMetricsEndpoint)
}
c.observability.metrics.options = append(
c.observability.metrics.options,
metrics.WithOTLP(endpoint),
)
case "stdout":
c.observability.metrics.options = append(
c.observability.metrics.options,
metrics.WithStdout(),
)
default:
return fmt.Errorf("must be one of: prometheus, otlp, stdout (got: %s)", exporter)
}
return nil
}
// applyTracingExporter configures tracing based on the exporter type.
func applyTracingExporter(c *config, prefix, exporter string, env *envConfig) error {
exporterLower := strings.ToLower(exporter)
// Create new tracing config (env overrides code)
c.observability.tracing = &tracingConfig{
enabled: true,
options: []tracing.Option{},
}
switch exporterLower {
case "otlp":
endpoint := os.Getenv(prefix + EnvTracingEndpoint)
if endpoint == "" {
return fmt.Errorf("requires %s%s to be set", prefix, EnvTracingEndpoint)
}
c.observability.tracing.options = append(
c.observability.tracing.options,
tracing.WithOTLP(endpoint),
)
case "otlp-http":
endpoint := os.Getenv(prefix + EnvTracingEndpoint)
if endpoint == "" {
return fmt.Errorf("requires %s%s to be set", prefix, EnvTracingEndpoint)
}
c.observability.tracing.options = append(
c.observability.tracing.options,
tracing.WithOTLPHTTP(endpoint),
)
case "stdout":
c.observability.tracing.options = append(
c.observability.tracing.options,
tracing.WithStdout(),
)
default:
return fmt.Errorf("must be one of: otlp, otlp-http, stdout (got: %s)", exporter)
}
return nil
}
// applyEnvDebug configures debug endpoints from environment variables.
func applyEnvDebug(c *config, prefix string, _ *envConfig) {
pprofEnabled, isSet := applyEnvBool(prefix, EnvPprofEnabled)
if !isSet {
return
}
if pprofEnabled {
if c.debug == nil {
c.debug = defaultDebugSettings()
}
c.debug.pprofEnabled = true
}
}