1use std::collections::VecDeque;
4use std::path::{Path, PathBuf};
5use std::time::Duration;
6
7use adk_core::{AdkError, ApprovalAction, ErrorCategory, ErrorComponent};
8use futures::stream::{self, BoxStream, StreamExt};
9use hyper::body::Bytes;
10use hyper::{Method, StatusCode};
11use serde::Serialize;
12use serde::de::DeserializeOwned;
13use serde_json::Value;
14
15use super::api::{
16 AgendaItemResponse, AgendaQuery, AgendaResponse, ApprovalItem, AttachRequest, AttachResponse,
17 FreezeRequest, FreezeResponse, KillRequest, NiceRequest, ProcessResponse, ProcessesQuery,
18 ProcessesResponse, RejectRequest, RunNowRequest, ScheduleRequest, SpawnRequest, SteerRequest,
19 SteerResponse,
20};
21use super::{ControlPlaneConfig, paths};
22use crate::agenda::AgendaItem;
23use crate::bus::EventRecord;
24use crate::error::{self, KernelError, Result};
25use crate::kernel::KernelHealth;
26use crate::process::Process;
27use crate::sched::QueueClass;
28use crate::wake::WakeSet;
29
30const APPROVALS: &str = "/approvals";
32
33const CALL_TIMEOUT: Duration = Duration::from_secs(30);
35
36#[derive(Debug, Clone)]
57pub struct ControlClient {
58 transport: Transport,
59 token: Option<String>,
60}
61
62#[derive(Debug, Clone)]
63enum Transport {
64 Socket(PathBuf),
65 #[cfg(windows)]
66 Pipe(String),
67 Http {
68 base: String,
69 client: reqwest::Client,
70 },
71}
72
73struct Answer {
75 status: StatusCode,
76 body: BoxStream<'static, Result<Bytes>>,
77}
78
79impl Answer {
80 async fn bytes(self) -> Result<Vec<u8>> {
81 let mut body = self.body;
82 let mut bytes = Vec::new();
83 while let Some(chunk) = body.next().await {
84 bytes.extend_from_slice(&chunk?);
85 }
86 Ok(bytes)
87 }
88}
89
90impl ControlClient {
91 pub fn socket(path: impl Into<PathBuf>) -> Self {
93 Self { transport: Transport::Socket(path.into()), token: None }
94 }
95
96 #[cfg(windows)]
100 pub fn pipe(name: impl Into<String>) -> Self {
101 Self { transport: Transport::Pipe(name.into()), token: None }
102 }
103
104 pub fn http(base_url: impl Into<String>) -> Self {
106 let base = base_url.into().trim_end_matches('/').to_string();
107 Self { transport: Transport::Http { base, client: reqwest::Client::new() }, token: None }
108 }
109
110 #[must_use]
112 pub fn with_bearer_token(mut self, token: impl Into<String>) -> Self {
113 self.token = Some(token.into());
114 self
115 }
116
117 pub fn bearer_token(&self) -> Option<&str> {
130 self.token.as_deref()
131 }
132
133 pub fn endpoint(&self) -> String {
135 match &self.transport {
136 Transport::Socket(path) => format!("unix:{}", path.display()),
137 #[cfg(windows)]
138 Transport::Pipe(name) => format!("pipe:{name}"),
139 Transport::Http { base, .. } => base.clone(),
140 }
141 }
142
143 pub async fn connect_local(home: &Path) -> Result<Option<Self>> {
156 #[cfg(windows)]
157 {
158 let Some(name) = ControlPlaneConfig::default().pipe_name(home) else {
159 return Ok(None);
160 };
161 match super::pipe::answers(&name).await {
162 Ok(true) => Ok(Some(Self::pipe(name))),
163 Ok(false) => Ok(None),
164 Err(error) => Err(KernelError::ControlPlane {
165 reason: format!(
166 "the kernel pipe {name} exists but cannot be used: {error}; it admits \
167 only the OS user that runs the kernel"
168 ),
169 }),
170 }
171 }
172 #[cfg(not(windows))]
173 {
174 let Some(path) = ControlPlaneConfig::default().socket_path(home) else {
175 return Ok(None);
176 };
177 connect_local_socket(path, &home.join(ControlPlaneConfig::DEFAULT_SOCKET)).await
178 }
179 }
180
181 pub async fn health(&self) -> Result<KernelHealth> {
188 self.call(Method::GET, paths::HEALTH.to_string(), None::<&()>).await
189 }
190
191 pub async fn inventory(&self) -> Result<crate::inventory::KernelInventory> {
199 self.call(Method::GET, paths::INVENTORY.to_string(), None::<&()>).await
200 }
201
202 pub async fn partitions(&self) -> Result<Vec<crate::partition::Partition>> {
209 let answer: super::api::PartitionsResponse =
210 self.call(Method::GET, paths::PARTITIONS.to_string(), None::<&()>).await?;
211 Ok(answer.partitions)
212 }
213
214 pub async fn agents(&self) -> Result<Vec<crate::agents::AgentView>> {
222 let answer: super::api::AgentsResponse =
223 self.call(Method::GET, paths::AGENTS.to_string(), None::<&()>).await?;
224 Ok(answer.agents)
225 }
226
227 pub async fn agent(&self, id: &str) -> Result<crate::agents::AgentView> {
235 let path = paths::AGENT.replace("{id}", &encode(id));
236 self.call(Method::GET, path, None::<&()>).await
237 }
238
239 pub async fn put_partition(
246 &self,
247 partition: &crate::partition::Partition,
248 ) -> Result<crate::partition::Partition> {
249 let answer: super::api::PartitionResponse =
250 self.call(Method::POST, paths::PARTITIONS.to_string(), Some(partition)).await?;
251 Ok(answer.partition)
252 }
253
254 pub async fn set_partition_mode(
261 &self,
262 id: &str,
263 mode: crate::partition::PartitionMode,
264 ) -> Result<crate::partition::Partition> {
265 let path = paths::PARTITION_MODE.replace("{id}", &encode(id));
266 let body = super::api::PartitionModeRequest { mode };
267 let answer: super::api::PartitionResponse =
268 self.call(Method::POST, path, Some(&body)).await?;
269 Ok(answer.partition)
270 }
271
272 pub async fn settings(&self) -> Result<Vec<super::api::AreaView>> {
280 let answer: super::api::SettingsResponse =
281 self.call(Method::GET, paths::SETTINGS.to_string(), None::<&()>).await?;
282 Ok(answer.areas)
283 }
284
285 pub async fn area_settings(&self, partition: &str) -> Result<super::api::AreaView> {
291 let path = paths::AREA_SETTINGS.replace("{partition}", &encode(partition));
292 let answer: super::api::AreaResponse = self.call(Method::GET, path, None::<&()>).await?;
293 Ok(answer.area)
294 }
295
296 pub async fn set_quiet_time(
305 &self,
306 partition: &str,
307 window: Option<crate::sched::QuietHours>,
308 ) -> Result<super::api::AreaView> {
309 let path = paths::QUIET_TIME.replace("{partition}", &encode(partition));
310 let body = super::api::QuietTimeRequest { window };
311 let answer: super::api::AreaResponse = self.call(Method::POST, path, Some(&body)).await?;
312 Ok(answer.area)
313 }
314
315 pub async fn set_spending_limit(
322 &self,
323 partition: &str,
324 micro_usd: Option<u64>,
325 ) -> Result<super::api::AreaView> {
326 let path = paths::SPENDING_LIMIT.replace("{partition}", &encode(partition));
327 let body = super::api::SpendingLimitRequest { micro_usd };
328 let answer: super::api::AreaResponse = self.call(Method::POST, path, Some(&body)).await?;
329 Ok(answer.area)
330 }
331
332 pub async fn set_area_mode(
339 &self,
340 partition: &str,
341 mode: crate::partition::PartitionMode,
342 ) -> Result<super::api::AreaView> {
343 let path = paths::AREA_MODE.replace("{partition}", &encode(partition));
344 let body = super::api::PartitionModeRequest { mode };
345 let answer: super::api::AreaResponse = self.call(Method::POST, path, Some(&body)).await?;
346 Ok(answer.area)
347 }
348
349 #[cfg(feature = "proc")]
357 pub async fn away(&self, query: &super::api::AwayQuery) -> Result<super::api::AwayResponse> {
358 let mut pairs = Vec::new();
359 if let Some(viewer) = &query.viewer {
360 pairs.push(format!("viewer={}", encode(viewer)));
361 }
362 if let Some(after) = query.after {
363 pairs.push(format!("after={after}"));
364 }
365 if let Some(limit) = query.limit {
366 pairs.push(format!("limit={limit}"));
367 }
368 let path = match pairs.is_empty() {
369 true => paths::AWAY.to_string(),
370 false => format!("{}?{}", paths::AWAY, pairs.join("&")),
371 };
372 self.call(Method::GET, path, None::<&()>).await
373 }
374
375 #[cfg(feature = "proc")]
383 pub async fn mark_away_seen(
384 &self,
385 viewer: Option<&str>,
386 through: u64,
387 ) -> Result<super::AwayCursor> {
388 let body = super::api::SeenRequest { viewer: viewer.map(str::to_string), through };
389 let answer: super::api::SeenResponse =
390 self.call(Method::POST, paths::AWAY_SEEN.to_string(), Some(&body)).await?;
391 Ok(answer.cursor)
392 }
393
394 #[cfg(feature = "proc")]
402 pub async fn away_line(&self, seq: u64) -> Result<super::api::AwayLineResponse> {
403 let path = paths::AWAY_LINE.replace("{seq}", &seq.to_string());
404 self.call(Method::GET, path, None::<&()>).await
405 }
406
407 pub async fn memory(&self, area: Option<&str>) -> Result<super::api::MemoryResponse> {
415 let path = match area {
416 Some(area) => format!("{}?area={}", paths::MEMORY, encode(area)),
417 None => paths::MEMORY.to_string(),
418 };
419 self.call(Method::GET, path, None::<&()>).await
420 }
421
422 pub async fn confirm_fact(&self, id: &str) -> Result<super::RememberedFact> {
430 let path = paths::FACT_CONFIRM.replace("{id}", &encode(id));
431 let answer: super::api::FactResponse = self.call(Method::POST, path, Some(&())).await?;
432 Ok(answer.fact)
433 }
434
435 pub async fn fix_fact(&self, id: &str, text: &str) -> Result<super::RememberedFact> {
442 let path = paths::FACT_FIX.replace("{id}", &encode(id));
443 let body = super::api::FixRequest { text: text.to_string() };
444 let answer: super::api::FactResponse = self.call(Method::POST, path, Some(&body)).await?;
445 Ok(answer.fact)
446 }
447
448 pub async fn forget_fact(&self, id: &str) -> Result<()> {
454 let path = paths::FACT_FORGET.replace("{id}", &encode(id));
455 let _: super::api::ForgetResponse = self.call(Method::POST, path, Some(&())).await?;
456 Ok(())
457 }
458
459 pub async fn undo_tidy_up(&self, id: Option<&str>) -> Result<super::TidyUpUndo> {
468 let body = super::api::UndoRequest { tidy_up: id.map(str::to_string) };
469 self.call(Method::POST, paths::MEMORY_UNDO.to_string(), Some(&body)).await
470 }
471
472 pub async fn record(&self, limit: Option<usize>) -> Result<Vec<super::RecordLine>> {
480 let path = match limit {
481 Some(limit) => format!("{}?limit={limit}", paths::RECORD),
482 None => paths::RECORD.to_string(),
483 };
484 let answer: super::api::RecordResponse = self.call(Method::GET, path, None::<&()>).await?;
485 Ok(answer.lines)
486 }
487
488 pub async fn check_record(&self) -> Result<super::RecordCheck> {
495 self.call(Method::GET, paths::RECORD_CHECK.to_string(), None::<&()>).await
496 }
497
498 pub async fn processes(&self, query: &ProcessesQuery) -> Result<Vec<Process>> {
505 let mut pairs = Vec::new();
506 if let Some(partition) = &query.partition {
507 pairs.push(format!("partition={}", encode(partition.as_str())));
508 }
509 if let Some(state) = query.state {
510 let state = serde_json::to_value(state)?;
511 pairs.push(format!("state={}", encode(state.as_str().unwrap_or_default())));
512 }
513 if let Some(limit) = query.limit {
514 pairs.push(format!("limit={limit}"));
515 }
516 let path = match pairs.is_empty() {
517 true => paths::PROCESSES.to_string(),
518 false => format!("{}?{}", paths::PROCESSES, pairs.join("&")),
519 };
520 let answer: ProcessesResponse = self.call(Method::GET, path, None::<&()>).await?;
521 Ok(answer.processes)
522 }
523
524 pub async fn spawn(&self, request: &SpawnRequest) -> Result<Process> {
532 let answer: ProcessResponse =
533 self.call(Method::POST, paths::PROCESSES.to_string(), Some(request)).await?;
534 Ok(answer.process)
535 }
536
537 pub async fn approvals(&self) -> Result<Vec<ApprovalItem>> {
544 #[derive(serde::Deserialize)]
545 struct Page {
546 items: Vec<ApprovalItem>,
547 }
548 let page: Page =
549 self.call(Method::GET, format!("{APPROVALS}?limit=200"), None::<&()>).await?;
550 Ok(page.items)
551 }
552
553 pub async fn decide(
561 &self,
562 id: &str,
563 version: u64,
564 action: ApprovalAction,
565 reason: Option<&str>,
566 ) -> Result<ApprovalItem> {
567 let body = serde_json::json!({
568 "expectedVersion": version,
569 "action": action,
570 "reason": reason,
571 });
572 let path = format!("{APPROVALS}/{}/decide", encode(id));
573 self.call(Method::POST, path, Some(&body)).await
574 }
575
576 pub async fn kill(&self, pid: &str, reason: Option<&str>) -> Result<Process> {
583 let body = KillRequest { reason: reason.map(str::to_string) };
584 self.process_action(paths::KILL, pid, &body).await
585 }
586
587 pub async fn nice(&self, pid: &str, queue: QueueClass) -> Result<Process> {
594 self.process_action(paths::NICE, pid, &NiceRequest { queue }).await
595 }
596
597 pub async fn suspend(&self, pid: &str) -> Result<Process> {
604 self.process_action(paths::SUSPEND, pid, &()).await
605 }
606
607 pub async fn resume(&self, pid: &str) -> Result<Process> {
614 self.process_action(paths::RESUME, pid, &()).await
615 }
616
617 pub async fn run_now(
626 &self,
627 pid: &str,
628 request_id: Option<&str>,
629 ) -> Result<crate::kernel::RunNow> {
630 let path = paths::RUN_NOW.replace("{pid}", &encode(pid));
631 self.call(Method::POST, path, Some(&run_now_request(request_id))).await
632 }
633
634 pub async fn run_trigger_now(
642 &self,
643 name: &str,
644 request_id: Option<&str>,
645 ) -> Result<crate::kernel::RunNow> {
646 let path = paths::TRIGGER_RUN_NOW.replace("{name}", &encode(name));
647 self.call(Method::POST, path, Some(&run_now_request(request_id))).await
648 }
649
650 #[cfg(feature = "drivers")]
657 pub async fn drivers(&self) -> Result<Vec<crate::drivers::DriverView>> {
658 let answer: super::api::DriversResponse =
659 self.call(Method::GET, paths::DRIVERS.to_string(), None::<&()>).await?;
660 Ok(answer.drivers)
661 }
662
663 #[cfg(feature = "drivers")]
671 pub async fn mount_driver(
672 &self,
673 id: &str,
674 manifest: &str,
675 confirm: bool,
676 ) -> Result<super::api::MountDriverResponse> {
677 let mut body = super::api::MountDriverRequest::new(manifest);
678 body.confirm = confirm;
679 let path = paths::DRIVER_MOUNT.replace("{id}", &encode(id));
680 self.call(Method::POST, path, Some(&body)).await
681 }
682
683 #[cfg(feature = "drivers")]
690 pub async fn unmount_driver(&self, id: &str) -> Result<bool> {
691 let path = paths::DRIVER_UNMOUNT.replace("{id}", &encode(id));
692 let answer: super::api::UnmountDriverResponse =
693 self.call(Method::POST, path, Some(&())).await?;
694 Ok(answer.unmounted)
695 }
696
697 #[cfg(feature = "drivers")]
704 pub async fn restart_driver(&self, id: &str) -> Result<crate::drivers::DriverView> {
705 let path = paths::DRIVER_RESTART.replace("{id}", &encode(id));
706 let answer: super::api::DriverResponse = self.call(Method::POST, path, Some(&())).await?;
707 Ok(answer.driver)
708 }
709
710 #[cfg(feature = "drivers")]
717 pub async fn reapprove_driver(&self, id: &str) -> Result<crate::drivers::DriverView> {
718 let path = paths::DRIVER_REAPPROVE.replace("{id}", &encode(id));
719 let answer: super::api::DriverResponse = self.call(Method::POST, path, Some(&())).await?;
720 Ok(answer.driver)
721 }
722
723 pub async fn freeze(&self, reason: Option<&str>) -> Result<FreezeResponse> {
730 let body = FreezeRequest { reason: reason.map(str::to_string) };
731 self.call(Method::POST, paths::FREEZE.to_string(), Some(&body)).await
732 }
733
734 pub async fn unfreeze(&self) -> Result<FreezeResponse> {
741 self.call(Method::POST, paths::UNFREEZE.to_string(), Some(&())).await
742 }
743
744 #[cfg(feature = "proc")]
752 pub async fn ledger(
753 &self,
754 params: &super::api::LedgerParams,
755 ) -> Result<super::api::LedgerResponse> {
756 let mut pairs = Vec::new();
757 let mut pair = |key: &str, value: Option<String>| {
758 if let Some(value) = value {
759 pairs.push(format!("{key}={}", encode(&value)));
760 }
761 };
762 pair("partition", params.partition.as_ref().map(|p| p.as_str().to_string()));
763 pair("kind", params.kind.clone());
764 pair("agent", params.agent.clone());
765 pair("from", params.from.map(|from| from.to_rfc3339()));
766 pair("to", params.to.map(|to| to.to_rfc3339()));
767 pair("after", params.after.map(|after| after.to_string()));
768 pair("limit", params.limit.map(|limit| limit.to_string()));
769 let path = match pairs.is_empty() {
770 true => paths::PROC_LEDGER.to_string(),
771 false => format!("{}?{}", paths::PROC_LEDGER, pairs.join("&")),
772 };
773 self.call(Method::GET, path, None::<&()>).await
774 }
775
776 #[cfg(feature = "proc")]
783 pub async fn baselines(&self) -> Result<Vec<crate::proc::PassState>> {
784 let answer: super::api::BaselinesResponse =
785 self.call(Method::GET, paths::PROC_BASELINES.to_string(), None::<&()>).await?;
786 Ok(answer.partitions)
787 }
788
789 #[cfg(feature = "proc")]
797 pub async fn observations(
798 &self,
799 params: &super::api::ObservationsParams,
800 ) -> Result<Vec<crate::proc::Observation>> {
801 let mut pairs = Vec::new();
802 if let Some(partition) = ¶ms.partition {
803 pairs.push(format!("partition={}", encode(partition.as_str())));
804 }
805 if let Some(since) = params.since {
806 pairs.push(format!("since={since}"));
807 }
808 if let Some(limit) = params.limit {
809 pairs.push(format!("limit={limit}"));
810 }
811 let path = match pairs.is_empty() {
812 true => paths::PROC_OBSERVATIONS.to_string(),
813 false => format!("{}?{}", paths::PROC_OBSERVATIONS, pairs.join("&")),
814 };
815 let answer: super::api::ObservationsResponse =
816 self.call(Method::GET, path, None::<&()>).await?;
817 Ok(answer.observations)
818 }
819
820 pub async fn events(
827 &self,
828 after: Option<u64>,
829 ) -> Result<BoxStream<'static, Result<EventRecord>>> {
830 let path = match after {
831 Some(cursor) => format!("{}?after={cursor}", paths::EVENTS),
832 None => paths::EVENTS.to_string(),
833 };
834 let answer = self.send(Method::GET, &path, None, None).await?;
835 if !answer.status.is_success() {
836 let status = answer.status;
837 return Err(answer_error(status, &answer.bytes().await?));
838 }
839 Ok(server_sent_records(answer.body))
840 }
841
842 pub async fn attach(
849 &self,
850 session_id: &str,
851 request: &AttachRequest,
852 ) -> Result<AttachResponse> {
853 let path = paths::ATTACH.replace("{session}", &encode(session_id));
854 self.call(Method::POST, path, Some(request)).await
855 }
856
857 pub async fn steer(&self, session_id: &str, text: &str) -> Result<SteerResponse> {
889 let path = paths::SESSION_STEER.replace("{session}", &encode(session_id));
890 self.call(Method::POST, path, Some(&SteerRequest::new(text))).await
891 }
892
893 pub async fn agenda(&self, query: &AgendaQuery) -> Result<Vec<AgendaItem>> {
900 let mut pairs = Vec::new();
901 if let Some(partition) = &query.partition {
902 pairs.push(format!("partition={}", encode(partition.as_str())));
903 }
904 if let Some(state) = query.state {
905 pairs.push(format!("state={}", encode(state.as_str())));
906 }
907 if let Some(limit) = query.limit {
908 pairs.push(format!("limit={limit}"));
909 }
910 if query.newest_first {
911 pairs.push("newestFirst=true".to_string());
912 }
913 if let Some(after) = &query.after {
914 pairs.push(format!("after={}", encode(after)));
915 }
916 let path = match pairs.is_empty() {
917 true => paths::AGENDA.to_string(),
918 false => format!("{}?{}", paths::AGENDA, pairs.join("&")),
919 };
920 let answer: AgendaResponse = self.call(Method::GET, path, None::<&()>).await?;
921 Ok(answer.items)
922 }
923
924 pub async fn approve_item(&self, id: &str) -> Result<AgendaItem> {
931 self.agenda_action(paths::AGENDA_APPROVE, id, &()).await
932 }
933
934 pub async fn reject_item(&self, id: &str, reason: Option<&str>) -> Result<AgendaItem> {
941 let body = RejectRequest { reason: reason.map(str::to_string) };
942 self.agenda_action(paths::AGENDA_REJECT, id, &body).await
943 }
944
945 pub async fn schedule_item(&self, id: &str, wake: WakeSet) -> Result<AgendaItem> {
953 self.agenda_action(paths::AGENDA_SCHEDULE, id, &ScheduleRequest { wake }).await
954 }
955
956 pub async fn issue_pairing_code(
965 &self,
966 request: &super::api::IssueRequest,
967 ) -> Result<crate::pairing::IssuedCode> {
968 self.call(Method::POST, paths::PAIRING.to_string(), Some(request)).await
969 }
970
971 pub async fn claim_pairing(
981 &self,
982 code: &str,
983 name: Option<&str>,
984 ) -> Result<crate::pairing::ClaimedDevice> {
985 let body =
986 super::api::ClaimRequest { code: code.to_string(), name: name.map(str::to_string) };
987 let anonymous = Self { transport: self.transport.clone(), token: None };
988 anonymous.call(Method::POST, paths::PAIRING_CLAIM.to_string(), Some(&body)).await
989 }
990
991 pub async fn devices(&self) -> Result<Vec<crate::pairing::DeviceView>> {
998 let answer: super::api::DevicesResponse =
999 self.call(Method::GET, paths::DEVICES.to_string(), None::<&()>).await?;
1000 Ok(answer.devices)
1001 }
1002
1003 pub async fn revoke_device(&self, id: &str) -> Result<crate::pairing::DeviceView> {
1011 let path = paths::DEVICE_REVOKE.replace("{id}", &encode(id));
1012 let answer: super::api::DeviceResponse = self.call(Method::POST, path, Some(&())).await?;
1013 Ok(answer.device)
1014 }
1015
1016 pub async fn channel_accounts(&self) -> Result<super::api::ChannelAccountsResponse> {
1024 self.call(Method::GET, paths::CHANNELS.to_string(), None::<&()>).await
1025 }
1026
1027 pub async fn accept_channel(&self, code: &str) -> Result<super::api::ChannelAccountView> {
1036 let body = super::api::AcceptChannelRequest { code: code.to_string() };
1037 let answer: super::api::ChannelAccountResponse =
1038 self.call(Method::POST, paths::CHANNEL_PAIR.to_string(), Some(&body)).await?;
1039 Ok(answer.account)
1040 }
1041
1042 pub async fn revoke_channel_account(&self, id: &str) -> Result<super::api::ChannelAccountView> {
1049 let path = paths::CHANNEL_REVOKE.replace("{id}", &encode(id));
1050 let answer: super::api::ChannelAccountResponse =
1051 self.call(Method::POST, path, Some(&())).await?;
1052 Ok(answer.account)
1053 }
1054
1055 pub async fn dismiss_channel_request(
1063 &self,
1064 id: &str,
1065 ) -> Result<super::api::ChannelPairingView> {
1066 let path = paths::CHANNEL_DISMISS.replace("{id}", &encode(id));
1067 let answer: super::api::ChannelPairingResponse =
1068 self.call(Method::POST, path, Some(&())).await?;
1069 Ok(answer.waiting)
1070 }
1071
1072 async fn agenda_action(
1073 &self,
1074 route: &str,
1075 id: &str,
1076 body: &impl Serialize,
1077 ) -> Result<AgendaItem> {
1078 let path = route.replace("{id}", &encode(id));
1079 let answer: AgendaItemResponse = self.call(Method::POST, path, Some(body)).await?;
1080 Ok(answer.item)
1081 }
1082
1083 async fn process_action(
1084 &self,
1085 route: &str,
1086 pid: &str,
1087 body: &impl Serialize,
1088 ) -> Result<Process> {
1089 let path = route.replace("{pid}", &encode(pid));
1090 let answer: ProcessResponse = self.call(Method::POST, path, Some(body)).await?;
1091 Ok(answer.process)
1092 }
1093
1094 pub(super) async fn call<T: DeserializeOwned>(
1096 &self,
1097 method: Method,
1098 path: String,
1099 body: Option<&impl Serialize>,
1100 ) -> Result<T> {
1101 let body = body.map(serde_json::to_vec).transpose()?;
1102 let answer = self.send(method, &path, body, Some(CALL_TIMEOUT)).await?;
1103 let status = answer.status;
1104 let bytes = answer.bytes().await?;
1105 if !status.is_success() {
1106 return Err(answer_error(status, &bytes));
1107 }
1108 serde_json::from_slice(&bytes).map_err(|error| KernelError::ControlPlane {
1109 reason: format!(
1110 "the kernel at {} answered {path} with a body this client cannot read ({error}); \
1111 are the CLI and the kernel the same version?",
1112 self.endpoint()
1113 ),
1114 })
1115 }
1116
1117 async fn send(
1118 &self,
1119 method: Method,
1120 path: &str,
1121 body: Option<Vec<u8>>,
1122 timeout: Option<Duration>,
1123 ) -> Result<Answer> {
1124 let path = format!("{}{path}", paths::API_PREFIX);
1125 let unreachable = |error: &dyn std::fmt::Display| KernelError::ControlPlane {
1126 reason: format!(
1127 "could not reach the kernel at {}: {error}; start it with `adk-rust up`",
1128 self.endpoint()
1129 ),
1130 };
1131 match &self.transport {
1132 Transport::Http { base, client } => {
1133 let mut request = client.request(method, format!("{base}{path}"));
1134 if let Some(token) = &self.token {
1135 request = request.bearer_auth(token);
1136 }
1137 if let Some(body) = body {
1138 request = request.header("content-type", "application/json").body(body);
1139 }
1140 if let Some(timeout) = timeout {
1141 request = request.timeout(timeout);
1142 }
1143 let response = request.send().await.map_err(|error| unreachable(&error))?;
1144 let status = StatusCode::from_u16(response.status().as_u16())
1145 .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1146 let body = response
1147 .bytes_stream()
1148 .map(|chunk| {
1149 chunk.map_err(|error| KernelError::ControlPlane {
1150 reason: format!("the kernel's answer broke off: {error}"),
1151 })
1152 })
1153 .boxed();
1154 Ok(Answer { status, body })
1155 }
1156 local => {
1157 let send = local_request(local, method, &path, self.token.as_deref(), body);
1158 let answer = match timeout {
1159 Some(timeout) => tokio::time::timeout(timeout, send)
1160 .await
1161 .map_err(|_| unreachable(&"the kernel did not answer in time"))?,
1162 None => send.await,
1163 };
1164 answer.map_err(|error| unreachable(&error))
1165 }
1166 }
1167 }
1168}
1169
1170#[cfg(unix)]
1171async fn connect_local_socket(path: PathBuf, configured: &Path) -> Result<Option<ControlClient>> {
1172 if path != configured
1175 && let Some(dir) = path.parent()
1176 && !super::socket::check_dir(dir)?
1177 {
1178 return Ok(None);
1179 }
1180 match tokio::fs::symlink_metadata(&path).await {
1181 Ok(_) => {}
1182 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1183 Err(error) => {
1184 return Err(KernelError::ControlPlane {
1185 reason: format!("could not read the kernel socket {}: {error}", path.display()),
1186 });
1187 }
1188 }
1189 match tokio::net::UnixStream::connect(&path).await {
1190 Ok(_) => Ok(Some(ControlClient::socket(path))),
1191 Err(error)
1192 if matches!(
1193 error.kind(),
1194 std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::NotFound
1195 ) =>
1196 {
1197 Ok(None)
1198 }
1199 Err(error) => Err(KernelError::ControlPlane {
1200 reason: format!(
1201 "the kernel socket {} exists but cannot be opened: {error}; it admits only the \
1202 OS user that runs the kernel",
1203 path.display()
1204 ),
1205 }),
1206 }
1207}
1208
1209#[cfg(all(not(unix), not(windows)))]
1210async fn connect_local_socket(_path: PathBuf, _configured: &Path) -> Result<Option<ControlClient>> {
1211 Ok(None)
1212}
1213
1214#[cfg(unix)]
1216async fn socket_exchange(
1217 socket: &Path,
1218 request: hyper::Request<http_body_util::Full<Bytes>>,
1219) -> std::result::Result<hyper::Response<hyper::body::Incoming>, String> {
1220 let stream =
1221 tokio::net::UnixStream::connect(socket).await.map_err(|error| error.to_string())?;
1222 let (mut sender, connection) =
1223 hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream))
1224 .await
1225 .map_err(|error| error.to_string())?;
1226 tokio::spawn(async move {
1227 if let Err(error) = connection.await {
1228 tracing::debug!(error = %error, "kernel socket connection closed");
1229 }
1230 });
1231 sender.send_request(request).await.map_err(|error| error.to_string())
1232}
1233
1234async fn local_request(
1236 local: &Transport,
1237 method: Method,
1238 path: &str,
1239 token: Option<&str>,
1240 body: Option<Vec<u8>>,
1241) -> std::result::Result<Answer, String> {
1242 use http_body_util::{BodyStream, Full};
1243
1244 let mut request =
1245 hyper::Request::builder().method(method).uri(path).header(hyper::header::HOST, "localhost");
1246 if let Some(token) = token {
1247 request = request.header(hyper::header::AUTHORIZATION, format!("Bearer {token}"));
1248 }
1249 if body.is_some() {
1250 request = request.header(hyper::header::CONTENT_TYPE, "application/json");
1251 }
1252 let request = request
1253 .body(Full::new(Bytes::from(body.unwrap_or_default())))
1254 .map_err(|error| error.to_string())?;
1255 let response = match local {
1256 #[cfg(unix)]
1257 Transport::Socket(socket) => socket_exchange(socket, request).await?,
1258 #[cfg(not(unix))]
1259 Transport::Socket(socket) => {
1260 let _ = request;
1261 return Err(format!(
1262 "the local control socket {} needs a Unix platform; on Windows the kernel \
1263 serves a named pipe, which ControlClient::connect_local finds",
1264 socket.display()
1265 ));
1266 }
1267 #[cfg(windows)]
1268 Transport::Pipe(name) => super::pipe::request(name, request).await?,
1269 Transport::Http { base, .. } => {
1270 return Err(format!("{base} is reached over HTTP, not over a local transport"));
1271 }
1272 };
1273 let status = response.status();
1274 let body = BodyStream::new(response.into_body())
1275 .filter_map(|frame| async move {
1276 match frame {
1277 Ok(frame) => frame.into_data().ok().map(Ok),
1278 Err(error) => Some(Err(KernelError::ControlPlane {
1279 reason: format!("the kernel's answer broke off: {error}"),
1280 })),
1281 }
1282 })
1283 .boxed();
1284 Ok(Answer { status, body })
1285}
1286
1287fn answer_error(status: StatusCode, body: &[u8]) -> KernelError {
1290 let value: Option<Value> = serde_json::from_slice(body).ok();
1291 let error = value.as_ref().and_then(|value| value.get("error"));
1292 if let Some(problem) = error.and_then(Value::as_object) {
1293 let message = problem.get("message").and_then(Value::as_str).unwrap_or("").to_string();
1294 let code = problem.get("code").and_then(Value::as_str).unwrap_or("");
1295 let category = problem
1296 .get("category")
1297 .and_then(|category| serde_json::from_value(category.clone()).ok())
1298 .unwrap_or_else(|| category_of(status));
1299 return KernelError::Core(AdkError::new(
1300 ErrorComponent::Server,
1301 category,
1302 known_code(code),
1303 message,
1304 ));
1305 }
1306 let message = match error.and_then(Value::as_str) {
1307 Some(message) => message.to_string(),
1308 None => String::from_utf8_lossy(body).trim().chars().take(300).collect(),
1309 };
1310 match status {
1311 StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => KernelError::Unauthorized {
1312 reason: format!(
1313 "{message}; pass the kernel's bearer token (--token or ADK_SERVE_TOKEN), or run \
1314 the command as the user that runs the kernel"
1315 ),
1316 },
1317 _ => {
1318 KernelError::ControlPlane { reason: format!("the kernel answered {status}: {message}") }
1319 }
1320 }
1321}
1322
1323fn category_of(status: StatusCode) -> ErrorCategory {
1325 match status.as_u16() {
1326 400 => ErrorCategory::InvalidInput,
1327 401 => ErrorCategory::Unauthorized,
1328 403 => ErrorCategory::Forbidden,
1329 404 => ErrorCategory::NotFound,
1330 409 => ErrorCategory::Conflict,
1331 429 => ErrorCategory::RateLimited,
1332 501 => ErrorCategory::Unsupported,
1333 503 => ErrorCategory::Unavailable,
1334 _ => ErrorCategory::Internal,
1335 }
1336}
1337
1338fn known_code(code: &str) -> &'static str {
1340 error::CODES.iter().copied().find(|known| *known == code).unwrap_or(error::CONTROL_PLANE_CODE)
1341}
1342
1343fn run_now_request(request_id: Option<&str>) -> RunNowRequest {
1346 match request_id {
1347 Some(id) => RunNowRequest::default().with_request_id(id),
1348 None => RunNowRequest::default(),
1349 }
1350}
1351
1352pub(super) fn encode(text: &str) -> String {
1353 let mut encoded = String::with_capacity(text.len());
1354 for byte in text.bytes() {
1355 match byte {
1356 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
1357 encoded.push(byte as char);
1358 }
1359 _ => encoded.push_str(&format!("%{byte:02X}")),
1360 }
1361 }
1362 encoded
1363}
1364
1365fn server_sent_records(
1368 body: BoxStream<'static, Result<Bytes>>,
1369) -> BoxStream<'static, Result<EventRecord>> {
1370 struct Reader {
1371 body: BoxStream<'static, Result<Bytes>>,
1372 buffer: Vec<u8>,
1373 ready: VecDeque<Result<EventRecord>>,
1374 done: bool,
1375 }
1376 let reader = Reader { body, buffer: Vec::new(), ready: VecDeque::new(), done: false };
1377 stream::unfold(reader, |mut reader| async move {
1378 loop {
1379 if let Some(record) = reader.ready.pop_front() {
1380 return Some((record, reader));
1381 }
1382 if reader.done {
1383 return None;
1384 }
1385 match reader.body.next().await {
1386 Some(Ok(chunk)) => {
1387 reader.buffer.extend_from_slice(&chunk);
1388 while let Some(end) = event_end(&reader.buffer) {
1389 let block: Vec<u8> = reader.buffer.drain(..end.0).collect();
1390 reader.buffer.drain(..end.1);
1391 if let Some(record) = parse_event(&block) {
1392 reader.ready.push_back(record);
1393 }
1394 }
1395 }
1396 Some(Err(error)) => {
1397 reader.done = true;
1398 reader.ready.push_back(Err(error));
1399 }
1400 None => reader.done = true,
1401 }
1402 }
1403 })
1404 .boxed()
1405}
1406
1407fn event_end(buffer: &[u8]) -> Option<(usize, usize)> {
1409 let lf = buffer.windows(2).position(|window| window == b"\n\n").map(|at| (at, 2));
1410 let crlf = buffer.windows(4).position(|window| window == b"\r\n\r\n").map(|at| (at, 4));
1411 match (lf, crlf) {
1412 (Some(lf), Some(crlf)) => Some(if lf.0 <= crlf.0 { lf } else { crlf }),
1413 (found, None) | (None, found) => found,
1414 }
1415}
1416
1417fn parse_event(block: &[u8]) -> Option<Result<EventRecord>> {
1419 let text = String::from_utf8_lossy(block);
1420 let data: Vec<&str> = text
1421 .lines()
1422 .filter_map(|line| line.strip_prefix("data:"))
1423 .map(|data| data.strip_prefix(' ').unwrap_or(data))
1424 .collect();
1425 if data.is_empty() {
1426 return None;
1427 }
1428 Some(serde_json::from_str(&data.join("\n")).map_err(KernelError::from))
1429}
1430
1431#[cfg(test)]
1432mod tests {
1433 use super::*;
1434
1435 #[test]
1436 fn segments_are_percent_encoded() {
1437 assert_eq!(encode("run-1_a.b~c"), "run-1_a.b~c");
1438 assert_eq!(encode("a/b c?d"), "a%2Fb%20c%3Fd");
1439 }
1440
1441 #[tokio::test]
1442 async fn server_sent_events_split_on_blank_lines_across_chunks() {
1443 let record = |cursor: u64| {
1444 serde_json::to_string(&EventRecord {
1445 cursor,
1446 at: chrono::Utc::now(),
1447 event: crate::KernelEvent::Governance { frozen: true, reason: None },
1448 })
1449 .unwrap()
1450 };
1451 let text = format!(
1452 ": keep-alive\n\nid: 1\nevent: governance\ndata: {}\n\nid: 2\r\ndata: {}\r\n\r\n",
1453 record(1),
1454 record(2)
1455 );
1456 let (head, tail) = text.split_at(40);
1457 let chunks = vec![Ok(Bytes::from(head.to_string())), Ok(Bytes::from(tail.to_string()))];
1458 let records: Vec<_> = server_sent_records(stream::iter(chunks).boxed())
1459 .map(|record| record.unwrap().cursor)
1460 .collect()
1461 .await;
1462 assert_eq!(records, vec![1, 2]);
1463 }
1464
1465 #[test]
1466 fn answers_map_to_kernel_errors() {
1467 let problem = AdkError::from(KernelError::NotFound { pid: "run-9".into() });
1468 let body = serde_json::to_vec(&problem.to_problem_json()).unwrap();
1469 let error = AdkError::from(answer_error(StatusCode::NOT_FOUND, &body));
1470 assert_eq!((error.code, error.category), (error::NOT_FOUND_CODE, ErrorCategory::NotFound));
1471 assert!(error.message.contains("run-9"));
1472
1473 let refused =
1474 answer_error(StatusCode::UNAUTHORIZED, br#"{"error":"missing authorization"}"#);
1475 assert!(matches!(refused, KernelError::Unauthorized { .. }), "{refused}");
1476
1477 let other = answer_error(StatusCode::BAD_GATEWAY, b"upstream down");
1478 assert!(other.to_string().contains("upstream down"), "{other}");
1479 }
1480
1481 #[test]
1482 fn every_kernel_code_reaches_the_client() {
1483 let refusals = [
1484 KernelError::AgendaNotFound { item: "agenda-1".into() },
1485 KernelError::AgendaState {
1486 item: "agenda-1".into(),
1487 state: crate::agenda::AgendaStateKind::Rejected,
1488 action: "approved",
1489 },
1490 KernelError::Quota { partition: "work".into(), reason: "max running 2".into() },
1491 ];
1492 for refusal in refusals {
1493 let problem = AdkError::from(refusal);
1494 let body = serde_json::to_vec(&problem.to_problem_json()).unwrap();
1495 let status = StatusCode::from_u16(problem.http_status_code()).unwrap();
1496 let error = AdkError::from(answer_error(status, &body));
1497 assert_eq!((error.code, error.category), (problem.code, problem.category));
1498 }
1499 for code in error::CODES {
1500 let problem =
1501 AdkError::new(ErrorComponent::Server, ErrorCategory::Conflict, code, "refused");
1502 let body = serde_json::to_vec(&problem.to_problem_json()).unwrap();
1503 assert_eq!(AdkError::from(answer_error(StatusCode::CONFLICT, &body)).code, *code);
1504 }
1505 let foreign = AdkError::new(
1507 ErrorComponent::Server,
1508 ErrorCategory::Conflict,
1509 "session.not_found",
1510 "refused",
1511 );
1512 let body = serde_json::to_vec(&foreign.to_problem_json()).unwrap();
1513 let error = AdkError::from(answer_error(StatusCode::CONFLICT, &body));
1514 assert_eq!((error.code, error.message.as_str()), (error::CONTROL_PLANE_CODE, "refused"));
1515 }
1516}