micromux-control 0.4.2

Micromux is a local process supervisor with a terminal UI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! The control client used by `micromux ctl` and the MCP proxy.
//!
//! Endpoint probing skips sockets that refuse a connection (dead), and removes those no session
//! owns.
//! It surfaces busy or incompatible endpoints and never prunes them.

use std::path::{Path, PathBuf};

use futures::future;

use crate::ControlError;
use crate::endpoint::ControlEndpoint;
use crate::protocol::{
    PROTOCOL_VERSION, ProtocolVersion, Request, Response, SessionInfo,
    supports_versioned_subscriptions,
};
#[cfg(unix)]
use crate::{PROBE_TIMEOUT, REQUEST_TIMEOUT, read_message, write_message};

/// A connected control client.
pub struct Client {
    #[cfg(unix)]
    conn: crate::Framing<tokio::net::UnixStream>,
}

/// A streaming subscription to liveness-only session changes.
pub struct Subscription {
    #[cfg(unix)]
    conn: crate::Framing<tokio::net::UnixStream>,
    #[cfg(unix)]
    read_timeout: Option<std::time::Duration>,
}

/// Probe result for one concrete endpoint.
#[derive(Debug, Clone)]
pub struct EndpointProbe {
    /// The endpoint that was probed.
    pub endpoint: ControlEndpoint,
    /// What happened when it was probed.
    pub result: EndpointProbeResult,
}

/// The outcome of probing one endpoint.
#[derive(Debug, Clone)]
pub enum EndpointProbeResult {
    /// The endpoint answered `Describe`.
    Session(Box<SessionInfo>),
    /// Nothing live answered on this endpoint.
    Absent(String),
    /// The endpoint answered `Describe`, but its protocol version is incompatible.
    ProtocolMismatch {
        /// The peer's protocol version.
        peer: ProtocolVersion,
        /// Our protocol version.
        ours: ProtocolVersion,
    },
    /// Something was listening, but it was busy or unusable.
    Unreachable(String),
}

/// Return every probe that answered `Describe`, preserving probe order.
#[must_use]
pub fn answering_session_probes(probes: &[EndpointProbe]) -> Vec<(ControlEndpoint, SessionInfo)> {
    probes
        .iter()
        .filter_map(|probe| match &probe.result {
            EndpointProbeResult::Session(info) => Some((probe.endpoint.clone(), (**info).clone())),
            EndpointProbeResult::Absent(_)
            | EndpointProbeResult::ProtocolMismatch { .. }
            | EndpointProbeResult::Unreachable(_) => None,
        })
        .collect()
}

/// Return answering sessions deduped by the session start token, preserving first-seen order.
#[must_use]
pub fn unique_answering_session_probes(
    probes: &[EndpointProbe],
) -> Vec<(ControlEndpoint, SessionInfo)> {
    let mut sessions = Vec::<(ControlEndpoint, SessionInfo)>::new();
    for (endpoint, info) in answering_session_probes(probes) {
        if !sessions
            .iter()
            .any(|(_, existing)| existing.is_same_instance(&info))
        {
            sessions.push((endpoint, info));
        }
    }
    sessions
}

