use super::{
area_rpc::SessionRoutes,
client::{encode_frame, read_frame, write_frame},
daemon::DaemonAdministration,
protocol::*,
service::HostService,
CatalogError,
};
use std::{collections::BTreeMap, path::PathBuf, sync::Arc, time::Duration};
use tokio::{
net::{UnixListener, UnixStream},
task::{JoinHandle, JoinSet},
time::Instant,
};
use tokio_util::sync::CancellationToken;
type SessionRoutesByAgent = BTreeMap<super::AgentId, Option<Arc<tokio::sync::Mutex<()>>>>;
#[derive(Clone, Default)]
struct ControlAuthority {
administration: Option<DaemonAdministration>,
mini: Option<super::mini_control::MiniControl>,
session_rpc: Arc<SessionRoutesByAgent>,
idle_timeout: Option<Duration>,
}
#[derive(Clone)]
pub struct ControlConfig {
pub socket_path: PathBuf,
pub host_id: HostId,
pub token: AuthToken,
pub max_connections: usize,
pub handshake_timeout: Duration,
pub request_timeout: Duration,
}
impl ControlConfig {
pub fn validate(&self) -> Result<(), ServerError> {
if !self.socket_path.is_absolute()
|| !(1..=64).contains(&self.max_connections)
|| [self.handshake_timeout, self.request_timeout]
.iter()
.any(|duration| duration.is_zero() || *duration > Duration::from_secs(300))
{
return Err(ServerError::InvalidConfiguration);
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ServerError {
#[error("invalid shared Host control configuration")]
InvalidConfiguration,
#[error("shared Host endpoint must be absent, with a private owned parent")]
UnsafeEndpoint,
#[error("shared Host endpoint could not be bound")]
Bind,
#[error("shared Host control listener stopped unexpectedly")]
ListenerStopped,
#[error("shared Host control task stopped unexpectedly")]
TaskStopped,
}
pub(super) struct SocketLease {
path: PathBuf,
dev: u64,
ino: u64,
unlink_on_drop: bool,
}
impl SocketLease {
#[cfg(target_os = "macos")]
pub(super) fn identity(&self) -> (u64, u64) {
(self.dev, self.ino)
}
#[cfg(target_os = "macos")]
pub(super) fn inherited(path: PathBuf, (dev, ino): (u64, u64)) -> Self {
Self {
path,
dev,
ino,
unlink_on_drop: false,
}
}
pub(super) fn remove(&self) {
use std::os::unix::fs::{FileTypeExt, MetadataExt};
if let Ok(metadata) = std::fs::symlink_metadata(&self.path) {
if metadata.file_type().is_socket()
&& metadata.dev() == self.dev
&& metadata.ino() == self.ino
{
let _ = std::fs::remove_file(&self.path);
}
}
}
}
impl Drop for SocketLease {
fn drop(&mut self) {
if self.unlink_on_drop {
self.remove();
}
}
}
pub(super) fn bind_endpoint(
path: PathBuf,
) -> Result<(std::os::unix::net::UnixListener, SocketLease), ServerError> {
use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
let parent = path.parent().ok_or(ServerError::InvalidConfiguration)?;
let metadata = std::fs::symlink_metadata(parent).map_err(|_| ServerError::UnsafeEndpoint)?;
if !metadata.is_dir()
|| metadata.uid() != nix::unistd::Uid::effective().as_raw()
|| metadata.mode() & 0o077 != 0
{
return Err(ServerError::UnsafeEndpoint);
}
match std::fs::symlink_metadata(&path) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
_ => return Err(ServerError::UnsafeEndpoint),
}
let listener = std::os::unix::net::UnixListener::bind(&path).map_err(|_| ServerError::Bind)?;
let metadata = std::fs::symlink_metadata(&path).map_err(|_| ServerError::Bind)?;
let lease = SocketLease {
path: path.clone(),
dev: metadata.dev(),
ino: metadata.ino(),
unlink_on_drop: true,
};
if !metadata.file_type().is_socket()
|| metadata.nlink() != 1
|| metadata.uid() != nix::unistd::Uid::effective().as_raw()
{
return Err(ServerError::UnsafeEndpoint);
}
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
.map_err(|_| ServerError::Bind)?;
listener
.set_nonblocking(true)
.map_err(|_| ServerError::Bind)?;
Ok((listener, lease))
}
pub struct ControlServer {
welcome: Welcome,
stop: CancellationToken,
task: Option<JoinHandle<Result<ControlExit, ServerError>>>,
terminal: Option<Result<ControlExit, ServerError>>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum ControlExit {
Stopped,
AdministrativeStop,
Idle,
}
impl ControlServer {
pub async fn bind(config: ControlConfig, service: HostService) -> Result<Self, ServerError> {
Self::bind_with_administration(config, service, None).await
}
pub(crate) async fn bind_with_administration(
config: ControlConfig,
service: HostService,
administration: Option<DaemonAdministration>,
) -> Result<Self, ServerError> {
Self::bind_with_controls(
config,
service,
administration,
None,
None,
SessionRoutes::default(),
None,
)
.await
}
pub(super) async fn bind_with_controls(
config: ControlConfig,
service: HostService,
administration: Option<DaemonAdministration>,
mini: Option<super::mini_control::MiniControl>,
inherited: Option<std::os::unix::net::UnixListener>,
routes: SessionRoutes,
idle_timeout: Option<Duration>,
) -> Result<Self, ServerError> {
config.validate()?;
if routes.restore_on_attach && administration.is_none() {
return Err(ServerError::InvalidConfiguration);
}
for &id in &routes.agents {
let record = service
.catalog()
.get(id)
.await
.map_err(|_| ServerError::InvalidConfiguration)?;
if record.spec.mode != super::AgentMode::Persistent {
return Err(ServerError::InvalidConfiguration);
}
match service.ordinary_client(id) {
Ok(client) => match client.area_session(false).await {
Ok(_) | Err(super::ordinary::BackendError::Closed) => (),
Err(_) => return Err(ServerError::InvalidConfiguration),
},
Err(
super::service::ServiceError::Busy | super::service::ServiceError::NotLoaded,
) => (),
Err(_) => return Err(ServerError::InvalidConfiguration),
}
}
let authority = ControlAuthority {
administration,
mini,
session_rpc: Arc::new(
routes
.agents
.into_iter()
.map(|id| {
(
id,
routes
.restore_on_attach
.then(|| Arc::new(tokio::sync::Mutex::new(()))),
)
})
.collect(),
),
idle_timeout,
};
let (listener, lease) = match inherited {
Some(listener) => (listener, None),
None => {
let path = config.socket_path.clone();
let (listener, lease) = tokio::task::spawn_blocking(move || bind_endpoint(path))
.await
.map_err(|_| ServerError::TaskStopped)??;
(listener, Some(lease))
}
};
let listener = UnixListener::from_std(listener).map_err(|_| ServerError::Bind)?;
let mut welcome = Welcome {
protocol: PROTOCOL.into(),
version: Version::default(),
host_id: config.host_id,
epoch: String::from(service.catalog().epoch())
.try_into()
.map_err(|_| ServerError::InvalidConfiguration)?,
capabilities: vec![
Capability::Status,
Capability::List,
Capability::Inspect,
Capability::Receipts,
Capability::Results,
Capability::Submit,
],
limits: Limits {
max_in_flight: 1,
..Limits::default()
},
};
if authority.mini.is_some() {
welcome.capabilities.push(Capability::Mini);
}
if authority.administration.is_some() {
welcome.capabilities.extend([
Capability::Profiles,
Capability::AdministrativeReceipts,
Capability::AdministrativeCreate,
Capability::AdministrativeRestore,
Capability::AdministrativeClose,
Capability::AdministrativeCancel,
Capability::AdministrativeStop,
]);
}
let stop = CancellationToken::new();
let task = tokio::spawn(serve(
listener,
lease,
config,
service,
authority,
welcome.clone(),
stop.clone(),
));
Ok(Self {
welcome,
stop,
task: Some(task),
terminal: None,
})
}
pub fn welcome(&self) -> &Welcome {
&self.welcome
}
pub fn stopped_by_administration(&self) -> bool {
matches!(self.terminal, Some(Ok(ControlExit::AdministrativeStop)))
}
pub(super) fn stopped_for_idleness(&self) -> bool {
matches!(self.terminal, Some(Ok(ControlExit::Idle)))
}
pub async fn wait(&mut self) -> Result<(), ServerError> {
if let Some(result) = self.terminal {
return result.map(|_| ());
}
let result = match self.task.as_mut() {
Some(task) => task.await.unwrap_or(Err(ServerError::TaskStopped)),
None => Ok(ControlExit::Stopped),
};
self.task.take();
self.terminal = Some(result);
result.map(|_| ())
}
pub async fn stop(&mut self) -> Result<(), ServerError> {
self.stop.cancel();
self.wait().await
}
}
impl Drop for ControlServer {
fn drop(&mut self) {
self.stop.cancel();
}
}
async fn serve(
listener: UnixListener,
lease: Option<SocketLease>,
config: ControlConfig,
service: HostService,
authority: ControlAuthority,
welcome: Welcome,
stop: CancellationToken,
) -> Result<ControlExit, ServerError> {
let native_stop = authority
.administration
.as_ref()
.map(DaemonAdministration::stop_completed)
.unwrap_or_default();
let mut connections = JoinSet::new();
let mut idle = authority.idle_timeout.zip(service.empty_since());
let mut disconnected_at = Instant::now();
let result = loop {
let deadline = idle.as_mut().and_then(|(timeout, empty_since)| {
empty_since
.borrow_and_update()
.map(|since| since.max(disconnected_at) + *timeout)
});
let idle_expired = async {
if let Some(deadline) = deadline {
tokio::time::sleep_until(deadline).await;
} else {
std::future::pending::<()>().await;
}
};
tokio::select! {
biased;
_ = native_stop.cancelled() => break Ok(ControlExit::AdministrativeStop),
_ = stop.cancelled() => break Ok(ControlExit::Stopped),
Some(_) = connections.join_next(), if !connections.is_empty() => {
if connections.is_empty() {
disconnected_at = Instant::now();
}
}
_ = async { if let Some((_, empty_since)) = idle.as_mut() { let _ = empty_since.changed().await; } }, if idle.is_some() => {},
accepted = listener.accept() => {
let (stream, _) = match accepted { Ok(pair) => pair, Err(_) => break Err(ServerError::ListenerStopped) };
if connections.len() >= config.max_connections { drop(stream); continue; }
connections.spawn(connection(stream, config.clone(), service.clone(), authority.clone(), welcome.clone(), native_stop.clone()));
}
_ = idle_expired, if connections.is_empty() => {
let (timeout, _) = idle.as_ref().expect("idle deadline requires a timeout");
match service.shutdown_if_idle(*timeout).await {
Ok(true) => break Ok(ControlExit::Idle),
Ok(false) => disconnected_at = Instant::now(),
Err(error) => {
use std::io::Write;
let _ = writeln!(std::io::stderr().lock(), "Host idle shutdown failed: {error}");
idle = None;
}
}
}
}
};
if result != Ok(ControlExit::AdministrativeStop) {
connections.abort_all();
}
while connections.join_next().await.is_some() {}
drop(lease);
drop(listener);
result
}
async fn connection(
mut stream: UnixStream,
config: ControlConfig,
service: HostService,
authority: ControlAuthority,
welcome: Welcome,
native_stop: CancellationToken,
) {
if stream.peer_cred().map(|peer| peer.uid()).ok()
!= Some(nix::unistd::Uid::effective().as_raw())
{
return;
}
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum Handshake {
Control(Hello),
Session(super::area_rpc::SessionHello),
}
let handshake = async {
let (hello, session) = match read_frame(&mut stream, MAX_FRAME_BYTES).await? {
Handshake::Control(hello) => (hello, None),
Handshake::Session(request) => (request.session_rpc, Some(request.agent_id)),
};
if !config.token.matches(&hello.token)
|| hello.host_id != config.host_id
|| hello.protocol != PROTOCOL
|| hello.version.major != MAJOR
{
return Err(super::client::Failure::IncompatiblePeer);
}
if session.is_none() {
write_frame(&mut stream, &encode_frame(&welcome, MAX_FRAME_BYTES)?).await?;
}
Ok(session)
};
let handshake_result = tokio::select! {
biased;
_ = native_stop.cancelled() => return,
result = tokio::time::timeout(config.handshake_timeout, handshake) => result,
};
match handshake_result {
Ok(Ok(Some(agent))) => {
if let Some(gate) = authority.session_rpc.get(&agent) {
let restore = gate.clone().zip(authority.administration.clone());
let session = tokio::select! {
biased;
_ = native_stop.cancelled() => return,
result = tokio::time::timeout(config.handshake_timeout,
super::area_rpc::Session::open(&service, agent, config.host_id, restore)) => result,
};
if let Ok(Ok(session)) = session {
session.serve(stream, native_stop).await;
}
}
return;
}
Ok(Ok(None)) => (),
_ => return,
}
loop {
let exchange = async {
let request: Request = tokio::select! {
biased;
_ = native_stop.cancelled() => return Err(super::client::Failure::Connection),
result = read_frame(&mut stream, welcome.limits.max_frame_bytes) => result?,
};
let reply = if request.epoch != welcome.epoch {
Reply::Error {
code: ErrorCode::StaleEpoch,
}
} else if !request.command.valid(welcome.limits) {
Reply::Error {
code: ErrorCode::InvalidRequest,
}
} else if !welcome.supports(request.command.capability()) {
Reply::Error {
code: ErrorCode::Unsupported,
}
} else {
dispatch(&service, &authority, config.host_id, request.command).await
};
let response = Response {
call_id: request.call_id,
epoch: welcome.epoch,
reply,
};
let bytes = encode_frame(&response, welcome.limits.max_frame_bytes)?;
write_frame(&mut stream, &bytes).await
};
if !matches!(
tokio::time::timeout(config.request_timeout, exchange).await,
Ok(Ok(()))
) {
return;
}
}
}
fn catalog_code(error: &CatalogError) -> ErrorCode {
match error {
CatalogError::UnknownAgent => ErrorCode::NotFound,
CatalogError::WorkerStopped => ErrorCode::Busy,
_ => ErrorCode::Internal,
}
}
fn catalog_error(error: CatalogError) -> Reply {
Reply::Error {
code: catalog_code(&error),
}
}
fn service_error(error: super::service::ServiceError) -> Reply {
use super::ordinary::BackendError;
use super::service::ServiceError;
Reply::Error {
code: match error {
ServiceError::Stopping
| ServiceError::Busy
| ServiceError::Backend(BackendError::Busy) => ErrorCode::Busy,
ServiceError::NotLoaded => ErrorCode::NotFound,
ServiceError::Backend(BackendError::AdmissionUncertain) => {
ErrorCode::PersistenceUncertain
}
ServiceError::AlreadyOwned => ErrorCode::Conflict,
ServiceError::Backend(_) | ServiceError::TaskStopped => ErrorCode::Internal,
ServiceError::Catalog(error) => catalog_code(&error),
ServiceError::ShutdownIncomplete { .. } => ErrorCode::Internal,
},
}
}
fn backend_code(error: &super::ordinary::BackendError) -> ErrorCode {
use super::ordinary::BackendError;
match error {
BackendError::AdmissionUncertain | BackendError::Unsaved => ErrorCode::PersistenceUncertain,
BackendError::Admission(_) | BackendError::InputTooLarge => ErrorCode::InvalidRequest,
BackendError::Busy => ErrorCode::Busy,
BackendError::Closed => ErrorCode::NotFound,
_ => ErrorCode::Internal,
}
}
async fn dispatch(
service: &HostService,
authority: &ControlAuthority,
host_id: HostId,
command: Command,
) -> Reply {
if matches!(
command,
Command::MiniExecute { .. } | Command::MiniReceipt { .. } | Command::MiniResult { .. }
) {
return match &authority.mini {
Some(mini) => mini.dispatch(command).await,
None => Reply::Error {
code: ErrorCode::Unsupported,
},
};
}
if matches!(
command,
Command::Profiles { .. }
| Command::AdministrativeReceipt { .. }
| Command::AdministrativeCreate { .. }
| Command::AdministrativeRestore { .. }
| Command::AdministrativeClose { .. }
| Command::AdministrativeCancel { .. }
| Command::AdministrativeStop { .. }
) {
return administrative::dispatch(authority.administration.as_ref(), command).await;
}
let result = match command {
Command::Status {} => service.catalog().status().await.map(|status| serde_json::json!({
"epoch": status.epoch, "registered": status.registered, "resident": status.resident,
"executing": status.executing, "busy": status.busy, "mini": status.mini,
"max_agents": status.max_agents, "owners": service.owner_count(), "stopping": service.is_stopping(),
})),
Command::Inspect { agent_id } => {
let Ok(id) = String::from(agent_id).try_into() else { return Reply::Error { code: ErrorCode::InvalidRequest }; };
service.catalog().get(id).await.and_then(|record| serde_json::to_value(record).map_err(CatalogError::from))
}
Command::Result { agent_id, request_id, run_id, offset, max_bytes } => {
return submission_result::query(service, host_id, agent_id, request_id, run_id, offset, max_bytes).await;
}
Command::Receipt {
agent_id,
request_id,
} => {
let Ok(id) = String::from(agent_id).try_into() else {
return Reply::Error {
code: ErrorCode::InvalidRequest,
};
};
return match service.admission(id, &String::from(request_id)).await {
Ok(Some(status)) => match serde_json::to_value(serde_json::json!({
"found": true,
"agent_id": agent_id,
"request_id": request_id,
"receipt": status.receipt,
"execution": status.execution,
})) {
Ok(data) => Reply::Data { data },
Err(_) => Reply::Error {
code: ErrorCode::Internal,
},
},
Ok(None) => Reply::Data {
data: serde_json::json!({
"found": false,
"agent_id": agent_id,
"request_id": request_id,
}),
},
Err(error) => service_error(error),
};
}
Command::Submit {
agent_id,
request_id,
prompt,
} => {
let Ok(id) = String::from(agent_id).try_into() else {
return Reply::Error {
code: ErrorCode::InvalidRequest,
};
};
let client = match service.ordinary_client(id) {
Ok(client) => client,
Err(error) => return service_error(error),
};
let messages = vec![rpi_ai::UserMessage::new(prompt, 0).into()];
let ticket = match client
.submit_admitted(
String::from(host_id),
String::from(request_id),
messages,
)
.await
{
Ok(ticket) => ticket,
Err(error) => {
return Reply::Error {
code: backend_code(&error),
}
}
};
return match ticket.wait_admitted().await {
Ok(receipt) => Reply::Data {
data: serde_json::json!({
"durable": true,
"agent_id": agent_id,
"request_id": request_id,
"receipt": receipt,
}),
},
Err(error) => Reply::Error {
code: backend_code(&error),
},
};
}
Command::List { after, limit } => {
let after = match after.map(|id| String::from(id).try_into()).transpose() { Ok(value) => value, Err(_) => return Reply::Error { code: ErrorCode::InvalidRequest } };
service.catalog().list(after, limit).await.map(|page| {
let agents: Vec<_> = page.agents.into_iter().map(|record| serde_json::json!({
"id": record.spec.id, "name": record.spec.name, "parent_id": record.spec.parent_id,
"mode": record.spec.mode, "state": record.state, "revision": record.revision,
})).collect();
serde_json::json!({"agents": agents, "next_cursor": page.next_cursor})
})
}
_ => return Reply::Error { code: ErrorCode::Unsupported },
};
match result {
Ok(data) => Reply::Data { data },
Err(error) => catalog_error(error),
}
}
#[path = "submission_result.rs"]
mod submission_result;
#[path = "server_administration.rs"]
mod administrative;
#[cfg(test)]
#[path = "server_tests.rs"]
mod tests;