forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

config.rs260 lines, 11.4 KiBHistoryRawDownload
1use std::env;
2
3use crate::constant::{
4 AI_DEFAULT_REQUEST_TIMEOUT_SECS, AI_MAX_REQUEST_TIMEOUT_SECS, DEFAULT_API_RATE_LIMIT,
5 DEFAULT_AUTH_RATE_LIMIT, DEFAULT_CHATBOT_RATE_LIMIT, DEFAULT_RAG_RATE_LIMIT,
6};
7use crate::rate_limit::RateLimitConfig;
8use crate::telemetry::{LogFormat, TelemetryConfig, TelemetryError};
9
10/// Runtime configuration, sourced from environment variables (see `.env.example`).
11#[derive(Clone, Debug)]
12pub struct Config {
13 pub host: String,
14 pub port: u16,
15 /// PostgreSQL connection string (`DATABASE_URL`), e.g.
16 /// `postgres://hezarfen:hezarfen@127.0.0.1:5432/hezarfen_control`. Also
17 /// read by sqlx's compile-time query macros, which prepare against the
18 /// union-schema prepare database (see `scripts/prepare_db.sh`).
19 pub database_url: String,
20 /// Directory for uploaded note-file blobs (`FILES_PATH`).
21 pub files_path: String,
22 /// Add the `Secure` attribute to the session cookie (HTTPS-only). Off by
23 /// default so plain-HTTP local dev keeps working; enable behind TLS.
24 pub cookie_secure: bool,
25 /// Per-IP request limits (`RATE_LIMIT_AUTH_PER_MINUTE`,
26 /// `RATE_LIMIT_API_PER_MINUTE`, `TRUST_PROXY`). `0` disables a tier.
27 pub rate_limit: RateLimitConfig,
28 /// Chatbot messages one user may send per minute
29 /// (`RATE_LIMIT_CHATBOT_PER_MINUTE`). `0` disables the tier. Kept out of
30 /// [`RateLimitConfig`], which is the per-IP middleware bundle: this tier is
31 /// keyed by user and is enforced inside the handler.
32 pub chatbot_per_minute: u32,
33 /// RAG messages one user may send per minute
34 /// (`RATE_LIMIT_RAG_PER_MINUTE`). `0` disables the tier. Kept out of
35 /// [`RateLimitConfig`], which is the per-IP middleware bundle: this tier is
36 /// keyed by user and is enforced inside the handler.
37 pub rag_per_minute: u32,
38 /// Startup builder seed (`BUILDER_USERNAME` + `BUILDER_PASSWORD`). When
39 /// both are set, a builder account with these credentials is created in the
40 /// control database at boot if the username doesn't exist yet. Blank values
41 /// count as unset. A builder manages schools; it is not a user of any of
42 /// them.
43 pub builder_username: Option<String>,
44 pub builder_password: Option<String>,
45 /// AI bridge listen address (`AI_QUIC_ADDR`, e.g. `0.0.0.0:8090`). Unset
46 /// leaves the bridge off entirely: the API runs exactly as before and any
47 /// AI-backed feature reports that no service is connected.
48 pub ai_quic_addr: Option<String>,
49 /// Shared secret every AI service must present (`AI_SHARED_TOKEN`).
50 /// Required whenever `ai_quic_addr` is set — the bridge refuses to start
51 /// without one rather than listening unauthenticated.
52 pub ai_shared_token: Option<String>,
53 /// PEM certificate/key for the bridge listener (`AI_TLS_CERT` /
54 /// `AI_TLS_KEY`). Both unset means a self-signed pair is generated at boot
55 /// and its fingerprint logged for the services to pin.
56 pub ai_tls_cert: Option<String>,
57 pub ai_tls_key: Option<String>,
58 /// Default per-request deadline for AI calls (`AI_REQUEST_TIMEOUT_SECS`).
59 pub ai_request_timeout_secs: u64,
60}
61
62impl Config {
63 pub fn from_env() -> Self {
64 Self {
65 host: env::var("HOST").unwrap_or_else(|_| "127.0.0.1".into()),
66 port: parse_port(env::var("PORT").ok()),
67 database_url: env::var("DATABASE_URL").unwrap_or_else(|_| {
68 "postgres://hezarfen:hezarfen@127.0.0.1:5432/hezarfen_control".into()
69 }),
70 files_path: env::var("FILES_PATH").unwrap_or_else(|_| "./data/files".into()),
71 cookie_secure: parse_flag(env::var("COOKIE_SECURE").ok()),
72 rate_limit: RateLimitConfig {
73 auth_per_minute: parse_limit(
74 env::var("RATE_LIMIT_AUTH_PER_MINUTE").ok(),
75 DEFAULT_AUTH_RATE_LIMIT,
76 ),
77 api_per_minute: parse_limit(
78 env::var("RATE_LIMIT_API_PER_MINUTE").ok(),
79 DEFAULT_API_RATE_LIMIT,
80 ),
81 trust_proxy: parse_flag(env::var("TRUST_PROXY").ok()),
82 },
83 chatbot_per_minute: parse_limit(
84 env::var("RATE_LIMIT_CHATBOT_PER_MINUTE").ok(),
85 DEFAULT_CHATBOT_RATE_LIMIT,
86 ),
87 rag_per_minute: parse_limit(
88 env::var("RATE_LIMIT_RAG_PER_MINUTE").ok(),
89 DEFAULT_RAG_RATE_LIMIT,
90 ),
91 builder_username: parse_optional(env::var("BUILDER_USERNAME").ok()),
92 builder_password: parse_optional(env::var("BUILDER_PASSWORD").ok()),
93 ai_quic_addr: parse_optional(env::var("AI_QUIC_ADDR").ok()),
94 ai_shared_token: parse_optional(env::var("AI_SHARED_TOKEN").ok()),
95 ai_tls_cert: parse_optional(env::var("AI_TLS_CERT").ok()),
96 ai_tls_key: parse_optional(env::var("AI_TLS_KEY").ok()),
97 ai_request_timeout_secs: parse_timeout(
98 env::var("AI_REQUEST_TIMEOUT_SECS").ok(),
99 AI_DEFAULT_REQUEST_TIMEOUT_SECS,
100 ),
101 }
102 }
103}
104
105/// Telemetry settings, read before [`Config::from_env`] because the logger has
106/// to exist before anything else can complain.
107///
108/// Only two variables are ours. Endpoint, headers, protocol, sampler and
109/// service name are read by the OpenTelemetry SDK from its own standard
110/// variables (documented in `.env.example`) — parsing them here would create a
111/// second source of truth that could disagree with the exporter.
112///
113/// Fallible where the rest of the config is not: a `LOG_FORMAT` we do not
114/// render is worth refusing to boot over, since the operator would otherwise
115/// discover it when they came looking for logs they never got.
116pub fn telemetry_from_env() -> Result<TelemetryConfig, TelemetryError> {
117 Ok(TelemetryConfig {
118 otlp_endpoint: parse_optional(env::var("OTEL_EXPORTER_OTLP_ENDPOINT").ok()),
119 log_format: LogFormat::parse(env::var("LOG_FORMAT").ok())?,
120 })
121}
122
123/// Treat an unset or blank variable as absent.
124fn parse_optional(value: Option<String>) -> Option<String> {
125 value.filter(|v| !v.trim().is_empty())
126}
127
128/// Parse a per-minute limit, falling back to `default` when unset or
129/// unparseable. An explicit `0` is honoured: it turns that tier off.
130fn parse_limit(value: Option<String>, default: u32) -> u32 {
131 value.and_then(|v| v.trim().parse().ok()).unwrap_or(default)
132}
133
134/// Parse the AI request deadline in seconds. Unlike a rate limit, `0` is *not*
135/// honoured — a zero deadline would fail every AI request instantly, which is
136/// never what an operator means — so it falls back with the rest of the
137/// garbage.
138///
139/// The ceiling is enforced here because here is the only place the number
140/// enters the process. A deadline above [`AI_MAX_REQUEST_TIMEOUT_SECS`] keeps
141/// a task and a worker slot busy past the point where the answer could still
142/// be shown to anyone (see that constant), so it is clamped rather than
143/// honoured.
144fn parse_timeout(value: Option<String>, default: u64) -> u64 {
145 let asked = value
146 .and_then(|v| v.trim().parse().ok())
147 .filter(|n| *n > 0)
148 .unwrap_or(default);
149 if asked > AI_MAX_REQUEST_TIMEOUT_SECS {
150 // Loud: the operator asked for something they are not getting, and the
151 // reason (a queue horizon) is not one they could guess from the name.
152 tracing::warn!(
153 "AI_REQUEST_TIMEOUT_SECS={asked} is above the {AI_MAX_REQUEST_TIMEOUT_SECS}s ceiling \
154 (a reply that late is discarded as stale before anyone sees it) — using \
155 {AI_MAX_REQUEST_TIMEOUT_SECS}s"
156 );
157 return AI_MAX_REQUEST_TIMEOUT_SECS;
158 }
159 asked
160}
161
162/// Parse the `PORT` value, falling back to 7656 when unset or unparseable.
163fn parse_port(value: Option<String>) -> u16 {
164 value.and_then(|p| p.parse().ok()).unwrap_or(7656)
165}
166
167/// Parse a boolean toggle: `1` / `true` / `yes` / `on` (any case, trimmed) are
168/// true. Anything else — including unset — is false.
169fn parse_flag(value: Option<String>) -> bool {
170 value.is_some_and(|v| {
171 matches!(
172 v.trim().to_ascii_lowercase().as_str(),
173 "1" | "true" | "yes" | "on"
174 )
175 })
176}
177
178#[cfg(test)]
179mod tests {
180 use super::{parse_flag, parse_limit, parse_port, parse_timeout};
181 use crate::constant::{
182 AI_DEFAULT_REQUEST_TIMEOUT_SECS, AI_MAX_REQUEST_TIMEOUT_SECS, CHATBOT_PENDING_STALE_SECS,
183 };
184
185 #[tokio::test]
186 async fn timeout_falls_back_on_absent_garbage_and_zero() {
187 assert_eq!(parse_timeout(None, 30), 30);
188 assert_eq!(parse_timeout(Some("nope".into()), 30), 30);
189 // A zero deadline would time out every AI call before it started.
190 assert_eq!(parse_timeout(Some("0".into()), 30), 30);
191 // Whitespace is trimmed; the ceiling has its own test below.
192 assert_eq!(parse_timeout(Some(" 45 ".into()), 30), 45);
193 }
194
195 #[tokio::test]
196 async fn a_configured_timeout_is_clamped_below_the_stale_horizon() {
197 // Nothing used to stop `AI_REQUEST_TIMEOUT_SECS=600`, and a dispatch
198 // that outlives `CHATBOT_PENDING_STALE_SECS` holds a worker slot for an
199 // answer every reader has already been shown as failed. The
200 // relationship, not a literal, is what is asserted: raising the ceiling
201 // past the staleness window cannot pass this.
202 for asked in ["61", "120", "600", "18446744073709551615"] {
203 let got = parse_timeout(Some(asked.into()), AI_DEFAULT_REQUEST_TIMEOUT_SECS);
204 assert!(
205 (got as i64) < CHATBOT_PENDING_STALE_SECS,
206 "AI_REQUEST_TIMEOUT_SECS={asked} was honoured as {got}s, at or past the \
207 {CHATBOT_PENDING_STALE_SECS}s staleness horizon"
208 );
209 assert_eq!(got, AI_MAX_REQUEST_TIMEOUT_SECS, "clamped to the ceiling");
210 }
211 // Everything under the ceiling — the default included — is honoured
212 // verbatim: this is a ceiling, not a fixed deadline.
213 assert_eq!(parse_timeout(Some("45".into()), 30), 45);
214 assert_eq!(
215 parse_timeout(None, AI_DEFAULT_REQUEST_TIMEOUT_SECS),
216 AI_DEFAULT_REQUEST_TIMEOUT_SECS
217 );
218 }
219
220 #[tokio::test]
221 async fn limit_defaults_when_absent_or_garbage() {
222 assert_eq!(parse_limit(None, 10), 10);
223 assert_eq!(parse_limit(Some("not-a-number".into()), 10), 10);
224 assert_eq!(parse_limit(Some("-5".into()), 10), 10);
225 }
226
227 #[tokio::test]
228 async fn limit_parses_values_and_honours_explicit_zero() {
229 assert_eq!(parse_limit(Some("25".into()), 10), 25);
230 assert_eq!(parse_limit(Some(" 25 ".into()), 10), 25);
231 assert_eq!(parse_limit(Some("0".into()), 10), 0);
232 }
233
234 #[tokio::test]
235 async fn defaults_when_absent() {
236 assert_eq!(parse_port(None), 7656);
237 }
238
239 #[tokio::test]
240 async fn flag_defaults_off_and_accepts_truthy_spellings() {
241 assert!(!parse_flag(None));
242 for v in ["1", "true", "TRUE", " yes ", "On"] {
243 assert!(parse_flag(Some(v.into())), "{v:?} should be true");
244 }
245 for v in ["0", "false", "nope", ""] {
246 assert!(!parse_flag(Some(v.into())), "{v:?} should be false");
247 }
248 }
249
250 #[tokio::test]
251 async fn parses_valid_port() {
252 assert_eq!(parse_port(Some("3000".into())), 3000);
253 }
254
255 #[tokio::test]
256 async fn falls_back_on_garbage() {
257 assert_eq!(parse_port(Some("not-a-port".into())), 7656);
258 assert_eq!(parse_port(Some(String::new())), 7656);
259 }
260}