impl Client {
    /// Connect to a control endpoint.
    ///
    /// # Errors
    ///
    /// Returns [`ControlError::Io`] if the endpoint refuses the connection (dead session) or
    /// [`ControlError::Unsupported`] on a platform without a transport.
    #[cfg_attr(
        not(unix),
        expect(
            clippy::unused_async,
            clippy::unused_async_trait_impl,
            reason = "Unix has the async transport implementation; unsupported platforms keep the same API shape"
        )
    )]
    pub async fn connect(endpoint: &ControlEndpoint) -> Result<Self, ControlError> {
        match endpoint {
            #[cfg(unix)]
            ControlEndpoint::Unix(path) => {
                let stream =
                    tokio::time::timeout(REQUEST_TIMEOUT, tokio::net::UnixStream::connect(path))
                        .await
                        .map_err(|_| ControlError::Timeout)??;
                Ok(Self {
                    conn: crate::framed(stream),
                })
            }
            #[cfg(not(unix))]
            ControlEndpoint::Unix(_) => Err(ControlError::Unsupported),
            ControlEndpoint::WindowsNamedPipe(_) => Err(ControlError::Unsupported),
        }
    }

    /// Send one request and await one response, bounded by [`REQUEST_TIMEOUT`].
    ///
    /// # Errors
    ///
    /// Returns [`ControlError::Timeout`] if the peer does not reply in time, [`ControlError::Closed`]
    /// if the connection ends first, or an I/O/serialization error.
    #[cfg_attr(
        not(unix),
        expect(
            clippy::unused_async,
            clippy::unused_async_trait_impl,
            reason = "Unix has the async transport implementation; unsupported platforms keep the same API shape"
        )
    )]
    pub async fn request(&mut self, request: Request) -> Result<Response, ControlError> {
        #[cfg(unix)]
        {
            write_message(&mut self.conn, &request).await?;
            let read =
                tokio::time::timeout(REQUEST_TIMEOUT, read_message::<_, Response>(&mut self.conn))
                    .await
                    .map_err(|_| ControlError::Timeout)?;
            match read? {
                Some(response) => Ok(response),
                None => Err(ControlError::Closed),
            }
        }
        #[cfg(not(unix))]
        {
            let _ = request;
            Err(ControlError::Unsupported)
        }
    }

    /// Subscribe to liveness-only [`micromux::SessionChange`] notifications from an endpoint.
    ///
    /// # Errors
    ///
    /// Returns a transport/protocol error if the endpoint cannot be reached or rejects the
    /// subscription.
    pub async fn subscribe(endpoint: &ControlEndpoint) -> Result<Subscription, ControlError> {
        Self::subscribe_request(endpoint, Request::Subscribe, None).await
    }

    /// Subscribe using capabilities supported by a previously described peer.
    ///
    /// Clients retain the legacy request for pre-3.7 peers, which avoids sending an enum variant
    /// that an older server cannot deserialize.
    ///
    /// # Errors
    ///
    /// Returns a transport/protocol error if the endpoint cannot be reached or rejects the
    /// subscription.
    pub async fn subscribe_for_version(
        endpoint: &ControlEndpoint,
        peer: ProtocolVersion,
    ) -> Result<Subscription, ControlError> {
        let version_aware = supports_versioned_subscriptions(peer);
        let request = if version_aware {
            Request::SubscribeWithVersion {
                protocol_version: PROTOCOL_VERSION,
            }
        } else {
            Request::Subscribe
        };
        let read_timeout = version_aware.then_some(crate::SUBSCRIPTION_READ_TIMEOUT);
        Self::subscribe_request(endpoint, request, read_timeout).await
    }

    #[cfg_attr(
        not(unix),
        expect(
            clippy::unused_async,
            clippy::unused_async_trait_impl,
            reason = "Unix has the async transport implementation; unsupported platforms keep the same API shape"
        )
    )]
    async fn subscribe_request(
        endpoint: &ControlEndpoint,
        request: Request,
        read_timeout: Option<std::time::Duration>,
    ) -> Result<Subscription, ControlError> {
        #[cfg(unix)]
        {
            let ControlEndpoint::Unix(path) = endpoint else {
                return Err(ControlError::Unsupported);
            };
            let stream =
                tokio::time::timeout(REQUEST_TIMEOUT, tokio::net::UnixStream::connect(path))
                    .await
                    .map_err(|_| ControlError::Timeout)??;
            let mut conn = crate::framed(stream);
            write_message(&mut conn, &request).await?;
            Ok(Subscription { conn, read_timeout })
        }

        #[cfg(not(unix))]
        {
            let _ = (endpoint, request, read_timeout);
            Err(ControlError::Unsupported)
        }
    }

    /// Fetch and compatibility-check the session identity.
    ///
    /// # Errors
    ///
    /// Returns [`ControlError::ProtocolMismatch`] on an incompatible major version, or
    /// [`ControlError::Unexpected`] if the peer replies with something other than a description.
    pub async fn describe(&mut self) -> Result<SessionInfo, ControlError> {
        match self.request(Request::Describe).await? {
            Response::Description(info) => {
                if PROTOCOL_VERSION.is_compatible_with(info.protocol_version) {
                    Ok(info)
                } else {
                    Err(ControlError::ProtocolMismatch {
                        peer: info.protocol_version,
                        ours: PROTOCOL_VERSION,
                    })
                }
            }
            other => Err(ControlError::Unexpected(format!("{other:?}"))),
        }
    }

    /// Fetch retained healthcheck attempts in oldest-first order.
    ///
    /// # Errors
    ///
    /// Returns a transport error if the request fails, or [`ControlError::Unexpected`] if the peer
    /// returns a typed rejection or a response for another request.
    pub async fn health_history(
        &mut self,
        service: &str,
    ) -> Result<Vec<micromux::HealthAttempt>, ControlError> {
        match self
            .request(Request::GetHealthHistory {
                service: service.to_string(),
            })
            .await?
        {
            Response::HealthHistory { attempts } => Ok(attempts),
            other => Err(ControlError::Unexpected(format!("{other:?}"))),
        }
    }
}

