use super::DaemonClient;
use crate::session_manager::{RegistrationReport, SupervisorRegistration};
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RegisterCallError {
#[error("the daemon is unreachable: {0}")]
Unreachable(String),
#[error("the daemon refused the registration ({status}): {reason}")]
Refused {
status: u16,
reason: String,
},
#[error("the registration call failed: {0}")]
Failed(String),
}
impl DaemonClient {
pub async fn register_supervisor(
&self,
reg: &SupervisorRegistration,
) -> Result<RegistrationReport, RegisterCallError> {
let resp = match self
.post("/api/v1/sessions/managed/supervisor")
.json(reg)
.send()
.await
{
Ok(resp) => resp,
Err(e) if e.is_connect() => return Err(RegisterCallError::Unreachable(e.to_string())),
Err(e) => return Err(RegisterCallError::Failed(format!("{e:#}"))),
};
let status = resp.status();
if !status.is_success() {
let reason = resp.text().await.unwrap_or_default();
return Err(RegisterCallError::Refused {
status: status.as_u16(),
reason,
});
}
resp.json()
.await
.map_err(|e| RegisterCallError::Failed(format!("unreadable answer: {e:#}")))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn a_registration_call_to_an_absent_socket_is_unreachable() {
let dir = crate::test_support::hermetic_temp_dir();
let client = DaemonClient::over_socket(dir.path().join("absent.sock"));
let reg = SupervisorRegistration {
dir: dir.path().to_path_buf(),
session: "tm-arch".into(),
poll_session: None,
collector_session: None,
};
let err = client
.register_supervisor(®)
.await
.expect_err("no daemon");
assert!(matches!(err, RegisterCallError::Unreachable(_)), "{err:?}");
}
}