respan_gateway/app/
reload.rs1use 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#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Reloaded {
21 pub restart_required: Vec<String>,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum ReloadError {
29 Unavailable,
31 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
52pub(crate) struct Process {
55 pub log: Arc<RequestLog>,
56 pub stopping: Arc<watch::Sender<bool>>,
59 pub listen: OnceLock<SocketAddr>,
61 pub started_at: SystemTime,
62 pub started: std::time::Instant,
63 pub reloaded_at: Mutex<Option<SystemTime>>,
65 pub switches: Arc<ToolSwitches>,
68 pub(super) reload: OnceLock<Box<Reload>>,
69}
70
71impl Process {
72 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
81pub(super) struct Shared {
83 pub(super) process: Arc<Process>,
84 pub(super) current: RwLock<Arc<Built>>,
85 pub(super) retired: Mutex<Vec<Gateway>>,
87 pub(super) loader: OnceLock<Box<Loader>>,
88 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 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 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 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 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}