|
| 1 | +// This file is Copyright its original authors, visible in version control history. |
| 2 | +// |
| 3 | +// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 4 | +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or |
| 5 | +// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in |
| 6 | +// accordance with one or both of these licenses. |
| 7 | + |
| 8 | +use ldk_node::lightning::util::logger::Logger as _; |
| 9 | +use ldk_node::lightning::{log_debug, log_error, log_trace}; |
| 10 | +use std::future::Future; |
| 11 | +use std::sync::{Arc, Mutex}; |
| 12 | +use std::time::Duration; |
| 13 | +use tokio::task::{JoinHandle, JoinSet}; |
| 14 | + |
| 15 | +use crate::logging::Logger; |
| 16 | + |
| 17 | +// The timeout after which we give up waiting on a background task to exit on shutdown. |
| 18 | +pub(crate) const BACKGROUND_TASK_SHUTDOWN_TIMEOUT_SECS: u64 = 5; |
| 19 | + |
| 20 | +pub(crate) struct Runtime { |
| 21 | + mode: RuntimeMode, |
| 22 | + background_tasks: Mutex<JoinSet<()>>, |
| 23 | + cancellable_background_tasks: Mutex<JoinSet<()>>, |
| 24 | + logger: Arc<Logger>, |
| 25 | +} |
| 26 | + |
| 27 | +impl Runtime { |
| 28 | + pub fn new(logger: Arc<Logger>) -> Result<Self, std::io::Error> { |
| 29 | + let mode = match tokio::runtime::Handle::try_current() { |
| 30 | + Ok(handle) => RuntimeMode::Handle(handle), |
| 31 | + Err(_) => { |
| 32 | + let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build()?; |
| 33 | + RuntimeMode::Owned(rt) |
| 34 | + }, |
| 35 | + }; |
| 36 | + let background_tasks = Mutex::new(JoinSet::new()); |
| 37 | + let cancellable_background_tasks = Mutex::new(JoinSet::new()); |
| 38 | + |
| 39 | + Ok(Self { mode, background_tasks, cancellable_background_tasks, logger }) |
| 40 | + } |
| 41 | + |
| 42 | + pub fn get_handle(&self) -> tokio::runtime::Handle { |
| 43 | + match &self.mode { |
| 44 | + RuntimeMode::Owned(rt) => rt.handle().clone(), |
| 45 | + RuntimeMode::Handle(h) => h.clone(), |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + #[allow(unused)] |
| 50 | + pub fn with_handle(handle: tokio::runtime::Handle, logger: Arc<Logger>) -> Self { |
| 51 | + let mode = RuntimeMode::Handle(handle); |
| 52 | + let background_tasks = Mutex::new(JoinSet::new()); |
| 53 | + let cancellable_background_tasks = Mutex::new(JoinSet::new()); |
| 54 | + |
| 55 | + Self { mode, background_tasks, cancellable_background_tasks, logger } |
| 56 | + } |
| 57 | + |
| 58 | + pub fn spawn_background_task<F>(&self, future: F) |
| 59 | + where |
| 60 | + F: Future<Output = ()> + Send + 'static, |
| 61 | + { |
| 62 | + let mut background_tasks = self.background_tasks.lock().unwrap(); |
| 63 | + let runtime_handle = self.handle(); |
| 64 | + background_tasks.spawn_on(future, runtime_handle); |
| 65 | + } |
| 66 | + |
| 67 | + pub fn spawn_cancellable_background_task<F>(&self, future: F) |
| 68 | + where |
| 69 | + F: Future<Output = ()> + Send + 'static, |
| 70 | + { |
| 71 | + let mut cancellable_background_tasks = self.cancellable_background_tasks.lock().unwrap(); |
| 72 | + let runtime_handle = self.handle(); |
| 73 | + cancellable_background_tasks.spawn_on(future, runtime_handle); |
| 74 | + } |
| 75 | + |
| 76 | + #[allow(unused)] |
| 77 | + pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R> |
| 78 | + where |
| 79 | + F: FnOnce() -> R + Send + 'static, |
| 80 | + R: Send + 'static, |
| 81 | + { |
| 82 | + let handle = self.handle(); |
| 83 | + handle.spawn_blocking(func) |
| 84 | + } |
| 85 | + |
| 86 | + pub fn block_on<F: Future>(&self, future: F) -> F::Output { |
| 87 | + // While we generally decided not to overthink via which call graph users would enter our |
| 88 | + // runtime context, we'd still try to reuse whatever current context would be present |
| 89 | + // during `block_on`, as this is the context `block_in_place` would operate on. So we try |
| 90 | + // to detect the outer context here, and otherwise use whatever was set during |
| 91 | + // initialization. |
| 92 | + let handle = tokio::runtime::Handle::try_current().unwrap_or(self.handle().clone()); |
| 93 | + tokio::task::block_in_place(move || handle.block_on(future)) |
| 94 | + } |
| 95 | + |
| 96 | + pub fn abort_cancellable_background_tasks(&self) { |
| 97 | + let mut tasks = core::mem::take(&mut *self.cancellable_background_tasks.lock().unwrap()); |
| 98 | + debug_assert!(!tasks.is_empty(), "Expected some cancellable background_tasks"); |
| 99 | + tasks.abort_all(); |
| 100 | + self.block_on(async { while tasks.join_next().await.is_some() {} }) |
| 101 | + } |
| 102 | + |
| 103 | + pub fn wait_on_background_tasks(&self) { |
| 104 | + let mut tasks = core::mem::take(&mut *self.background_tasks.lock().unwrap()); |
| 105 | + debug_assert!(!tasks.is_empty(), "Expected some background_tasks"); |
| 106 | + self.block_on(async { |
| 107 | + loop { |
| 108 | + let timeout_fut = tokio::time::timeout( |
| 109 | + Duration::from_secs(BACKGROUND_TASK_SHUTDOWN_TIMEOUT_SECS), |
| 110 | + tasks.join_next_with_id(), |
| 111 | + ); |
| 112 | + match timeout_fut.await { |
| 113 | + Ok(Some(Ok((id, _)))) => { |
| 114 | + log_trace!(self.logger, "Stopped background task with id {id}"); |
| 115 | + }, |
| 116 | + Ok(Some(Err(e))) => { |
| 117 | + tasks.abort_all(); |
| 118 | + log_trace!(self.logger, "Stopping background task failed: {e}"); |
| 119 | + break; |
| 120 | + }, |
| 121 | + Ok(None) => { |
| 122 | + log_debug!(self.logger, "Stopped all background tasks"); |
| 123 | + break; |
| 124 | + }, |
| 125 | + Err(e) => { |
| 126 | + tasks.abort_all(); |
| 127 | + log_error!(self.logger, "Stopping background task timed out: {e}"); |
| 128 | + break; |
| 129 | + }, |
| 130 | + } |
| 131 | + } |
| 132 | + }) |
| 133 | + } |
| 134 | + |
| 135 | + fn handle(&self) -> &tokio::runtime::Handle { |
| 136 | + match &self.mode { |
| 137 | + RuntimeMode::Owned(rt) => rt.handle(), |
| 138 | + RuntimeMode::Handle(handle) => handle, |
| 139 | + } |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +enum RuntimeMode { |
| 144 | + Owned(tokio::runtime::Runtime), |
| 145 | + Handle(tokio::runtime::Handle), |
| 146 | +} |
0 commit comments