rainier_framework/keys.rs
1//! The configuration keys Rainier itself reads — a typed index of the tree.
2//!
3//! Laravel's answer to "what can I put in `config/app.php`?" is to read the
4//! shipped file. Rainier's is this module: every key the framework writes or
5//! reads, with the type stored at it.
6//!
7//! ```
8//! use rainier_framework::config::Config;
9//! use rainier_framework::keys;
10//!
11//! let config = Config::new();
12//! config.set(keys::APP_NAME, "My App".to_string()).unwrap();
13//!
14//! assert_eq!(config.get(keys::APP_NAME).as_deref(), Some("My App"));
15//! ```
16//!
17//! Using them is optional — every `Config` method still takes a `&str` — but
18//! it is what turns two classes of silent mistake into compile errors:
19//!
20//! ```compile_fail
21//! # use rainier_framework::{config::Config, keys};
22//! # let config = Config::new();
23//! // The port is a u16, so this does not compile.
24//! config.set(keys::SERVER_PORT, "8000").unwrap();
25//! ```
26//!
27//! ```compile_fail
28//! # use rainier_framework::{config::Config, keys};
29//! # let config = Config::new();
30//! // Neither does a driver spelled as a string.
31//! config.set(keys::CACHE_DRIVER, "redis").unwrap();
32//! ```
33//!
34//! ## Reading a driver
35//!
36//! The driver keys hold [settings](rainier_support::Setting) — closed sets with
37//! their own parser. Read them with [`Config::setting`], which distinguishes
38//! *unset* (use the default) from *set to nonsense* (fail, and list what was
39//! expected):
40//!
41//! ```
42//! use rainier_framework::cache::CacheDriver;
43//! use rainier_framework::config::Config;
44//! use rainier_framework::keys;
45//!
46//! let config = Config::new();
47//! config.set(keys::CACHE_DRIVER, CacheDriver::Redis).unwrap();
48//!
49//! match config.setting(keys::CACHE_DRIVER).unwrap() {
50//! CacheDriver::Memory => { /* … */ }
51//! CacheDriver::Redis | CacheDriver::RedisCluster => { /* … */ }
52//! CacheDriver::Memcached => { /* … */ }
53//! CacheDriver::DynamoDb => { /* … */ }
54//! }
55//! ```
56//!
57//! [`Config::setting`]: rainier_config::Config::setting
58//!
59//! ## Adding your own
60//!
61//! An application declares its keys the same way, next to the section that
62//! writes them:
63//!
64//! ```
65//! use rainier_framework::config::config_keys;
66//!
67//! config_keys! {
68//! /// How many posts a listing shows.
69//! pub POSTS_PER_PAGE: u64 = "posts.per_page";
70//! }
71//! ```
72
73use rainier_cache::CacheDriver;
74use rainier_config::{config_keys, AppEnv};
75use rainier_mail::MailDriver;
76use rainier_queue::QueueDriver;
77use rainier_session::SessionDriver;
78
79config_keys! {
80 // --- app ---------------------------------------------------------------
81
82 /// The application's display name, in page titles and mail.
83 pub APP_NAME: String = "app.name";
84
85 /// Which deployment this is.
86 ///
87 /// Defaults to [`AppEnv::Production`] when `APP_ENV` is unset — the safe
88 /// direction to be wrong in.
89 pub APP_ENV: AppEnv = "app.env";
90
91 /// Whether a failure may show its internals to the client.
92 ///
93 /// Separate from [`APP_ENV`] because they drift the moment someone debugs
94 /// staging.
95 pub APP_DEBUG: bool = "app.debug";
96
97 /// The application's canonical base URL, used to generate absolute links.
98 pub APP_URL: String = "app.url";
99
100 /// The directory the application was started from. Set by the framework;
101 /// there is no environment variable for it.
102 pub APP_BASE_PATH: String = "app.base_path";
103
104 // --- server ------------------------------------------------------------
105
106 /// The interface the HTTP server binds to.
107 pub SERVER_HOST: String = "server.host";
108
109 /// The port the HTTP server binds to.
110 pub SERVER_PORT: u16 = "server.port";
111
112 /// The largest request body that will be buffered, in bytes.
113 pub SERVER_MAX_BODY_BYTES: u64 = "server.max_body_bytes";
114
115 // --- observability ------------------------------------------------------
116 //
117 // All three are off by default. Each costs something a request pays for —
118 // a lock and a timer, a document rendered at boot, a span per request —
119 // and an application that has not asked for them should not pay it.
120
121 /// Whether to record Prometheus metrics.
122 pub METRICS_ENABLED: bool = "metrics.enabled";
123
124 /// The path the scrape endpoint is served at.
125 ///
126 /// Configurable because it is the one endpoint you may want somewhere
127 /// unguessable, on a deployment where it cannot be put behind auth.
128 pub METRICS_PATH: String = "metrics.path";
129
130 /// Whether to serve the OpenAPI document.
131 pub OPENAPI_ENABLED: bool = "openapi.enabled";
132
133 /// The path the document is served at.
134 pub OPENAPI_PATH: String = "openapi.path";
135
136 /// The `info.title` of the document.
137 pub OPENAPI_TITLE: String = "openapi.title";
138
139 /// The `info.version` of the document — your API's version, not the
140 /// framework's.
141 pub OPENAPI_VERSION: String = "openapi.version";
142
143 /// The base URL clients should use, if the document should name one.
144 pub OPENAPI_SERVER: String = "openapi.server";
145
146 /// Whether to join and propagate W3C trace context.
147 ///
148 /// Cheap: no exporter, no collector, just the `traceparent` header and a
149 /// trace id on every log line. Worth having on even without OTLP.
150 pub TELEMETRY_ENABLED: bool = "telemetry.enabled";
151
152 /// The OTLP collector's gRPC endpoint — `http://localhost:4317`.
153 ///
154 /// Absent unless set, and absent means spans are not exported. Needs the
155 /// `otlp` feature.
156 pub TELEMETRY_ENDPOINT: String = "telemetry.endpoint";
157
158 /// What this service calls itself in a trace.
159 pub TELEMETRY_SERVICE_NAME: String = "telemetry.service_name";
160
161 /// What fraction of traces this service *starts* to record, `0.0` to
162 /// `1.0`.
163 ///
164 /// A trace that arrives with a decision keeps it, whatever this says.
165 pub TELEMETRY_SAMPLE_RATIO: f64 = "telemetry.sample_ratio";
166
167 // --- database ----------------------------------------------------------
168
169 /// The database DSN — `sqlite::memory:`, `mysql://…`, `postgres://…`.
170 pub DATABASE_URL: String = "database.url";
171
172 // --- cache -------------------------------------------------------------
173
174 /// Which cache store to build.
175 pub CACHE_DRIVER: CacheDriver = "cache.driver";
176
177 /// The Redis DSN, or a comma-separated seed list for a cluster.
178 pub CACHE_REDIS_URL: String = "cache.redis_url";
179
180 /// `host:port` of the Memcached server.
181 pub CACHE_MEMCACHED_URL: String = "cache.memcached_url";
182
183 /// Prepended to every cache key, so two applications can share a server.
184 pub CACHE_PREFIX: String = "cache.prefix";
185
186 // --- session -----------------------------------------------------------
187
188 /// Where session state lives.
189 pub SESSION_DRIVER: SessionDriver = "session.driver";
190
191 /// How long a session survives without a request, in seconds.
192 pub SESSION_LIFETIME: i64 = "session.lifetime";
193
194 /// The name of the session cookie.
195 pub SESSION_COOKIE: String = "session.cookie";
196
197 /// Whether the session cookie is `Secure`. Must be true over HTTPS.
198 pub SESSION_SECURE: bool = "session.secure";
199
200 // --- queue -------------------------------------------------------------
201
202 /// Where queued jobs wait.
203 pub QUEUE_DRIVER: QueueDriver = "queue.driver";
204
205 /// The queue a job goes on when it does not name one.
206 pub QUEUE_DEFAULT: String = "queue.default";
207
208 // --- mail --------------------------------------------------------------
209
210 /// Where mail goes.
211 pub MAIL_DRIVER: MailDriver = "mail.driver";
212
213 /// The default `From` address.
214 pub MAIL_FROM_ADDRESS: String = "mail.from.address";
215
216 /// The default `From` display name.
217 pub MAIL_FROM_NAME: String = "mail.from.name";
218}
219
220#[cfg(test)]
221mod tests {
222 use super::*;
223 use rainier_config::Config;
224
225 #[test]
226 fn a_driver_key_round_trips_as_its_wire_spelling() {
227 let config = Config::new();
228 config.set(CACHE_DRIVER, CacheDriver::RedisCluster).unwrap();
229
230 // What a `.env` would hold, and what a config dump should show.
231 assert_eq!(config.string("cache.driver").as_deref(), Some("redis-cluster"));
232 assert_eq!(config.setting(CACHE_DRIVER).unwrap(), CacheDriver::RedisCluster);
233 }
234
235 #[test]
236 fn every_key_is_under_the_section_its_name_says() {
237 // A key filed under the wrong prefix reads fine and writes somewhere
238 // nothing looks. Cheap to assert, and it has caught a paste already.
239 let pairs: &[(&str, &str)] = &[
240 ("APP", APP_NAME.path()),
241 ("APP", APP_ENV.path()),
242 ("APP", APP_DEBUG.path()),
243 ("APP", APP_URL.path()),
244 ("APP", APP_BASE_PATH.path()),
245 ("SERVER", SERVER_HOST.path()),
246 ("SERVER", SERVER_PORT.path()),
247 ("SERVER", SERVER_MAX_BODY_BYTES.path()),
248 ("DATABASE", DATABASE_URL.path()),
249 ("CACHE", CACHE_DRIVER.path()),
250 ("CACHE", CACHE_REDIS_URL.path()),
251 ("CACHE", CACHE_MEMCACHED_URL.path()),
252 ("CACHE", CACHE_PREFIX.path()),
253 ("SESSION", SESSION_DRIVER.path()),
254 ("SESSION", SESSION_LIFETIME.path()),
255 ("SESSION", SESSION_COOKIE.path()),
256 ("SESSION", SESSION_SECURE.path()),
257 ("QUEUE", QUEUE_DRIVER.path()),
258 ("QUEUE", QUEUE_DEFAULT.path()),
259 ("MAIL", MAIL_DRIVER.path()),
260 ("MAIL", MAIL_FROM_ADDRESS.path()),
261 ("MAIL", MAIL_FROM_NAME.path()),
262 ];
263
264 for (section, path) in pairs {
265 assert!(
266 path.starts_with(&format!("{}.", section.to_lowercase())),
267 "`{path}` is filed under the wrong section"
268 );
269 }
270 }
271
272 #[test]
273 fn no_two_keys_name_the_same_path() {
274 let paths = [
275 APP_NAME.path(),
276 APP_ENV.path(),
277 APP_DEBUG.path(),
278 APP_URL.path(),
279 APP_BASE_PATH.path(),
280 SERVER_HOST.path(),
281 SERVER_PORT.path(),
282 SERVER_MAX_BODY_BYTES.path(),
283 DATABASE_URL.path(),
284 CACHE_DRIVER.path(),
285 CACHE_REDIS_URL.path(),
286 CACHE_MEMCACHED_URL.path(),
287 CACHE_PREFIX.path(),
288 SESSION_DRIVER.path(),
289 SESSION_LIFETIME.path(),
290 SESSION_COOKIE.path(),
291 SESSION_SECURE.path(),
292 QUEUE_DRIVER.path(),
293 QUEUE_DEFAULT.path(),
294 MAIL_DRIVER.path(),
295 MAIL_FROM_ADDRESS.path(),
296 MAIL_FROM_NAME.path(),
297 ];
298
299 let unique: std::collections::BTreeSet<_> = paths.iter().collect();
300 assert_eq!(unique.len(), paths.len(), "two keys share a path: {paths:?}");
301 }
302}