Skip to main content

centralcore/process/
mod.rs

1//! Asynchronous multi-instance Minecraft process lifecycle management.
2
3use std::{
4    collections::HashMap,
5    path::{Path, PathBuf},
6    process::Stdio,
7    sync::Arc,
8};
9
10use serde::{Deserialize, Serialize};
11use sysinfo::{Pid, ProcessesToUpdate, System};
12use tokio::{
13    io::{AsyncBufReadExt, AsyncRead, BufReader},
14    sync::{broadcast, mpsc, watch, RwLock},
15    time::{sleep, Duration, Instant},
16};
17
18use crate::{
19    events::{CoreEvent, EventBus, ProcessStream},
20    instance::InstanceId,
21    lock::LockManager,
22    minecraft::{LaunchPlan, MinecraftError},
23    Error, Result,
24};
25
26/// Completed process status.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28pub struct ProcessExit {
29    pub code: Option<i32>,
30    pub success: bool,
31}
32
33/// Handle returned after a process has been detached from the current runtime.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct DetachedInstance {
36    pub instance_id: InstanceId,
37    pub pid: u32,
38}
39
40/// Result of scanning persisted process identities.
41#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
42pub struct ProcessRecoveryReport {
43    pub recovered: u64,
44    pub lost: u64,
45    pub identity_mismatches: u64,
46}
47
48/// Structured persisted-process failures.
49#[derive(Debug, thiserror::Error)]
50#[non_exhaustive]
51pub enum ProcessRecoveryError {
52    #[error(
53        "persisted PID {pid} no longer matches the Minecraft process identity for `{instance_id}`"
54    )]
55    IdentityMismatch { instance_id: String, pid: u32 },
56    #[error("persisted process state for `{instance_id}` is invalid: {reason}")]
57    InvalidState { instance_id: String, reason: String },
58    #[error("operating system refused to stop PID {pid} for instance `{instance_id}`: {reason}")]
59    StopFailed {
60        instance_id: String,
61        pid: u32,
62        reason: String,
63    },
64}
65
66#[derive(Debug, Clone)]
67struct ProcessEntry {
68    pid: u32,
69    executable: PathBuf,
70    kill: mpsc::Sender<ProcessCommand>,
71    exit: watch::Receiver<Option<ProcessExit>>,
72    stdout: broadcast::Sender<String>,
73    stderr: broadcast::Sender<String>,
74}
75
76#[derive(Debug)]
77enum ProcessCommand {
78    Kill,
79}
80
81#[derive(Debug, Clone, Serialize, Deserialize)]
82struct PersistedProcess {
83    pid: u32,
84    executable: PathBuf,
85    working_directory: PathBuf,
86    #[serde(default)]
87    start_time: Option<u64>,
88}
89
90/// Registry capable of tracking several Minecraft processes concurrently.
91#[derive(Debug, Clone)]
92pub struct ProcessManager {
93    entries: Arc<RwLock<HashMap<InstanceId, ProcessEntry>>>,
94    state_root: PathBuf,
95    events: EventBus,
96    locks: LockManager,
97}
98
99impl ProcessManager {
100    pub(crate) fn new(state_root: PathBuf, events: EventBus) -> Self {
101        let lock_root = state_root
102            .parent()
103            .unwrap_or_else(|| Path::new("."))
104            .join("locks");
105        Self {
106            entries: Arc::new(RwLock::new(HashMap::new())),
107            state_root,
108            events,
109            locks: LockManager::new(lock_root),
110        }
111    }
112
113    /// Launches one plan without invoking a shell.
114    pub async fn launch(
115        &self,
116        instance_id: &InstanceId,
117        plan: &LaunchPlan,
118    ) -> Result<RunningInstance> {
119        let _process_lock = self
120            .locks
121            .try_acquire_exclusive(format!("process:{instance_id}"))
122            .await?;
123        if self.is_running(instance_id).await? {
124            return Err(MinecraftError::AlreadyRunning(instance_id.to_string()).into());
125        }
126        let mut command = plan.command();
127        command
128            .stdout(Stdio::piped())
129            .stderr(Stdio::piped())
130            .kill_on_drop(false);
131        let mut child = command
132            .spawn()
133            .map_err(|error| MinecraftError::Launch(error.to_string()))?;
134        let pid = child
135            .id()
136            .ok_or_else(|| Error::Process("spawned process did not expose a PID".into()))?;
137        let stdout = child.stdout.take();
138        let stderr = child.stderr.take();
139        let (kill_tx, mut kill_rx) = mpsc::channel(2);
140        let (exit_tx, exit_rx) = watch::channel(None);
141        let (stdout_tx, _) = broadcast::channel(1024);
142        let (stderr_tx, _) = broadcast::channel(1024);
143        let entry = ProcessEntry {
144            pid,
145            executable: tokio::fs::canonicalize(plan.executable()).await?,
146            kill: kill_tx,
147            exit: exit_rx.clone(),
148            stdout: stdout_tx.clone(),
149            stderr: stderr_tx.clone(),
150        };
151        if let Err(error) = self.persist(instance_id, pid, plan).await {
152            let _ = child.start_kill();
153            let _ = child.wait().await;
154            return Err(error);
155        }
156        self.entries
157            .write()
158            .await
159            .insert(instance_id.clone(), entry.clone());
160
161        self.events.emit(CoreEvent::MinecraftStarted {
162            instance_id: instance_id.to_string(),
163            pid,
164        });
165        if let Some(stdout) = stdout {
166            tokio::spawn(read_stream(
167                stdout,
168                instance_id.to_string(),
169                ProcessStream::Stdout,
170                self.events.clone(),
171                plan.sensitive_values().to_vec(),
172                stdout_tx,
173            ));
174        }
175        if let Some(stderr) = stderr {
176            tokio::spawn(read_stream(
177                stderr,
178                instance_id.to_string(),
179                ProcessStream::Stderr,
180                self.events.clone(),
181                plan.sensitive_values().to_vec(),
182                stderr_tx,
183            ));
184        }
185
186        let events = self.events.clone();
187        let state_path = self.state_path(instance_id);
188        let id = instance_id.to_string();
189        tokio::spawn(async move {
190            let status = tokio::select! {
191                status = child.wait() => status,
192                command = kill_rx.recv() => {
193                    if matches!(command, Some(ProcessCommand::Kill)) {
194                        let _ = child.start_kill();
195                    }
196                    child.wait().await
197                }
198            };
199            let exit = match status {
200                Ok(status) => ProcessExit {
201                    code: status.code(),
202                    success: status.success(),
203                },
204                Err(_) => ProcessExit {
205                    code: None,
206                    success: false,
207                },
208            };
209            let _ = exit_tx.send(Some(exit));
210            let _ = tokio::fs::remove_file(state_path).await;
211            events.emit(CoreEvent::MinecraftStopped {
212                instance_id: id.clone(),
213                exit_code: exit.code,
214            });
215            events.emit(CoreEvent::ProcessStopped {
216                instance_id: id,
217                pid,
218            });
219        });
220
221        Ok(RunningInstance {
222            instance_id: instance_id.clone(),
223            entry,
224            events: self.events.clone(),
225        })
226    }
227
228    /// Launches Minecraft with file-backed logs and leaves it running when the
229    /// current Tokio runtime or CLI process exits.
230    pub async fn launch_detached(
231        &self,
232        instance_id: &InstanceId,
233        plan: &LaunchPlan,
234    ) -> Result<DetachedInstance> {
235        let _process_lock = self
236            .locks
237            .try_acquire_exclusive(format!("process:{instance_id}"))
238            .await?;
239        if self.is_running(instance_id).await? {
240            return Err(MinecraftError::AlreadyRunning(instance_id.to_string()).into());
241        }
242        let instance_root = plan.working_directory().parent().ok_or_else(|| {
243            Error::Process("launch working directory has no instance root".into())
244        })?;
245        let logs = instance_root.join("logs");
246        tokio::fs::create_dir_all(&logs).await?;
247        let stdout = tokio::fs::OpenOptions::new()
248            .create(true)
249            .append(true)
250            .open(logs.join("minecraft-stdout.log"))
251            .await?
252            .into_std()
253            .await;
254        let stderr = tokio::fs::OpenOptions::new()
255            .create(true)
256            .append(true)
257            .open(logs.join("minecraft-stderr.log"))
258            .await?
259            .into_std()
260            .await;
261        let mut command = plan.command();
262        command
263            .stdin(Stdio::null())
264            .stdout(Stdio::from(stdout))
265            .stderr(Stdio::from(stderr))
266            .kill_on_drop(false);
267        let child = command
268            .spawn()
269            .map_err(|error| MinecraftError::Launch(error.to_string()))?;
270        let pid = child
271            .id()
272            .ok_or_else(|| Error::Process("spawned process did not expose a PID".into()))?;
273        self.persist(instance_id, pid, plan).await?;
274        self.events.emit(CoreEvent::MinecraftStarted {
275            instance_id: instance_id.to_string(),
276            pid,
277        });
278        drop(child);
279        Ok(DetachedInstance {
280            instance_id: instance_id.clone(),
281            pid,
282        })
283    }
284
285    /// Reconciles every persisted process record with the operating system.
286    pub async fn recover(&self) -> Result<ProcessRecoveryReport> {
287        tokio::fs::create_dir_all(&self.state_root).await?;
288        let mut reader = tokio::fs::read_dir(&self.state_root).await?;
289        let mut report = ProcessRecoveryReport::default();
290        while let Some(entry) = reader.next_entry().await? {
291            let path = entry.path();
292            if path.extension().and_then(|value| value.to_str()) != Some("json") {
293                continue;
294            }
295            let Some(stem) = path.file_stem().and_then(|value| value.to_str()) else {
296                continue;
297            };
298            let Ok(id) = InstanceId::new(stem) else {
299                continue;
300            };
301            let Some(process) = self.read_persisted(&id).await? else {
302                continue;
303            };
304            match probe_process(&process).await? {
305                ProcessProbe::Alive => {
306                    report.recovered += 1;
307                    self.events.emit(CoreEvent::ProcessRecovered {
308                        instance_id: id.to_string(),
309                        pid: process.pid,
310                    });
311                }
312                ProcessProbe::Gone => {
313                    report.lost += 1;
314                    tokio::fs::remove_file(path).await?;
315                    self.events.emit(CoreEvent::ProcessLost {
316                        instance_id: id.to_string(),
317                        pid: process.pid,
318                    });
319                }
320                ProcessProbe::IdentityMismatch => {
321                    report.identity_mismatches += 1;
322                    tokio::fs::remove_file(path).await?;
323                    self.events.emit(CoreEvent::ProcessIdentityMismatch {
324                        instance_id: id.to_string(),
325                        pid: process.pid,
326                    });
327                }
328            }
329        }
330        Ok(report)
331    }
332
333    /// Returns whether an in-memory or safely identified persisted process is alive.
334    pub async fn is_running(&self, instance_id: &InstanceId) -> Result<bool> {
335        if let Some(entry) = self.entries.read().await.get(instance_id) {
336            return Ok(entry.exit.borrow().is_none());
337        }
338        let Some(process) = self.read_persisted(instance_id).await? else {
339            return Ok(false);
340        };
341        match probe_process(&process).await? {
342            ProcessProbe::Alive => {
343                self.events.emit(CoreEvent::ProcessRecovered {
344                    instance_id: instance_id.to_string(),
345                    pid: process.pid,
346                });
347                Ok(true)
348            }
349            ProcessProbe::Gone => {
350                let _ = tokio::fs::remove_file(self.state_path(instance_id)).await;
351                self.events.emit(CoreEvent::ProcessLost {
352                    instance_id: instance_id.to_string(),
353                    pid: process.pid,
354                });
355                Ok(false)
356            }
357            ProcessProbe::IdentityMismatch => {
358                let _ = tokio::fs::remove_file(self.state_path(instance_id)).await;
359                self.events.emit(CoreEvent::ProcessIdentityMismatch {
360                    instance_id: instance_id.to_string(),
361                    pid: process.pid,
362                });
363                Ok(false)
364            }
365        }
366    }
367
368    /// Reports whether an active tracked process uses the given executable.
369    pub async fn is_executable_running(&self, executable: impl AsRef<Path>) -> Result<bool> {
370        let executable = tokio::fs::canonicalize(executable).await?;
371        if self.entries.read().await.values().any(|entry| {
372            entry.exit.borrow().is_none()
373                && path_matches(Some(entry.executable.as_path()), &executable)
374        }) {
375            return Ok(true);
376        }
377        if !tokio::fs::try_exists(&self.state_root).await? {
378            return Ok(false);
379        }
380        let mut reader = tokio::fs::read_dir(&self.state_root).await?;
381        while let Some(entry) = reader.next_entry().await? {
382            if entry.path().extension().and_then(|value| value.to_str()) != Some("json") {
383                continue;
384            }
385            let Ok(bytes) = tokio::fs::read(entry.path()).await else {
386                continue;
387            };
388            let Ok(process) = serde_json::from_slice::<PersistedProcess>(&bytes) else {
389                continue;
390            };
391            if path_matches(Some(process.executable.as_path()), &executable)
392                && matches!(probe_process(&process).await?, ProcessProbe::Alive)
393            {
394                return Ok(true);
395            }
396        }
397        Ok(false)
398    }
399
400    /// Stops a tracked process, including one launched by another CLI process.
401    pub async fn kill(&self, instance_id: &InstanceId) -> Result<bool> {
402        let _process_lock = self
403            .locks
404            .acquire_exclusive(format!("process:{instance_id}"))
405            .await?;
406        if let Some(entry) = self.entries.read().await.get(instance_id).cloned() {
407            self.events.emit(CoreEvent::ProcessStopping {
408                instance_id: instance_id.to_string(),
409                pid: entry.pid,
410            });
411            entry
412                .kill
413                .send(ProcessCommand::Kill)
414                .await
415                .map_err(|_| Error::Process("process monitor is no longer available".into()))?;
416            return Ok(true);
417        }
418        let Some(process) = self.read_persisted(instance_id).await? else {
419            return Ok(false);
420        };
421        match probe_process(&process).await? {
422            ProcessProbe::Alive => {}
423            ProcessProbe::Gone => {
424                let _ = tokio::fs::remove_file(self.state_path(instance_id)).await;
425                self.events.emit(CoreEvent::ProcessLost {
426                    instance_id: instance_id.to_string(),
427                    pid: process.pid,
428                });
429                return Ok(false);
430            }
431            ProcessProbe::IdentityMismatch => {
432                let _ = tokio::fs::remove_file(self.state_path(instance_id)).await;
433                self.events.emit(CoreEvent::ProcessIdentityMismatch {
434                    instance_id: instance_id.to_string(),
435                    pid: process.pid,
436                });
437                return Err(ProcessRecoveryError::IdentityMismatch {
438                    instance_id: instance_id.to_string(),
439                    pid: process.pid,
440                }
441                .into());
442            }
443        }
444        self.events.emit(CoreEvent::ProcessStopping {
445            instance_id: instance_id.to_string(),
446            pid: process.pid,
447        });
448        let pid = process.pid;
449        if let Err(reason) = stop_persisted(&process).await? {
450            return Err(ProcessRecoveryError::StopFailed {
451                instance_id: instance_id.to_string(),
452                pid,
453                reason,
454            }
455            .into());
456        }
457        let _ = tokio::fs::remove_file(self.state_path(instance_id)).await;
458        self.events.emit(CoreEvent::ProcessStopped {
459            instance_id: instance_id.to_string(),
460            pid,
461        });
462        Ok(true)
463    }
464
465    async fn persist(&self, id: &InstanceId, pid: u32, plan: &LaunchPlan) -> Result<()> {
466        tokio::fs::create_dir_all(&self.state_root).await?;
467        let root_metadata = tokio::fs::symlink_metadata(&self.state_root).await?;
468        if !root_metadata.is_dir() || root_metadata.file_type().is_symlink() {
469            return Err(Error::UnsafeFilesystemEntry {
470                path: self.state_root.clone(),
471                reason: "process state root must be a real directory",
472            });
473        }
474        let state = PersistedProcess {
475            pid,
476            executable: tokio::fs::canonicalize(plan.executable()).await?,
477            working_directory: tokio::fs::canonicalize(plan.working_directory()).await?,
478            start_time: process_start_time(pid).await?,
479        };
480        let destination = self.state_path(id);
481        let temporary = self
482            .state_root
483            .join(format!("{}.{}.tmp", id.as_str(), std::process::id()));
484        tokio::fs::write(&temporary, serde_json::to_vec_pretty(&state)?).await?;
485        if tokio::fs::try_exists(&destination).await? {
486            let metadata = tokio::fs::symlink_metadata(&destination).await?;
487            if !metadata.is_file() || metadata.file_type().is_symlink() {
488                return Err(Error::UnsafeFilesystemEntry {
489                    path: destination,
490                    reason: "process state must be a real file",
491                });
492            }
493            tokio::fs::remove_file(&destination).await?;
494        }
495        tokio::fs::rename(temporary, destination).await?;
496        Ok(())
497    }
498
499    async fn read_persisted(&self, id: &InstanceId) -> Result<Option<PersistedProcess>> {
500        let path = self.state_path(id);
501        match tokio::fs::read(path).await {
502            Ok(bytes) => Ok(Some(serde_json::from_slice(&bytes)?)),
503            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
504            Err(error) => Err(error.into()),
505        }
506    }
507
508    fn state_path(&self, id: &InstanceId) -> PathBuf {
509        self.state_root.join(format!("{}.json", id.as_str()))
510    }
511}
512
513/// Handle for one live or recently-exited Minecraft process.
514#[derive(Debug, Clone)]
515pub struct RunningInstance {
516    instance_id: InstanceId,
517    entry: ProcessEntry,
518    events: EventBus,
519}
520
521impl RunningInstance {
522    #[must_use]
523    pub fn instance_id(&self) -> &InstanceId {
524        &self.instance_id
525    }
526
527    #[must_use]
528    pub fn pid(&self) -> u32 {
529        self.entry.pid
530    }
531
532    #[must_use]
533    pub fn is_running(&self) -> bool {
534        self.entry.exit.borrow().is_none()
535    }
536
537    #[must_use]
538    pub fn exit_code(&self) -> Option<i32> {
539        self.entry.exit.borrow().as_ref().and_then(|exit| exit.code)
540    }
541
542    /// Subscribes to redacted stdout lines for this process.
543    #[must_use]
544    pub fn stdout(&self) -> broadcast::Receiver<String> {
545        self.entry.stdout.subscribe()
546    }
547
548    /// Subscribes to redacted stderr lines for this process.
549    #[must_use]
550    pub fn stderr(&self) -> broadcast::Receiver<String> {
551        self.entry.stderr.subscribe()
552    }
553
554    pub async fn kill(&self) -> Result<()> {
555        self.entry
556            .kill
557            .send(ProcessCommand::Kill)
558            .await
559            .map_err(|_| Error::Process("process monitor is no longer available".into()))
560    }
561
562    pub async fn wait(&self) -> Result<ProcessExit> {
563        let mut receiver = self.entry.exit.clone();
564        loop {
565            if let Some(exit) = *receiver.borrow() {
566                return Ok(exit);
567            }
568            receiver.changed().await.map_err(|_| {
569                Error::Process("process monitor closed without an exit status".into())
570            })?;
571        }
572    }
573
574    #[must_use]
575    pub fn subscribe_events(&self) -> tokio::sync::broadcast::Receiver<CoreEvent> {
576        self.events.subscribe()
577    }
578}
579
580async fn read_stream<R: AsyncRead + Unpin>(
581    stream: R,
582    instance_id: String,
583    kind: ProcessStream,
584    events: EventBus,
585    secrets: Vec<String>,
586    output: broadcast::Sender<String>,
587) {
588    let mut lines = BufReader::new(stream).lines();
589    while let Ok(Some(line)) = lines.next_line().await {
590        let line = redact(&line, &secrets);
591        let _ = output.send(line.clone());
592        events.emit(CoreEvent::MinecraftLog {
593            instance_id: instance_id.clone(),
594            stream: kind,
595            line: line.clone(),
596        });
597        events.emit(match kind {
598            ProcessStream::Stdout => CoreEvent::MinecraftStdout {
599                instance_id: instance_id.clone(),
600                line,
601            },
602            ProcessStream::Stderr => CoreEvent::MinecraftStderr {
603                instance_id: instance_id.clone(),
604                line,
605            },
606        });
607    }
608}
609
610fn redact(line: &str, secrets: &[String]) -> String {
611    secrets
612        .iter()
613        .filter(|secret| !secret.is_empty())
614        .fold(line.to_owned(), |line, secret| {
615            line.replace(secret, "[REDACTED]")
616        })
617}
618
619#[derive(Debug, Clone, Copy, PartialEq, Eq)]
620enum ProcessProbe {
621    Alive,
622    Gone,
623    IdentityMismatch,
624}
625
626async fn probe_process(expected: &PersistedProcess) -> Result<ProcessProbe> {
627    let pid_value = expected.pid;
628    let executable = expected.executable.clone();
629    let working_directory = expected.working_directory.clone();
630    let start_time = expected.start_time;
631    tokio::task::spawn_blocking(move || {
632        let mut system = System::new();
633        let pid = Pid::from_u32(pid_value);
634        system.refresh_processes(ProcessesToUpdate::Some(&[pid]), true);
635        let Some(process) = system.process(pid) else {
636            return ProcessProbe::Gone;
637        };
638        let expected = PersistedProcess {
639            pid: pid_value,
640            executable,
641            working_directory,
642            start_time,
643        };
644        if persisted_identity_matches(process, &expected) {
645            ProcessProbe::Alive
646        } else {
647            ProcessProbe::IdentityMismatch
648        }
649    })
650    .await
651    .map_err(|error| Error::Process(error.to_string()))
652}
653
654async fn stop_persisted(expected: &PersistedProcess) -> Result<std::result::Result<(), String>> {
655    let expected_for_check = expected.clone();
656    let identity_still_matches = tokio::task::spawn_blocking(move || {
657        let mut system = System::new();
658        let pid = Pid::from_u32(expected_for_check.pid);
659        system.refresh_processes(ProcessesToUpdate::Some(&[pid]), true);
660        let Some(process) = system.process(pid) else {
661            return false;
662        };
663        persisted_identity_matches(process, &expected_for_check)
664    })
665    .await
666    .map_err(|error| Error::Process(error.to_string()))?;
667    if !identity_still_matches {
668        return Ok(Err(
669            "the persisted process identity changed before termination".into(),
670        ));
671    }
672
673    let request = request_forced_stop(expected.pid).await;
674    let deadline = Instant::now() + Duration::from_secs(5);
675    loop {
676        match probe_process(expected).await? {
677            ProcessProbe::Gone | ProcessProbe::IdentityMismatch => return Ok(Ok(())),
678            ProcessProbe::Alive if Instant::now() < deadline => {
679                sleep(Duration::from_millis(50)).await;
680            }
681            ProcessProbe::Alive => {
682                let reason = request
683                    .err()
684                    .unwrap_or_else(|| "the process remained alive after the stop timeout".into());
685                return Ok(Err(reason));
686            }
687        }
688    }
689}
690
691#[cfg(windows)]
692async fn request_forced_stop(pid: u32) -> std::result::Result<(), String> {
693    const CREATE_NO_WINDOW: u32 = 0x0800_0000;
694
695    let taskkill = tokio::process::Command::new("taskkill.exe")
696        .args(["/PID", &pid.to_string(), "/F"])
697        .creation_flags(CREATE_NO_WINDOW)
698        .output()
699        .await
700        .map_err(|error| format!("could not execute taskkill.exe: {error}"))?;
701    if taskkill.status.success() {
702        return Ok(());
703    }
704
705    // Some Windows environments deny `taskkill.exe` while still allowing the
706    // owning user to terminate the process through the native process API.
707    // Windows PowerShell's Stop-Process provides that safe, system-supplied
708    // fallback without weakening the persisted PID identity checks above.
709    let powershell = std::env::var_os("SystemRoot")
710        .map(PathBuf::from)
711        .map(|root| {
712            root.join("System32")
713                .join("WindowsPowerShell")
714                .join("v1.0")
715                .join("powershell.exe")
716        })
717        .unwrap_or_else(|| PathBuf::from("powershell.exe"));
718    let script = format!("Stop-Process -Id {pid} -Force -ErrorAction Stop");
719    let fallback = tokio::process::Command::new(powershell)
720        .args(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"])
721        .arg(script)
722        .creation_flags(CREATE_NO_WINDOW)
723        .output()
724        .await;
725    if fallback
726        .as_ref()
727        .is_ok_and(|output| output.status.success())
728    {
729        return Ok(());
730    }
731
732    let taskkill_reason = command_failure("taskkill.exe", &taskkill);
733    let fallback_reason = match fallback {
734        Ok(output) => command_failure("Stop-Process", &output),
735        Err(error) => format!("could not execute Windows PowerShell: {error}"),
736    };
737    Err(format!(
738        "{taskkill_reason}; fallback failed: {fallback_reason}"
739    ))
740}
741
742#[cfg(windows)]
743fn command_failure(command: &str, output: &std::process::Output) -> String {
744    let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned();
745    let stdout = String::from_utf8_lossy(&output.stdout).trim().to_owned();
746    let detail = if !stderr.is_empty() { stderr } else { stdout };
747    if detail.is_empty() {
748        format!("{command} exited with status {}", output.status)
749    } else {
750        format!("{command} exited with status {}: {detail}", output.status)
751    }
752}
753
754#[cfg(not(windows))]
755async fn request_forced_stop(pid_value: u32) -> std::result::Result<(), String> {
756    tokio::task::spawn_blocking(move || {
757        let mut system = System::new();
758        let pid = Pid::from_u32(pid_value);
759        system.refresh_processes(ProcessesToUpdate::Some(&[pid]), true);
760        let Some(process) = system.process(pid) else {
761            return Ok(());
762        };
763        if process.kill() {
764            Ok(())
765        } else {
766            Err("the operating system rejected the forced termination request".into())
767        }
768    })
769    .await
770    .map_err(|error| error.to_string())?
771}
772
773fn path_matches(actual: Option<&Path>, expected: &Path) -> bool {
774    actual.is_some_and(|actual| path_key(actual) == path_key(expected))
775}
776
777fn persisted_identity_matches(process: &sysinfo::Process, expected: &PersistedProcess) -> bool {
778    path_matches(process.exe(), &expected.executable)
779        && expected
780            .start_time
781            .is_none_or(|start_time| process.start_time() == start_time)
782        && process
783            .cwd()
784            .is_none_or(|cwd| path_matches(Some(cwd), &expected.working_directory))
785}
786
787async fn process_start_time(pid: u32) -> Result<Option<u64>> {
788    tokio::task::spawn_blocking(move || {
789        let mut system = System::new();
790        let pid = Pid::from_u32(pid);
791        system.refresh_processes(ProcessesToUpdate::Some(&[pid]), true);
792        system.process(pid).map(sysinfo::Process::start_time)
793    })
794    .await
795    .map_err(|error| Error::Process(error.to_string()))
796}
797
798fn path_key(path: &Path) -> String {
799    let value = path.to_string_lossy();
800    let value = value
801        .strip_prefix(r"\\?\UNC\")
802        .map(|path| format!(r"\\{path}"))
803        .or_else(|| value.strip_prefix(r"\\?\").map(str::to_owned))
804        .unwrap_or_else(|| value.into_owned());
805    if cfg!(windows) {
806        value.to_lowercase()
807    } else {
808        value
809    }
810}
811
812#[cfg(test)]
813mod tests {
814    use std::{ffi::OsString, time::Duration};
815
816    use super::*;
817
818    #[test]
819    fn redacts_every_known_secret() {
820        assert_eq!(
821            redact("token=secret", &["secret".into()]),
822            "token=[REDACTED]"
823        );
824    }
825
826    #[test]
827    fn normalizes_windows_verbatim_paths_for_identity_checks() {
828        assert_eq!(
829            path_key(Path::new(r"\\?\C:\Games\Minecraft")),
830            path_key(Path::new(r"C:\Games\Minecraft"))
831        );
832    }
833
834    #[tokio::test]
835    async fn launches_tracks_and_kills_without_blocking_tokio() {
836        let temporary = tempfile::tempdir().expect("tempdir");
837        let manager = ProcessManager::new(temporary.path().join("processes"), EventBus::new(32));
838        let plan = LaunchPlan::from_parts_for_test(
839            std::env::current_exe().expect("test executable"),
840            vec![OsString::from("--exact"), OsString::from("--ignored")],
841            "process::tests::long_running_child".into(),
842            vec![OsString::from("--nocapture")],
843            temporary.path().to_path_buf(),
844        );
845        let id = InstanceId::new("process-test").expect("id");
846        let running = manager.launch(&id, &plan).await.expect("launch");
847        assert!(running.is_running());
848        assert!(manager.is_running(&id).await.expect("status"));
849        let external = ProcessManager::new(temporary.path().join("processes"), EventBus::new(32));
850        assert!(external.is_running(&id).await.expect("external status"));
851        assert_eq!(external.recover().await.expect("recovery").recovered, 1);
852        running.kill().await.expect("kill");
853        let exit = tokio::time::timeout(Duration::from_secs(5), running.wait())
854            .await
855            .expect("wait timeout")
856            .expect("wait");
857        assert!(!exit.success);
858    }
859
860    #[tokio::test]
861    async fn detached_process_is_visible_to_a_new_manager() {
862        let temporary = tempfile::tempdir().expect("tempdir");
863        let manager = ProcessManager::new(temporary.path().join("processes"), EventBus::new(32));
864        let plan = LaunchPlan::from_parts_for_test(
865            std::env::current_exe().expect("test executable"),
866            vec![OsString::from("--exact"), OsString::from("--ignored")],
867            "process::tests::short_lived_child".into(),
868            vec![OsString::from("--nocapture")],
869            temporary.path().join(".minecraft"),
870        );
871        tokio::fs::create_dir_all(plan.working_directory())
872            .await
873            .expect("working directory");
874        let id = InstanceId::new("detached-test").expect("id");
875        let detached = manager
876            .launch_detached(&id, &plan)
877            .await
878            .expect("detached launch");
879        assert!(detached.pid > 0);
880        let external = ProcessManager::new(temporary.path().join("processes"), EventBus::new(32));
881        assert!(external.is_running(&id).await.expect("running"));
882        tokio::time::sleep(Duration::from_millis(900)).await;
883        assert!(!external.is_running(&id).await.expect("stopped"));
884    }
885
886    #[tokio::test]
887    async fn detached_process_can_be_stopped_by_a_new_manager() {
888        let temporary = tempfile::tempdir().expect("tempdir");
889        let manager = ProcessManager::new(temporary.path().join("processes"), EventBus::new(32));
890        let plan = LaunchPlan::from_parts_for_test(
891            std::env::current_exe().expect("test executable"),
892            vec![OsString::from("--exact"), OsString::from("--ignored")],
893            "process::tests::long_running_child".into(),
894            vec![OsString::from("--nocapture")],
895            temporary.path().join(".minecraft"),
896        );
897        tokio::fs::create_dir_all(plan.working_directory())
898            .await
899            .expect("working directory");
900        let id = InstanceId::new("detached-stop-test").expect("id");
901        let detached = manager
902            .launch_detached(&id, &plan)
903            .await
904            .expect("detached launch");
905        assert!(detached.pid > 0);
906
907        let external = ProcessManager::new(temporary.path().join("processes"), EventBus::new(32));
908        assert!(external.is_running(&id).await.expect("running"));
909        assert!(external.kill(&id).await.expect("external stop"));
910        assert!(!external.is_running(&id).await.expect("stopped"));
911    }
912
913    #[tokio::test]
914    async fn identity_mismatch_is_never_reported_as_running() {
915        let temporary = tempfile::tempdir().expect("tempdir");
916        let manager = ProcessManager::new(temporary.path().join("processes"), EventBus::new(32));
917        tokio::fs::create_dir_all(&manager.state_root)
918            .await
919            .expect("state root");
920        let id = InstanceId::new("mismatch").expect("id");
921        let state = PersistedProcess {
922            pid: std::process::id(),
923            executable: PathBuf::from("definitely-not-this-process.exe"),
924            working_directory: temporary.path().to_path_buf(),
925            start_time: None,
926        };
927        tokio::fs::write(
928            manager.state_path(&id),
929            serde_json::to_vec(&state).expect("state"),
930        )
931        .await
932        .expect("write state");
933        assert!(!manager.is_running(&id).await.expect("status"));
934        assert!(!manager.state_path(&id).exists());
935    }
936
937    #[test]
938    #[ignore = "helper process spawned by launches_tracks_and_kills_without_blocking_tokio"]
939    fn long_running_child() {
940        std::thread::sleep(Duration::from_secs(30));
941    }
942
943    #[test]
944    #[ignore = "helper process spawned by detached_process_is_visible_to_a_new_manager"]
945    fn short_lived_child() {
946        std::thread::sleep(Duration::from_millis(500));
947    }
948}