micromux_control/server.rs
1//! The per-session control server: bind (race-safe), accept, dispatch.
2//!
3//! The server holds two model capabilities — a [`SessionModelReader`] (queries + `subscribe`) and a
4//! [`ServiceControl`] (mutations and the environment read) — plus the session's shutdown token
5//! (passed to `serve`), which a `Request::Shutdown` cancels to stop the whole session.
6//! It has no model writer, so a request becomes a write only after the scheduler processes it.
7//! PTY input and resize requests reach the session only through the [`TerminalControl`] given to
8//! [`ControlServer::with_terminal`]; without one the server refuses them.
9
10#[cfg(not(unix))]
11#[path = "server/unsupported.rs"]
12mod platform;
13#[cfg(unix)]
14#[path = "server/unix.rs"]
15mod platform;
16
17use std::path::Path;
18use std::sync::Arc;
19use std::sync::atomic::{AtomicU64, Ordering};
20use std::time::{SystemTime, UNIX_EPOCH};
21
22use micromux::{ServiceControl, SessionModelReader, TerminalControl};
23use tokio_util::sync::CancellationToken;
24
25use crate::ControlError;
26use crate::endpoint::{CanonicalConfigPath, ControlEndpoint, endpoint_hash};
27
28pub use platform::EndpointGuard;
29
30static LAST_SESSION_START_TOKEN: AtomicU64 = AtomicU64::new(0);
31
32/// Static session identity used to answer `Describe`.
33#[derive(Debug, Clone)]
34pub struct SessionIdentity {
35 /// Deterministic endpoint hash of the canonical config path.
36 pub id: String,
37 /// Process id of the session.
38 pub pid: u32,
39 /// Monotonic session start token as Unix nanoseconds.
40 pub start_time: u64,
41 /// Session name.
42 pub name: String,
43 /// The directory the session was launched in.
44 pub working_dir: String,
45 /// The canonical config path keying this session's endpoint.
46 pub config_path: String,
47 /// The micromux version of the session binary.
48 pub micromux_version: String,
49}
50
51impl SessionIdentity {
52 /// Build an identity for the current process.
53 #[must_use]
54 pub fn new(name: String, working_dir: &Path, config_path: &CanonicalConfigPath) -> Self {
55 Self {
56 id: endpoint_hash(config_path),
57 pid: std::process::id(),
58 start_time: session_start_token(),
59 name,
60 working_dir: working_dir.to_string_lossy().into_owned(),
61 config_path: config_path.to_string_lossy().into_owned(),
62 micromux_version: env!("CARGO_PKG_VERSION").to_string(),
63 }
64 }
65}
66
67fn session_start_token() -> u64 {
68 let now = SystemTime::now()
69 .duration_since(UNIX_EPOCH)
70 .map_or(0, |duration| {
71 u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX)
72 });
73 let mut previous = LAST_SESSION_START_TOKEN.load(Ordering::Relaxed);
74 loop {
75 let next = now.max(previous.saturating_add(1));
76 match LAST_SESSION_START_TOKEN.compare_exchange_weak(
77 previous,
78 next,
79 Ordering::Relaxed,
80 Ordering::Relaxed,
81 ) {
82 Ok(_) => return next,
83 Err(observed) => previous = observed,
84 }
85 }
86}
87
88/// Bind the control endpoint via the race-safe lifetime-lock dance.
89///
90/// Returns `Ok(Some(guard))` when this process acquired the per-hash ownership lock and bound the
91/// endpoint; `Ok(None)` when a live owner already holds this project (second-instance policy: run
92/// with control disabled); `Err(Unsupported)` on a platform without a transport.
93///
94/// # Errors
95///
96/// Returns [`ControlError::Io`] if the lock file or socket cannot be created/bound, or
97/// [`ControlError::Unsupported`] on an unsupported platform.
98pub fn bind(endpoint: &ControlEndpoint) -> Result<Option<EndpointGuard>, ControlError> {
99 platform::bind(endpoint)
100}
101
102/// How the error a session reports when another session holds its config's owner lock begins,
103/// for a process that only sees the session's stderr, such as the one that started it.
104pub const SESSION_ALREADY_STARTING: &str =
105 "a session for this config is already starting or running";
106
107/// A config's owner lock, which makes the config's session unique.
108///
109/// A session claims it before it waits for anything, so a second start for the same config fails
110/// at once, and [`bind_project`] then serves the endpoint under it.
111/// Dropping it releases the lock.
112#[derive(Debug)]
113pub struct ProjectClaim {
114 // The OS releases the advisory lock when the last descriptor closes, also on a crash.
115 #[cfg_attr(
116 not(unix),
117 expect(
118 dead_code,
119 reason = "platforms without a control transport take no lock, so nothing reads it"
120 )
121 )]
122 lock: Option<std::fs::File>,
123}
124
125/// Why [`claim_project`] could not claim a config.
126#[derive(Debug, thiserror::Error)]
127pub enum ClaimError {
128 /// Another session holds the config's owner lock.
129 #[error(
130 "{SESSION_ALREADY_STARTING}{}; stop it first, or attach to it with `micromux attach`",
131 pid.map(|pid| format!(" (pid {pid})")).unwrap_or_default()
132 )]
133 Held {
134 /// The process id the holder recorded, when it could be read.
135 pid: Option<u32>,
136 },
137 /// The lock file could not be opened or locked.
138 #[error(transparent)]
139 Control(#[from] ControlError),
140}
141
142/// Claims the owner lock of `config_path` for this process, and records its process id there.
143///
144/// The lock lives in a fixed per-user directory under `/tmp`, so changing `XDG_RUNTIME_DIR` or
145/// `TMPDIR` cannot start another supervisor for the same config.
146/// On a platform without a control transport the claim holds no lock.
147///
148/// # Errors
149///
150/// Returns [`ClaimError::Held`] when another process holds the lock, and
151/// [`ClaimError::Control`] when the lock file cannot be opened or locked.
152pub fn claim_project(config_path: &CanonicalConfigPath) -> Result<ProjectClaim, ClaimError> {
153 platform::claim_project(config_path)
154}
155
156/// Claims the owner lock at `lock_path` like [`claim_project`], for tests that keep their locks
157/// out of the user's coordination directory.
158///
159/// # Errors
160///
161/// Returns the same errors as [`claim_project`].
162#[cfg(unix)]
163pub fn claim_project_at(lock_path: &std::path::Path) -> Result<ProjectClaim, ClaimError> {
164 platform::claim_project_at(lock_path)
165}
166
167/// Binds a session endpoint under the config's owner lock, which `claim` holds.
168///
169/// The returned guard shares the owner lock, which stays held until both the guard and `claim`
170/// are dropped.
171///
172/// # Errors
173///
174/// Returns [`ControlError::Io`] if the endpoint lock or the socket cannot be created, or
175/// [`ControlError::Unsupported`] when this platform has no control transport.
176pub fn bind_project(
177 endpoint: &ControlEndpoint,
178 claim: &ProjectClaim,
179) -> Result<Option<EndpointGuard>, ControlError> {
180 platform::bind_project(endpoint, claim)
181}
182
183/// Return whether a live owner currently holds the endpoint's lifetime lock.
184///
185/// This is a read-only diagnostic/probing operation: unlike [`bind`], it never unlinks a socket or
186/// creates a missing lock file.
187///
188/// # Errors
189///
190/// Returns [`ControlError::Io`] if the existing lock file cannot be opened or probed, or
191/// [`ControlError::Unsupported`] on an unsupported platform.
192pub fn endpoint_owner_lock_held(endpoint: &ControlEndpoint) -> Result<bool, ControlError> {
193 platform::endpoint_owner_lock_held(endpoint)
194}
195
196/// A shared hold on a config's owner lock, which shows that no session claims the config while
197/// it lasts.
198///
199/// A session that claims the config meanwhile waits for the hold to end, as it waits out every
200/// probe, so whatever its holder checks under it, such as whether a stopping session still
201/// drains, cannot be overtaken by a successor's claim.
202/// Drop it promptly: a claim gives up after waiting a few seconds.
203#[derive(Debug)]
204pub struct UnclaimedProject {
205 #[expect(
206 dead_code,
207 reason = "held for RAII: the shared lock keeps a successor from claiming the config"
208 )]
209 lock: std::fs::File,
210}
211
212/// Take a hold on the owner lock of `config_path` when no session claims the config, or return
213/// `None` when one does.
214///
215/// A session holds that lock from before it starts anything until it starts stopping, so a
216/// session that is still starting, or runs without a control plane, claims its config too.
217///
218/// # Errors
219///
220/// Returns [`ControlError::Io`] if the lock file cannot be opened or locked, or
221/// [`ControlError::Unsupported`] on an unsupported platform.
222pub fn hold_unclaimed_project(
223 config_path: &CanonicalConfigPath,
224) -> Result<Option<UnclaimedProject>, ControlError> {
225 platform::hold_unclaimed_project(config_path)
226}
227
228/// Takes a hold on the owner lock at `lock_path` like [`hold_unclaimed_project`], for tests that
229/// keep their locks out of the user's coordination directory.
230///
231/// # Errors
232///
233/// Returns the same errors as [`hold_unclaimed_project`].
234#[cfg(unix)]
235pub fn hold_unclaimed_project_at(
236 lock_path: &Path,
237) -> Result<Option<UnclaimedProject>, ControlError> {
238 platform::hold_unclaimed_project_at(lock_path)
239}
240
241/// Unlinks a dead endpoint's leftover socket when its ownership lock proves no session owns it,
242/// and returns whether it removed one.
243///
244/// A held lock, from a running or still starting session, keeps the socket.
245/// Named pipes vanish with their owner, so only Unix sockets can be left behind.
246#[cfg(unix)]
247pub(crate) fn prune_dead_socket(socket_path: &Path) -> std::io::Result<bool> {
248 platform::prune_dead_socket(socket_path)
249}
250
251/// The control server. Cheap to clone-share via `Arc`.
252#[cfg_attr(
253 not(unix),
254 expect(
255 dead_code,
256 reason = "unsupported platforms construct the shared type but do not have a server transport that reads the fields"
257 )
258)]
259pub struct ControlServer {
260 reader: SessionModelReader,
261 control: ServiceControl,
262 identity: SessionIdentity,
263 dynamic_policy: micromux::DynamicServicesPolicy,
264 session: Option<micromux::SessionStatus>,
265 terminal: Option<TerminalControl>,
266}
267
268impl ControlServer {
269 /// Construct a control server over a read capability and a narrow command port.
270 #[must_use]
271 pub fn new(
272 reader: SessionModelReader,
273 control: ServiceControl,
274 identity: SessionIdentity,
275 dynamic_policy: micromux::DynamicServicesPolicy,
276 ) -> Self {
277 Self {
278 reader,
279 control,
280 identity,
281 dynamic_policy,
282 session: None,
283 terminal: None,
284 }
285 }
286
287 /// Reports the session's name, URLs, and allocated ports in [`crate::Request::Describe`].
288 #[must_use]
289 pub fn with_session_status(mut self, session: micromux::SessionStatus) -> Self {
290 self.session = Some(session);
291 self
292 }
293
294 /// Forwards attached TUIs' PTY input and resizes to the session through `terminal`.
295 ///
296 /// Clones share their byte budgets, so remote input counts against the same session-wide and
297 /// per-service limits as the session's own TUI.
298 #[must_use]
299 pub fn with_terminal(mut self, terminal: TerminalControl) -> Self {
300 self.terminal = Some(terminal);
301 self
302 }
303
304 /// Accept connections until `shutdown`, then unlink the endpoint and remove the session's
305 /// environment files (via the guard's `Drop`).
306 ///
307 /// # Errors
308 ///
309 /// Returns [`ControlError::Unsupported`] on a platform without a transport, or an I/O error if
310 /// accepting fails fatally.
311 pub async fn serve(
312 self: Arc<Self>,
313 guard: EndpointGuard,
314 shutdown: CancellationToken,
315 ) -> Result<(), ControlError> {
316 platform::serve(self, guard, shutdown).await
317 }
318}
319
320/// Platforms without a control transport must degrade to a typed `Unsupported` error — never
321/// panic, never bind. This is the contract the CLI's `control::spawn` and every client rely on.
322#[cfg(all(test, not(unix)))]
323mod unsupported_transport_tests {
324 use std::path::Path;
325
326 use super::{bind, endpoint_owner_lock_held};
327 use crate::ControlError;
328 use crate::endpoint::endpoint_from_hash;
329
330 #[test]
331 fn bind_and_owner_probe_report_unsupported_transport() {
332 let endpoint = endpoint_from_hash(Path::new("ignored"), "0011223344556677");
333
334 assert!(matches!(bind(&endpoint), Err(ControlError::Unsupported)));
335 assert!(matches!(
336 endpoint_owner_lock_held(&endpoint),
337 Err(ControlError::Unsupported)
338 ));
339 }
340}
341
342#[cfg(all(test, unix))]
343mod tests {
344 use super::*;
345
346 #[test]
347 fn session_start_token_is_unique_for_fast_successive_sessions() {
348 let first = session_start_token();
349 let second = session_start_token();
350
351 assert_ne!(first, second);
352 }
353
354 #[test]
355 fn session_identity_id_uses_raw_config_path_hash() {
356 use similar_asserts::assert_eq;
357 use std::ffi::OsString;
358 use std::os::unix::ffi::OsStringExt;
359 use std::path::PathBuf;
360
361 // A path whose bytes are not valid UTF-8: the identity must hash the raw bytes, not the
362 // lossy string it advertises to clients. Built through the trusted constructor rather than
363 // a real file because macOS filesystems reject non-UTF-8 filenames outright (EILSEQ), and
364 // the property under test is byte handling, not canonicalization.
365 let config_path = CanonicalConfigPath::from_canonicalized(PathBuf::from(
366 OsString::from_vec(b"/tmp/micromux-\xff.yaml".to_vec()),
367 ));
368 let identity = SessionIdentity::new("test".to_string(), Path::new("."), &config_path);
369
370 assert_eq!(identity.id, endpoint_hash(&config_path));
371 assert_ne!(
372 identity.id,
373 crate::endpoint::hash_path(Path::new(&identity.config_path))
374 );
375 }
376}