use std::{
collections::BTreeMap,
fs::File,
io,
path::{Path, PathBuf},
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use crate::{
platform::{self, ipc as os},
process::ChildIdentity,
project::{VerifyOptions, selection::Selection},
runs::{CancelAcknowledgement, Origin},
types::{RequestKey, RunId},
};
pub(super) use os::{Listener, Stream, validate_peer};
pub(super) const VERSION: u32 = 1;
const MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
#[derive(Clone)]
pub(super) struct EngineEndpoint {
pub identity: crate::config::EndpointId,
directory: PathBuf,
address: PathBuf,
}
impl EngineEndpoint {
pub fn new(state: &Path) -> io::Result<Self> {
let state = platform::paths::ipc_identity(state)?;
let user = os::user()?;
let mut digest = Sha256::new();
digest.update(user.as_bytes());
digest.update([0]);
digest.update(state);
let identity: crate::config::EndpointId = digest
.finalize()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>()
.parse()
.expect("SHA-256 endpoint identity");
let directory = os::directory(&identity, &user)?;
let address = os::engine_address(&directory, &identity);
let endpoint = Self {
identity,
directory,
address,
};
endpoint.validate()?;
Ok(endpoint)
}
fn validate(&self) -> io::Result<()> {
os::validate_directory(&self.directory)
}
pub fn take_owner(&self) -> io::Result<Option<File>> {
self.validate()?;
let file = platform::open_no_follow(
platform::private_options()
.read(true)
.write(true)
.create(true)
.truncate(false),
&self.directory.join("engine.lock"),
)?;
if !platform::is_private_file(&file)? || !os::owned(&file)? {
return Err(io::ErrorKind::PermissionDenied.into());
}
match platform::paths::try_lock(&file) {
Ok(()) => Ok(Some(file)),
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
Err(std::fs::TryLockError::Error(error)) => Err(error),
}
}
pub fn is_locked(&self) -> bool {
matches!(self.take_owner(), Ok(None))
}
pub fn listen(&self) -> io::Result<Listener> {
self.validate()?;
os::listen(&self.address)
}
pub async fn connect(&self) -> io::Result<Stream> {
self.validate()?;
os::connect(&self.address).await
}
}
#[derive(Debug, Serialize, Deserialize)]
pub(super) enum ClientFrame {
Hello {
version: u32,
identity: crate::config::EndpointId,
},
SubmitRun {
#[serde(with = "crate::platform::path_serde")]
repo: PathBuf,
selection: Selection,
options: Box<VerifyOptions>,
env: BTreeMap<String, String>,
request_key: Option<RequestKey>,
request_args_hash: Option<String>,
origin: Origin,
},
CancelRun {
#[serde(with = "crate::platform::path_serde")]
repo: PathBuf,
run_id: RunId,
},
ShutdownIfIdle,
}
#[derive(Debug, Serialize, Deserialize)]
pub(super) enum ServerFrame {
Welcome {
version: u32,
owner: ChildIdentity,
},
Incompatible {
server_version: u32,
},
ShuttingDown,
Submitted {
run: RunId,
accepted: bool,
owner: ChildIdentity,
},
Cancelled(CancelAcknowledgement),
Ack,
Busy,
Error(String),
}
pub(super) async fn read_frame<R: AsyncRead + Unpin, T: serde::de::DeserializeOwned>(
reader: &mut R,
) -> io::Result<T> {
let bytes = reader.read_u32().await? as usize;
if bytes == 0 || bytes > MAX_FRAME_BYTES {
return Err(io::ErrorKind::InvalidData.into());
}
let mut data = vec![0; bytes];
reader.read_exact(&mut data).await?;
serde_json::from_slice(&data).map_err(io::Error::other)
}
pub(super) async fn write_frame<W: AsyncWrite + Unpin, T: Serialize>(
writer: &mut W,
frame: &T,
) -> io::Result<()> {
let data = serde_json::to_vec(frame).map_err(io::Error::other)?;
if data.len() > MAX_FRAME_BYTES {
return Err(io::ErrorKind::InvalidData.into());
}
writer.write_u32(data.len() as u32).await?;
writer.write_all(&data).await?;
writer.flush().await
}