impl Subscription {
    /// Receive the next change notification, or `Ok(None)` if the session closed the stream.
    ///
    /// # Errors
    ///
    /// Returns [`ControlError::Timeout`] when a version-aware subscription receives no frame before
    /// its liveness deadline, or a transport/protocol error if the stream is malformed.
    #[cfg_attr(
        not(unix),
        expect(
            clippy::unused_async,
            clippy::unused_async_trait_impl,
            reason = "Unix reads from an async subscription stream; unsupported platforms keep the same API shape"
        )
    )]
    pub async fn recv(&mut self) -> Result<Option<micromux::SessionChange>, ControlError> {
        #[cfg(unix)]
        {
            let response = if let Some(timeout) = self.read_timeout {
                tokio::time::timeout(timeout, read_message::<_, Response>(&mut self.conn))
                    .await
                    .map_err(|_| ControlError::Timeout)??
            } else {
                read_message::<_, Response>(&mut self.conn).await?
            };
            match response {
                Some(Response::Change(change)) => Ok(Some(change)),
                Some(Response::Error { code, message }) => Err(ControlError::Unexpected(format!(
                    "subscription error {code:?}: {message}"
                ))),
                Some(other) => Err(ControlError::Unexpected(format!("{other:?}"))),
                None => Ok(None),
            }
        }

        #[cfg(not(unix))]
        {
            Err(ControlError::Unsupported)
        }
    }
}

/// Probe every socket endpoint in one runtime directory.
///
/// Hard-dead endpoints are included as [`EndpointProbeResult::Absent`] instead of being dropped, so
/// callers can surface detailed discovery diagnostics.
///
/// # Errors
///
/// Returns [`ControlError::Unsupported`] on platforms without a concrete control transport.
pub async fn probe_runtime_dir(runtime_dir: &Path) -> Result<Vec<EndpointProbe>, ControlError> {
    #[cfg(unix)]
    {
        let endpoints = runtime_dir_endpoints(runtime_dir);
        Ok(probe_endpoints(&endpoints).await)
    }

    #[cfg(not(unix))]
    {
        let _ = runtime_dir;
        Err(ControlError::Unsupported)
    }
}

/// Probe every socket endpoint across runtime directories in one concurrent batch.
///
/// # Errors
///
/// Returns [`ControlError::Unsupported`] on platforms without a concrete control transport.
pub async fn probe_runtime_dirs(
    runtime_dirs: &[PathBuf],
) -> Result<Vec<EndpointProbe>, ControlError> {
    #[cfg(unix)]
    {
        let mut endpoints = Vec::new();
        for runtime_dir in runtime_dirs {
            endpoints.extend(runtime_dir_endpoints(runtime_dir));
        }
        Ok(probe_endpoints(&endpoints).await)
    }

    #[cfg(not(unix))]
    {
        let _ = runtime_dirs;
        Err(ControlError::Unsupported)
    }
}

/// Probe known endpoints in order.
pub async fn probe_endpoints(endpoints: &[ControlEndpoint]) -> Vec<EndpointProbe> {
    future::join_all(endpoints.iter().map(probe_endpoint)).await
}

