diff --git a/swarm-queue-client/src/agent_term.rs b/swarm-queue-client/src/agent_term.rs index 4d9139446..9e3fae7b7 100644 --- a/swarm-queue-client/src/agent_term.rs +++ b/swarm-queue-client/src/agent_term.rs @@ -15,8 +15,9 @@ const MAX_BYTES: i64 = 64 * 1024 * 1024; /// The config [`open_or_create`] creates `agent`'s stream with. /// -/// `max_message_size` tracks the queue's live `max_payload`, as the subagent -/// stream's does, so the stream never rejects a row the queue accepted. +/// `max_message_size` is the queue's `max_payload` when the stream is created, as +/// the subagent stream's is, and stays at that size when the queue's limit +/// later changes. fn stream_config(agent: &str, max_message_size: i32) -> async_nats::jetstream::stream::Config { async_nats::jetstream::stream::Config { name: stream_name(agent), diff --git a/swarm-queue-client/src/bash_task.rs b/swarm-queue-client/src/bash_task.rs index 46e8ba83a..4fa645516 100644 --- a/swarm-queue-client/src/bash_task.rs +++ b/swarm-queue-client/src/bash_task.rs @@ -13,8 +13,9 @@ const OUTPUT_MAX_BYTES: i64 = 64 * 1024 * 1024; /// The config [`open_output`] creates `agent`'s output stream with. /// -/// `max_message_size` is the queue's live `max_payload` ([`crate::max_payload`]), -/// so the stream never rejects a row the queue itself accepted. +/// `max_message_size` is the queue's `max_payload` ([`crate::max_payload`]) when +/// the stream is created, and stays at that size when the queue's limit later +/// changes. pub(crate) fn output_config( agent: &str, max_message_size: i32, diff --git a/swarm-queue-client/src/lib.rs b/swarm-queue-client/src/lib.rs index 813ca7716..fa7191180 100644 --- a/swarm-queue-client/src/lib.rs +++ b/swarm-queue-client/src/lib.rs @@ -602,16 +602,25 @@ impl TokenCache { self.mint_into(&mut slot, mint).await } - /// Mint a replacement now and cache it, whatever the cached token has - /// left. The rotation task's way of having the next connection's token + /// Mint a replacement now and cache it, if the cached token is due for + /// rotation (see [`Self::rotate_in`]) once the lock is held, and say whether + /// it did. The rotation task's way of having the next connection's token /// ready before the current one expires. - async fn rotate(&self, mint: F) -> Result<(), Error> + /// + /// The due check is made under the lock that guards the mint: a reconnect + /// that replaced the token while this waited for the lock leaves nothing to + /// rotate, and a second token minted on top of it would be a wasted request + /// and a reconnect for nothing. + async fn rotate(&self, mint: F) -> Result where F: FnOnce() -> Fut, Fut: Future>, { let mut slot = self.slot.lock().await; - self.mint_into(&mut slot, mint).await.map(drop) + if self.due_in(slot.as_ref()) != Some(std::time::Duration::ZERO) { + return Ok(false); + } + self.mint_into(&mut slot, mint).await.map(|_| true) } async fn mint_into( @@ -638,8 +647,12 @@ impl TokenCache { /// reusable (`usable_at`) and rotating it would reconnect at least every /// life minus skew, so the reconnect path mints for it as it always did. async fn rotate_in(&self) -> Option { - let slot = self.slot.lock().await; - let minted = slot.as_ref()?; + self.due_in(self.slot.lock().await.as_ref()) + } + + /// [`Self::rotate_in`] for the token in a slot already locked. + fn due_in(&self, minted: Option<&MintedToken>) -> Option { + let minted = minted?; if minted.token.lifetime < TOKEN_REFRESH_SKEW * 2 { return None; } @@ -907,6 +920,32 @@ fn token_request( audience: Option<&str>, scope: Option<&str>, ) -> reqwest::RequestBuilder { + http.post(&cfg.token_endpoint) + .basic_auth(&cfg.client_id, Some(secret)) + .form(&token_form(audience, scope)) +} + +/// [`token_request`] for the blocking client: the same endpoint, credentials +/// and form, the form from the one [`token_form`]. +fn token_request_blocking( + http: &reqwest::blocking::Client, + cfg: &QueueConfig, + secret: &str, + audience: Option<&str>, + scope: Option<&str>, +) -> reqwest::blocking::RequestBuilder { + http.post(&cfg.token_endpoint) + .basic_auth(&cfg.client_id, Some(secret)) + .form(&token_form(audience, scope)) +} + +/// The form of a token request: `client_credentials`, with `audience` and +/// `scope` when given. Shared by the async and blocking requests, which differ +/// only in the client type, so what they send cannot drift apart. +fn token_form<'a>( + audience: Option<&'a str>, + scope: Option<&'a str>, +) -> Vec<(&'static str, &'a str)> { let mut form = vec![("grant_type", "client_credentials")]; if let Some(audience) = audience { form.push(("audience", audience)); @@ -914,9 +953,7 @@ fn token_request( if let Some(scope) = scope { form.push(("scope", scope)); } - http.post(&cfg.token_endpoint) - .basic_auth(&cfg.client_id, Some(secret)) - .form(&form) + form } /// Read + parse `path` as a PEM root certificate. Shared by the async and @@ -1035,17 +1072,7 @@ fn mint_with_blocking( audience: Option<&str>, scope: Option<&str>, ) -> Result { - let mut form = vec![("grant_type", "client_credentials")]; - if let Some(audience) = audience { - form.push(("audience", audience)); - } - if let Some(scope) = scope { - form.push(("scope", scope)); - } - let response = http - .post(&cfg.token_endpoint) - .basic_auth(&cfg.client_id, Some(secret.trim())) - .form(&form) + let response = token_request_blocking(http, cfg, secret.trim(), audience, scope) .send() .map_err(Error::TokenRequest)?; @@ -1117,9 +1144,9 @@ pub fn ready_when_connected( /// connection, costing the row and a reconnect — so a publisher of /// variable-size rows must size them against this before handing them over. /// -/// ⚠️ The value is per connection. Before the first successful CONNECT the -/// client reports the library's own default, which is smaller than any -/// deployment sets; call this after [`ensure_connected`], and the answer is +/// ⚠️ The value is per connection. Before the first successful CONNECT it is +/// `0`: `async-nats`' `server_info()` is its all-zero default until the +/// server's INFO arrives. Call this after [`ensure_connected`], and the answer is /// the one this server actually announced. #[must_use] pub fn max_payload(client: &async_nats::Client) -> usize { @@ -1261,7 +1288,12 @@ fn rotation_wait(rotate_in: Option) -> std::time::Duration /// hammered; the same floor holds after a rotation that worked. If every try fails the connection still ends at the expiry and the /// reconnect path takes over, as it did before this task existed. /// -/// Runs for the life of the process, like the client it keeps. +/// Runs for the life of the process, like the client it keeps: it holds a clone +/// of the `Client`, so dropping the caller's clones never closes the +/// connection, and nothing ends the task. [`connect`] returns the bare +/// `async_nats::Client`, so a handle that aborts it on drop would need a +/// wrapper type through every caller; each daemon connects once, for its whole +/// life, so none is changed for it. async fn rotate_before_expiry( cache: std::sync::Arc, client: async_nats::Client, @@ -1270,18 +1302,22 @@ async fn rotate_before_expiry( ) { loop { tokio::time::sleep(rotation_wait(cache.rotate_in().await)).await; - // Look again after the sleep: the token may have been replaced by a - // reconnect meanwhile, and the clock may have moved. - if cache.rotate_in().await != Some(std::time::Duration::ZERO) { - continue; - } - if let Err(e) = cache.rotate(|| mint_token(&http, &cfg, None, None)).await { - tracing::warn!( + // `rotate` looks again once it holds the lock: the token may have been + // replaced by a reconnect during the sleep, and the clock may have moved. + match cache.rotate(|| mint_token(&http, &cfg, None, None)).await { + Ok(false) => {} + Ok(true) => { + if let Err(e) = client.force_reconnect().await { + tracing::warn!( + error = %e, + "reconnecting to the queue with the next token failed" + ); + } + } + Err(e) => tracing::warn!( error = %chain(&e), "minting the next queue token ahead of expiry failed; retrying" - ); - } else if let Err(e) = client.force_reconnect().await { - tracing::warn!(error = %e, "reconnecting to the queue with the next token failed"); + ), } } } @@ -1848,8 +1884,10 @@ mod tests { let clock = FakeClock::starting_at(START); let (cache, mints) = (clock.cache(), AtomicUsize::new(0)); assert_eq!(take(&cache, &mints).await, "token-1"); + // Due, but still usable: the skew is what rotation runs ahead of. + clock.advance(3599 - 120); - cache + let rotated = cache .rotate(|| async { mints.fetch_add(1, Ordering::SeqCst); Ok(CachedToken { @@ -1859,6 +1897,7 @@ mod tests { }) .await .expect("the stub mint succeeds"); + assert!(rotated); assert_eq!(take(&cache, &mints).await, "token-2"); assert_eq!(mints.load(Ordering::SeqCst), 2, "the connect did not mint"); @@ -2016,4 +2055,64 @@ mod tests { } assert_eq!(ready, 200, "connected"); } + + /// Rotate `cache` with a stub mint that counts itself in `mints`, and say + /// whether it rotated. + async fn rotate_counting(cache: &TokenCache, mints: &AtomicUsize) -> bool { + cache + .rotate(|| async { + mints.fetch_add(1, Ordering::SeqCst); + Ok(CachedToken { + token: "rotated".to_owned(), + lifetime: std::time::Duration::from_hours(1), + }) + }) + .await + .expect("the stub mint succeeds") + } + + /// The due check is made under the lock that guards the mint: a token that + /// is not due, or that a reconnect replaced while the rotation waited for + /// the lock, is left alone, with no request to the identity provider. + #[tokio::test] + async fn a_rotation_that_is_not_due_when_the_lock_is_held_mints_nothing() { + let clock = FakeClock::starting_at(START); + let (cache, mints) = (clock.cache(), AtomicUsize::new(0)); + let rotate = |cache| rotate_counting(cache, &mints); + assert!(!rotate(&cache).await, "nothing cached"); + take(&cache, &mints).await; + assert!(!rotate(&cache).await, "a fresh token is not due"); + assert_eq!(mints.load(Ordering::SeqCst), 1); + + clock.advance(3599 - 120); + assert!(rotate(&cache).await, "due"); + assert_eq!(mints.load(Ordering::SeqCst), 2); + assert!(!rotate(&cache).await, "the rotation just replaced it"); + assert_eq!(mints.load(Ordering::SeqCst), 2); + } + + /// The blocking mint sends what the async one does: the form is built in + /// one place, so the audience and scope reach both. + #[test] + fn the_blocking_token_request_is_the_async_one() { + let (audience, scope) = (Some("https://swarm.example/queue"), Some("queue")); + macro_rules! asked { + ($req:expr) => { + ( + $req.method().clone(), + $req.url().clone(), + $req.headers().clone(), + $req.body().and_then(|b| b.as_bytes()).map(<[u8]>::to_vec), + ) + }; + } + let a = token_request(&offline_client(), &token_cfg(), "s3cret", audience, scope) + .build() + .expect("an async request"); + let blocking = reqwest::blocking::Client::new(); + let b = token_request_blocking(&blocking, &token_cfg(), "s3cret", audience, scope) + .build() + .expect("a blocking request"); + assert_eq!(asked!(a), asked!(b)); + } } diff --git a/swarm-queue-client/src/subagent_term.rs b/swarm-queue-client/src/subagent_term.rs index 3a6dd853b..90d27e649 100644 --- a/swarm-queue-client/src/subagent_term.rs +++ b/swarm-queue-client/src/subagent_term.rs @@ -15,10 +15,11 @@ const MAX_BYTES: i64 = 64 * 1024 * 1024; /// The config [`open_or_create`] creates `agent`'s stream with. /// /// `max_message_size` is taken as a parameter rather than read from a -/// constant here: it tracks the queue's live `max_payload` -/// ([`crate::max_payload`]), the same value the publisher already sizes its -/// rows against, so the stream never rejects a row the queue itself -/// accepted. +/// constant here: it is the queue's `max_payload` ([`crate::max_payload`]) when +/// the stream is created, the same value the publisher sizes its rows against, +/// so the stream rejects no row the queue accepted then. It is fixed at +/// creation: a stream that exists keeps its size when the queue's limit later +/// changes. pub(crate) fn stream_config( agent: &str, max_message_size: i32,