Compare commits
19 changed files with 83 additions and 576 deletions
3
Cargo.lock
generated
3
Cargo.lock
generated
|
|
@ -5278,7 +5278,6 @@ dependencies = [
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_norway",
|
"serde_norway",
|
||||||
"swarm-authelia-bridge-sock",
|
"swarm-authelia-bridge-sock",
|
||||||
"swarm-secret-client",
|
|
||||||
"tokio",
|
"tokio",
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
|
|
@ -5439,7 +5438,6 @@ dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"axum",
|
"axum",
|
||||||
"clap",
|
"clap",
|
||||||
"futures-util",
|
|
||||||
"sha2 0.11.1",
|
"sha2 0.11.1",
|
||||||
"swarm-agent-verify",
|
"swarm-agent-verify",
|
||||||
"swarm-secret-client",
|
"swarm-secret-client",
|
||||||
|
|
@ -5601,7 +5599,6 @@ version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"backon",
|
"backon",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"libc",
|
|
||||||
"opentelemetry",
|
"opentelemetry",
|
||||||
"opentelemetry-otlp",
|
"opentelemetry-otlp",
|
||||||
"opentelemetry_sdk",
|
"opentelemetry_sdk",
|
||||||
|
|
|
||||||
|
|
@ -385,7 +385,17 @@ async fn cmd_serve(
|
||||||
let coord_sig = coord.clone();
|
let coord_sig = coord.clone();
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
res = server::serve(socket, coord) => { res? }
|
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();
|
coord_sig.request_shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -19,8 +19,6 @@ serde.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
serde_norway = "0.9.42"
|
serde_norway = "0.9.42"
|
||||||
swarm-authelia-bridge-sock.workspace = true
|
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
|
tokio.workspace = true
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
tracing-subscriber.workspace = true
|
tracing-subscriber.workspace = true
|
||||||
|
|
|
||||||
|
|
@ -106,7 +106,6 @@ struct AppState {
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<()> {
|
async fn main() -> Result<()> {
|
||||||
let stop = swarm_secret_client::shutdown_signal();
|
|
||||||
tracing_subscriber::fmt()
|
tracing_subscriber::fmt()
|
||||||
.with_env_filter(
|
.with_env_filter(
|
||||||
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()),
|
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)?;
|
let listener = bind_socket(&socket)?;
|
||||||
tracing::info!(socket = %socket.display(), "swarm-authelia-bridge listening");
|
tracing::info!(socket = %socket.display(), "swarm-authelia-bridge listening");
|
||||||
serve(listener, app, stop).await
|
axum::serve(listener, app)
|
||||||
}
|
|
||||||
|
|
||||||
/// 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<Output = ()> + Clone + Send + 'static,
|
|
||||||
) -> Result<()> {
|
|
||||||
let serving = axum::serve(listener, app).with_graceful_shutdown(stop.clone());
|
|
||||||
swarm_secret_client::serve_bounded(stop, serving.into_future())
|
|
||||||
.await
|
.await
|
||||||
.transpose()
|
.context("serving swarm-authelia-bridge")
|
||||||
.context("serving swarm-authelia-bridge")?;
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Bind the listening socket at `path`, replacing a stale one a crash left
|
/// Bind the listening socket at `path`, replacing a stale one a crash left
|
||||||
|
|
|
||||||
|
|
@ -88,7 +88,6 @@ fn push_budget(reply_by: tokio::time::Instant) -> Duration {
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<()> {
|
async fn main() -> Result<()> {
|
||||||
let stop = swarm_secret_client::shutdown_signal();
|
|
||||||
hive_log::init();
|
hive_log::init();
|
||||||
swarm_secret_client::install_crypto_provider();
|
swarm_secret_client::install_crypto_provider();
|
||||||
let var = |name: &str| {
|
let var = |name: &str| {
|
||||||
|
|
@ -175,19 +174,8 @@ async fn main() -> Result<()> {
|
||||||
let slot = Arc::new(tokio::sync::Semaphore::new(1));
|
let slot = Arc::new(tokio::sync::Semaphore::new(1));
|
||||||
serve_meta_builds(&queue, &publisher, Store, &builder, &slot, &metrics).await?;
|
serve_meta_builds(&queue, &publisher, Store, &builder, &slot, &metrics).await?;
|
||||||
|
|
||||||
answer_builds(
|
answer_builds(requests, publisher, Store, builder, slot, metrics).await;
|
||||||
requests.take_until(stop.clone()),
|
bail!("the subscription to {SUBJECT} ended")
|
||||||
publisher,
|
|
||||||
Store,
|
|
||||||
builder,
|
|
||||||
slot,
|
|
||||||
metrics,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
if stop.peek().is_none() {
|
|
||||||
bail!("the subscription to {SUBJECT} ended");
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Where a reply goes. [`Queue`] in production; tests record.
|
/// 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.
|
/// 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(
|
async fn answer_builds(
|
||||||
mut requests: impl Stream<Item = Message> + Unpin,
|
mut requests: impl Stream<Item = Message> + Unpin,
|
||||||
publisher: impl Publisher,
|
publisher: impl Publisher,
|
||||||
|
|
|
||||||
|
|
@ -100,7 +100,6 @@ impl login::CredentialSink for AgentLeaf {
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<()> {
|
async fn main() -> Result<()> {
|
||||||
let stop = swarm_secret_client::shutdown_signal();
|
|
||||||
hive_log::init();
|
hive_log::init();
|
||||||
swarm_secret_client::install_crypto_provider();
|
swarm_secret_client::install_crypto_provider();
|
||||||
let var = |name: &str| {
|
let var = |name: &str| {
|
||||||
|
|
@ -139,11 +138,9 @@ async fn main() -> Result<()> {
|
||||||
let mut requests = queue
|
let mut requests = queue
|
||||||
.subscribe(SUBJECT)
|
.subscribe(SUBJECT)
|
||||||
.await
|
.await
|
||||||
.with_context(|| format!("subscribing to {SUBJECT}"))?
|
.with_context(|| format!("subscribing to {SUBJECT}"))?;
|
||||||
.take_until(stop.clone());
|
|
||||||
tracing::info!(subject = SUBJECT, "claude login minter: awaiting logins");
|
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 {
|
while let Some(msg) = requests.next().await {
|
||||||
let Some(reply_to) = msg.reply.clone() else {
|
let Some(reply_to) = msg.reply.clone() else {
|
||||||
tracing::warn!("a login step arrived with no reply subject; dropping it");
|
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 queue = queue.clone();
|
||||||
let logins = Arc::clone(&logins);
|
let logins = Arc::clone(&logins);
|
||||||
let metrics = Arc::clone(&metrics);
|
let metrics = Arc::clone(&metrics);
|
||||||
in_flight.spawn(async move {
|
tokio::spawn(async move {
|
||||||
let reply = handle(&msg.payload, &logins, &metrics).await;
|
let reply = handle(&msg.payload, &logins, &metrics).await;
|
||||||
match serde_json::to_vec(&reply) {
|
match serde_json::to_vec(&reply) {
|
||||||
Ok(body) => {
|
Ok(body) => {
|
||||||
|
|
@ -164,11 +161,7 @@ async fn main() -> Result<()> {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
in_flight.drain().await;
|
bail!("the subscription to {SUBJECT} ended")
|
||||||
if stop.peek().is_none() {
|
|
||||||
bail!("the subscription to {SUBJECT} ended");
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Answer one step and count it.
|
/// Answer one step and count it.
|
||||||
|
|
|
||||||
|
|
@ -269,7 +269,7 @@ async fn main() -> Result<()> {
|
||||||
reviews: Arc::default(),
|
reviews: Arc::default(),
|
||||||
alerts: alerts::from_env(),
|
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
|
/// 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
|
/// Start taking the queued review requests and answering the notification
|
||||||
/// router's, then serve `state` on `listener` until `stop` resolves. The
|
/// router's, then serve `state` on `listener`.
|
||||||
/// requests in hand finish for at most the drain; the review queue takes no
|
async fn serve(listener: tokio::net::UnixListener, state: AppState) -> Result<()> {
|
||||||
/// request after `stop`.
|
review_classifier::review::spawn_queue(&state);
|
||||||
async fn serve(
|
|
||||||
listener: tokio::net::UnixListener,
|
|
||||||
state: AppState,
|
|
||||||
stop: impl Future<Output = ()> + Clone + Send + 'static,
|
|
||||||
) -> Result<()> {
|
|
||||||
review_classifier::review::spawn_queue(&state, stop.clone());
|
|
||||||
request_reviewer::spawn(&state);
|
request_reviewer::spawn(&state);
|
||||||
let serving = axum::serve(listener, build_app(state)).with_graceful_shutdown(stop.clone());
|
axum::serve(listener, build_app(state))
|
||||||
swarm_secret_client::serve_bounded(stop, serving.into_future())
|
|
||||||
.await
|
.await
|
||||||
.transpose()
|
.context("serving swarm-controller")
|
||||||
.context("serving swarm-controller")?;
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -443,10 +443,7 @@ async fn open_consumer(
|
||||||
|
|
||||||
/// Take the queued review requests and review each, for as long as the
|
/// Take the queued review requests and review each, for as long as the
|
||||||
/// controller runs, once this host has forge access.
|
/// controller runs, once this host has forge access.
|
||||||
pub(crate) fn spawn_queue(
|
pub(crate) fn spawn_queue(state: &AppState) {
|
||||||
state: &AppState,
|
|
||||||
stop: impl Future<Output = ()> + Clone + Send + 'static,
|
|
||||||
) {
|
|
||||||
let Some(client) = state.status.as_ref().map(|s| s.queue_client()) else {
|
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");
|
tracing::warn!("no swarm queue is configured on this host; requested reviews don't run");
|
||||||
return;
|
return;
|
||||||
|
|
@ -469,7 +466,7 @@ pub(crate) fn spawn_queue(
|
||||||
runs,
|
runs,
|
||||||
metrics: Metrics::global(),
|
metrics: Metrics::global(),
|
||||||
};
|
};
|
||||||
consume(&client, TIMING, &reviews, handles, stop).await;
|
consume(&client, TIMING, &reviews, handles).await;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -497,9 +494,8 @@ impl<S, Q: Clone, P> Clone for Handles<S, Q, P> {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Take requests from [`REQUEST_STREAM`] one at a time, each once a run
|
/// 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`
|
/// place is free, and review each in a task of its own. Never returns;
|
||||||
/// resolves, taking no request after it; dropping it, as the return does, stops
|
/// dropping it stops every review it started, and the queue delivers their
|
||||||
/// every review it started without acking, and the queue delivers their
|
|
||||||
/// requests again.
|
/// requests again.
|
||||||
///
|
///
|
||||||
/// The limit is read from the settings before each wait for a place. A
|
/// The limit is read from the settings before each wait for a place. A
|
||||||
|
|
@ -510,7 +506,6 @@ async fn consume<S, Q, P>(
|
||||||
timing: Timing,
|
timing: Timing,
|
||||||
reviews: &Arc<Reviews>,
|
reviews: &Arc<Reviews>,
|
||||||
handles: Handles<S, Q, P>,
|
handles: Handles<S, Q, P>,
|
||||||
stop: impl Future<Output = ()> + Clone,
|
|
||||||
) where
|
) where
|
||||||
S: FileSource + PullSource + Send + Sync + 'static,
|
S: FileSource + PullSource + Send + Sync + 'static,
|
||||||
Q: RunSink + SettingsSource,
|
Q: RunSink + SettingsSource,
|
||||||
|
|
@ -524,11 +519,7 @@ async fn consume<S, Q, P>(
|
||||||
"opening the review request queue failed; trying again"
|
"opening the review request queue failed; trying again"
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
tokio::select! {
|
tokio::time::sleep(timing.pull_wait).await;
|
||||||
biased;
|
|
||||||
() = stop.clone() => return,
|
|
||||||
() = tokio::time::sleep(timing.pull_wait) => {}
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
let mut tasks = JoinSet::new();
|
let mut tasks = JoinSet::new();
|
||||||
loop {
|
loop {
|
||||||
|
|
@ -545,17 +536,8 @@ async fn consume<S, Q, P>(
|
||||||
the last limit read"
|
the last limit read"
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
let slot = tokio::select! {
|
let slot = reviews.slot().await;
|
||||||
biased;
|
let message = match next(&consumer, timing.pull_wait).await {
|
||||||
() = 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 {
|
|
||||||
Ok(Some(message)) => message,
|
Ok(Some(message)) => message,
|
||||||
Ok(None) => continue,
|
Ok(None) => continue,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
|
|
@ -564,11 +546,7 @@ async fn consume<S, Q, P>(
|
||||||
"taking a review request from the queue failed; trying again"
|
"taking a review request from the queue failed; trying again"
|
||||||
);
|
);
|
||||||
drop(slot);
|
drop(slot);
|
||||||
tokio::select! {
|
tokio::time::sleep(timing.pull_wait).await;
|
||||||
biased;
|
|
||||||
() = stop.clone() => return,
|
|
||||||
() = tokio::time::sleep(timing.pull_wait) => {}
|
|
||||||
}
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
@ -2054,15 +2032,6 @@ mod tests {
|
||||||
|
|
||||||
/// A controller taking requests, its run places in `reviews`.
|
/// A controller taking requests, its run places in `reviews`.
|
||||||
fn consume(&self, reviews: &Arc<Reviews>) -> JoinHandle<()> {
|
fn consume(&self, reviews: &Arc<Reviews>) -> JoinHandle<()> {
|
||||||
self.consume_until(reviews, std::future::pending())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A controller that takes no request once `stop` resolves.
|
|
||||||
fn consume_until(
|
|
||||||
&self,
|
|
||||||
reviews: &Arc<Reviews>,
|
|
||||||
stop: impl Future<Output = ()> + Clone + Send + 'static,
|
|
||||||
) -> JoinHandle<()> {
|
|
||||||
let client = self.client.clone();
|
let client = self.client.clone();
|
||||||
let reviews = Arc::clone(reviews);
|
let reviews = Arc::clone(reviews);
|
||||||
let forge = Arc::clone(&self.rig.forge);
|
let forge = Arc::clone(&self.rig.forge);
|
||||||
|
|
@ -2078,7 +2047,7 @@ mod tests {
|
||||||
runs: store,
|
runs: store,
|
||||||
metrics,
|
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");
|
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]
|
#[tokio::test]
|
||||||
async fn a_newer_request_for_a_pr_replaces_the_waiting_one() {
|
async fn a_newer_request_for_a_pr_replaces_the_waiting_one() {
|
||||||
let q = Queued::new().await;
|
let q = Queued::new().await;
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,3 @@ tracing-subscriber.workspace = true
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
# `Shared`, so the injected stop future can be cloned like `shutdown_signal`'s.
|
|
||||||
futures-util.workspace = true
|
|
||||||
|
|
|
||||||
|
|
@ -195,7 +195,6 @@ async fn handle(
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
let stop = swarm_secret_client::shutdown_signal();
|
|
||||||
swarm_secret_client::install_crypto_provider();
|
swarm_secret_client::install_crypto_provider();
|
||||||
tracing_subscriber::fmt()
|
tracing_subscriber::fmt()
|
||||||
.with_env_filter(
|
.with_env_filter(
|
||||||
|
|
@ -236,31 +235,14 @@ async fn main() -> anyhow::Result<()> {
|
||||||
tracing::info!(socket = %args.socket.display(), "swarm-logs-auth listening");
|
tracing::info!(socket = %args.socket.display(), "swarm-logs-auth listening");
|
||||||
|
|
||||||
let app = axum::Router::new().fallback(handle).with_state(responder);
|
let app = axum::Router::new().fallback(handle).with_state(responder);
|
||||||
serve(listener, app, stop).await
|
axum::serve(listener, app).await.context("serving")
|
||||||
}
|
|
||||||
|
|
||||||
/// 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<Output = ()> + 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(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use futures_util::FutureExt as _;
|
|
||||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
use swarm_secret_client::queue::AgentCredential;
|
use swarm_secret_client::queue::AgentCredential;
|
||||||
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
|
|
||||||
|
|
||||||
/// What the mirrored grant leaf answers.
|
/// What the mirrored grant leaf answers.
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
|
|
@ -492,59 +474,4 @@ mod tests {
|
||||||
}
|
}
|
||||||
assert_eq!(store.lookups(), 3);
|
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -282,7 +282,6 @@ async fn handle(State(responder): State<Arc<Responder<Store>>>, headers: HeaderM
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
let stop = swarm_secret_client::shutdown_signal();
|
|
||||||
swarm_secret_client::install_crypto_provider();
|
swarm_secret_client::install_crypto_provider();
|
||||||
tracing_subscriber::fmt()
|
tracing_subscriber::fmt()
|
||||||
.with_env_filter(
|
.with_env_filter(
|
||||||
|
|
@ -323,22 +322,7 @@ async fn main() -> anyhow::Result<()> {
|
||||||
tracing::info!(socket = %args.socket.display(), "swarm-metrics-auth listening");
|
tracing::info!(socket = %args.socket.display(), "swarm-metrics-auth listening");
|
||||||
|
|
||||||
let app = axum::Router::new().fallback(handle).with_state(responder);
|
let app = axum::Router::new().fallback(handle).with_state(responder);
|
||||||
serve(listener, app, stop).await
|
axum::serve(listener, app).await.context("serving")
|
||||||
}
|
|
||||||
|
|
||||||
/// 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<Output = ()> + 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(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|
|
||||||
|
|
@ -182,7 +182,6 @@ struct Args {
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
let stop = swarm_secret_client::shutdown_signal();
|
|
||||||
swarm_secret_client::install_crypto_provider();
|
swarm_secret_client::install_crypto_provider();
|
||||||
tracing_subscriber::fmt()
|
tracing_subscriber::fmt()
|
||||||
.with_env_filter(
|
.with_env_filter(
|
||||||
|
|
@ -211,14 +210,14 @@ async fn main() -> anyhow::Result<()> {
|
||||||
)
|
)
|
||||||
.await
|
.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"),
|
(None, None) => unreachable!("clap requires the responder's flags when no verb is given"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The responder: answers every authorization request until its
|
/// The responder: answers every authorization request until its
|
||||||
/// subscription ends.
|
/// 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
|
// 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
|
// 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
|
// way for two deployments to disagree about which one that is. This
|
||||||
|
|
@ -280,10 +279,7 @@ async fn serve(args: Args, stop: swarm_secret_client::Shutdown) -> anyhow::Resul
|
||||||
callout_xkey,
|
callout_xkey,
|
||||||
issuer,
|
issuer,
|
||||||
});
|
});
|
||||||
answer_each(
|
answer_each(requests, CONCURRENT_REQUESTS, move |msg| {
|
||||||
requests.take_until(stop.clone()),
|
|
||||||
CONCURRENT_REQUESTS,
|
|
||||||
move |msg| {
|
|
||||||
let responder = Arc::clone(&responder);
|
let responder = Arc::clone(&responder);
|
||||||
let client = client.clone();
|
let client = client.clone();
|
||||||
async move {
|
async move {
|
||||||
|
|
@ -294,19 +290,14 @@ async fn serve(args: Args, stop: swarm_secret_client::Shutdown) -> anyhow::Resul
|
||||||
tracing::warn!(error = ?e, "failed to publish auth response");
|
tracing::warn!(error = ?e, "failed to publish auth response");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
})
|
||||||
)
|
|
||||||
.await;
|
.await;
|
||||||
if stop.peek().is_none() {
|
anyhow::bail!("subscription to {AUTH_SUBJECT} ended")
|
||||||
anyhow::bail!("subscription to {AUTH_SUBJECT} ended");
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs `answer` on each of `requests`, at most `permits` at once. A request
|
/// 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`
|
/// 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
|
/// and `user_nkey`, so the order answers go out in does not matter.
|
||||||
/// `requests` ends, the answers in hand get the drain to finish.
|
|
||||||
async fn answer_each<R, F, Fut>(
|
async fn answer_each<R, F, Fut>(
|
||||||
mut requests: impl futures_util::Stream<Item = R> + Unpin,
|
mut requests: impl futures_util::Stream<Item = R> + Unpin,
|
||||||
permits: usize,
|
permits: usize,
|
||||||
|
|
@ -316,18 +307,16 @@ async fn answer_each<R, F, Fut>(
|
||||||
Fut: std::future::Future<Output = ()> + Send + 'static,
|
Fut: std::future::Future<Output = ()> + Send + 'static,
|
||||||
{
|
{
|
||||||
let permits = Arc::new(tokio::sync::Semaphore::new(permits));
|
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 {
|
while let Some(request) = requests.next().await {
|
||||||
let Ok(permit) = Arc::clone(&permits).acquire_owned().await else {
|
let Ok(permit) = Arc::clone(&permits).acquire_owned().await else {
|
||||||
unreachable!("the semaphore is never closed");
|
unreachable!("the semaphore is never closed");
|
||||||
};
|
};
|
||||||
let answering = answer(request);
|
let answering = answer(request);
|
||||||
in_flight.spawn(async move {
|
tokio::spawn(async move {
|
||||||
answering.await;
|
answering.await;
|
||||||
drop(permit);
|
drop(permit);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
in_flight.drain().await;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether the server has stopped waiting for the answer to a request whose
|
/// Whether the server has stopped waiting for the answer to a request whose
|
||||||
|
|
|
||||||
|
|
@ -35,7 +35,7 @@ use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use anyhow::{Context as _, Result, bail};
|
use anyhow::{Context as _, Result, bail};
|
||||||
use async_nats::jetstream::{self, consumer::pull, kv, message::PublishMessage};
|
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 metrics::Handled;
|
||||||
use swarm_queue_client::{ClientSecret, QueueConfig};
|
use swarm_queue_client::{ClientSecret, QueueConfig};
|
||||||
use swarm_secret_client::stored_secret::StoredSecret;
|
use swarm_secret_client::stored_secret::StoredSecret;
|
||||||
|
|
@ -79,7 +79,6 @@ const ROSTER_TTL: Duration = Duration::from_mins(1);
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<()> {
|
async fn main() -> Result<()> {
|
||||||
let stop = swarm_secret_client::shutdown_signal();
|
|
||||||
hive_log::init();
|
hive_log::init();
|
||||||
swarm_secret_client::install_crypto_provider();
|
swarm_secret_client::install_crypto_provider();
|
||||||
let var = |name: &str| {
|
let var = |name: &str| {
|
||||||
|
|
@ -114,26 +113,16 @@ async fn main() -> Result<()> {
|
||||||
stream = forge_events::STREAM,
|
stream = forge_events::STREAM,
|
||||||
"notify router: routing forge events"
|
"notify router: routing forge events"
|
||||||
);
|
);
|
||||||
while stop.clone().now_or_never().is_none() {
|
loop {
|
||||||
let pulled =
|
if let Err(e) = router.pull_once().await {
|
||||||
swarm_secret_client::serve_bounded(stop.clone(), router.pull_once(stop.clone())).await;
|
|
||||||
match pulled {
|
|
||||||
Some(Ok(())) => {}
|
|
||||||
Some(Err(e)) => {
|
|
||||||
router.metrics.pull_failed();
|
router.metrics.pull_failed();
|
||||||
tracing::warn!(
|
tracing::warn!(
|
||||||
error = format!("{e:#}"),
|
error = format!("{e:#}"),
|
||||||
"notify router: pulling events failed; retrying"
|
"notify router: pulling events failed; retrying"
|
||||||
);
|
);
|
||||||
tokio::select! {
|
tokio::time::sleep(RETRY_DELAY).await;
|
||||||
() = stop.clone() => {}
|
|
||||||
() = tokio::time::sleep(RETRY_DELAY) => {}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => break,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Router {
|
struct Router {
|
||||||
|
|
@ -195,11 +184,8 @@ impl Router {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pull one batch and handle each event in stream order, taking no event
|
/// Pull one batch and handle each event in stream order.
|
||||||
/// after `stop` resolves. The one being handled finishes and is settled;
|
async fn pull_once(&mut self) -> Result<()> {
|
||||||
/// 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<()> {
|
|
||||||
if let Ok(info) = self.events.info().await {
|
if let Ok(info) = self.events.info().await {
|
||||||
self.metrics
|
self.metrics
|
||||||
.consumer(info.num_pending, info.num_ack_pending, info.num_redelivered);
|
.consumer(info.num_pending, info.num_ack_pending, info.num_redelivered);
|
||||||
|
|
@ -213,10 +199,7 @@ impl Router {
|
||||||
.await
|
.await
|
||||||
.context("requesting a batch")?;
|
.context("requesting a batch")?;
|
||||||
let batch = batch.map(|m| m.map_err(|e| anyhow::anyhow!("{e}")));
|
let batch = batch.map(|m| m.map_err(|e| anyhow::anyhow!("{e}")));
|
||||||
settle::batch(batch, stop, async |m: &jetstream::Message| {
|
settle::batch(batch, async |m: &jetstream::Message| self.handle(m).await).await
|
||||||
self.handle(m).await
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle one event and count how it went.
|
/// Handle one event and count how it went.
|
||||||
|
|
|
||||||
|
|
@ -33,15 +33,11 @@ impl Pulled for async_nats::jetstream::Message {
|
||||||
/// Handle each event of `batch` with `handle` and settle it. Returns the
|
/// 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
|
/// error of the first event that has to be retried, once the rest of the
|
||||||
/// batch is nakked behind it.
|
/// 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<P: Pulled>(
|
pub(crate) async fn batch<P: Pulled>(
|
||||||
batch: impl Stream<Item = Result<P>>,
|
batch: impl Stream<Item = Result<P>>,
|
||||||
stop: impl Future<Output = ()>,
|
|
||||||
mut handle: impl AsyncFnMut(&P) -> Result<(), Skip>,
|
mut handle: impl AsyncFnMut(&P) -> Result<(), Skip>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let mut batch = std::pin::pin!(batch.take_until(stop));
|
let mut batch = std::pin::pin!(batch);
|
||||||
let mut failed: Option<anyhow::Error> = None;
|
let mut failed: Option<anyhow::Error> = None;
|
||||||
while let Some(event) = batch.next().await {
|
while let Some(event) = batch.next().await {
|
||||||
let event = event?;
|
let event = event?;
|
||||||
|
|
@ -106,18 +102,14 @@ mod tests {
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
let mut handled = Vec::new();
|
let mut handled = Vec::new();
|
||||||
let result = batch(
|
let result = batch(futures_util::stream::iter(events), async |e: &Fake<'_>| {
|
||||||
futures_util::stream::iter(events),
|
|
||||||
std::future::pending(),
|
|
||||||
async |e: &Fake<'_>| {
|
|
||||||
handled.push(e.name);
|
handled.push(e.name);
|
||||||
if e.name == "assigned" {
|
if e.name == "assigned" {
|
||||||
Err(Skip::Retry(anyhow::anyhow!("the queue is down")))
|
Err(Skip::Retry(anyhow::anyhow!("the queue is down")))
|
||||||
} else {
|
} else {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
},
|
})
|
||||||
)
|
|
||||||
.await;
|
.await;
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
assert_eq!(handled, ["opened", "assigned"]);
|
assert_eq!(handled, ["opened", "assigned"]);
|
||||||
|
|
@ -143,17 +135,13 @@ mod tests {
|
||||||
settled: &settled,
|
settled: &settled,
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
let result = batch(
|
let result = batch(futures_util::stream::iter(events), async |e: &Fake<'_>| {
|
||||||
futures_util::stream::iter(events),
|
|
||||||
std::future::pending(),
|
|
||||||
async |e: &Fake<'_>| {
|
|
||||||
if e.name == "bad" {
|
if e.name == "bad" {
|
||||||
Err(Skip::Unusable("no".to_owned()))
|
Err(Skip::Unusable("no".to_owned()))
|
||||||
} else {
|
} else {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
},
|
})
|
||||||
)
|
|
||||||
.await;
|
.await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
assert_eq!(
|
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)),
|
|
||||||
]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -47,7 +47,6 @@ fn main() -> Result<()> {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn serve() -> Result<()> {
|
async fn serve() -> Result<()> {
|
||||||
let stop = swarm_secret_client::shutdown_signal();
|
|
||||||
hive_log::init();
|
hive_log::init();
|
||||||
swarm_secret_client::install_crypto_provider();
|
swarm_secret_client::install_crypto_provider();
|
||||||
let var = |name: &str| {
|
let var = |name: &str| {
|
||||||
|
|
@ -93,8 +92,7 @@ async fn serve() -> Result<()> {
|
||||||
let mut requests = queue
|
let mut requests = queue
|
||||||
.queue_subscribe(SUBJECT, QUEUE_GROUP.to_owned())
|
.queue_subscribe(SUBJECT, QUEUE_GROUP.to_owned())
|
||||||
.await
|
.await
|
||||||
.with_context(|| format!("subscribing to {SUBJECT}"))?
|
.with_context(|| format!("subscribing to {SUBJECT}"))?;
|
||||||
.take_until(stop.clone());
|
|
||||||
tracing::info!(subject = SUBJECT, "review classifier: awaiting try-outs");
|
tracing::info!(subject = SUBJECT, "review classifier: awaiting try-outs");
|
||||||
|
|
||||||
let models = std::sync::Arc::new(models);
|
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")
|
||||||
bail!("the subscription to {SUBJECT} ended");
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Decode one request, answer it and log the run.
|
/// Decode one request, answer it and log the run.
|
||||||
|
|
|
||||||
|
|
@ -47,8 +47,6 @@ workspace = true
|
||||||
# provider compiled in rustls picks it without an install, so the provider
|
# provider compiled in rustls picks it without an install, so the provider
|
||||||
# test would pass with `install_crypto_provider` doing nothing.
|
# test would pass with `install_crypto_provider` doing nothing.
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
# `raise`, to send the test process a real SIGTERM.
|
|
||||||
libc.workspace = true
|
|
||||||
# `InMemoryMetricExporter`, to read back what `cert_metrics` exports.
|
# `InMemoryMetricExporter`, to read back what `cert_metrics` exports.
|
||||||
opentelemetry_sdk = { workspace = true, features = ["testing"] }
|
opentelemetry_sdk = { workspace = true, features = ["testing"] }
|
||||||
rustls = { workspace = true, features = ["ring"] }
|
rustls = { workspace = true, features = ["ring"] }
|
||||||
|
|
|
||||||
|
|
@ -55,12 +55,10 @@ pub mod policy;
|
||||||
pub mod proxy;
|
pub mod proxy;
|
||||||
pub mod queue;
|
pub mod queue;
|
||||||
pub mod review_classifier;
|
pub mod review_classifier;
|
||||||
pub mod shutdown;
|
|
||||||
pub mod startup_read;
|
pub mod startup_read;
|
||||||
pub mod stored_secret;
|
pub mod stored_secret;
|
||||||
|
|
||||||
pub use client::SecretStore;
|
pub use client::SecretStore;
|
||||||
pub use shutdown::{DRAIN, InFlight, Shutdown, serve_bounded, shutdown_signal};
|
|
||||||
pub use startup_read::read_with_startup_retry;
|
pub use startup_read::read_with_startup_retry;
|
||||||
|
|
||||||
/// What can go wrong between "we have a client certificate" and "we have the
|
/// What can go wrong between "we have a client certificate" and "we have the
|
||||||
|
|
|
||||||
|
|
@ -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<BoxFuture<'static, ()>>;
|
|
||||||
|
|
||||||
/// 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<T>(
|
|
||||||
stop: impl Future<Output = ()>,
|
|
||||||
serving: impl Future<Output = T>,
|
|
||||||
) -> Option<T> {
|
|
||||||
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<Output = ()> + 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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -115,7 +115,6 @@ async fn connect_queue(var: Var<'_>) -> Result<async_nats::Client> {
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<()> {
|
async fn main() -> Result<()> {
|
||||||
let stop = swarm_secret_client::shutdown_signal();
|
|
||||||
hive_log::init();
|
hive_log::init();
|
||||||
swarm_secret_client::install_crypto_provider();
|
swarm_secret_client::install_crypto_provider();
|
||||||
let var = |name: &str| {
|
let var = |name: &str| {
|
||||||
|
|
@ -152,8 +151,7 @@ async fn main() -> Result<()> {
|
||||||
let mut requests = queue
|
let mut requests = queue
|
||||||
.queue_subscribe(subject_wildcard(), QUEUE_GROUP.to_owned())
|
.queue_subscribe(subject_wildcard(), QUEUE_GROUP.to_owned())
|
||||||
.await
|
.await
|
||||||
.context("subscribing to the request subject")?
|
.context("subscribing to the request subject")?;
|
||||||
.take_until(stop.clone());
|
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
subject = subject_wildcard(),
|
subject = subject_wildcard(),
|
||||||
"swarm-stt: answering requests"
|
"swarm-stt: answering requests"
|
||||||
|
|
@ -209,10 +207,7 @@ async fn main() -> Result<()> {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if stop.peek().is_none() {
|
bail!("the request subscription ended")
|
||||||
bail!("the request subscription ended");
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One agent's place among the requests in flight; dropping it frees the place.
|
/// One agent's place among the requests in flight; dropping it frees the place.
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue