diff --git a/Cargo.lock b/Cargo.lock index 0ae9dd629..e0660ac22 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5278,7 +5278,6 @@ dependencies = [ "serde_json", "serde_norway", "swarm-authelia-bridge-sock", - "swarm-secret-client", "tokio", "tracing", "tracing-subscriber", @@ -5439,7 +5438,6 @@ dependencies = [ "anyhow", "axum", "clap", - "futures-util", "sha2 0.11.1", "swarm-agent-verify", "swarm-secret-client", @@ -5601,7 +5599,6 @@ version = "0.1.0" dependencies = [ "backon", "futures-util", - "libc", "opentelemetry", "opentelemetry-otlp", "opentelemetry_sdk", diff --git a/hive-c0re/src/main.rs b/hive-c0re/src/main.rs index 63341f285..af73b613b 100644 --- a/hive-c0re/src/main.rs +++ b/hive-c0re/src/main.rs @@ -385,7 +385,17 @@ async fn cmd_serve( let coord_sig = coord.clone(); tokio::select! { res = server::serve(socket, coord) => { res? } - () = swarm_secret_client::shutdown_signal() => { + _ = tokio::signal::ctrl_c() => { + tracing::info!("SIGINT received — requesting shutdown"); + coord_sig.request_shutdown(); + } + () = async { + let mut sig = tokio::signal::unix::signal( + tokio::signal::unix::SignalKind::terminate() + ).expect("failed to install SIGTERM handler"); + sig.recv().await; + } => { + tracing::info!("SIGTERM received — requesting shutdown"); coord_sig.request_shutdown(); } } diff --git a/swarm-authelia-bridge/Cargo.toml b/swarm-authelia-bridge/Cargo.toml index 226fc8ade..01812e22e 100644 --- a/swarm-authelia-bridge/Cargo.toml +++ b/swarm-authelia-bridge/Cargo.toml @@ -19,8 +19,6 @@ serde.workspace = true serde_json.workspace = true serde_norway = "0.9.42" swarm-authelia-bridge-sock.workspace = true -# `shutdown_signal`: the bridge drains its in-flight requests on SIGTERM. -swarm-secret-client.workspace = true tokio.workspace = true tracing.workspace = true tracing-subscriber.workspace = true diff --git a/swarm-authelia-bridge/src/main.rs b/swarm-authelia-bridge/src/main.rs index adbf7b21c..bfed6c38e 100644 --- a/swarm-authelia-bridge/src/main.rs +++ b/swarm-authelia-bridge/src/main.rs @@ -106,7 +106,6 @@ struct AppState { #[tokio::main] async fn main() -> Result<()> { - let stop = swarm_secret_client::shutdown_signal(); tracing_subscriber::fmt() .with_env_filter( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), @@ -131,22 +130,9 @@ async fn main() -> Result<()> { let listener = bind_socket(&socket)?; tracing::info!(socket = %socket.display(), "swarm-authelia-bridge listening"); - serve(listener, app, stop).await -} - -/// Answers on `listener` until `stop` resolves, then lets the requests in hand -/// finish, for at most the drain, and returns. -async fn serve( - listener: tokio::net::UnixListener, - app: Router, - stop: impl Future + Clone + Send + 'static, -) -> Result<()> { - let serving = axum::serve(listener, app).with_graceful_shutdown(stop.clone()); - swarm_secret_client::serve_bounded(stop, serving.into_future()) + axum::serve(listener, app) .await - .transpose() - .context("serving swarm-authelia-bridge")?; - Ok(()) + .context("serving swarm-authelia-bridge") } /// Bind the listening socket at `path`, replacing a stale one a crash left diff --git a/swarm-builder/src/main.rs b/swarm-builder/src/main.rs index ab42f5694..e5b45ef6d 100644 --- a/swarm-builder/src/main.rs +++ b/swarm-builder/src/main.rs @@ -88,7 +88,6 @@ fn push_budget(reply_by: tokio::time::Instant) -> Duration { #[tokio::main] async fn main() -> Result<()> { - let stop = swarm_secret_client::shutdown_signal(); hive_log::init(); swarm_secret_client::install_crypto_provider(); let var = |name: &str| { @@ -175,19 +174,8 @@ async fn main() -> Result<()> { let slot = Arc::new(tokio::sync::Semaphore::new(1)); serve_meta_builds(&queue, &publisher, Store, &builder, &slot, &metrics).await?; - answer_builds( - requests.take_until(stop.clone()), - publisher, - Store, - builder, - slot, - metrics, - ) - .await; - if stop.peek().is_none() { - bail!("the subscription to {SUBJECT} ended"); - } - Ok(()) + answer_builds(requests, publisher, Store, builder, slot, metrics).await; + bail!("the subscription to {SUBJECT} ended") } /// Where a reply goes. [`Queue`] in production; tests record. @@ -272,8 +260,6 @@ async fn send_reply( } /// Answer every PR check, each in its own task, with the build's result. -/// Returns once `requests` ends; a build still running is not waited for, and -/// its requester gets no reply, as when the process is killed. async fn answer_builds( mut requests: impl Stream + Unpin, publisher: impl Publisher, diff --git a/swarm-claude-login/src/main.rs b/swarm-claude-login/src/main.rs index 0c58db0cd..3859915a3 100644 --- a/swarm-claude-login/src/main.rs +++ b/swarm-claude-login/src/main.rs @@ -100,7 +100,6 @@ impl login::CredentialSink for AgentLeaf { #[tokio::main] async fn main() -> Result<()> { - let stop = swarm_secret_client::shutdown_signal(); hive_log::init(); swarm_secret_client::install_crypto_provider(); let var = |name: &str| { @@ -139,11 +138,9 @@ async fn main() -> Result<()> { let mut requests = queue .subscribe(SUBJECT) .await - .with_context(|| format!("subscribing to {SUBJECT}"))? - .take_until(stop.clone()); + .with_context(|| format!("subscribing to {SUBJECT}"))?; tracing::info!(subject = SUBJECT, "claude login minter: awaiting logins"); - let mut in_flight = swarm_secret_client::InFlight::new(); while let Some(msg) = requests.next().await { let Some(reply_to) = msg.reply.clone() else { tracing::warn!("a login step arrived with no reply subject; dropping it"); @@ -152,7 +149,7 @@ async fn main() -> Result<()> { let queue = queue.clone(); let logins = Arc::clone(&logins); let metrics = Arc::clone(&metrics); - in_flight.spawn(async move { + tokio::spawn(async move { let reply = handle(&msg.payload, &logins, &metrics).await; match serde_json::to_vec(&reply) { Ok(body) => { @@ -164,11 +161,7 @@ async fn main() -> Result<()> { } }); } - in_flight.drain().await; - if stop.peek().is_none() { - bail!("the subscription to {SUBJECT} ended"); - } - Ok(()) + bail!("the subscription to {SUBJECT} ended") } /// Answer one step and count it. diff --git a/swarm-controller/src/main.rs b/swarm-controller/src/main.rs index f35a6c171..2ec3e8bcb 100644 --- a/swarm-controller/src/main.rs +++ b/swarm-controller/src/main.rs @@ -269,7 +269,7 @@ async fn main() -> Result<()> { reviews: Arc::default(), alerts: alerts::from_env(), }; - serve(listener, state, swarm_secret_client::shutdown_signal()).await + serve(listener, state).await } /// Registers the `bao.client_cert.*` gauges for the controller's own store @@ -286,20 +286,11 @@ fn register_cert_gauges(provider: Option<&opentelemetry_sdk::metrics::SdkMeterPr } /// Start taking the queued review requests and answering the notification -/// router's, then serve `state` on `listener` until `stop` resolves. The -/// requests in hand finish for at most the drain; the review queue takes no -/// request after `stop`. -async fn serve( - listener: tokio::net::UnixListener, - state: AppState, - stop: impl Future + Clone + Send + 'static, -) -> Result<()> { - review_classifier::review::spawn_queue(&state, stop.clone()); +/// router's, then serve `state` on `listener`. +async fn serve(listener: tokio::net::UnixListener, state: AppState) -> Result<()> { + review_classifier::review::spawn_queue(&state); request_reviewer::spawn(&state); - let serving = axum::serve(listener, build_app(state)).with_graceful_shutdown(stop.clone()); - swarm_secret_client::serve_bounded(stop, serving.into_future()) + axum::serve(listener, build_app(state)) .await - .transpose() - .context("serving swarm-controller")?; - Ok(()) + .context("serving swarm-controller") } diff --git a/swarm-controller/src/review_classifier/review.rs b/swarm-controller/src/review_classifier/review.rs index b663ea972..9d14b75c5 100644 --- a/swarm-controller/src/review_classifier/review.rs +++ b/swarm-controller/src/review_classifier/review.rs @@ -443,10 +443,7 @@ async fn open_consumer( /// Take the queued review requests and review each, for as long as the /// controller runs, once this host has forge access. -pub(crate) fn spawn_queue( - state: &AppState, - stop: impl Future + Clone + Send + 'static, -) { +pub(crate) fn spawn_queue(state: &AppState) { let Some(client) = state.status.as_ref().map(|s| s.queue_client()) else { tracing::warn!("no swarm queue is configured on this host; requested reviews don't run"); return; @@ -469,7 +466,7 @@ pub(crate) fn spawn_queue( runs, metrics: Metrics::global(), }; - consume(&client, TIMING, &reviews, handles, stop).await; + consume(&client, TIMING, &reviews, handles).await; }); } @@ -497,9 +494,8 @@ impl Clone for Handles { } /// Take requests from [`REQUEST_STREAM`] one at a time, each once a run -/// place is free, and review each in a task of its own. Returns once `stop` -/// resolves, taking no request after it; dropping it, as the return does, stops -/// every review it started without acking, and the queue delivers their +/// place is free, and review each in a task of its own. Never returns; +/// dropping it stops every review it started, and the queue delivers their /// requests again. /// /// The limit is read from the settings before each wait for a place. A @@ -510,7 +506,6 @@ async fn consume( timing: Timing, reviews: &Arc, handles: Handles, - stop: impl Future + Clone, ) where S: FileSource + PullSource + Send + Sync + 'static, Q: RunSink + SettingsSource, @@ -524,11 +519,7 @@ async fn consume( "opening the review request queue failed; trying again" ), } - tokio::select! { - biased; - () = stop.clone() => return, - () = tokio::time::sleep(timing.pull_wait) => {} - } + tokio::time::sleep(timing.pull_wait).await; }; let mut tasks = JoinSet::new(); loop { @@ -545,17 +536,8 @@ async fn consume( the last limit read" ), } - let slot = tokio::select! { - biased; - () = stop.clone() => return, - slot = reviews.slot() => slot, - }; - let taken = tokio::select! { - biased; - () = stop.clone() => return, - taken = next(&consumer, timing.pull_wait) => taken, - }; - let message = match taken { + let slot = reviews.slot().await; + let message = match next(&consumer, timing.pull_wait).await { Ok(Some(message)) => message, Ok(None) => continue, Err(e) => { @@ -564,11 +546,7 @@ async fn consume( "taking a review request from the queue failed; trying again" ); drop(slot); - tokio::select! { - biased; - () = stop.clone() => return, - () = tokio::time::sleep(timing.pull_wait) => {} - } + tokio::time::sleep(timing.pull_wait).await; continue; } }; @@ -2054,15 +2032,6 @@ mod tests { /// A controller taking requests, its run places in `reviews`. fn consume(&self, reviews: &Arc) -> JoinHandle<()> { - self.consume_until(reviews, std::future::pending()) - } - - /// A controller that takes no request once `stop` resolves. - fn consume_until( - &self, - reviews: &Arc, - stop: impl Future + Clone + Send + 'static, - ) -> JoinHandle<()> { let client = self.client.clone(); let reviews = Arc::clone(reviews); let forge = Arc::clone(&self.rig.forge); @@ -2078,7 +2047,7 @@ mod tests { runs: store, metrics, }; - consume(&client, TEST_TIMING, &reviews, handles, stop).await; + consume(&client, TEST_TIMING, &reviews, handles).await; }) } @@ -2144,36 +2113,6 @@ mod tests { assert_eq!(q.rig.gate.reached(), 2, "no run after the ack"); } - /// After the stop the controller returns and takes no request, and the - /// review it was running stays un-acked, so the queue still holds it. - #[tokio::test] - async fn after_the_stop_no_request_is_taken_and_the_running_one_stays_unacked() { - let q = Queued::new().await; - q.request(7, "abc123").await; - let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); - let stop = futures_util::FutureExt::shared(async move { - let _ = stop_rx.await; - }); - let consumer = q.consume_until(&q.rig.reviews, stop); - until("the first run started", || q.rig.gate.reached() == 1).await; - - stop_tx.send(()).expect("stop"); - tokio::time::timeout(Duration::from_secs(5), consumer) - .await - .expect("consume returns after the stop") - .expect("consume did not panic"); - // A request that arrives now, and the one running, which the queue - // would redeliver after its ack wait: neither runs. - q.request(8, "abc123").await; - tokio::time::sleep(TEST_TIMING.ack_wait * 3).await; - assert_eq!(q.rig.gate.reached(), 1, "no request taken after the stop"); - assert!( - q.rig.posted().is_empty(), - "the unfinished review is not posted" - ); - assert_eq!(q.waiting().await, 2, "neither request is acked"); - } - #[tokio::test] async fn a_newer_request_for_a_pr_replaces_the_waiting_one() { let q = Queued::new().await; diff --git a/swarm-logs-auth/Cargo.toml b/swarm-logs-auth/Cargo.toml index ff5079ffc..ac742a909 100644 --- a/swarm-logs-auth/Cargo.toml +++ b/swarm-logs-auth/Cargo.toml @@ -21,7 +21,3 @@ tracing-subscriber.workspace = true [lints] workspace = true - -[dev-dependencies] -# `Shared`, so the injected stop future can be cloned like `shutdown_signal`'s. -futures-util.workspace = true diff --git a/swarm-logs-auth/src/main.rs b/swarm-logs-auth/src/main.rs index 9bc40783e..c4c40e14e 100644 --- a/swarm-logs-auth/src/main.rs +++ b/swarm-logs-auth/src/main.rs @@ -195,7 +195,6 @@ async fn handle( #[tokio::main] async fn main() -> anyhow::Result<()> { - let stop = swarm_secret_client::shutdown_signal(); swarm_secret_client::install_crypto_provider(); tracing_subscriber::fmt() .with_env_filter( @@ -236,31 +235,14 @@ async fn main() -> anyhow::Result<()> { tracing::info!(socket = %args.socket.display(), "swarm-logs-auth listening"); let app = axum::Router::new().fallback(handle).with_state(responder); - serve(listener, app, stop).await -} - -/// Answers on `listener` until `stop` resolves, then lets the requests in hand -/// finish, for at most the drain, and returns. -async fn serve( - listener: tokio::net::UnixListener, - app: axum::Router, - stop: impl Future + Clone + Send + 'static, -) -> anyhow::Result<()> { - let serving = axum::serve(listener, app).with_graceful_shutdown(stop.clone()); - swarm_secret_client::serve_bounded(stop, serving.into_future()) - .await - .transpose() - .context("serving")?; - Ok(()) + axum::serve(listener, app).await.context("serving") } #[cfg(test)] mod tests { use super::*; - use futures_util::FutureExt as _; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use swarm_secret_client::queue::AgentCredential; - use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; /// What the mirrored grant leaf answers. #[derive(Clone, Copy)] @@ -492,59 +474,4 @@ mod tests { } assert_eq!(store.lookups(), 3); } - - /// A request that is being answered when the stop arrives is still - /// answered, and `serve` returns only afterwards. - #[tokio::test] - async fn a_request_in_flight_at_the_stop_is_answered_before_serve_returns() { - let started = Arc::new(tokio::sync::Notify::new()); - let release = Arc::new(tokio::sync::Notify::new()); - let app = { - let (started, release) = (Arc::clone(&started), Arc::clone(&release)); - axum::Router::new().fallback(move || { - let (started, release) = (Arc::clone(&started), Arc::clone(&release)); - async move { - started.notify_one(); - release.notified().await; - "answered" - } - }) - }; - let socket = - std::env::temp_dir().join(format!("swarm-logs-auth-stop-{}.sock", std::process::id())); - let _ = std::fs::remove_file(&socket); - let listener = tokio::net::UnixListener::bind(&socket).expect("bind"); - let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); - let stop = async move { - let _ = stop_rx.await; - } - .shared(); - let mut serving = tokio::spawn(serve(listener, app, stop)); - - let mut conn = tokio::net::UnixStream::connect(&socket) - .await - .expect("connect"); - conn.write_all(b"GET / HTTP/1.1\r\nhost: x\r\nconnection: close\r\n\r\n") - .await - .expect("send"); - started.notified().await; - - stop_tx.send(()).expect("stop"); - tokio::time::sleep(Duration::from_millis(200)).await; - assert!( - !serving.is_finished(), - "serve returned with a request in flight" - ); - - release.notify_one(); - let mut reply = String::new(); - conn.read_to_string(&mut reply).await.expect("reply"); - assert!(reply.starts_with("HTTP/1.1 200"), "{reply}"); - assert!(reply.ends_with("answered"), "{reply}"); - let finished = tokio::time::timeout(Duration::from_secs(5), &mut serving) - .await - .expect("serve returns once the request is answered"); - finished.expect("task").expect("serve is Ok"); - let _ = std::fs::remove_file(&socket); - } } diff --git a/swarm-metrics-auth/src/main.rs b/swarm-metrics-auth/src/main.rs index d4845a3ba..fd4bc4f2b 100644 --- a/swarm-metrics-auth/src/main.rs +++ b/swarm-metrics-auth/src/main.rs @@ -282,7 +282,6 @@ async fn handle(State(responder): State>>, headers: HeaderM #[tokio::main] async fn main() -> anyhow::Result<()> { - let stop = swarm_secret_client::shutdown_signal(); swarm_secret_client::install_crypto_provider(); tracing_subscriber::fmt() .with_env_filter( @@ -323,22 +322,7 @@ async fn main() -> anyhow::Result<()> { tracing::info!(socket = %args.socket.display(), "swarm-metrics-auth listening"); let app = axum::Router::new().fallback(handle).with_state(responder); - serve(listener, app, stop).await -} - -/// Answers on `listener` until `stop` resolves, then lets the requests in hand -/// finish, for at most the drain, and returns. -async fn serve( - listener: tokio::net::UnixListener, - app: axum::Router, - stop: impl Future + Clone + Send + 'static, -) -> anyhow::Result<()> { - let serving = axum::serve(listener, app).with_graceful_shutdown(stop.clone()); - swarm_secret_client::serve_bounded(stop, serving.into_future()) - .await - .transpose() - .context("serving")?; - Ok(()) + axum::serve(listener, app).await.context("serving") } #[cfg(test)] diff --git a/swarm-nats-auth/src/main.rs b/swarm-nats-auth/src/main.rs index d08c17365..f3fe7a639 100644 --- a/swarm-nats-auth/src/main.rs +++ b/swarm-nats-auth/src/main.rs @@ -182,7 +182,6 @@ struct Args { #[tokio::main] async fn main() -> anyhow::Result<()> { - let stop = swarm_secret_client::shutdown_signal(); swarm_secret_client::install_crypto_provider(); tracing_subscriber::fmt() .with_env_filter( @@ -211,14 +210,14 @@ async fn main() -> anyhow::Result<()> { ) .await } - (None, Some(args)) => serve(args, stop).await, + (None, Some(args)) => serve(args).await, (None, None) => unreachable!("clap requires the responder's flags when no verb is given"), } } /// The responder: answers every authorization request until its /// subscription ends. -async fn serve(args: Args, stop: swarm_secret_client::Shutdown) -> anyhow::Result<()> { +async fn serve(args: Args) -> anyhow::Result<()> { // The bucket is NOT a flag. `swarm_queue_client::status`'s own docs say // why: reader and writer must name the same bucket, and an option is a // way for two deployments to disagree about which one that is. This @@ -280,33 +279,25 @@ async fn serve(args: Args, stop: swarm_secret_client::Shutdown) -> anyhow::Resul callout_xkey, issuer, }); - answer_each( - requests.take_until(stop.clone()), - CONCURRENT_REQUESTS, - move |msg| { - let responder = Arc::clone(&responder); - let client = client.clone(); - async move { - let Some((reply_to, reply)) = responder.answer(&msg).await else { - return; - }; - if let Err(e) = client.publish(reply_to, reply.into()).await { - tracing::warn!(error = ?e, "failed to publish auth response"); - } + answer_each(requests, CONCURRENT_REQUESTS, move |msg| { + let responder = Arc::clone(&responder); + let client = client.clone(); + async move { + let Some((reply_to, reply)) = responder.answer(&msg).await else { + return; + }; + if let Err(e) = client.publish(reply_to, reply.into()).await { + tracing::warn!(error = ?e, "failed to publish auth response"); } - }, - ) + } + }) .await; - if stop.peek().is_none() { - anyhow::bail!("subscription to {AUTH_SUBJECT} ended"); - } - Ok(()) + anyhow::bail!("subscription to {AUTH_SUBJECT} ended") } /// Runs `answer` on each of `requests`, at most `permits` at once. A request /// waits in `requests` until a permit is free; the reply carries `server_id` -/// and `user_nkey`, so the order answers go out in does not matter. Once -/// `requests` ends, the answers in hand get the drain to finish. +/// and `user_nkey`, so the order answers go out in does not matter. async fn answer_each( mut requests: impl futures_util::Stream + Unpin, permits: usize, @@ -316,18 +307,16 @@ async fn answer_each( Fut: std::future::Future + Send + 'static, { let permits = Arc::new(tokio::sync::Semaphore::new(permits)); - let mut in_flight = swarm_secret_client::InFlight::new(); while let Some(request) = requests.next().await { let Ok(permit) = Arc::clone(&permits).acquire_owned().await else { unreachable!("the semaphore is never closed"); }; let answering = answer(request); - in_flight.spawn(async move { + tokio::spawn(async move { answering.await; drop(permit); }); } - in_flight.drain().await; } /// Whether the server has stopped waiting for the answer to a request whose diff --git a/swarm-notify-router/src/main.rs b/swarm-notify-router/src/main.rs index 2d484d22b..fb3005b04 100644 --- a/swarm-notify-router/src/main.rs +++ b/swarm-notify-router/src/main.rs @@ -35,7 +35,7 @@ use std::time::{Duration, Instant}; use anyhow::{Context as _, Result, bail}; use async_nats::jetstream::{self, consumer::pull, kv, message::PublishMessage}; -use futures_util::{FutureExt as _, StreamExt as _}; +use futures_util::StreamExt as _; use metrics::Handled; use swarm_queue_client::{ClientSecret, QueueConfig}; use swarm_secret_client::stored_secret::StoredSecret; @@ -79,7 +79,6 @@ const ROSTER_TTL: Duration = Duration::from_mins(1); #[tokio::main] async fn main() -> Result<()> { - let stop = swarm_secret_client::shutdown_signal(); hive_log::init(); swarm_secret_client::install_crypto_provider(); let var = |name: &str| { @@ -114,26 +113,16 @@ async fn main() -> Result<()> { stream = forge_events::STREAM, "notify router: routing forge events" ); - while stop.clone().now_or_never().is_none() { - let pulled = - swarm_secret_client::serve_bounded(stop.clone(), router.pull_once(stop.clone())).await; - match pulled { - Some(Ok(())) => {} - Some(Err(e)) => { - router.metrics.pull_failed(); - tracing::warn!( - error = format!("{e:#}"), - "notify router: pulling events failed; retrying" - ); - tokio::select! { - () = stop.clone() => {} - () = tokio::time::sleep(RETRY_DELAY) => {} - } - } - None => break, + loop { + if let Err(e) = router.pull_once().await { + router.metrics.pull_failed(); + tracing::warn!( + error = format!("{e:#}"), + "notify router: pulling events failed; retrying" + ); + tokio::time::sleep(RETRY_DELAY).await; } } - Ok(()) } struct Router { @@ -195,11 +184,8 @@ impl Router { }) } - /// Pull one batch and handle each event in stream order, taking no event - /// after `stop` resolves. The one being handled finishes and is settled; - /// the rest of the batch is left un-acked and comes back after the ack - /// wait. - async fn pull_once(&mut self, stop: swarm_secret_client::Shutdown) -> Result<()> { + /// Pull one batch and handle each event in stream order. + async fn pull_once(&mut self) -> Result<()> { if let Ok(info) = self.events.info().await { self.metrics .consumer(info.num_pending, info.num_ack_pending, info.num_redelivered); @@ -213,10 +199,7 @@ impl Router { .await .context("requesting a batch")?; let batch = batch.map(|m| m.map_err(|e| anyhow::anyhow!("{e}"))); - settle::batch(batch, stop, async |m: &jetstream::Message| { - self.handle(m).await - }) - .await + settle::batch(batch, async |m: &jetstream::Message| self.handle(m).await).await } /// Handle one event and count how it went. diff --git a/swarm-notify-router/src/settle.rs b/swarm-notify-router/src/settle.rs index 034deb639..e498c1dd2 100644 --- a/swarm-notify-router/src/settle.rs +++ b/swarm-notify-router/src/settle.rs @@ -33,15 +33,11 @@ impl Pulled for async_nats::jetstream::Message { /// Handle each event of `batch` with `handle` and settle it. Returns the /// error of the first event that has to be retried, once the rest of the /// batch is nakked behind it. -/// -/// Once `stop` resolves no further event is taken: the one being handled is -/// settled, and the rest stay un-acked and come back after the ack wait. pub(crate) async fn batch( batch: impl Stream>, - stop: impl Future, mut handle: impl AsyncFnMut(&P) -> Result<(), Skip>, ) -> Result<()> { - let mut batch = std::pin::pin!(batch.take_until(stop)); + let mut batch = std::pin::pin!(batch); let mut failed: Option = None; while let Some(event) = batch.next().await { let event = event?; @@ -106,18 +102,14 @@ mod tests { }) }); let mut handled = Vec::new(); - let result = batch( - futures_util::stream::iter(events), - std::future::pending(), - async |e: &Fake<'_>| { - handled.push(e.name); - if e.name == "assigned" { - Err(Skip::Retry(anyhow::anyhow!("the queue is down"))) - } else { - Ok(()) - } - }, - ) + let result = batch(futures_util::stream::iter(events), async |e: &Fake<'_>| { + handled.push(e.name); + if e.name == "assigned" { + Err(Skip::Retry(anyhow::anyhow!("the queue is down"))) + } else { + Ok(()) + } + }) .await; assert!(result.is_err()); assert_eq!(handled, ["opened", "assigned"]); @@ -143,17 +135,13 @@ mod tests { settled: &settled, }) }); - let result = batch( - futures_util::stream::iter(events), - std::future::pending(), - async |e: &Fake<'_>| { - if e.name == "bad" { - Err(Skip::Unusable("no".to_owned())) - } else { - Ok(()) - } - }, - ) + let result = batch(futures_util::stream::iter(events), async |e: &Fake<'_>| { + if e.name == "bad" { + Err(Skip::Unusable("no".to_owned())) + } else { + Ok(()) + } + }) .await; assert!(result.is_ok()); assert_eq!( @@ -164,44 +152,4 @@ mod tests { ] ); } - - /// The stop arrives while `assigned` is being handled: it is still - /// settled, and `unassigned` and `closed` are neither handled nor settled, - /// so the queue redelivers them. - #[tokio::test] - async fn after_the_stop_the_event_in_hand_is_settled_and_the_rest_is_left_unacked() { - let settled = RefCell::new(Vec::new()); - let events = ["opened", "assigned", "unassigned", "closed"].map(|name| { - Ok(Fake { - name, - settled: &settled, - }) - }); - let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); - let mut stop_tx = Some(stop_tx); - let mut handled = Vec::new(); - let result = batch( - futures_util::stream::iter(events), - async { - let _ = stop_rx.await; - }, - async |e: &Fake<'_>| { - handled.push(e.name); - if e.name == "assigned" { - stop_tx.take().expect("sent once").send(()).expect("stop"); - } - Ok(()) - }, - ) - .await; - assert!(result.is_ok()); - assert_eq!(handled, ["opened", "assigned"]); - assert_eq!( - settled.into_inner(), - [ - ("opened", format!("{:?}", AckKind::Ack)), - ("assigned", format!("{:?}", AckKind::Ack)), - ] - ); - } } diff --git a/swarm-review-classifier/src/main.rs b/swarm-review-classifier/src/main.rs index dfef53a15..b5cc39559 100644 --- a/swarm-review-classifier/src/main.rs +++ b/swarm-review-classifier/src/main.rs @@ -47,7 +47,6 @@ fn main() -> Result<()> { } async fn serve() -> Result<()> { - let stop = swarm_secret_client::shutdown_signal(); hive_log::init(); swarm_secret_client::install_crypto_provider(); let var = |name: &str| { @@ -93,8 +92,7 @@ async fn serve() -> Result<()> { let mut requests = queue .queue_subscribe(SUBJECT, QUEUE_GROUP.to_owned()) .await - .with_context(|| format!("subscribing to {SUBJECT}"))? - .take_until(stop.clone()); + .with_context(|| format!("subscribing to {SUBJECT}"))?; tracing::info!(subject = SUBJECT, "review classifier: awaiting try-outs"); let models = std::sync::Arc::new(models); @@ -117,10 +115,7 @@ async fn serve() -> Result<()> { } }); } - if stop.peek().is_none() { - bail!("the subscription to {SUBJECT} ended"); - } - Ok(()) + bail!("the subscription to {SUBJECT} ended") } /// Decode one request, answer it and log the run. diff --git a/swarm-secret-client/Cargo.toml b/swarm-secret-client/Cargo.toml index fd3484b67..5904e4400 100644 --- a/swarm-secret-client/Cargo.toml +++ b/swarm-secret-client/Cargo.toml @@ -47,8 +47,6 @@ workspace = true # provider compiled in rustls picks it without an install, so the provider # test would pass with `install_crypto_provider` doing nothing. [dev-dependencies] -# `raise`, to send the test process a real SIGTERM. -libc.workspace = true # `InMemoryMetricExporter`, to read back what `cert_metrics` exports. opentelemetry_sdk = { workspace = true, features = ["testing"] } rustls = { workspace = true, features = ["ring"] } diff --git a/swarm-secret-client/src/lib.rs b/swarm-secret-client/src/lib.rs index d0ea6c07d..7e059ee81 100644 --- a/swarm-secret-client/src/lib.rs +++ b/swarm-secret-client/src/lib.rs @@ -55,12 +55,10 @@ pub mod policy; pub mod proxy; pub mod queue; pub mod review_classifier; -pub mod shutdown; pub mod startup_read; pub mod stored_secret; pub use client::SecretStore; -pub use shutdown::{DRAIN, InFlight, Shutdown, serve_bounded, shutdown_signal}; pub use startup_read::read_with_startup_retry; /// What can go wrong between "we have a client certificate" and "we have the diff --git a/swarm-secret-client/src/shutdown.rs b/swarm-secret-client/src/shutdown.rs deleted file mode 100644 index 4fb9b5e00..000000000 --- a/swarm-secret-client/src/shutdown.rs +++ /dev/null @@ -1,206 +0,0 @@ -//! Stopping a daemon when its unit is stopped. -//! -//! `systemctl stop` and a container runtime both send SIGTERM. A process with -//! no handler dies on the default action, mid-request; one that waits on -//! [`shutdown_signal`] finishes what it has in hand and exits 0. Every swarm -//! daemon's `main` shares this one definition of "told to stop" and of how -//! long it then gets ([`DRAIN`]). - -use std::future::Future; -use std::time::Duration; - -use futures_util::FutureExt as _; -use futures_util::future::{BoxFuture, Shared}; -use tokio::signal::unix::{SignalKind, signal}; -use tokio::task::JoinSet; - -/// How long work in hand may take once the signal has arrived. Well under -/// systemd's default `TimeoutStopSec` (90 s) and a pod's 30 s grace period, so -/// the process exits 0 before either escalates to SIGKILL. -pub const DRAIN: Duration = Duration::from_secs(10); - -/// What [`shutdown_signal`] returns: a future that is `Clone`, and whose clones -/// all resolve on the one signal. -pub type Shutdown = Shared>; - -/// Resolves when the process receives SIGTERM or SIGINT. -/// -/// The handlers are installed when this is called, not when the future is -/// first polled, so call it early in `main`: a signal arriving between the -/// call and the first poll is still seen, and one before the call kills the -/// process as before. Clones of the [`Shutdown`] it returns all resolve on the -/// one signal, so a server, a message loop and a bound can all wait on it. -/// -/// # Panics -/// -/// When the runtime is not running, or the kernel refuses a handler. -pub fn shutdown_signal() -> Shutdown { - let mut term = signal(SignalKind::terminate()).expect("installing the SIGTERM handler"); - let mut int = signal(SignalKind::interrupt()).expect("installing the SIGINT handler"); - async move { - tokio::select! { - _ = term.recv() => tracing::info!("SIGTERM received; shutting down"), - _ = int.recv() => tracing::info!("SIGINT received; shutting down"), - } - } - .boxed() - .shared() -} - -/// Runs `serving`, a server built with `with_graceful_shutdown` on a clone of -/// `stop`, and stops waiting for it [`DRAIN`] after `stop` resolves. `None` -/// means connections were still open then. -/// -/// A graceful shutdown waits for every connection to close, and a streaming -/// response never does on its own; without this bound such a daemon sits out -/// the unit's stop timeout and is killed. -pub async fn serve_bounded( - stop: impl Future, - serving: impl Future, -) -> Option { - tokio::pin!(serving); - tokio::select! { - out = &mut serving => Some(out), - () = async { - stop.await; - tokio::time::sleep(DRAIN).await; - } => { - tracing::warn!(drain = ?DRAIN, "still running after the drain; exiting anyway"); - None - } - } -} - -/// The handlers a daemon has spawned for messages it already took. -/// -/// After the signal the daemon takes no more, calls [`InFlight::drain`], and -/// whatever is still running then is abandoned. Nothing is acknowledged on -/// its behalf, so an unfinished message is redelivered or times out at its -/// sender exactly as it would after a kill. -#[derive(Default)] -pub struct InFlight(JoinSet<()>); - -impl InFlight { - /// An empty set. - #[must_use] - pub fn new() -> Self { - Self::default() - } - - /// Runs `handler` on its own task. Handlers that already finished are - /// dropped first, so the set stays as small as the work in hand. - pub fn spawn(&mut self, handler: impl Future + Send + 'static) { - while self.0.try_join_next().is_some() {} - self.0.spawn(handler); - } - - /// Waits up to [`DRAIN`] for the handlers still running. - pub async fn drain(mut self) { - let finished = - tokio::time::timeout(DRAIN, async { while self.0.join_next().await.is_some() {} }) - .await; - if finished.is_err() { - tracing::warn!( - abandoned = self.0.len(), - drain = ?DRAIN, - "handlers still running after the drain; abandoning them" - ); - } - } -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - use std::sync::atomic::{AtomicBool, Ordering}; - - use tokio::sync::Notify; - - use super::*; - - /// A real SIGTERM, then a real SIGINT, raised at this process: the handlers - /// are installed by the call, so the signals are consumed rather than - /// killing the test binary. One test, so the two raises never overlap. - #[tokio::test] - async fn resolves_on_a_sigterm_and_on_a_sigint_raised_at_the_process() { - let stop = shutdown_signal(); - let mut stop = std::pin::pin!(stop); - assert!( - stop.as_mut().now_or_never().is_none(), - "resolved with no signal" - ); - // SAFETY: `raise` takes a signal number and touches no memory. - assert_eq!(unsafe { libc::raise(libc::SIGTERM) }, 0); - tokio::time::timeout(Duration::from_secs(5), stop) - .await - .expect("SIGTERM resolves the future"); - - let stop = shutdown_signal(); - // SAFETY: as above. - assert_eq!(unsafe { libc::raise(libc::SIGINT) }, 0); - tokio::time::timeout(Duration::from_secs(5), stop) - .await - .expect("SIGINT resolves the future"); - } - - /// A server that finishes by itself is returned from at once, and its - /// output is the caller's. - #[tokio::test] - async fn serve_bounded_returns_what_the_server_returns() { - let out = serve_bounded(std::future::pending(), async { 7 }).await; - assert_eq!(out, Some(7)); - } - - /// After `stop`, a server that never ends is given up on once [`DRAIN`] - /// has passed, and not before. - #[tokio::test(start_paused = true)] - async fn serve_bounded_gives_up_only_after_the_drain() { - let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); - let bounded = tokio::spawn(serve_bounded( - async { stop_rx.await.unwrap() }, - std::future::pending::<()>(), - )); - tokio::time::sleep(DRAIN * 3).await; - assert!(!bounded.is_finished(), "gave up with no stop"); - stop_tx.send(()).unwrap(); - tokio::time::sleep(DRAIN / 2).await; - assert!(!bounded.is_finished(), "gave up inside the drain"); - tokio::time::sleep(DRAIN / 2 + Duration::from_secs(1)).await; - assert!(bounded.is_finished(), "still waiting past the drain"); - assert_eq!(bounded.await.unwrap(), None); - } - - /// A handler that finishes inside the drain is waited for. - #[tokio::test(start_paused = true)] - async fn drain_waits_for_a_handler_that_finishes_in_time() { - let done = Arc::new(AtomicBool::new(false)); - let mut in_flight = InFlight::new(); - let flag = Arc::clone(&done); - in_flight.spawn(async move { - tokio::time::sleep(DRAIN / 2).await; - flag.store(true, Ordering::SeqCst); - }); - in_flight.drain().await; - assert!(done.load(Ordering::SeqCst)); - } - - /// A handler that outlives the drain is abandoned: the drain returns at - /// the bound with the handler unfinished. - #[tokio::test(start_paused = true)] - async fn drain_abandons_a_handler_that_outlives_it() { - let done = Arc::new(AtomicBool::new(false)); - let started = Arc::new(Notify::new()); - let mut in_flight = InFlight::new(); - let (flag, up) = (Arc::clone(&done), Arc::clone(&started)); - in_flight.spawn(async move { - up.notify_one(); - tokio::time::sleep(DRAIN * 5).await; - flag.store(true, Ordering::SeqCst); - }); - started.notified().await; - let before = tokio::time::Instant::now(); - in_flight.drain().await; - assert_eq!(before.elapsed(), DRAIN); - assert!(!done.load(Ordering::SeqCst)); - } -} diff --git a/swarm-stt/src/main.rs b/swarm-stt/src/main.rs index 90e2af7e6..23921c291 100644 --- a/swarm-stt/src/main.rs +++ b/swarm-stt/src/main.rs @@ -115,7 +115,6 @@ async fn connect_queue(var: Var<'_>) -> Result { #[tokio::main] async fn main() -> Result<()> { - let stop = swarm_secret_client::shutdown_signal(); hive_log::init(); swarm_secret_client::install_crypto_provider(); let var = |name: &str| { @@ -152,8 +151,7 @@ async fn main() -> Result<()> { let mut requests = queue .queue_subscribe(subject_wildcard(), QUEUE_GROUP.to_owned()) .await - .context("subscribing to the request subject")? - .take_until(stop.clone()); + .context("subscribing to the request subject")?; tracing::info!( subject = subject_wildcard(), "swarm-stt: answering requests" @@ -209,10 +207,7 @@ async fn main() -> Result<()> { } }); } - if stop.peek().is_none() { - bail!("the request subscription ended"); - } - Ok(()) + bail!("the request subscription ended") } /// One agent's place among the requests in flight; dropping it frees the place.