/// Probe one known endpoint.
pub async fn probe_endpoint(endpoint: &ControlEndpoint) -> EndpointProbe {
    #[cfg(unix)]
    {
        enum ProbeError {
            Connect(ControlError),
            Describe(ControlError),
        }

        let outcome = tokio::time::timeout(PROBE_TIMEOUT, async {
            let mut client = Client::connect(endpoint)
                .await
                .map_err(ProbeError::Connect)?;
            client.describe().await.map_err(ProbeError::Describe)
        })
        .await;
        match outcome {
            Err(_) => EndpointProbe {
                endpoint: endpoint.clone(),
                result: EndpointProbeResult::Unreachable("probe timed out".to_string()),
            },
            Ok(Ok(info)) => EndpointProbe {
                endpoint: endpoint.clone(),
                result: EndpointProbeResult::Session(Box::new(info)),
            },
            Ok(Err(ProbeError::Describe(ControlError::ProtocolMismatch { peer, ours }))) => {
                EndpointProbe {
                    endpoint: endpoint.clone(),
                    result: EndpointProbeResult::ProtocolMismatch { peer, ours },
                }
            }
            Ok(Err(ProbeError::Connect(ControlError::Io(err))))
                if is_hard_connection_error(&err) || !endpoint_path_is_socket(endpoint) =>
            {
                EndpointProbe {
                    endpoint: endpoint.clone(),
                    result: EndpointProbeResult::Absent(absent_after_connect(endpoint, &err)),
                }
            }
            Ok(Err(ProbeError::Describe(ControlError::Io(err))))
                if is_hard_connection_error(&err) =>
            {
                EndpointProbe {
                    endpoint: endpoint.clone(),
                    result: EndpointProbeResult::Absent(format!("describe: {err}")),
                }
            }
            Ok(Err(ProbeError::Describe(ControlError::Closed))) => EndpointProbe {
                endpoint: endpoint.clone(),
                result: EndpointProbeResult::Unreachable("closed before Describe".to_string()),
            },
            Ok(Err(ProbeError::Connect(err) | ProbeError::Describe(err))) => EndpointProbe {
                endpoint: endpoint.clone(),
                result: EndpointProbeResult::Unreachable(err.to_string()),
            },
        }
    }

    #[cfg(not(unix))]
    {
        EndpointProbe {
            endpoint: endpoint.clone(),
            result: EndpointProbeResult::Unreachable(
                "the control plane is not supported on this platform".to_string(),
            ),
        }
    }
}

/// Describes an endpoint that nothing listens on, after pruning it when it is proven dead.
///
/// A socket or file left behind by a crashed session is removed once its ownership lock shows
/// that no session owns it; see [`crate::server::prune_dead_socket`].
#[cfg(unix)]
fn absent_after_connect(endpoint: &ControlEndpoint, err: &std::io::Error) -> String {
    let reason = format!("connect: {err}");
    let ControlEndpoint::Unix(path) = endpoint else {
        return reason;
    };
    // A missing path leaves nothing to remove, and taking its lock would create a lock file.
    if err.kind() == std::io::ErrorKind::NotFound {
        return reason;
    }
    match crate::server::prune_dead_socket(path) {
        Ok(true) => format!("{reason}; removed the dead endpoint"),
        Ok(false) => reason,
        Err(prune) => {
            tracing::debug!(%prune, path = %path.display(), "cannot prune a dead endpoint");
            reason
        }
    }
}

#[cfg(unix)]
fn is_hard_connection_error(err: &std::io::Error) -> bool {
    matches!(
        err.kind(),
        std::io::ErrorKind::NotFound | std::io::ErrorKind::ConnectionRefused
    )
}

/// Whether the endpoint path is actually a socket file.
///
/// A path that exists but is not a socket — a leaked regular file, a directory — can never have a
/// listener, so a failed connect there means the endpoint is absent, not that a live session is
/// wedged. Platforms disagree on the errno for connecting to a non-socket (Linux reports
/// `ECONNREFUSED`, which [`is_hard_connection_error`] already covers; macOS does not), so decide on
/// the file type instead of the error. Misreading these as unreachable makes callers report
/// "session busy" where they should report "no session".
#[cfg(unix)]
fn endpoint_path_is_socket(endpoint: &ControlEndpoint) -> bool {
    use std::os::unix::fs::FileTypeExt as _;

    match endpoint {
        ControlEndpoint::Unix(path) => {
            std::fs::metadata(path).is_ok_and(|metadata| metadata.file_type().is_socket())
        }
        ControlEndpoint::WindowsNamedPipe(_) => false,
    }
}

