|
| 1 | +/* |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +//! Maintain a cache of discovered endpoints |
| 7 | +
|
| 8 | +use aws_smithy_async::rt::sleep::AsyncSleep; |
| 9 | +use aws_smithy_async::time::TimeSource; |
| 10 | +use aws_smithy_client::erase::boxclone::BoxFuture; |
| 11 | +use aws_smithy_http::endpoint::{ResolveEndpoint, ResolveEndpointError}; |
| 12 | +use aws_smithy_types::endpoint::Endpoint; |
| 13 | +use std::fmt::{Debug, Formatter}; |
| 14 | +use std::future::Future; |
| 15 | +use std::sync::{Arc, Mutex}; |
| 16 | +use std::time::{Duration, SystemTime}; |
| 17 | +use tokio::sync::oneshot::error::TryRecvError; |
| 18 | +use tokio::sync::oneshot::{Receiver, Sender}; |
| 19 | + |
| 20 | +/// Endpoint reloader |
| 21 | +#[must_use] |
| 22 | +pub struct ReloadEndpoint { |
| 23 | + loader: Box<dyn Fn() -> BoxFuture<(Endpoint, SystemTime), ResolveEndpointError> + Send + Sync>, |
| 24 | + endpoint: Arc<Mutex<Option<ExpiringEndpoint>>>, |
| 25 | + error: Arc<Mutex<Option<ResolveEndpointError>>>, |
| 26 | + rx: Receiver<()>, |
| 27 | + sleep: Arc<dyn AsyncSleep>, |
| 28 | + time: Arc<dyn TimeSource>, |
| 29 | +} |
| 30 | + |
| 31 | +impl Debug for ReloadEndpoint { |
| 32 | + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { |
| 33 | + f.debug_struct("ReloadEndpoint").finish() |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +impl ReloadEndpoint { |
| 38 | + /// Reload the endpoint once |
| 39 | + pub async fn reload_once(&self) { |
| 40 | + match (self.loader)().await { |
| 41 | + Ok((endpoint, expiry)) => { |
| 42 | + *self.endpoint.lock().unwrap() = Some(ExpiringEndpoint { endpoint, expiry }) |
| 43 | + } |
| 44 | + Err(err) => *self.error.lock().unwrap() = Some(err), |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + /// An infinite loop task that will reload the endpoint |
| 49 | + /// |
| 50 | + /// This task will terminate when the corresponding [`Client`](crate::Client) is dropped. |
| 51 | + pub async fn reload_task(mut self) { |
| 52 | + loop { |
| 53 | + match self.rx.try_recv() { |
| 54 | + Ok(_) | Err(TryRecvError::Closed) => break, |
| 55 | + _ => {} |
| 56 | + } |
| 57 | + self.reload_increment(self.time.now()).await; |
| 58 | + self.sleep.sleep(Duration::from_secs(60)).await; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + async fn reload_increment(&self, now: SystemTime) { |
| 63 | + let should_reload = self |
| 64 | + .endpoint |
| 65 | + .lock() |
| 66 | + .unwrap() |
| 67 | + .as_ref() |
| 68 | + .map(|e| e.is_expired(now)) |
| 69 | + .unwrap_or(true); |
| 70 | + if should_reload { |
| 71 | + tracing::debug!("reloading endpoint, previous endpoint was expired"); |
| 72 | + self.reload_once().await; |
| 73 | + } |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +#[derive(Debug, Clone)] |
| 78 | +pub(crate) struct EndpointCache { |
| 79 | + error: Arc<Mutex<Option<ResolveEndpointError>>>, |
| 80 | + endpoint: Arc<Mutex<Option<ExpiringEndpoint>>>, |
| 81 | + // When the sender is dropped, this allows the reload loop to stop |
| 82 | + _drop_guard: Arc<Sender<()>>, |
| 83 | +} |
| 84 | + |
| 85 | +impl<T> ResolveEndpoint<T> for EndpointCache { |
| 86 | + fn resolve_endpoint(&self, _params: &T) -> aws_smithy_http::endpoint::Result { |
| 87 | + self.resolve_endpoint() |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +#[derive(Debug)] |
| 92 | +struct ExpiringEndpoint { |
| 93 | + endpoint: Endpoint, |
| 94 | + expiry: SystemTime, |
| 95 | +} |
| 96 | + |
| 97 | +impl ExpiringEndpoint { |
| 98 | + fn is_expired(&self, now: SystemTime) -> bool { |
| 99 | + tracing::debug!(expiry = ?self.expiry, now = ?now, delta = ?self.expiry.duration_since(now), "checking expiry status of endpoint"); |
| 100 | + match self.expiry.duration_since(now) { |
| 101 | + Err(_) => true, |
| 102 | + Ok(t) => t < Duration::from_secs(120), |
| 103 | + } |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +pub(crate) async fn create_cache<F>( |
| 108 | + loader_fn: impl Fn() -> F + Send + Sync + 'static, |
| 109 | + sleep: Arc<dyn AsyncSleep>, |
| 110 | + time: Arc<dyn TimeSource>, |
| 111 | +) -> Result<(EndpointCache, ReloadEndpoint), ResolveEndpointError> |
| 112 | +where |
| 113 | + F: Future<Output = Result<(Endpoint, SystemTime), ResolveEndpointError>> + Send + 'static, |
| 114 | +{ |
| 115 | + let error_holder = Arc::new(Mutex::new(None)); |
| 116 | + let endpoint_holder = Arc::new(Mutex::new(None)); |
| 117 | + let (tx, rx) = tokio::sync::oneshot::channel(); |
| 118 | + let cache = EndpointCache { |
| 119 | + error: error_holder.clone(), |
| 120 | + endpoint: endpoint_holder.clone(), |
| 121 | + _drop_guard: Arc::new(tx), |
| 122 | + }; |
| 123 | + let reloader = ReloadEndpoint { |
| 124 | + loader: Box::new(move || Box::pin((loader_fn)()) as _), |
| 125 | + endpoint: endpoint_holder, |
| 126 | + error: error_holder, |
| 127 | + rx, |
| 128 | + sleep, |
| 129 | + time, |
| 130 | + }; |
| 131 | + reloader.reload_once().await; |
| 132 | + // if we didn't successfully get an endpoint, bail out so the client knows |
| 133 | + // configuration failed to work |
| 134 | + cache.resolve_endpoint()?; |
| 135 | + Ok((cache, reloader)) |
| 136 | +} |
| 137 | + |
| 138 | +impl EndpointCache { |
| 139 | + fn resolve_endpoint(&self) -> aws_smithy_http::endpoint::Result { |
| 140 | + self.endpoint |
| 141 | + .lock() |
| 142 | + .unwrap() |
| 143 | + .as_ref() |
| 144 | + .map(|e| e.endpoint.clone()) |
| 145 | + .ok_or_else(|| { |
| 146 | + self.error |
| 147 | + .lock() |
| 148 | + .unwrap() |
| 149 | + .take() |
| 150 | + .unwrap_or_else(|| ResolveEndpointError::message("no endpoint loaded")) |
| 151 | + }) |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +#[cfg(test)] |
| 156 | +mod test { |
| 157 | + use crate::endpoint_discovery::create_cache; |
| 158 | + use aws_smithy_async::rt::sleep::TokioSleep; |
| 159 | + use aws_smithy_async::test_util::controlled_time_and_sleep; |
| 160 | + use aws_smithy_async::time::SystemTimeSource; |
| 161 | + use aws_smithy_types::endpoint::Endpoint; |
| 162 | + use std::sync::atomic::{AtomicUsize, Ordering}; |
| 163 | + use std::sync::Arc; |
| 164 | + use std::time::{Duration, SystemTime, UNIX_EPOCH}; |
| 165 | + use tokio::time::timeout; |
| 166 | + |
| 167 | + fn check_send_v<T: Send>(t: T) -> T { |
| 168 | + t |
| 169 | + } |
| 170 | + |
| 171 | + #[tokio::test] |
| 172 | + #[allow(unused_must_use)] |
| 173 | + async fn check_traits() { |
| 174 | + let (cache, reloader) = create_cache( |
| 175 | + || async { |
| 176 | + Ok(( |
| 177 | + Endpoint::builder().url("http://foo.com").build(), |
| 178 | + SystemTime::now(), |
| 179 | + )) |
| 180 | + }, |
| 181 | + Arc::new(TokioSleep::new()), |
| 182 | + Arc::new(SystemTimeSource::new()), |
| 183 | + ) |
| 184 | + .await |
| 185 | + .unwrap(); |
| 186 | + check_send_v(reloader.reload_task()); |
| 187 | + check_send_v(cache); |
| 188 | + } |
| 189 | + |
| 190 | + #[tokio::test] |
| 191 | + async fn erroring_endpoint_always_reloaded() { |
| 192 | + let expiry = UNIX_EPOCH + Duration::from_secs(123456789); |
| 193 | + let ct = Arc::new(AtomicUsize::new(0)); |
| 194 | + let (cache, reloader) = create_cache( |
| 195 | + move || { |
| 196 | + let shared_ct = ct.clone(); |
| 197 | + shared_ct.fetch_add(1, Ordering::AcqRel); |
| 198 | + async move { |
| 199 | + Ok(( |
| 200 | + Endpoint::builder() |
| 201 | + .url(format!("http://foo.com/{shared_ct:?}")) |
| 202 | + .build(), |
| 203 | + expiry, |
| 204 | + )) |
| 205 | + } |
| 206 | + }, |
| 207 | + Arc::new(TokioSleep::new()), |
| 208 | + Arc::new(SystemTimeSource::new()), |
| 209 | + ) |
| 210 | + .await |
| 211 | + .expect("returns an endpoint"); |
| 212 | + assert_eq!( |
| 213 | + cache.resolve_endpoint().expect("ok").url(), |
| 214 | + "http://foo.com/1" |
| 215 | + ); |
| 216 | + // 120 second buffer |
| 217 | + reloader |
| 218 | + .reload_increment(expiry - Duration::from_secs(240)) |
| 219 | + .await; |
| 220 | + assert_eq!( |
| 221 | + cache.resolve_endpoint().expect("ok").url(), |
| 222 | + "http://foo.com/1" |
| 223 | + ); |
| 224 | + |
| 225 | + reloader.reload_increment(expiry).await; |
| 226 | + assert_eq!( |
| 227 | + cache.resolve_endpoint().expect("ok").url(), |
| 228 | + "http://foo.com/2" |
| 229 | + ); |
| 230 | + } |
| 231 | + |
| 232 | + #[tokio::test] |
| 233 | + async fn test_advance_of_task() { |
| 234 | + let expiry = UNIX_EPOCH + Duration::from_secs(123456789); |
| 235 | + // expires in 8 minutes |
| 236 | + let (time, sleep, mut gate) = controlled_time_and_sleep(expiry - Duration::from_secs(239)); |
| 237 | + let ct = Arc::new(AtomicUsize::new(0)); |
| 238 | + let (cache, reloader) = create_cache( |
| 239 | + move || { |
| 240 | + let shared_ct = ct.clone(); |
| 241 | + shared_ct.fetch_add(1, Ordering::AcqRel); |
| 242 | + async move { |
| 243 | + Ok(( |
| 244 | + Endpoint::builder() |
| 245 | + .url(format!("http://foo.com/{shared_ct:?}")) |
| 246 | + .build(), |
| 247 | + expiry, |
| 248 | + )) |
| 249 | + } |
| 250 | + }, |
| 251 | + Arc::new(sleep.clone()), |
| 252 | + Arc::new(time.clone()), |
| 253 | + ) |
| 254 | + .await |
| 255 | + .expect("first load success"); |
| 256 | + let reload_task = tokio::spawn(reloader.reload_task()); |
| 257 | + assert!(!reload_task.is_finished()); |
| 258 | + // expiry occurs after 2 sleeps |
| 259 | + // t = 0 |
| 260 | + assert_eq!( |
| 261 | + gate.expect_sleep().await.duration(), |
| 262 | + Duration::from_secs(60) |
| 263 | + ); |
| 264 | + assert_eq!(cache.resolve_endpoint().unwrap().url(), "http://foo.com/1"); |
| 265 | + // t = 60 |
| 266 | + |
| 267 | + let sleep = gate.expect_sleep().await; |
| 268 | + // we're still holding the drop guard, so we haven't expired yet. |
| 269 | + assert_eq!(cache.resolve_endpoint().unwrap().url(), "http://foo.com/1"); |
| 270 | + assert_eq!(sleep.duration(), Duration::from_secs(60)); |
| 271 | + sleep.allow_progress(); |
| 272 | + // t = 120 |
| 273 | + |
| 274 | + let sleep = gate.expect_sleep().await; |
| 275 | + assert_eq!(cache.resolve_endpoint().unwrap().url(), "http://foo.com/2"); |
| 276 | + sleep.allow_progress(); |
| 277 | + |
| 278 | + let sleep = gate.expect_sleep().await; |
| 279 | + drop(cache); |
| 280 | + sleep.allow_progress(); |
| 281 | + |
| 282 | + timeout(Duration::from_secs(1), reload_task) |
| 283 | + .await |
| 284 | + .expect("task finishes successfully") |
| 285 | + .expect("finishes"); |
| 286 | + } |
| 287 | +} |
0 commit comments