1use super::{CancellationToken, Runtime, RuntimeConfig};
24
25use futures::Future;
26use once_cell::sync::OnceCell;
27use parking_lot::Mutex;
28use std::time::Duration;
29use tokio::{signal, task::JoinHandle};
30
31static RT: OnceCell<tokio::runtime::Runtime> = OnceCell::new();
32static RTHANDLE: OnceCell<tokio::runtime::Handle> = OnceCell::new();
33static INIT: OnceCell<Mutex<Option<tokio::task::JoinHandle<anyhow::Result<()>>>>> = OnceCell::new();
34
35use crate::config::environment_names::worker as env_worker;
36
37const SHUTDOWN_MESSAGE: &str =
38 "Application received shutdown signal; attempting to gracefully shutdown";
39const SHUTDOWN_TIMEOUT_MESSAGE: &str =
40 "Use DYN_WORKER_GRACEFUL_SHUTDOWN_TIMEOUT to control the graceful shutdown timeout";
41
42pub const DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_DEBUG: u64 = 5;
44
45pub const DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_RELEASE: u64 = 30;
47
48#[derive(Debug, Clone)]
49pub struct Worker {
50 runtime: Runtime,
51 config: RuntimeConfig,
52}
53
54impl Worker {
55 pub fn from_settings() -> anyhow::Result<Worker> {
57 let config = RuntimeConfig::from_settings()?;
58 Worker::from_config(config)
59 }
60
61 pub fn from_config(config: RuntimeConfig) -> anyhow::Result<Worker> {
63 if RT.get().is_some() || RTHANDLE.get().is_some() {
65 return Err(anyhow::anyhow!("Worker already initialized"));
66 }
67
68 let rt = RT.try_insert(config.create_runtime()?).map_err(|_| {
72 anyhow::anyhow!("Failed to create worker; Only a single Worker should ever be created")
73 })?;
74
75 let runtime = Runtime::from_handle(rt.handle().clone())?;
76 Ok(Worker { runtime, config })
77 }
78
79 pub fn runtime_from_existing() -> anyhow::Result<Runtime> {
80 if let Some(rt) = RT.get() {
81 Ok(Runtime::from_handle(rt.handle().clone())?)
82 } else if let Some(rt) = RTHANDLE.get() {
83 Ok(Runtime::from_handle(rt.clone())?)
84 } else {
85 Runtime::from_settings()
86 }
87 }
88
89 pub fn tokio_runtime(&self) -> anyhow::Result<&'static tokio::runtime::Runtime> {
90 RT.get()
91 .ok_or_else(|| anyhow::anyhow!("Worker not initialized"))
92 }
93
94 pub fn runtime(&self) -> &Runtime {
95 &self.runtime
96 }
97
98 pub fn execute<F, Fut>(self, f: F) -> anyhow::Result<()>
99 where
100 F: FnOnce(Runtime) -> Fut + Send + 'static,
101 Fut: Future<Output = anyhow::Result<()>> + Send + 'static,
102 {
103 let runtime = self.runtime.clone();
104 runtime.secondary().block_on(self.execute_internal(f))??;
105 runtime.shutdown();
106 Ok(())
107 }
108
109 pub async fn execute_async<F, Fut>(self, f: F) -> anyhow::Result<()>
110 where
111 F: FnOnce(Runtime) -> Fut + Send + 'static,
112 Fut: Future<Output = anyhow::Result<()>> + Send + 'static,
113 {
114 let runtime = self.runtime.clone();
115 let task = self.execute_internal(f);
116 task.await??;
117 runtime.shutdown();
118 Ok(())
119 }
120
121 fn execute_internal<F, Fut>(self, f: F) -> JoinHandle<anyhow::Result<()>>
124 where
125 F: FnOnce(Runtime) -> Fut + Send + 'static,
126 Fut: Future<Output = anyhow::Result<()>> + Send + 'static,
127 {
128 let runtime = self.runtime.clone();
129 let primary = runtime.primary();
130 let secondary = runtime.secondary();
131
132 let timeout = std::env::var(env_worker::DYN_WORKER_GRACEFUL_SHUTDOWN_TIMEOUT)
133 .ok()
134 .and_then(|s| s.parse::<u64>().ok())
135 .unwrap_or({
136 if cfg!(debug_assertions) {
137 DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_DEBUG
138 } else {
139 DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_RELEASE
140 }
141 });
142
143 INIT.set(Mutex::new(Some(secondary.spawn(async move {
144 tokio::spawn(signal_handler(runtime.primary_token().clone()));
146
147 let cancel_token = runtime.child_token();
148 let (mut app_tx, app_rx) = tokio::sync::oneshot::channel::<()>();
149
150 let task: JoinHandle<anyhow::Result<()>> = primary.spawn(async move {
152 let _rx = app_rx;
153 f(runtime).await
154 });
155
156 tokio::select! {
157 _ = cancel_token.cancelled() => {
158 tracing::debug!("{}", SHUTDOWN_MESSAGE);
159 tracing::debug!("{} {} seconds", SHUTDOWN_TIMEOUT_MESSAGE, timeout);
160 }
161
162 _ = app_tx.closed() => {
163 }
164 };
165
166 let result = tokio::select! {
167 result = task => {
168 result
169 }
170
171 _ = tokio::time::sleep(tokio::time::Duration::from_secs(timeout)) => {
172 tracing::debug!("Application did not shutdown in time; terminating");
173 std::process::exit(911);
174 }
175 }?;
176
177 match &result {
178 Ok(_) => {
179 tracing::debug!("Application shutdown successfully");
180 }
181 Err(e) => {
182 tracing::error!("Application shutdown with error: {:?}", e);
183 }
184 }
185
186 result
187 }))))
188 .expect("Failed to spawn application task");
189
190 INIT
191 .get()
192 .expect("Application task not initialized")
193 .lock()
194 .take()
195 .expect("Application initialized; but another thread is awaiting it; Worker.execute() can only be called once")
196 }
197
198 pub fn from_current() -> anyhow::Result<Worker> {
199 if RT.get().is_some() || RTHANDLE.get().is_some() {
200 return Err(anyhow::anyhow!("Worker already initialized"));
201 }
202 let runtime = Runtime::from_current()?;
203 let config = RuntimeConfig::from_settings()?;
204 Ok(Worker { runtime, config })
205 }
206}
207
208async fn signal_handler(cancel_token: CancellationToken) -> anyhow::Result<()> {
210 let ctrl_c = async {
211 signal::ctrl_c().await?;
212 anyhow::Ok(())
213 };
214
215 let sigterm = async {
216 signal::unix::signal(signal::unix::SignalKind::terminate())?
217 .recv()
218 .await;
219 anyhow::Ok(())
220 };
221
222 tokio::select! {
223 _ = ctrl_c => {
224 tracing::info!("Ctrl+C received, starting graceful shutdown");
225 },
226 _ = sigterm => {
227 tracing::info!("SIGTERM received, starting graceful shutdown");
228 },
229 _ = cancel_token.cancelled() => {
230 tracing::debug!("CancellationToken triggered; shutting down");
231 },
232 }
233
234 cancel_token.cancel();
236
237 Ok(())
238}