Skip to main content

respan_gateway/app/
reload.rs

1//! Reloading: the state that outlives a config, and the swap to a new one.
2
3use parking_lot::{Mutex, RwLock};
4use std::net::SocketAddr;
5use std::sync::{Arc, OnceLock};
6use std::time::SystemTime;
7
8use respan_gateway_core::Gateway;
9use respan_gateway_core::futures::FutureExt;
10use respan_gateway_plugin_tool_loop::ToolSwitches;
11use tokio::sync::watch;
12
13use super::Built;
14use crate::logging::Level;
15use crate::requests::RequestLog;
16use crate::{Config, Error};
17
18/// What a reload took in.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Reloaded {
21    /// What the new config changes that only a restart applies, such as
22    /// the listen address; empty when everything took effect.
23    pub restart_required: Vec<String>,
24}
25
26/// Why a reload did not happen. The gateway keeps serving as it was.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum ReloadError {
29    /// This app has no config source to read again.
30    Unavailable,
31    /// The config cannot be read, composed or served; why.
32    Invalid(Error),
33}
34
35impl std::fmt::Display for ReloadError {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        match self {
38            ReloadError::Unavailable => f.write_str(
39                "this gateway was not started from a config file or the environment, \
40                 so there is nothing to read again",
41            ),
42            ReloadError::Invalid(e) => write!(f, "{e}"),
43        }
44    }
45}
46
47impl std::error::Error for ReloadError {}
48
49type Loader = dyn Fn() -> Result<Config, Error> + Send + Sync;
50type Reload = dyn Fn() -> Result<Reloaded, ReloadError> + Send + Sync;
51
52/// What outlives a reload: the request log and totals, the clock, the
53/// bound address, the signal that the server is stopping.
54pub(crate) struct Process {
55    pub log: Arc<RequestLog>,
56    /// Set once the server stops: open sessions then close 1001, and open
57    /// event streams end.
58    pub stopping: Arc<watch::Sender<bool>>,
59    /// Where it was bound, once served.
60    pub listen: OnceLock<SocketAddr>,
61    pub started_at: SystemTime,
62    pub started: std::time::Instant,
63    /// When the config was last reloaded.
64    pub reloaded_at: Mutex<Option<SystemTime>>,
65    /// The tool servers and tools turned off from the admin API: in memory
66    /// only, so kept across reloads and lost on a restart.
67    pub switches: Arc<ToolSwitches>,
68    pub(super) reload: OnceLock<Box<Reload>>,
69}
70
71impl Process {
72    /// Reads the config again and swaps it in; see [`App::reload`].
73    pub fn reload(&self) -> Result<Reloaded, ReloadError> {
74        match self.reload.get() {
75            Some(reload) => reload(),
76            None => Err(ReloadError::Unavailable),
77        }
78    }
79}
80
81/// The app: the current build, swapped on reload, and what it needs.
82pub(super) struct Shared {
83    pub(super) process: Arc<Process>,
84    pub(super) current: RwLock<Arc<Built>>,
85    /// The gateways swapped out, which may still have requests open.
86    pub(super) retired: Mutex<Vec<Gateway>>,
87    pub(super) loader: OnceLock<Box<Loader>>,
88    /// One reload at a time.
89    pub(super) reloading: Mutex<()>,
90}
91
92impl Shared {
93    pub(super) fn current(&self) -> Arc<Built> {
94        let current = self.current.read();
95        current.clone()
96    }
97
98    /// Every gateway that may have work open: the current and the retired.
99    pub(super) fn gateways(&self) -> Vec<Gateway> {
100        let retired = self.retired.lock();
101        let mut all = vec![self.current().gateway.clone()];
102        all.extend(retired.iter().cloned());
103        all
104    }
105
106    pub(super) fn reload(&self) -> Result<Reloaded, ReloadError> {
107        let loader = self.loader.get().ok_or(ReloadError::Unavailable)?;
108        let _one_at_a_time = self.reloading.lock();
109        let log = self.current().config.log;
110        let done = loader().map_err(ReloadError::Invalid).and_then(|config| {
111            let built = Built::new(config, &self.process).map_err(ReloadError::Invalid)?;
112            self.swap_in(built)
113        });
114        match &done {
115            Ok(reloaded) => {
116                log.say(Level::Info, "config reloaded");
117                for note in &reloaded.restart_required {
118                    log.say(Level::Warn, &format!("reload: {note}"));
119                }
120            }
121            Err(e) => log.say(
122                Level::Warn,
123                &format!("reload failed, still serving the previous config: {e}"),
124            ),
125        }
126        done
127    }
128
129    fn swap_in(&self, built: Built) -> Result<Reloaded, ReloadError> {
130        let process = &self.process;
131        // Keys that were set may not be dropped under an address beyond
132        // loopback, as at start.
133        if let Some(refusal) = process.listen.get().and_then(|a| built.open_refusal(*a)) {
134            return Err(ReloadError::Invalid(Error::new(refusal)));
135        }
136        if let Some(addr) = process.listen.get() {
137            built.local_is_on(*addr);
138        }
139        let old = self.current();
140        // Until its own lists are in, the new build knows the models the
141        // old one did, such as their prices.
142        built
143            .plan
144            .routes
145            .catalog()
146            .fill_from(old.plan.routes.catalog());
147        let mut restart_required = Vec::new();
148        if let Some(bound) = process.listen.get()
149            && built.listen() != old.listen()
150        {
151            restart_required.push(format!(
152                "the config now says listen {}, but the gateway stays on {bound}; \
153                 restart it to move",
154                built.listen()
155            ));
156        }
157        process.log.configure(&built.config);
158        let built = Arc::new(built);
159        let previous = {
160            let mut current = self.current.write();
161            std::mem::replace(&mut *current, built)
162        };
163        {
164            let mut retired = self.retired.lock();
165            retired.retain(|g| g.idle().now_or_never().is_none());
166            retired.push(previous.gateway.clone());
167        }
168        // Its tool loop's and its aggregate's sessions end once the requests on
169        // it do.
170        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
171            let (tool_loop, aggregate) = (previous.closer.clone(), previous.aggregate.clone());
172            let gateway = previous.gateway.clone();
173            if tool_loop.is_some() || aggregate.is_some() {
174                runtime.spawn(async move {
175                    gateway.idle().await;
176                    if let Some(closer) = tool_loop {
177                        closer.close(&gateway).await;
178                    }
179                    if let Some(closer) = aggregate {
180                        closer.close(&gateway).await;
181                    }
182                });
183            }
184        }
185        *process.reloaded_at.lock() = Some(SystemTime::now());
186        Ok(Reloaded { restart_required })
187    }
188}