Skip to main content

renox_core/
state.rs

1use std::fmt::Display;
2use std::sync::Arc;
3
4use cookie::Key;
5
6use crate::auth::{Gates, LoginThrottle};
7use crate::cache::Cache;
8use crate::db::Db;
9use crate::events::Listeners;
10use crate::i18n::Translator;
11use crate::mail::Mailer;
12use crate::queue::Queue;
13use crate::storage::Storage;
14use crate::{Config, Result, RouteTable, Views};
15
16/// Shared state available to every handler through `State<AppState>`.
17///
18/// One `Arc` around [`AppStateInner`]: every middleware layer, the request's
19/// extensions and each handler's `State` clone it, so a clone is one atomic
20/// increment (it was a struct of about 35 fields, cloned tens of times per
21/// request: #334). Read its parts as fields, through `Deref`:
22/// `state.db`, `state.config`, `state.queue`…
23#[derive(Clone)]
24pub struct AppState(Arc<AppStateInner>);
25
26impl std::ops::Deref for AppState {
27    type Target = AppStateInner;
28
29    fn deref(&self) -> &AppStateInner {
30        &self.0
31    }
32}
33
34impl AppState {
35    /// Wraps the parts made at boot (`App::boot`).
36    pub(crate) fn new(inner: AppStateInner) -> Self {
37        AppState(Arc::new(inner))
38    }
39}
40
41/// What an [`AppState`] holds. Apps read these as the state's fields
42/// (`state.db`); only Renox builds one, at boot.
43#[non_exhaustive]
44pub struct AppStateInner {
45    /// The configuration.
46    pub config: Arc<Config>,
47    /// Named routes, to build URLs (`state.url(name, params)`).
48    pub(crate) routes: Arc<RouteTable>,
49    /// The template engine (`view()` renders, `mail_view` for mail).
50    pub(crate) views: Views,
51    /// The database connection pool.
52    pub db: Db,
53    /// Sends mail (`MAIL_MAILER`).
54    pub mailer: Mailer,
55    /// Limits on queued deliveries per channel (`App::channel_rate_limit`).
56    pub(crate) channel_limits: Arc<std::collections::HashMap<String, crate::queue::Limit>>,
57    /// Limits on queued mail per mailer (`App::mailer_rate_limit`).
58    pub(crate) mailer_limits: Arc<std::collections::HashMap<String, crate::queue::Limit>>,
59    /// The app's other mailers (`App::mailer`), by name.
60    pub(crate) mailers: Arc<std::collections::HashMap<String, Mailer>>,
61    /// The themes the app can serve at `/_renox/theme/{hash}.css`.
62    pub(crate) themes: crate::theme::ThemeRegistry,
63    /// The installable-app configuration (`App::pwa`), for `<rx-pwa/>`.
64    pub(crate) pwa: Option<Arc<crate::pwa::Pwa>>,
65    /// Dispatches jobs.
66    pub queue: Queue,
67    /// The cache (`CACHE_STORE`).
68    pub cache: Cache,
69    /// The file storage disk (`STORAGE_DISK`).
70    pub storage: Storage,
71    /// The app's other disks (`App::disk`), by name; see [`AppState::disk`].
72    pub(crate) disks: Arc<std::collections::HashMap<String, Storage>>,
73    /// The steps uploaded files pass (`App::uploads`).
74    pub(crate) uploads: crate::upload::Pipeline,
75    /// Calls other services; faked in tests (`TestApp::fake_http`).
76    pub http: crate::http::Http,
77    /// Translations from `LANG_PATH` and the built-in ones (`Lang`, `t()`).
78    pub(crate) translator: Arc<Translator>,
79    /// Live reload, only while developing locally.
80    pub(crate) live: Option<Arc<crate::live::Live>>,
81    /// Wakes the users' open notification streams.
82    pub(crate) notification_hub: Arc<crate::auth::notifications::Hub>,
83    pub(crate) listeners: Listeners,
84    pub(crate) key: Key,
85    /// With `SESSION_DRIVER=database` in tests, sessions are kept here
86    /// instead of the table (keyed by the id's hash).
87    pub(crate) session_mirror:
88        Option<Arc<std::sync::Mutex<std::collections::HashMap<String, String>>>>,
89    pub(crate) gates: Gates,
90    pub(crate) async_gates: Arc<std::collections::HashMap<String, crate::auth::AsyncGate>>,
91    pub(crate) throttle: Arc<LoginThrottle>,
92    /// A module's second login step (`Registry::second_factor`).
93    pub(crate) second_factor: Option<Arc<crate::auth::second_factor::SecondFactor>>,
94    /// Sections other modules add to `/account` (`Registry::account_section`).
95    pub(crate) account_sections: Arc<Vec<crate::auth::account::AccountSection>>,
96    /// The navigation menus (`App::nav`).
97    #[allow(dead_code)]
98    pub(crate) nav: Arc<crate::nav::Nav>,
99    /// Secrets of the senders whose signed requests are accepted
100    /// (`App::signing_key`), by key id.
101    pub(crate) signing_keys: Arc<std::collections::HashMap<String, String>>,
102    /// The values modules contributed in `register` (`AppState::contributions`).
103    pub(crate) contributions: Arc<crate::Contributions>,
104    /// The `Auth` module's settings, when the app has it.
105    pub(crate) auth: Option<Arc<crate::auth::module::Settings>>,
106    /// `App::detect_locale`: the browser's `Accept-Language` picks the locale.
107    pub(crate) detect_locale: bool,
108    /// `App::rtl_locales`: replaces the default right-to-left languages.
109    pub(crate) rtl_locales: Option<Arc<Vec<String>>>,
110    pub(crate) security: Arc<crate::security::Security>,
111    pub(crate) webhooks: crate::webhook::Handlers,
112    /// Events `App::webhook_event` made subscribable.
113    pub(crate) webhook_events: crate::webhook::outbound::EventDefs,
114    /// Read by the live component route (#433).
115    #[allow(dead_code)]
116    pub(crate) live_components: crate::live_component::LiveMap,
117    /// Values every view gets (`App::share`).
118    pub(crate) shares: Arc<Vec<(String, crate::view::ShareFn)>>,
119    /// The app's notification channels (`App::channel`).
120    pub(crate) channels:
121        Arc<std::collections::HashMap<String, crate::auth::notifications::ChannelFn>>,
122    /// The app's own values (`App::provide`).
123    pub(crate) provided: crate::provided::ProvidedMap,
124    /// `/_renox/debug`'s recent requests, while developing locally.
125    pub(crate) inspector: Option<Arc<crate::inspector::Inspector>>,
126    /// Named rate limiters (`App::rate_limiter`).
127    pub(crate) limiters: Arc<std::collections::HashMap<String, crate::rate_limit::NamedLimiter>>,
128    /// The app's error reporters (`App::report`).
129    pub(crate) reporters: Arc<Vec<crate::report::ReportFn>>,
130    /// What tests asked to record instead of doing (`TestApp::fake_events`, …).
131    pub(crate) fakes: Arc<Fakes>,
132    /// The settings groups the app declared and the ones this process has
133    /// read (`AppState::settings`).
134    pub(crate) settings_store: Arc<crate::settings::Store>,
135}
136
137/// A notification a test recorded instead of sending.
138#[derive(Debug, Clone)]
139#[non_exhaustive]
140pub struct SentNotification {
141    /// `Notification::kind`.
142    pub kind: &'static str,
143    /// Who it was sent to.
144    pub to: crate::auth::Recipient,
145}
146
147/// An event a test recorded instead of sending it to the open pages
148/// (`TestApp::fake_broadcasts`, `AppState::broadcast`).
149#[derive(Debug, Clone, PartialEq)]
150#[non_exhaustive]
151pub struct SentBroadcast {
152    /// The user whose pages it was for; `None` for every page.
153    pub user_id: Option<i64>,
154    /// The DOM event's name.
155    pub event: String,
156    /// Its data (the DOM event's `detail`).
157    pub data: serde_json::Value,
158}
159
160/// Recorders for `TestApp::fake_events`, `fake_notifications` and
161/// `fake_broadcasts`.
162#[derive(Default)]
163pub(crate) struct Fakes {
164    pub events: std::sync::Mutex<Option<Vec<Box<dyn std::any::Any + Send>>>>,
165    pub notifications: std::sync::Mutex<Option<Vec<SentNotification>>>,
166    pub broadcasts: std::sync::Mutex<Option<Vec<SentBroadcast>>>,
167}
168
169impl Fakes {
170    /// Records `event` if events are faked; returns whether it did.
171    pub(crate) fn record_event<E: Send + 'static>(&self, event: E) -> bool {
172        let mut events = self.events.lock().unwrap_or_else(|e| e.into_inner());
173        match events.as_mut() {
174            Some(list) => {
175                list.push(Box::new(event));
176                true
177            }
178            None => false,
179        }
180    }
181
182    /// Records a broadcast if broadcasts are faked; returns whether it did.
183    pub(crate) fn record_broadcast(&self, broadcast: SentBroadcast) -> bool {
184        let mut sent = self.broadcasts.lock().unwrap_or_else(|e| e.into_inner());
185        match sent.as_mut() {
186            Some(list) => {
187                list.push(broadcast);
188                true
189            }
190            None => false,
191        }
192    }
193
194    /// Records a notification if notifications are faked.
195    pub(crate) fn record_notification(
196        &self,
197        kind: &'static str,
198        to: &crate::auth::Recipient,
199    ) -> bool {
200        let mut sent = self.notifications.lock().unwrap_or_else(|e| e.into_inner());
201        match sent.as_mut() {
202            Some(list) => {
203                list.push(SentNotification {
204                    kind,
205                    to: to.clone(),
206                });
207                true
208            }
209            None => false,
210        }
211    }
212}
213
214impl AppState {
215    /// Every `T` modules contributed with `Registry::contribute`, in order:
216    /// the app's own first, then each module's as listed.
217    ///
218    /// ```
219    /// # use renox::prelude::*;
220    /// struct Link(&'static str);
221    /// # fn demo(state: AppState) {
222    /// let links: &[Link] = state.contributions::<Link>();
223    /// # let _ = links;
224    /// # }
225    /// ```
226    pub fn contributions<T: 'static>(&self) -> &[T] {
227        self.contributions.all::<T>()
228    }
229
230    /// The URL path of a named route, e.g. `state.url("products.show", &[&id])`.
231    pub fn url(&self, name: &str, params: &[&dyn Display]) -> Result<String> {
232        Ok(self.routes.url(name, params)?)
233    }
234
235    /// Encrypts `plain` with `APP_KEY` (AES-256-GCM), e.g. an API secret a
236    /// user saves, before storing it. The result is base64 text; only
237    /// [`AppState::decrypt`] with the same key reads it back, and any change
238    /// to it is detected. Rotating `APP_KEY` makes old values unreadable.
239    ///
240    /// ```
241    /// # use renox::prelude::*;
242    /// # fn demo(state: AppState) -> Result {
243    /// let sealed = state.encrypt("sk_live_123");
244    /// assert_eq!(state.decrypt(&sealed)?, "sk_live_123");
245    /// # Ok(()) }
246    /// ```
247    pub fn encrypt(&self, plain: &str) -> String {
248        crate::crypto::seal(&self.key, plain)
249    }
250
251    /// Reads a value from [`AppState::encrypt`]. Fails if it was changed or
252    /// sealed with another key.
253    pub fn decrypt(&self, sealed: &str) -> Result<String> {
254        Ok(crate::crypto::open(&self.key, sealed)?)
255    }
256}
257
258impl AppState {
259    /// A disk the app added with [`App::disk`](crate::App::disk), e.g.
260    /// `state.disk_named("backups")?`; an unknown name is an error (500).
261    pub fn disk_named(&self, name: &str) -> Result<&Storage> {
262        self.disks.get(name).ok_or_else(|| {
263            anyhow::anyhow!("no disk named `{name}`: add it with `App::disk(\"{name}\", …)`").into()
264        })
265    }
266}