Files
leleka/crates/deploy/src/supervisor/api.rs
T

95 lines
3.1 KiB
Rust

//! The public API process: readiness wait, answers to the operator and restart.
use super::*;
impl ServiceSupervisor {
pub(super) async fn wait_api_ready(&mut self, api: &mut Child) -> Result<(), Flow> {
let started = Instant::now();
loop {
if self.stopping() {
return Err(Flow::Stopped);
}
self.fail_if_api_exited(api)?;
if let Some(answer) = self.ready_answer().await {
return answer;
}
if started.elapsed() > Duration::from_secs(180) {
return fail(
1,
"the API was not ready within 180 s after the model loaded",
);
}
if !self.pause(Duration::from_secs(1)).await {
return Err(Flow::Stopped);
}
}
}
fn fail_if_api_exited(&self, api: &mut Child) -> Result<(), Flow> {
if let Ok(Some(status)) = api.try_wait() {
return fail(
1,
format!(
"the API exited ({status}); see {}",
self.paths.logs().join("api.log").display()
),
);
}
Ok(())
}
/// One look at `/ready`: `Some` when it settles the wait (ready, or the key is rejected), `None` to keep waiting.
async fn ready_answer(&self) -> Option<Result<(), Flow>> {
let response = http::get(
self.api_addr,
"/ready",
Some(&self.api_key),
Duration::from_secs(5),
)
.await
.ok()?;
if response.status == 200 {
return Some(Ok(()));
}
if response.status == 401 || response.status == 403 {
return Some(fail(1, "the API rejected the key in the api-key file"));
}
None
}
/// Leave the supervisor answer to a reconfigure request (best effort: the CLI times out without one).
pub(super) fn answer(
&self,
id: &str,
state: reconfigure::State,
message: impl Into<String>,
persisted: bool,
) {
let outcome = reconfigure::Outcome {
id: id.to_owned(),
state,
message: message.into(),
effective: Some(reconfigure::effective(&self.config)),
persisted,
};
if let Err(error) = reconfigure::write_outcome(&self.paths, &outcome) {
self.log
.line(&format!("reconfigure: cannot write the answer: {error}"));
}
}
/// Stop the API process and start it again (its configuration changed). The port stays the same.
pub(super) async fn restart_api(&mut self, api: &mut Child) -> Result<(), Flow> {
self.kill_children(&mut [Some(&mut *api)]).await;
let args = vec![
"serve".to_owned(),
"--config".to_owned(),
self.paths.strata_config().display().to_string(),
];
let program = self.paths.bin("strata-next");
*api = self.spawn("api", ChildSpec::plain(&program, &args))?;
self.pids[2] = api.id();
self.wait_api_ready(api).await
}
}