1use super::{
8 area_rpc::SessionRoutes,
9 client::{encode_frame, read_frame, write_frame},
10 daemon::DaemonAdministration,
11 protocol::*,
12 service::HostService,
13 CatalogError,
14};
15use std::{collections::BTreeMap, path::PathBuf, sync::Arc, time::Duration};
16use tokio::{
17 net::{UnixListener, UnixStream},
18 task::{JoinHandle, JoinSet},
19 time::Instant,
20};
21use tokio_util::sync::CancellationToken;
22
23type SessionRoutesByAgent = BTreeMap<super::AgentId, Option<Arc<tokio::sync::Mutex<()>>>>;
24
25#[derive(Clone, Default)]
26struct ControlAuthority {
27 administration: Option<DaemonAdministration>,
28 mini: Option<super::mini_control::MiniControl>,
29 session_rpc: Arc<SessionRoutesByAgent>,
30 idle_timeout: Option<Duration>,
31}
32
33#[derive(Clone)]
34pub struct ControlConfig {
35 pub socket_path: PathBuf,
36 pub host_id: HostId,
37 pub token: AuthToken,
38 pub max_connections: usize,
39 pub handshake_timeout: Duration,
40 pub request_timeout: Duration,
42}
43impl ControlConfig {
44 pub fn validate(&self) -> Result<(), ServerError> {
45 if !self.socket_path.is_absolute()
46 || !(1..=64).contains(&self.max_connections)
47 || [self.handshake_timeout, self.request_timeout]
48 .iter()
49 .any(|duration| duration.is_zero() || *duration > Duration::from_secs(300))
50 {
51 return Err(ServerError::InvalidConfiguration);
52 }
53 Ok(())
54 }
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
59pub enum ServerError {
60 #[error("invalid shared Host control configuration")]
61 InvalidConfiguration,
62 #[error("shared Host endpoint must be absent, with a private owned parent")]
63 UnsafeEndpoint,
64 #[error("shared Host endpoint could not be bound")]
65 Bind,
66 #[error("shared Host control listener stopped unexpectedly")]
67 ListenerStopped,
68 #[error("shared Host control task stopped unexpectedly")]
69 TaskStopped,
70}
71
72pub(super) struct SocketLease {
75 path: PathBuf,
76 dev: u64,
77 ino: u64,
78 unlink_on_drop: bool,
79}
80impl SocketLease {
81 #[cfg(target_os = "macos")]
82 pub(super) fn identity(&self) -> (u64, u64) {
83 (self.dev, self.ino)
84 }
85
86 #[cfg(target_os = "macos")]
87 pub(super) fn inherited(path: PathBuf, (dev, ino): (u64, u64)) -> Self {
88 Self {
89 path,
90 dev,
91 ino,
92 unlink_on_drop: false,
93 }
94 }
95
96 pub(super) fn remove(&self) {
97 use std::os::unix::fs::{FileTypeExt, MetadataExt};
98 if let Ok(metadata) = std::fs::symlink_metadata(&self.path) {
99 if metadata.file_type().is_socket()
100 && metadata.dev() == self.dev
101 && metadata.ino() == self.ino
102 {
103 let _ = std::fs::remove_file(&self.path);
104 }
105 }
106 }
107}
108impl Drop for SocketLease {
109 fn drop(&mut self) {
110 if self.unlink_on_drop {
111 self.remove();
112 }
113 }
114}
115pub(super) fn bind_endpoint(
116 path: PathBuf,
117) -> Result<(std::os::unix::net::UnixListener, SocketLease), ServerError> {
118 use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
119 let parent = path.parent().ok_or(ServerError::InvalidConfiguration)?;
120 let metadata = std::fs::symlink_metadata(parent).map_err(|_| ServerError::UnsafeEndpoint)?;
121 if !metadata.is_dir()
122 || metadata.uid() != nix::unistd::Uid::effective().as_raw()
123 || metadata.mode() & 0o077 != 0
124 {
125 return Err(ServerError::UnsafeEndpoint);
126 }
127 match std::fs::symlink_metadata(&path) {
128 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
129 _ => return Err(ServerError::UnsafeEndpoint),
130 }
131 let listener = std::os::unix::net::UnixListener::bind(&path).map_err(|_| ServerError::Bind)?;
132 let metadata = std::fs::symlink_metadata(&path).map_err(|_| ServerError::Bind)?;
133 let lease = SocketLease {
134 path: path.clone(),
135 dev: metadata.dev(),
136 ino: metadata.ino(),
137 unlink_on_drop: true,
138 };
139 if !metadata.file_type().is_socket()
140 || metadata.nlink() != 1
141 || metadata.uid() != nix::unistd::Uid::effective().as_raw()
142 {
143 return Err(ServerError::UnsafeEndpoint);
144 }
145 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
146 .map_err(|_| ServerError::Bind)?;
147 listener
148 .set_nonblocking(true)
149 .map_err(|_| ServerError::Bind)?;
150 Ok((listener, lease))
151}
152
153pub struct ControlServer {
156 welcome: Welcome,
157 stop: CancellationToken,
158 task: Option<JoinHandle<Result<ControlExit, ServerError>>>,
159 terminal: Option<Result<ControlExit, ServerError>>,
160}
161
162#[derive(Clone, Copy, PartialEq, Eq)]
163enum ControlExit {
164 Stopped,
165 AdministrativeStop,
166 Idle,
167}
168impl ControlServer {
169 pub async fn bind(config: ControlConfig, service: HostService) -> Result<Self, ServerError> {
170 Self::bind_with_administration(config, service, None).await
171 }
172 pub(crate) async fn bind_with_administration(
173 config: ControlConfig,
174 service: HostService,
175 administration: Option<DaemonAdministration>,
176 ) -> Result<Self, ServerError> {
177 Self::bind_with_controls(
178 config,
179 service,
180 administration,
181 None,
182 None,
183 SessionRoutes::default(),
184 None,
185 )
186 .await
187 }
188 pub(super) async fn bind_with_controls(
189 config: ControlConfig,
190 service: HostService,
191 administration: Option<DaemonAdministration>,
192 mini: Option<super::mini_control::MiniControl>,
193 inherited: Option<std::os::unix::net::UnixListener>,
194 routes: SessionRoutes,
195 idle_timeout: Option<Duration>,
196 ) -> Result<Self, ServerError> {
197 config.validate()?;
198 if routes.restore_on_attach && administration.is_none() {
199 return Err(ServerError::InvalidConfiguration);
200 }
201 for &id in &routes.agents {
202 let record = service
203 .catalog()
204 .get(id)
205 .await
206 .map_err(|_| ServerError::InvalidConfiguration)?;
207 if record.spec.mode != super::AgentMode::Persistent {
208 return Err(ServerError::InvalidConfiguration);
209 }
210 match service.ordinary_client(id) {
215 Ok(client) => match client.area_session(false).await {
216 Ok(_) | Err(super::ordinary::BackendError::Closed) => (),
217 Err(_) => return Err(ServerError::InvalidConfiguration),
218 },
219 Err(
220 super::service::ServiceError::Busy | super::service::ServiceError::NotLoaded,
221 ) => (),
222 Err(_) => return Err(ServerError::InvalidConfiguration),
223 }
224 }
225 let authority = ControlAuthority {
226 administration,
227 mini,
228 session_rpc: Arc::new(
229 routes
230 .agents
231 .into_iter()
232 .map(|id| {
233 (
234 id,
235 routes
236 .restore_on_attach
237 .then(|| Arc::new(tokio::sync::Mutex::new(()))),
238 )
239 })
240 .collect(),
241 ),
242 idle_timeout,
243 };
244 let (listener, lease) = match inherited {
245 Some(listener) => (listener, None),
246 None => {
247 let path = config.socket_path.clone();
248 let (listener, lease) = tokio::task::spawn_blocking(move || bind_endpoint(path))
250 .await
251 .map_err(|_| ServerError::TaskStopped)??;
252 (listener, Some(lease))
253 }
254 };
255 let listener = UnixListener::from_std(listener).map_err(|_| ServerError::Bind)?;
256 let mut welcome = Welcome {
257 protocol: PROTOCOL.into(),
258 version: Version::default(),
259 host_id: config.host_id,
260 epoch: String::from(service.catalog().epoch())
261 .try_into()
262 .map_err(|_| ServerError::InvalidConfiguration)?,
263 capabilities: vec![
264 Capability::Status,
265 Capability::List,
266 Capability::Inspect,
267 Capability::Receipts,
268 Capability::Results,
269 Capability::Submit,
270 ],
271 limits: Limits {
272 max_in_flight: 1,
273 ..Limits::default()
274 },
275 };
276 if authority.mini.is_some() {
277 welcome.capabilities.push(Capability::Mini);
278 }
279 if authority.administration.is_some() {
280 welcome.capabilities.extend([
281 Capability::Profiles,
282 Capability::AdministrativeReceipts,
283 Capability::AdministrativeCreate,
284 Capability::AdministrativeRestore,
285 Capability::AdministrativeClose,
286 Capability::AdministrativeCancel,
287 Capability::AdministrativeStop,
288 ]);
289 }
290 let stop = CancellationToken::new();
291 let task = tokio::spawn(serve(
292 listener,
293 lease,
294 config,
295 service,
296 authority,
297 welcome.clone(),
298 stop.clone(),
299 ));
300 Ok(Self {
301 welcome,
302 stop,
303 task: Some(task),
304 terminal: None,
305 })
306 }
307 pub fn welcome(&self) -> &Welcome {
308 &self.welcome
309 }
310 pub fn stopped_by_administration(&self) -> bool {
311 matches!(self.terminal, Some(Ok(ControlExit::AdministrativeStop)))
312 }
313 pub(super) fn stopped_for_idleness(&self) -> bool {
314 matches!(self.terminal, Some(Ok(ControlExit::Idle)))
315 }
316 pub async fn wait(&mut self) -> Result<(), ServerError> {
318 if let Some(result) = self.terminal {
319 return result.map(|_| ());
320 }
321 let result = match self.task.as_mut() {
322 Some(task) => task.await.unwrap_or(Err(ServerError::TaskStopped)),
323 None => Ok(ControlExit::Stopped),
324 };
325 self.task.take();
326 self.terminal = Some(result);
327 result.map(|_| ())
328 }
329 pub async fn stop(&mut self) -> Result<(), ServerError> {
330 self.stop.cancel();
331 self.wait().await
332 }
333}
334impl Drop for ControlServer {
335 fn drop(&mut self) {
336 self.stop.cancel();
337 }
338}
339
340async fn serve(
341 listener: UnixListener,
342 lease: Option<SocketLease>,
343 config: ControlConfig,
344 service: HostService,
345 authority: ControlAuthority,
346 welcome: Welcome,
347 stop: CancellationToken,
348) -> Result<ControlExit, ServerError> {
349 let native_stop = authority
350 .administration
351 .as_ref()
352 .map(DaemonAdministration::stop_completed)
353 .unwrap_or_default();
354 let mut connections = JoinSet::new();
355 let mut idle = authority.idle_timeout.zip(service.empty_since());
356 let mut disconnected_at = Instant::now();
357 let result = loop {
358 let deadline = idle.as_mut().and_then(|(timeout, empty_since)| {
359 empty_since
360 .borrow_and_update()
361 .map(|since| since.max(disconnected_at) + *timeout)
362 });
363 let idle_expired = async {
364 if let Some(deadline) = deadline {
365 tokio::time::sleep_until(deadline).await;
366 } else {
367 std::future::pending::<()>().await;
368 }
369 };
370 tokio::select! {
371 biased;
372 _ = native_stop.cancelled() => break Ok(ControlExit::AdministrativeStop),
373 _ = stop.cancelled() => break Ok(ControlExit::Stopped),
374 Some(_) = connections.join_next(), if !connections.is_empty() => {
375 if connections.is_empty() {
376 disconnected_at = Instant::now();
377 }
378 }
379 _ = async { if let Some((_, empty_since)) = idle.as_mut() { let _ = empty_since.changed().await; } }, if idle.is_some() => {},
380 accepted = listener.accept() => {
381 let (stream, _) = match accepted { Ok(pair) => pair, Err(_) => break Err(ServerError::ListenerStopped) };
382 if connections.len() >= config.max_connections { drop(stream); continue; }
384 connections.spawn(connection(stream, config.clone(), service.clone(), authority.clone(), welcome.clone(), native_stop.clone()));
385 }
386 _ = idle_expired, if connections.is_empty() => {
387 let (timeout, _) = idle.as_ref().expect("idle deadline requires a timeout");
388 match service.shutdown_if_idle(*timeout).await {
389 Ok(true) => break Ok(ControlExit::Idle),
390 Ok(false) => disconnected_at = Instant::now(),
391 Err(error) => {
392 use std::io::Write;
393 let _ = writeln!(std::io::stderr().lock(), "Host idle shutdown failed: {error}");
394 idle = None;
395 }
396 }
397 }
398 }
399 };
400 if result != Ok(ControlExit::AdministrativeStop) {
405 connections.abort_all();
407 }
408 while connections.join_next().await.is_some() {}
409 drop(lease);
412 drop(listener);
413 result
414}
415
416async fn connection(
417 mut stream: UnixStream,
418 config: ControlConfig,
419 service: HostService,
420 authority: ControlAuthority,
421 welcome: Welcome,
422 native_stop: CancellationToken,
423) {
424 if stream.peer_cred().map(|peer| peer.uid()).ok()
425 != Some(nix::unistd::Uid::effective().as_raw())
426 {
427 return;
428 }
429 #[derive(serde::Deserialize)]
430 #[serde(untagged)]
431 enum Handshake {
432 Control(Hello),
433 Session(super::area_rpc::SessionHello),
434 }
435 let handshake = async {
436 let (hello, session) = match read_frame(&mut stream, MAX_FRAME_BYTES).await? {
437 Handshake::Control(hello) => (hello, None),
438 Handshake::Session(request) => (request.session_rpc, Some(request.agent_id)),
439 };
440 if !config.token.matches(&hello.token)
441 || hello.host_id != config.host_id
442 || hello.protocol != PROTOCOL
443 || hello.version.major != MAJOR
444 {
445 return Err(super::client::Failure::IncompatiblePeer);
446 }
447 if session.is_none() {
448 write_frame(&mut stream, &encode_frame(&welcome, MAX_FRAME_BYTES)?).await?;
449 }
450 Ok(session)
451 };
452 let handshake_result = tokio::select! {
453 biased;
454 _ = native_stop.cancelled() => return,
455 result = tokio::time::timeout(config.handshake_timeout, handshake) => result,
456 };
457 match handshake_result {
458 Ok(Ok(Some(agent))) => {
459 if let Some(gate) = authority.session_rpc.get(&agent) {
460 let restore = gate.clone().zip(authority.administration.clone());
461 let session = tokio::select! {
462 biased;
463 _ = native_stop.cancelled() => return,
464 result = tokio::time::timeout(config.handshake_timeout,
465 super::area_rpc::Session::open(&service, agent, config.host_id, restore)) => result,
466 };
467 if let Ok(Ok(session)) = session {
468 session.serve(stream, native_stop).await;
469 }
470 }
471 return;
472 }
473 Ok(Ok(None)) => (),
474 _ => return,
475 }
476 loop {
477 let exchange = async {
478 let request: Request = tokio::select! {
479 biased;
480 _ = native_stop.cancelled() => return Err(super::client::Failure::Connection),
481 result = read_frame(&mut stream, welcome.limits.max_frame_bytes) => result?,
482 };
483 let reply = if request.epoch != welcome.epoch {
486 Reply::Error {
487 code: ErrorCode::StaleEpoch,
488 }
489 } else if !request.command.valid(welcome.limits) {
490 Reply::Error {
491 code: ErrorCode::InvalidRequest,
492 }
493 } else if !welcome.supports(request.command.capability()) {
494 Reply::Error {
495 code: ErrorCode::Unsupported,
496 }
497 } else {
498 dispatch(&service, &authority, config.host_id, request.command).await
499 };
500 let response = Response {
501 call_id: request.call_id,
502 epoch: welcome.epoch,
503 reply,
504 };
505 let bytes = encode_frame(&response, welcome.limits.max_frame_bytes)?;
506 write_frame(&mut stream, &bytes).await
507 };
508 if !matches!(
509 tokio::time::timeout(config.request_timeout, exchange).await,
510 Ok(Ok(()))
511 ) {
512 return;
513 }
514 }
515}
516fn catalog_code(error: &CatalogError) -> ErrorCode {
517 match error {
518 CatalogError::UnknownAgent => ErrorCode::NotFound,
519 CatalogError::WorkerStopped => ErrorCode::Busy,
520 _ => ErrorCode::Internal,
521 }
522}
523fn catalog_error(error: CatalogError) -> Reply {
524 Reply::Error {
525 code: catalog_code(&error),
526 }
527}
528fn service_error(error: super::service::ServiceError) -> Reply {
529 use super::ordinary::BackendError;
530 use super::service::ServiceError;
531 Reply::Error {
532 code: match error {
533 ServiceError::Stopping | ServiceError::Busy => ErrorCode::Busy,
534 ServiceError::NotLoaded => ErrorCode::NotFound,
535 ServiceError::Backend(BackendError::AdmissionUncertain) => {
536 ErrorCode::PersistenceUncertain
537 }
538 ServiceError::AlreadyOwned => ErrorCode::Conflict,
539 ServiceError::Backend(_) | ServiceError::TaskStopped => ErrorCode::Internal,
540 ServiceError::Catalog(error) => catalog_code(&error),
541 ServiceError::ShutdownIncomplete { .. } => ErrorCode::Internal,
542 },
543 }
544}
545fn backend_code(error: &super::ordinary::BackendError) -> ErrorCode {
546 use super::ordinary::BackendError;
547 match error {
548 BackendError::AdmissionUncertain | BackendError::Unsaved => ErrorCode::PersistenceUncertain,
549 BackendError::Admission(_) | BackendError::InputTooLarge => ErrorCode::InvalidRequest,
550 BackendError::Busy => ErrorCode::Busy,
551 BackendError::Closed => ErrorCode::NotFound,
552 _ => ErrorCode::Internal,
553 }
554}
555async fn dispatch(
556 service: &HostService,
557 authority: &ControlAuthority,
558 host_id: HostId,
559 command: Command,
560) -> Reply {
561 if matches!(
562 command,
563 Command::MiniExecute { .. } | Command::MiniReceipt { .. } | Command::MiniResult { .. }
564 ) {
565 return match &authority.mini {
566 Some(mini) => mini.dispatch(command).await,
567 None => Reply::Error {
568 code: ErrorCode::Unsupported,
569 },
570 };
571 }
572 if matches!(
573 command,
574 Command::Profiles { .. }
575 | Command::AdministrativeReceipt { .. }
576 | Command::AdministrativeCreate { .. }
577 | Command::AdministrativeRestore { .. }
578 | Command::AdministrativeClose { .. }
579 | Command::AdministrativeCancel { .. }
580 | Command::AdministrativeStop { .. }
581 ) {
582 return administrative::dispatch(authority.administration.as_ref(), command).await;
583 }
584 let result = match command {
585 Command::Status {} => service.catalog().status().await.map(|status| serde_json::json!({
586 "epoch": status.epoch, "registered": status.registered, "resident": status.resident,
587 "executing": status.executing, "busy": status.busy, "mini": status.mini,
588 "max_agents": status.max_agents, "owners": service.owner_count(), "stopping": service.is_stopping(),
589 })),
590 Command::Inspect { agent_id } => {
591 let Ok(id) = String::from(agent_id).try_into() else { return Reply::Error { code: ErrorCode::InvalidRequest }; };
592 service.catalog().get(id).await.and_then(|record| serde_json::to_value(record).map_err(CatalogError::from))
593 }
594 Command::Result { agent_id, request_id, run_id, offset, max_bytes } => {
595 return submission_result::query(service, host_id, agent_id, request_id, run_id, offset, max_bytes).await;
596 }
597 Command::Receipt {
598 agent_id,
599 request_id,
600 } => {
601 let Ok(id) = String::from(agent_id).try_into() else {
602 return Reply::Error {
603 code: ErrorCode::InvalidRequest,
604 };
605 };
606 return match service.admission(id, &String::from(request_id)).await {
609 Ok(Some(status)) => match serde_json::to_value(serde_json::json!({
610 "found": true,
611 "agent_id": agent_id,
612 "request_id": request_id,
613 "receipt": status.receipt,
614 "execution": status.execution,
615 })) {
616 Ok(data) => Reply::Data { data },
617 Err(_) => Reply::Error {
618 code: ErrorCode::Internal,
619 },
620 },
621 Ok(None) => Reply::Data {
622 data: serde_json::json!({
623 "found": false,
624 "agent_id": agent_id,
625 "request_id": request_id,
626 }),
627 },
628 Err(error) => service_error(error),
629 };
630 }
631 Command::Submit {
632 agent_id,
633 request_id,
634 prompt,
635 } => {
636 let Ok(id) = String::from(agent_id).try_into() else {
637 return Reply::Error {
638 code: ErrorCode::InvalidRequest,
639 };
640 };
641 let client = match service.ordinary_client(id) {
642 Ok(client) => client,
643 Err(error) => return service_error(error),
644 };
645 let messages = vec![rpi_ai::UserMessage::new(prompt, 0).into()];
649 let ticket = match client
650 .submit_admitted(
651 String::from(host_id),
652 String::from(request_id),
653 messages,
654 )
655 .await
656 {
657 Ok(ticket) => ticket,
658 Err(error) => {
659 return Reply::Error {
660 code: backend_code(&error),
661 }
662 }
663 };
664 return match ticket.wait_admitted().await {
668 Ok(receipt) => Reply::Data {
669 data: serde_json::json!({
670 "durable": true,
671 "agent_id": agent_id,
672 "request_id": request_id,
673 "receipt": receipt,
674 }),
675 },
676 Err(error) => Reply::Error {
677 code: backend_code(&error),
678 },
679 };
680 }
681 Command::List { after, limit } => {
682 let after = match after.map(|id| String::from(id).try_into()).transpose() { Ok(value) => value, Err(_) => return Reply::Error { code: ErrorCode::InvalidRequest } };
683 service.catalog().list(after, limit).await.map(|page| {
684 let agents: Vec<_> = page.agents.into_iter().map(|record| serde_json::json!({
686 "id": record.spec.id, "name": record.spec.name, "parent_id": record.spec.parent_id,
687 "mode": record.spec.mode, "state": record.state, "revision": record.revision,
688 })).collect();
689 serde_json::json!({"agents": agents, "next_cursor": page.next_cursor})
690 })
691 }
692 _ => return Reply::Error { code: ErrorCode::Unsupported },
693 };
694 match result {
695 Ok(data) => Reply::Data { data },
696 Err(error) => catalog_error(error),
697 }
698}
699
700#[path = "submission_result.rs"]
701mod submission_result;
702
703#[path = "server_administration.rs"]
704mod administrative;
705
706#[cfg(test)]
707#[path = "server_tests.rs"]
708mod tests;