use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
use crate::platform::process::{self, CREATE_NO_WINDOW, Job, free_port, state_file};
const PORT: u16 = 3773;
const POLL: Duration = Duration::from_millis(250);
const START_TIMEOUT: Duration = Duration::from_secs(60);
const SOMEONE_ELSE: Duration = Duration::from_secs(10);
fn desktop_lock() -> Option<PathBuf> {
std::env::var_os("APPDATA").map(|d| PathBuf::from(d).join("t3code-v2").join("lockfile"))
}
fn is_held(path: &Path) -> bool {
match std::fs::OpenOptions::new().read(true).share_mode(0).open(path) {
Ok(_) => false,
Err(e) => e.kind() != std::io::ErrorKind::NotFound,
}
}
fn desktop_running() -> bool {
desktop_lock().is_some_and(|lock| is_held(&lock))
}
fn stop_request() -> Option<PathBuf> {
state_file("t3-server.stop")
}
fn note(message: &str) {
let Some(path) = state_file("t3-server.log") else { return };
if let Some(folder) = path.parent() {
let _ = std::fs::create_dir_all(folder);
}
let when = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
let before = std::fs::read_to_string(&path).unwrap_or_default();
let kept = if message.starts_with("starting") { String::new() } else { before };
let _ = std::fs::write(path, format!("{kept}{when} {message}\n"));
}
trait Starting {
fn ended(&mut self) -> bool;
}
impl Starting for Child {
fn ended(&mut self) -> bool {
self.try_wait().is_ok_and(|status| status.is_some())
}
}
fn wait_for<T>(
ready: &mut dyn FnMut() -> Option<T>,
watcher: Option<&mut dyn Starting>,
app_open: &dyn Fn() -> bool,
patience: (Duration, Duration),
pause: Duration,
) -> Result<T, &'static str> {
let (timeout, after_ours) = patience;
let began = Instant::now();
let mut watcher = watcher;
let mut give_up_at = began + timeout;
loop {
if let Some(answer) = ready() {
return Ok(answer);
}
if watcher.as_mut().is_some_and(|w| w.ended()) {
watcher = None;
if !app_open() {
give_up_at = give_up_at.min(Instant::now() + after_ours);
}
}
if Instant::now() >= give_up_at {
return Err(if app_open() {
"the T3 Code app is open, but its server is not answering"
} else if watcher.is_some() {
"T3 Code's server did not become ready in time. Run `t3 serve` to see why"
} else {
"T3 Code's server stopped while starting. Run `t3 serve` to see why"
});
}
std::thread::sleep(pause);
}
}
pub(super) fn ensure<T>(mut ready: impl FnMut() -> Option<T>) -> Result<T, String> {
let mut watcher = if desktop_running() {
None
} else {
let child =
process::start_watcher("--t3-server").map_err(|e| format!("could not start T3 Code's server: {e}"))?;
Some(child)
};
let result = wait_for(
&mut ready,
watcher.as_mut().map(|w| w as &mut dyn Starting),
&desktop_running,
(START_TIMEOUT, SOMEONE_ELSE),
POLL,
);
if result.is_err()
&& let Some(child) = watcher.as_mut()
{
let _ = child.kill();
let _ = child.wait();
}
result.map_err(str::to_string)
}
pub fn supervise() -> i32 {
if desktop_running() {
return 0;
}
let Ok(cli) = super::cli_path() else {
note("T3 Code's CLI was not found");
return 1;
};
if let Some(stop) = stop_request() {
let _ = std::fs::remove_file(stop);
}
let port = free_port(PORT);
note(&format!("starting T3 Code's server on port {port}"));
let mut command = Command::new(cli);
command
.args(["serve", "--host", "127.0.0.1", "--port", &port.to_string()])
.envs(crate::platform::winenv::fresh())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.creation_flags(CREATE_NO_WINDOW);
if let Some(home) = dirs::home_dir() {
command.current_dir(home);
}
let mut server = match command.spawn() {
Ok(child) => child,
Err(e) => {
note(&format!("could not start it: {e}"));
return 1;
}
};
let Some(job) = Job::holding(&server) else {
note("could not keep hold of the server's processes, so it was not left running");
let _ = server.kill();
return 1;
};
let why = loop {
std::thread::sleep(POLL);
if let Ok(Some(status)) = server.try_wait() {
break format!("the server ended ({status})");
}
if desktop_running() {
break "stopped, to let the T3 Code app take over".to_string();
}
if let Some(stop) = stop_request().filter(|s| s.exists()) {
let _ = std::fs::remove_file(stop);
break "stopped, as asked".to_string();
}
};
drop(job);
let _ = server.wait();
note(&why);
0
}
pub(super) fn stop() -> Result<&'static str, String> {
let request = stop_request().ok_or("could not find rustimal's folder")?;
if let Some(folder) = request.parent() {
std::fs::create_dir_all(folder).map_err(|e| e.to_string())?;
}
std::fs::write(&request, "").map_err(|e| e.to_string())?;
let began = Instant::now();
while began.elapsed() < Duration::from_secs(3) {
if !request.exists() {
return Ok("Stopped the T3 Code server that was running in the background");
}
std::thread::sleep(POLL);
}
let _ = std::fs::remove_file(request);
Ok("rustimal has no T3 Code server running in the background (the app's own is left alone)")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn the_open_t3_app_is_noticed() {
let lock = desktop_lock().unwrap();
assert!(lock.exists(), "open the T3 Code app first");
assert!(desktop_running(), "the app holds {} but was not noticed", lock.display());
}
#[test]
fn a_lock_counts_only_while_it_is_held() {
let path = std::env::temp_dir().join(format!("rustimal-t3-lock-{}", std::process::id()));
let _ = std::fs::remove_file(&path);
assert!(!is_held(&path), "no file");
std::fs::write(&path, "").unwrap();
assert!(!is_held(&path), "left over from before");
const DELETE_ON_CLOSE: u32 = 0x0400_0000;
const SHARE_READ: u32 = 1;
let held = std::fs::OpenOptions::new()
.write(true)
.share_mode(SHARE_READ)
.custom_flags(DELETE_ON_CLOSE)
.open(&path)
.unwrap();
assert!(is_held(&path));
drop(held);
assert!(!path.exists() && !is_held(&path), "gone with its holder");
let held =
std::fs::OpenOptions::new().write(true).create(true).truncate(true).share_mode(0).open(&path).unwrap();
assert!(is_held(&path));
drop(held);
std::fs::remove_file(path).unwrap();
}
struct Fake(bool);
impl Starting for Fake {
fn ended(&mut self) -> bool {
self.0
}
}
fn wait(ready_after: u32, watcher: Option<&mut dyn Starting>, app: bool) -> Result<u32, &'static str> {
let mut asked = 0;
let mut ready = || {
asked += 1;
(asked > ready_after).then_some(asked)
};
let patience = (Duration::from_millis(400), Duration::from_millis(120));
wait_for(&mut ready, watcher, &|| app, patience, Duration::from_millis(5))
}
#[test]
fn it_keeps_asking_until_the_server_can_be_used() {
assert_eq!(wait(3, Some(&mut Fake(false)), false), Ok(4), "not ready at first is no failure");
assert_eq!(wait(3, Some(&mut Fake(true)), false), Ok(4));
assert_eq!(wait(3, None, true), Ok(4), "the app's own server");
}
#[test]
fn it_gives_up_and_says_which_way_it_failed() {
let never = u32::MAX;
assert!(wait(never, Some(&mut Fake(false)), false).unwrap_err().contains("did not become ready"));
let began = Instant::now();
assert!(wait(never, Some(&mut Fake(true)), false).unwrap_err().contains("stopped while starting"));
assert!(began.elapsed() < Duration::from_millis(350), "sooner once ours has ended");
assert!(wait(never, None, true).unwrap_err().contains("app is open"));
}
}