#[cfg(unix)]
fn runtime_dir_endpoints(runtime_dir: &Path) -> Vec<ControlEndpoint> {
    let Ok(entries) = std::fs::read_dir(runtime_dir) else {
        return Vec::new();
    };
    let mut endpoints = Vec::new();
    for entry in entries.flatten() {
        let path = entry.path();
        if crate::endpoint::session_socket_hash(&path).is_some() {
            endpoints.push(ControlEndpoint::Unix(path));
        }
    }
    endpoints.sort();
    endpoints
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(unix)]
    use color_eyre::eyre;
    use similar_asserts::assert_eq;
    use std::path::PathBuf;

    fn session(id: &str, pid: u32, start_time: u64, name: &str) -> SessionInfo {
        SessionInfo {
            session: None,
            protocol_version: PROTOCOL_VERSION,
            id: id.to_string(),
            pid,
            start_time,
            name: name.to_string(),
            working_dir: ".".to_string(),
            config_path: "/project/micromux.yaml".to_string(),
            services: Vec::new(),
            services_truncated: false,
            micromux_version: env!("CARGO_PKG_VERSION").to_string(),
            capabilities: None,
        }
    }

    #[test]
    fn unique_answering_session_probes_dedupes_aliases() {
        let first = session("aaa", 42, 100, "first");
        let alias = session("aaa", 42, 100, "alias");
        let second = session("bbb", 43, 101, "second");
        let probes = vec![
            EndpointProbe {
                endpoint: ControlEndpoint::Unix(PathBuf::from("/first.sock")),
                result: EndpointProbeResult::Session(Box::new(first)),
            },
            EndpointProbe {
                endpoint: ControlEndpoint::Unix(PathBuf::from("/alias.sock")),
                result: EndpointProbeResult::Session(Box::new(alias)),
            },
            EndpointProbe {
                endpoint: ControlEndpoint::Unix(PathBuf::from("/second.sock")),
                result: EndpointProbeResult::Session(Box::new(second)),
            },
        ];

        let sessions = unique_answering_session_probes(&probes);

        assert_eq!(sessions.len(), 2);
        assert_eq!(sessions[0].1.name, "first");
        assert_eq!(sessions[1].1.name, "second");
    }

    #[cfg(unix)]
    #[test]
    fn runtime_dir_endpoints_are_sorted() -> eyre::Result<()> {
        let dir = tempfile::tempdir()?;
        let first = format!("{:016x}.sock", 0xa);
        let last = format!("{:016x}.sock", 0xf);
        std::fs::write(dir.path().join(&last), b"")?;
        std::fs::write(dir.path().join(&first), b"")?;
        // Files not named after an endpoint hash, such as the proxy's socket, are never sessions.
        std::fs::write(dir.path().join("proxy.sock"), b"")?;
        std::fs::write(dir.path().join("ignore.txt"), b"")?;

        let endpoints = runtime_dir_endpoints(dir.path());

        assert_eq!(
            endpoints,
            vec![
                ControlEndpoint::Unix(dir.path().join(first)),
                ControlEndpoint::Unix(dir.path().join(last)),
            ],
        );
        Ok(())
    }

    /// A leaked regular file in the runtime dir must probe as `Absent`, never `Unreachable`:
    /// selectors treat unreachable endpoints as "possibly the target, but busy" and report
    /// `session busy` instead of `no session`. Linux reaches this via `ECONNREFUSED`, macOS via a
    /// different errno, so the classification is pinned here for every unix platform.
    #[cfg(unix)]
    #[tokio::test]
    async fn probe_reports_a_leaked_non_socket_file_as_absent() -> eyre::Result<()> {
        let dir = tempfile::tempdir()?;
        let leaked = dir.path().join("dead.sock");
        std::fs::write(&leaked, b"")?;

        let probe = probe_endpoint(&ControlEndpoint::Unix(leaked)).await;

        assert!(
            matches!(probe.result, EndpointProbeResult::Absent(_)),
            "a non-socket file must be absent, got {:?}",
            probe.result
        );
        Ok(())
    }

    /// On platforms without a control transport, `connect` must fail with the typed
    /// `Unsupported` error for every endpoint kind — clients map it to a clear message.
    #[cfg(not(unix))]
    #[tokio::test]
    async fn connect_reports_unsupported_transport_off_unix() {
        let pipe = ControlEndpoint::WindowsNamedPipe(r"\\.\pipe\micromux-test".to_string());
        assert!(matches!(
            Client::connect(&pipe).await,
            Err(ControlError::Unsupported)
        ));

        let socket = ControlEndpoint::Unix(PathBuf::from("/never/bound.sock"));
        assert!(matches!(
            Client::connect(&socket).await,
            Err(ControlError::Unsupported)
        ));
    }
}