-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconfig.go
More file actions
301 lines (256 loc) · 9.57 KB
/
Copy pathconfig.go
File metadata and controls
301 lines (256 loc) · 9.57 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
package config
import (
"errors"
"fmt"
"os"
"strconv"
"strings"
"time"
)
// Config centralizza tutte le variabili d'ambiente del sistema PCMI.
// Usare Load() per caricare e MustLoad() per fail-fast all'avvio.
type Config struct {
// Database
DatabaseURL string
DatabaseReadURL string // opzionale: replica di lettura
// Redis
RedisAddr string
EventBackend string // streams (default) or pubsub — see EVENT_BACKEND
// API Server
APIPort string
// gRPC
GRPCPort string
// Authentication
AdminAPIKey string
MetricsScrapeToken string // optional: Bearer token for GET /metrics (Prometheus)
// MCP server (cmd/mcp — stdio JSON-RPC client to PCMI HTTP API)
PCMIBaseURL string
PCMIAPIKey string
// OpenAI / Embedding
OpenAIAPIKey string
OpenAIBaseURL string // optional: proxy or Azure OpenAI endpoint base
EmbeddingModel string
// Migrations
MigrationsDir string // directory containing .sql files; default "migrations"
// Distillation / Worker
DistillationModel string
DistillationBatchSize int
DistillationConcurrency int // max parallel LLM jobs, default 4
DistillationPolicyDisabled bool // skip policy engine (e2e smoke, explicit refine only)
PruneRetentionDays int
PruneIntervalSecs int
ExpiryIntervalSecs int
WebhookMaxAttempts int
// Rate limiting
RateLimitDisabled bool
RateLimitBackend string // memory (default) or redis
RateLimitWindowSecs int
RateLimitMaxRequests int
RateLimitRPM int
RateLimitRPMAdmin int
RateLimitRPMWrite int
RateLimitRPMReadonly int
// TLS (optional — leave empty for plain HTTP)
TLSCertFile string
TLSKeyFile string
// Encryption
EncryptionKey string
// OpenTelemetry
OTELTracesEndpoint string
OTELEndpoint string
OTELServiceName string
// Dedup (PCMI-011): default ingest dedup mode when tenant/request omit it.
DedupMode string
// Logging
LogFormat string // "json" (default) or "text"
LogLevel string // "info" (default) | "debug" | "warn" | "error"
LogSource string // "1" | "true" to enable source file:line in every record
}
// APIConfig returns the subset of fields required by the API service.
// Validation is still performed on the full Config; this is a convenience view.
func (c *Config) APIConfig() *Config { return c }
// WorkerConfig returns the subset of fields required by the Worker service.
func (c *Config) WorkerConfig() *Config { return c }
// Load reads all environment variables and applies defaults.
// It does NOT return an error — call Validate() or use MustLoad().
func Load() *Config {
cfg := &Config{
DatabaseURL: envOr("DATABASE_URL", ""),
DatabaseReadURL: os.Getenv("DATABASE_READ_URL"),
RedisAddr: envOr("REDIS_ADDR", "redis:6379"),
EventBackend: envOr("EVENT_BACKEND", "streams"),
APIPort: envOr("API_PORT", "8000"),
GRPCPort: envOr("GRPC_PORT", "50051"),
AdminAPIKey: os.Getenv("ADMIN_API_KEY"),
MetricsScrapeToken: strings.TrimSpace(os.Getenv("METRICS_SCRAPE_TOKEN")),
PCMIBaseURL: strings.TrimSpace(os.Getenv("PCMI_BASE_URL")),
PCMIAPIKey: strings.TrimSpace(os.Getenv("PCMI_API_KEY")),
OpenAIAPIKey: os.Getenv("OPENAI_API_KEY"),
OpenAIBaseURL: strings.TrimSpace(os.Getenv("OPENAI_BASE_URL")),
EmbeddingModel: envOr("EMBEDDING_MODEL", "text-embedding-3-small"),
MigrationsDir: envOr("MIGRATIONS_DIR", "migrations"),
DistillationModel: envOr("DISTILLATION_MODEL", "gpt-4o-mini"),
DistillationBatchSize: envInt("DISTILLATION_BATCH_SIZE", 10),
DistillationConcurrency: envInt("DISTILLATION_CONCURRENCY", 4),
DistillationPolicyDisabled: envBool("DISTILLATION_POLICY_DISABLED", false),
PruneRetentionDays: envInt("PRUNE_RETENTION_DAYS", 30),
PruneIntervalSecs: envInt("PRUNE_INTERVAL_SECS", 3600),
ExpiryIntervalSecs: envInt("EXPIRY_INTERVAL_SECS", 3600),
WebhookMaxAttempts: envInt("WEBHOOK_MAX_ATTEMPTS", 5),
RateLimitDisabled: envBool("RATE_LIMIT_DISABLED", false),
RateLimitBackend: envOr("RATE_LIMIT_BACKEND", "memory"),
RateLimitWindowSecs: envInt("RATE_LIMIT_WINDOW_SECS", 60),
RateLimitMaxRequests: envInt("RATE_LIMIT_MAX_REQUESTS", 100),
RateLimitRPM: envInt("RATE_LIMIT_RPM", 120),
RateLimitRPMAdmin: envInt("RATE_LIMIT_RPM_ADMIN", 30),
RateLimitRPMWrite: envInt("RATE_LIMIT_RPM_WRITE", 100),
RateLimitRPMReadonly: envInt("RATE_LIMIT_RPM_READONLY", 200),
TLSCertFile: strings.TrimSpace(os.Getenv("PCMI_TLS_CERT")),
TLSKeyFile: strings.TrimSpace(os.Getenv("PCMI_TLS_KEY")),
EncryptionKey: strings.TrimSpace(os.Getenv("PCMI_ENCRYPTION_KEY")),
OTELTracesEndpoint: strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT")),
OTELEndpoint: strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT")),
OTELServiceName: strings.TrimSpace(os.Getenv("OTEL_SERVICE_NAME")),
DedupMode: envOr("DEDUP_MODE", "none"),
LogFormat: envOr("PCMI_LOG_FORMAT", ""),
LogLevel: envOr("PCMI_LOG_LEVEL", ""),
LogSource: strings.TrimSpace(os.Getenv("PCMI_LOG_SOURCE")),
}
return cfg
}
// Validate verifies that all required fields are set and values are in valid ranges.
// Returns a multi-error with all problems found so the operator can fix everything at once.
func (c *Config) Validate(requiredFields ...RequiredField) error {
var errs []string
for _, f := range requiredFields {
switch f {
case RequireDatabaseURL:
if c.DatabaseURL == "" {
errs = append(errs, "DATABASE_URL is required")
}
case RequireAdminAPIKey:
if c.AdminAPIKey == "" {
errs = append(errs, "ADMIN_API_KEY is required")
}
case RequireEncryptionKey:
if c.EncryptionKey == "" {
errs = append(errs, "PCMI_ENCRYPTION_KEY is required")
}
case RequirePCMIBaseURL:
if c.PCMIBaseURL == "" {
errs = append(errs, "PCMI_BASE_URL is required")
}
case RequirePCMIAPIKey:
if c.PCMIAPIKey == "" {
errs = append(errs, "PCMI_API_KEY is required")
}
}
}
// Range validations (always checked)
if c.DistillationBatchSize < 1 || c.DistillationBatchSize > 1000 {
errs = append(errs, fmt.Sprintf("DISTILLATION_BATCH_SIZE must be 1–1000 (got %d)", c.DistillationBatchSize))
}
if c.DistillationConcurrency < 1 || c.DistillationConcurrency > 16 {
errs = append(errs, fmt.Sprintf("DISTILLATION_CONCURRENCY must be 1–16 (got %d)", c.DistillationConcurrency))
}
if c.PruneRetentionDays < 1 {
errs = append(errs, fmt.Sprintf("PRUNE_RETENTION_DAYS must be ≥ 1 (got %d)", c.PruneRetentionDays))
}
if c.PruneIntervalSecs < 1 {
errs = append(errs, fmt.Sprintf("PRUNE_INTERVAL_SECS must be ≥ 1 (got %d)", c.PruneIntervalSecs))
}
if c.ExpiryIntervalSecs < 1 {
errs = append(errs, fmt.Sprintf("EXPIRY_INTERVAL_SECS must be ≥ 1 (got %d)", c.ExpiryIntervalSecs))
}
if c.WebhookMaxAttempts < 1 || c.WebhookMaxAttempts > 100 {
errs = append(errs, fmt.Sprintf("WEBHOOK_MAX_ATTEMPTS must be 1–100 (got %d)", c.WebhookMaxAttempts))
}
if c.RateLimitRPM < 1 {
errs = append(errs, fmt.Sprintf("RATE_LIMIT_RPM must be ≥ 1 (got %d)", c.RateLimitRPM))
}
backend := strings.ToLower(strings.TrimSpace(c.RateLimitBackend))
if backend == "" {
backend = "memory"
}
if backend != "memory" && backend != "redis" {
errs = append(errs, fmt.Sprintf("RATE_LIMIT_BACKEND must be memory or redis (got %q)", c.RateLimitBackend))
}
if c.RateLimitWindowSecs < 0 {
errs = append(errs, fmt.Sprintf("RATE_LIMIT_WINDOW_SECS must be ≥ 1 (got %d)", c.RateLimitWindowSecs))
}
if c.RateLimitMaxRequests < 0 {
errs = append(errs, fmt.Sprintf("RATE_LIMIT_MAX_REQUESTS must be ≥ 1 (got %d)", c.RateLimitMaxRequests))
}
if _, err := parseDedupModeConfig(c.DedupMode); err != nil {
errs = append(errs, err.Error())
}
if len(errs) == 0 {
return nil
}
return errors.New("config validation failed:\n - " + strings.Join(errs, "\n - "))
}
// RequiredField enumerates fields that are mandatory for a given service.
type RequiredField int
const (
RequireDatabaseURL RequiredField = iota
RequireAdminAPIKey
RequireEncryptionKey
RequirePCMIBaseURL
RequirePCMIAPIKey
)
// APIRequiredFields are the fields that the API service must have at startup.
var APIRequiredFields = []RequiredField{
RequireDatabaseURL,
}
// WorkerRequiredFields are the fields that the Worker service must have at startup.
var WorkerRequiredFields = []RequiredField{
RequireDatabaseURL,
}
// MCPRequiredFields are the fields that the MCP stdio server must have at startup.
var MCPRequiredFields = []RequiredField{
RequirePCMIBaseURL,
RequirePCMIAPIKey,
}
// PruneInterval returns PruneIntervalSecs as a time.Duration.
func (c *Config) PruneInterval() time.Duration {
return time.Duration(c.PruneIntervalSecs) * time.Second
}
// ExpiryInterval returns ExpiryIntervalSecs as a time.Duration.
func (c *Config) ExpiryInterval() time.Duration {
return time.Duration(c.ExpiryIntervalSecs) * time.Second
}
// -------------------------------------------------------------------
// helpers
func envOr(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
func envInt(key string, fallback int) int {
if v := os.Getenv(key); v != "" {
if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil {
return n
}
}
return fallback
}
func parseDedupModeConfig(s string) (string, error) {
s = strings.ToLower(strings.TrimSpace(s))
switch s {
case "", "none", "skip", "link", "merge":
if s == "" {
return "none", nil
}
return s, nil
default:
return "", fmt.Errorf("DEDUP_MODE must be none|skip|link|merge (got %q)", s)
}
}
func envBool(key string, fallback bool) bool {
v := strings.TrimSpace(os.Getenv(key))
if v == "" {
return fallback
}
return v == "true" || v == "1" || v == "yes"
}