use std::time::Duration;
use crate::{
platform, process,
project::{VerifyOptions, selection::Selection},
runs::{CancelAcknowledgement, Context, RunObservation},
types::{RequestKey, RunId},
};
use super::transport::{
ClientFrame, EngineEndpoint, ServerFrame, Stream, VERSION, read_frame, write_frame,
};
const START_TIMEOUT: Duration = Duration::from_secs(30);
const RETRY_INITIAL: Duration = Duration::from_millis(15);
const RETRY_CAP: Duration = Duration::from_millis(100);
const RESPAWN_AFTER: Duration = Duration::from_secs(1);
const RPC_TIMEOUT: Duration = Duration::from_secs(60);
struct Connected {
stream: Stream,
}
async fn connect_once(
endpoint: &EngineEndpoint,
request_idle_shutdown_on_mismatch: bool,
) -> Result<Handshake, std::io::Error> {
let mut stream = endpoint.connect().await?;
write_frame(
&mut stream,
&ClientFrame::Hello {
version: VERSION,
identity: endpoint.identity.clone(),
},
)
.await?;
let reply: ServerFrame = read_frame(&mut stream).await?;
Ok(match reply {
ServerFrame::Welcome {
version: VERSION, ..
} => Handshake::Ready(Connected { stream }),
ServerFrame::Welcome { version, .. } => Handshake::Incompatible(version),
ServerFrame::Incompatible { server_version } => {
if request_idle_shutdown_on_mismatch
&& write_frame(&mut stream, &ClientFrame::ShutdownIfIdle)
.await
.is_ok()
&& matches!(read_frame(&mut stream).await, Ok(ServerFrame::Ack))
{
Handshake::ShuttingDown
} else {
Handshake::Incompatible(server_version)
}
}
ServerFrame::ShuttingDown => Handshake::ShuttingDown,
other => {
return Err(std::io::Error::other(format!(
"Unexpected Verify engine handshake reply: {other:?}"
)));
}
})
}
enum Handshake {
Ready(Connected),
ShuttingDown,
Incompatible(u32),
}
async fn try_connect_existing(endpoint: &EngineEndpoint) -> Result<Option<Connected>, String> {
match tokio::time::timeout(RPC_TIMEOUT, connect_once(endpoint, false)).await {
Ok(Ok(Handshake::Ready(connected))) => Ok(Some(connected)),
Ok(Ok(Handshake::ShuttingDown)) | Ok(Err(_)) | Err(_) => Ok(None),
Ok(Ok(Handshake::Incompatible(server_version))) => Err(format!(
"Verify engine protocol mismatch: client expects version {VERSION}, running engine serves version {server_version}."
)),
}
}
async fn connect_or_start(context: &Context) -> Result<Connected, String> {
crate::workspace::prepare_directory(&context.state, &context.repo)
.map_err(|error| error.to_string())?;
let endpoint = EngineEndpoint::new(&context.state).map_err(|error| error.to_string())?;
let deadline = tokio::time::Instant::now() + START_TIMEOUT;
let mut backoff = RETRY_INITIAL;
let mut last_spawn: Option<tokio::time::Instant> = None;
loop {
match tokio::time::timeout(RPC_TIMEOUT, connect_once(&endpoint, true)).await {
Ok(Ok(Handshake::Ready(connected))) => return Ok(connected),
Ok(Ok(Handshake::ShuttingDown)) => {
last_spawn = None;
}
Ok(Ok(Handshake::Incompatible(server_version))) => {
return Err(format!(
"Verify engine protocol mismatch: client expects version {VERSION}, running engine serves version {server_version} and has active Runs."
));
}
Ok(Err(_)) => {
if last_spawn.is_none_or(|at| at.elapsed() >= RESPAWN_AFTER)
&& !endpoint.is_locked()
{
process::launch_engine(&context.executable, &context.state, &context.repo)
.map_err(|error| format!("Verify engine handoff failed: {error}"))?;
last_spawn = Some(tokio::time::Instant::now());
}
}
Err(_) => {
return Err("Timed out connecting to the Verify engine.".into());
}
}
if tokio::time::Instant::now() >= deadline {
return Err("Timed out waiting for the Verify engine to start.".into());
}
tokio::time::sleep(backoff).await;
backoff = (backoff * 2).min(RETRY_CAP);
}
}
pub(crate) async fn submit_run(
context: &Context,
selection: &Selection,
options: &VerifyOptions,
request_key: Option<RequestKey>,
request_args_hash: Option<String>,
mut launched: impl FnMut(&RunId, process::ChildIdentity),
) -> Result<RunObservation, String> {
crate::store::receipts::check_existing_state(&context.state)?;
if let Some(key) = &request_key
&& let Some(existing) = crate::store::run_control::read_keyed_run(
&context.state,
&context.repo,
key,
request_args_hash.as_deref(),
)
.await?
{
return crate::runs::status(context, &existing).await;
}
crate::project::verify::validate_submission(&context.repo, &context.state, selection, options)?;
let env = platform::environment::snapshot_text();
let deadline = tokio::time::Instant::now() + START_TIMEOUT;
loop {
let mut connected = connect_or_start(context).await?;
let frame = ClientFrame::SubmitRun {
repo: context.repo.clone(),
selection: selection.clone(),
options: Box::new(options.clone()),
env: env.clone(),
request_key: request_key.clone(),
request_args_hash: request_args_hash.clone(),
origin: context.origin.clone(),
};
let wrote = tokio::time::timeout(RPC_TIMEOUT, write_frame(&mut connected.stream, &frame))
.await
.map_err(|_| "Timed out sending Run submission to the Verify engine.".to_owned())?;
if let Err(error) = wrote {
if tokio::time::Instant::now() < deadline {
tokio::time::sleep(RETRY_INITIAL).await;
continue;
}
return Err(error.to_string());
}
let reply = tokio::time::timeout(
RPC_TIMEOUT,
read_frame::<_, ServerFrame>(&mut connected.stream),
)
.await
.map_err(|_| "Timed out waiting for Verify engine submission reply.".to_owned())?;
match reply {
Ok(ServerFrame::Submitted {
run,
accepted,
owner,
}) => {
if accepted {
launched(&run, owner);
}
return crate::runs::status(context, &run).await;
}
Ok(ServerFrame::ShuttingDown) if tokio::time::Instant::now() < deadline => {
tokio::time::sleep(RETRY_INITIAL).await;
continue;
}
Ok(ServerFrame::Error(message)) => return Err(message),
Ok(other) => {
return Err(format!(
"Unexpected Verify engine reply to submission: {other:?}"
));
}
Err(error) if request_key.is_some() && tokio::time::Instant::now() < deadline => {
let _ = error;
tokio::time::sleep(RETRY_INITIAL).await;
continue;
}
Err(error) => return Err(error.to_string()),
}
}
}
pub(crate) async fn cancel_run(
context: &Context,
id: &RunId,
) -> Result<Option<CancelAcknowledgement>, String> {
let Ok(endpoint) = EngineEndpoint::new(&context.state) else {
return Ok(None);
};
let Some(mut connected) = try_connect_existing(&endpoint).await? else {
return Ok(None);
};
let result = tokio::time::timeout(RPC_TIMEOUT, async {
write_frame(
&mut connected.stream,
&ClientFrame::CancelRun {
repo: context.repo.clone(),
run_id: id.clone(),
},
)
.await
.map_err(|error| error.to_string())?;
read_frame::<_, ServerFrame>(&mut connected.stream)
.await
.map_err(|error| error.to_string())
})
.await;
match result {
Ok(Ok(ServerFrame::Cancelled(ack))) => Ok(Some(ack)),
Ok(Ok(ServerFrame::Error(message))) => Err(message),
Ok(Ok(ServerFrame::ShuttingDown)) | Ok(Err(_)) | Err(_) => Ok(None),
Ok(Ok(other)) => Err(format!(
"Unexpected Verify engine reply to cancel: {other:?}"
)),
}
}