Watch
0
0
Fork
You've already forked hyperhive
0

swarm-claude-login: export login step, duration, expiry and active session metrics

This commit is contained in:
damocles 2026-11-04 22:59:29 +01:00 • committed by mara
commit 652c0e9614

View file

@ -13,15 +13,18 @@
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;
use anyhow::{Context, Result, bail};
use futures_util::StreamExt as _;
use metrics::Metrics;
use swarm_queue_client::{ClientSecret, QueueConfig};
use swarm_secret_client::claude_login::{Credentials, client_secret_path, credentials_path};
use swarm_secret_client::stored_secret::StoredSecret;
use swarm_wire::claude_login::{Reply, Request, SESSION_DEADLINE, STEP_DEADLINE, SUBJECT};
mod login;
mod metrics;
/// The cert-auth role this service logs in to the store as. `swarm-bao.nix`
/// writes it, matching the leaf's subject.
@ -57,6 +60,7 @@ async fn main() -> Result<()> {
std::env::var(&full).with_context(|| format!("{full} is unset"))
};
let client_id = var("OIDC_CLIENT_ID")?;
let metrics = Arc::new(Metrics::from_env());
let logins = Arc::new(login::Logins::new(
PathBuf::from(var("CLAUDE")?),
std::env::temp_dir(),
@ -97,8 +101,9 @@ async fn main() -> Result<()> {
};
let queue = queue.clone();
let logins = Arc::clone(&logins);
let metrics = Arc::clone(&metrics);
tokio::spawn(async move {
let reply = handle(&msg.payload, &logins).await;
let reply = handle(&msg.payload, &logins, &metrics).await;
match serde_json::to_vec(&reply) {
Ok(body) => {
if let Err(e) = queue.publish(reply_to, body.into()).await {
@ -112,15 +117,28 @@ async fn main() -> Result<()> {
bail!("the subscription to {SUBJECT} ended")
}
/// Decode one step, run it and log it. Never logs the code or the URL.
async fn handle(payload: &[u8], logins: &Arc<login::Logins>) -> Reply {
/// Answer one step and count it.
async fn handle(payload: &[u8], logins: &Arc<login::Logins>, metrics: &Arc<Metrics>) -> Reply {
let started = Instant::now();
let (step, reply) = run_step(payload, logins, metrics).await;
metrics.step(step, &reply, started.elapsed());
metrics.active(logins.active().await);
reply
}
/// Decode one step, run it and log it, with the kind of step it was. Never
/// logs the code or the URL.
async fn run_step(
payload: &[u8],
logins: &Arc<login::Logins>,
metrics: &Arc<Metrics>,
) -> (&'static str, Reply) {
let request: Request = match serde_json::from_slice(payload) {
Ok(r) => r,
Err(e) => {
tracing::warn!(error = %e, "an undecodable login step; answering with the error");
return Reply::Failed {
error: format!("the minter could not decode the request: {e}"),
};
let error = format!("the minter could not decode the request: {e}");
return ("invalid", Reply::Failed { error });
}
};
// Before anything else: the name becomes a scratch directory's name and
@ -129,31 +147,34 @@ async fn handle(payload: &[u8], logins: &Arc<login::Logins>) -> Reply {
&request;
if let Err(reason) = hive_types::Ident::parse(agent) {
tracing::warn!(agent = ?agent, reason, "a login step for an invalid agent name; refused");
return Reply::Failed {
error: format!("{agent:?} is not an agent name: {reason}"),
};
let error = format!("{agent:?} is not an agent name: {reason}");
return ("invalid", Reply::Failed { error });
}
let (agent, reply) = match request {
let (step, agent, reply) = match request {
Request::Start { agent, operator } => {
tracing::info!(%agent, %operator, "starting a claude login");
let (reply, id) = logins.start(&agent).await;
if let Some(id) = id {
let logins = Arc::clone(logins);
let expiring = agent.clone();
let metrics = Arc::clone(metrics);
tokio::spawn(async move {
tokio::time::sleep(SESSION_DEADLINE).await;
logins.expire(&expiring, id).await;
if logins.expire(&expiring, id).await {
metrics.expired();
metrics.active(logins.active().await);
}
});
}
(agent, reply)
("start", agent, reply)
}
Request::Code { agent, code } => {
let reply = logins.code(&agent, &code, &AgentLeaf).await;
(agent, reply)
("code", agent, reply)
}
Request::Cancel { agent } => {
let reply = logins.cancel(&agent).await;
(agent, reply)
("cancel", agent, reply)
}
};
match &reply {
@ -162,7 +183,7 @@ async fn handle(payload: &[u8], logins: &Arc<login::Logins>) -> Reply {
Reply::Cancelled => tracing::info!(%agent, "claude login cancelled"),
Reply::Failed { error } => tracing::warn!(%agent, %error, "claude login step failed"),
}
reply
(step, reply)
}
async fn client_secret(client_id: &str) -> Result<String> {
@ -192,7 +213,7 @@ mod tests {
use swarm_wire::claude_login::{Reply, Request};
use super::{handle, login};
use super::{Metrics, handle, login};
#[tokio::test]
async fn a_step_for_an_invalid_agent_name_is_refused_before_anything_is_made() {
@ -223,7 +244,7 @@ mod tests {
},
] {
let payload = serde_json::to_vec(&request).expect("encodes");
let reply = handle(&payload, &logins).await;
let reply = handle(&payload, &logins, &Arc::new(Metrics::noop())).await;
assert!(
matches!(reply, Reply::Failed { .. }),
"{agent:?}: {reply:?}"
@ -247,7 +268,7 @@ mod tests {
})
.expect("encodes");
assert!(matches!(
handle(&payload, &logins).await,
handle(&payload, &logins, &Arc::new(Metrics::noop())).await,
Reply::Started { .. }
));
drop(logins);