1use crate::Result;
2use crate::daemon::{Daemon, RunOptions};
3use crate::daemon_id::DaemonId;
4use crate::env;
5#[cfg(unix)]
6use crate::error::IpcError;
7use interprocess::local_socket::Name;
8#[cfg(unix)]
9use interprocess::local_socket::{GenericFilePath, ToFsName};
10#[cfg(windows)]
11use interprocess::local_socket::{GenericNamespaced, ToNsName};
12use miette::{Context, IntoDiagnostic};
13#[cfg(unix)]
14use std::path::Path;
15use std::path::PathBuf;
16
17pub(crate) mod batch;
18pub(crate) mod client;
19pub(crate) mod server;
20
21#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIs)]
36#[allow(clippy::large_enum_variant)]
37pub enum IpcRequest {
38 Connect,
39 ConnectV2 {
43 version: String,
44 },
45 Clean,
46 Stop {
47 id: DaemonId,
48 },
49 GetActiveDaemons,
50 GetDisabledDaemons,
51 Shutdown,
55 Run(RunOptions),
56 Enable {
57 id: DaemonId,
58 },
59 Disable {
60 id: DaemonId,
61 },
62 UpdateShellDir {
63 shell_pid: u32,
64 dir: PathBuf,
65 },
66 GetNotifications,
67 SyncMdns,
70 ReloadConfig,
73 ProjectEnter {
75 pid: u32,
76 dir: PathBuf,
77 },
78 ProjectLeave {
80 pid: u32,
81 dir: PathBuf,
82 },
83 GetProjectSessions,
86 SinkOutputLine {
94 id: DaemonId,
95 token: u64,
98 fires_hook: bool,
102 line: String,
103 },
104 GetWebUrl,
107 CleanFiltered {
110 namespaces: Vec<String>,
111 daemons: Vec<DaemonId>,
112 prune: bool,
113 },
114 ClaimDaemons {
120 ids: Vec<DaemonId>,
121 },
122 GetDaemons {
126 ids: Vec<DaemonId>,
127 },
128 SinkProgramStatus {
132 id: DaemonId,
133 token: u64,
135 status: Option<crate::program_status::ProgramStatus>,
136 },
137 #[serde(skip)]
139 Invalid {
140 error: String,
141 },
142}
143
144#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
150pub struct ProjectSessionInfo {
151 pub pid: u32,
152 pub directory: PathBuf,
153 #[serde(skip_serializing_if = "Option::is_none", default)]
154 pub liveness_title: Option<String>,
155 pub alive: bool,
156 #[serde(skip_serializing_if = "Option::is_none", default)]
157 pub current_title: Option<String>,
158}
159
160#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIs)]
161pub enum IpcResponse {
162 Ok,
163 ConnectOk {
165 version: String,
166 },
167 Yes,
168 No,
169 Error(String),
170 Notifications(Vec<(log::LevelFilter, String)>),
171 ActiveDaemons(Vec<Daemon>),
172 DisabledDaemons(Vec<DaemonId>),
173 ShuttingDown {
176 budget_ms: u64,
177 },
178 DaemonAlreadyRunning,
179 DaemonStart {
180 daemon: Daemon,
181 },
182 DaemonFailed {
183 error: String,
184 },
185 PortConflict {
187 port: u16,
188 process: String,
189 pid: u32,
190 #[serde(default, skip_serializing_if = "Option::is_none")]
193 address: Option<String>,
194 },
195 NoAvailablePort {
197 start_port: u16,
198 attempts: u32,
199 },
200 DaemonReady {
201 daemon: Daemon,
202 },
203 DaemonFailedWithCode {
204 exit_code: Option<i32>,
205 #[serde(default)]
208 resolved_ports: Vec<u16>,
209 },
210 DaemonWasNotRunning,
212 MdnsSynced,
214 ConfigReloaded,
216 WebUrl {
218 url: Option<String>,
219 },
220 DaemonStopFailed {
222 error: String,
223 },
224 DaemonNotRunning,
226 DaemonNotFound,
227 ProjectSessions(Vec<ProjectSessionInfo>),
229 Cleaned {
231 count: u64,
232 },
233 Daemons(Vec<Daemon>),
235}
236
237#[cfg(unix)]
241const SOCKET_PATH_CAPACITY: usize = {
242 let sun = unsafe { std::mem::zeroed::<libc::sockaddr_un>() };
244 sun.sun_path.len()
245};
246
247#[cfg(unix)]
253fn check_socket_path(path: &Path, capacity: usize) -> Result<()> {
254 use std::os::unix::ffi::OsStrExt;
255 let len = path.as_os_str().as_bytes().len();
256 if len <= capacity {
257 return Ok(());
258 }
259 let over = len - capacity;
260 let help = format!(
261 "the socket is {path} and is {over} byte(s) over the limit.\n\
262 Set PITCHFORK_STATE_DIR (or XDG_STATE_HOME) to a shorter directory, for example \
263 PITCHFORK_STATE_DIR=/tmp/pitchfork, so that <state dir>/sock/main.sock is at most \
264 {capacity} bytes.",
265 path = path.display()
266 );
267 Err(IpcError::SocketPathTooLong {
268 path: path.to_path_buf(),
269 len,
270 limit: capacity,
271 help,
272 }
273 .into())
274}
275
276fn fs_name(name: &str) -> Result<Name<'_>> {
277 #[cfg(unix)]
279 {
280 let path = env::IPC_SOCK_DIR.join(name).with_extension("sock");
281 check_socket_path(&path, SOCKET_PATH_CAPACITY)?;
282 let fs_name = path.to_fs_name::<GenericFilePath>().into_diagnostic()?;
283 Ok(fs_name)
284 }
285 #[cfg(windows)]
294 {
295 let state_dir = env::PITCHFORK_STATE_DIR.to_string_lossy();
296 let mut hash: u64 = 0xcbf29ce484222325;
301 for byte in state_dir.bytes() {
302 hash ^= byte as u64;
303 hash = hash.wrapping_mul(0x100000001b3);
304 }
305 let pipe_name = format!("pitchfork-{hash:016x}-{name}");
306 pipe_name
307 .to_ns_name::<GenericNamespaced>()
308 .into_diagnostic()
309 }
310}
311
312pub(crate) fn socket_display() -> String {
314 #[cfg(unix)]
315 {
316 env::IPC_SOCK_MAIN.display().to_string()
317 }
318 #[cfg(windows)]
319 {
320 "the supervisor named pipe".to_string()
321 }
322}
323
324pub(crate) async fn supervisor_listening() -> bool {
332 use interprocess::local_socket::traits::tokio::Stream as _;
333 let Ok(name) = fs_name("main") else {
334 return false;
335 };
336 let connect = interprocess::local_socket::tokio::Stream::connect(name);
337 match tokio::time::timeout(std::time::Duration::from_secs(1), connect).await {
340 Ok(Ok(_)) => true,
341 Ok(Err(err)) => {
342 trace!("no supervisor listening on the IPC socket: {err}");
343 false
344 }
345 Err(_) => {
346 debug!("timed out probing the IPC socket; treating it as not listening");
347 false
348 }
349 }
350}
351
352fn serialize<T: serde::Serialize>(msg: &T) -> Result<Vec<u8>> {
357 serde_json::to_vec(msg)
358 .into_diagnostic()
359 .wrap_err("failed to serialize IPC message as JSON")
360}
361
362fn deserialize<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<T> {
363 let mut bytes = bytes.to_vec();
364 bytes.pop();
365 let preview = std::str::from_utf8(&bytes).unwrap_or("<binary>");
366 trace!("msg: {preview:?}");
367 serde_json::from_slice(&bytes)
368 .into_diagnostic()
369 .wrap_err("failed to deserialize IPC JSON response")
370}
371
372#[cfg(test)]
373mod tests {
374 #[test]
375 fn port_conflict_from_an_older_supervisor_has_no_address() {
376 let rsp: IpcResponse =
377 serde_json::from_str(r#"{"PortConflict":{"port":3000,"process":"node","pid":42}}"#)
378 .unwrap();
379 assert!(matches!(
380 rsp,
381 IpcResponse::PortConflict {
382 port: 3000,
383 pid: 42,
384 address: None,
385 ..
386 }
387 ));
388 }
389
390 use super::*;
391
392 #[cfg(unix)]
393 #[test]
394 fn socket_path_over_sun_path_capacity_names_path_length_and_fix() {
395 let fits = PathBuf::from(format!("/{}", "a".repeat(SOCKET_PATH_CAPACITY - 1)));
396 assert_eq!(fits.as_os_str().len(), SOCKET_PATH_CAPACITY);
397 assert!(check_socket_path(&fits, SOCKET_PATH_CAPACITY).is_ok());
398
399 let long = PathBuf::from(format!(
400 "/{}/sock/main.sock",
401 "a".repeat(SOCKET_PATH_CAPACITY)
402 ));
403 let err = check_socket_path(&long, SOCKET_PATH_CAPACITY).unwrap_err();
404 let len = long.as_os_str().len();
405 let message = err.to_string();
406 assert!(message.contains(&format!("{len} bytes")), "{message}");
407 assert!(
408 message.contains(&format!("allows {SOCKET_PATH_CAPACITY}")),
409 "{message}"
410 );
411 let help = err.help().expect("help text").to_string();
412 assert!(help.contains(&long.display().to_string()), "{help}");
413 assert!(help.contains("PITCHFORK_STATE_DIR"), "{help}");
414 assert!(help.contains("XDG_STATE_HOME"), "{help}");
415 assert!(
416 matches!(
417 err.downcast_ref::<IpcError>(),
418 Some(IpcError::SocketPathTooLong { len: l, limit, .. })
419 if *l == len && *limit == SOCKET_PATH_CAPACITY
420 ),
421 "{err:?}"
422 );
423 }
424
425 #[cfg(unix)]
426 #[test]
427 fn socket_path_capacity_matches_the_platform() {
428 assert!((100..=108).contains(&SOCKET_PATH_CAPACITY));
430 }
431
432 #[test]
433 fn filtered_clean_ipc_round_trips() {
434 let request = IpcRequest::CleanFiltered {
435 namespaces: vec!["worktree".to_string()],
436 daemons: vec![DaemonId::new("worktree", "api")],
437 prune: true,
438 };
439 let mut bytes = serialize(&request).unwrap();
440 bytes.push(b'\n');
441 let decoded: IpcRequest = deserialize(&bytes).unwrap();
442 match decoded {
443 IpcRequest::CleanFiltered {
444 namespaces,
445 daemons,
446 prune,
447 } => {
448 assert_eq!(namespaces, ["worktree"]);
449 assert_eq!(daemons, [DaemonId::new("worktree", "api")]);
450 assert!(prune);
451 }
452 other => panic!("unexpected request: {other:?}"),
453 }
454
455 let mut bytes = serialize(&IpcResponse::Cleaned { count: 3 }).unwrap();
456 bytes.push(b'\n');
457 let decoded: IpcResponse = deserialize(&bytes).unwrap();
458 assert!(matches!(decoded, IpcResponse::Cleaned { count: 3 }));
459 }
460
461 fn round_trip<T: serde::Serialize + serde::de::DeserializeOwned>(value: &T) -> T {
462 let mut bytes = serialize(value).unwrap();
463 bytes.push(b'\n');
464 deserialize(&bytes).unwrap()
465 }
466
467 #[test]
468 fn claim_daemons_ipc_round_trips() {
469 let ids = vec![DaemonId::new("proj", "api"), DaemonId::new("proj", "db")];
470 match round_trip(&IpcRequest::ClaimDaemons { ids: ids.clone() }) {
471 IpcRequest::ClaimDaemons { ids: decoded } => assert_eq!(decoded, ids),
472 other => panic!("unexpected request: {other:?}"),
473 }
474 }
475
476 #[test]
479 fn proxy_idle_timeout_survives_the_ipc_encoding() {
480 let daemon = Daemon {
481 id: DaemonId::new("proj", "api"),
482 proxy_idle_timeout_ms: Some(900_000),
483 ..Default::default()
484 };
485 match round_trip(&IpcResponse::ActiveDaemons(vec![daemon])) {
486 IpcResponse::ActiveDaemons(daemons) => {
487 assert_eq!(daemons[0].proxy_idle_timeout_ms, Some(900_000));
488 assert!(!daemons[0].oneshot);
489 }
490 other => panic!("unexpected response: {other:?}"),
491 }
492
493 let opts = RunOptions {
494 id: DaemonId::new("proj", "api"),
495 proxy_idle_timeout_ms: Some(900_000),
496 ..Default::default()
497 };
498 match round_trip(&IpcRequest::Run(opts)) {
499 IpcRequest::Run(opts) => assert_eq!(opts.proxy_idle_timeout_ms, Some(900_000)),
500 other => panic!("unexpected request: {other:?}"),
501 }
502 }
503
504 #[test]
507 fn replaces_saved_record_is_opt_in_across_ipc() {
508 let full = RunOptions {
509 id: DaemonId::new("proj", "api"),
510 replaces_saved_record: true,
511 ..Default::default()
512 };
513 match round_trip(&IpcRequest::Run(full)) {
514 IpcRequest::Run(opts) => assert!(opts.replaces_saved_record),
515 other => panic!("unexpected request: {other:?}"),
516 }
517
518 let older_client = RunOptions {
519 id: DaemonId::new("proj", "api"),
520 ..Default::default()
521 };
522 let bytes = serialize(&IpcRequest::Run(older_client)).unwrap();
523 assert!(!String::from_utf8_lossy(&bytes).contains("replaces_saved_record"));
524 match round_trip(&IpcRequest::Run(RunOptions {
525 id: DaemonId::new("proj", "api"),
526 ..Default::default()
527 })) {
528 IpcRequest::Run(opts) => assert!(!opts.replaces_saved_record),
529 other => panic!("unexpected request: {other:?}"),
530 }
531 }
532}