BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / single_instance.rs

single_instance.rs

single_instance.rs 8.1 KiB Download Raw
1use std::sync::Mutex;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::time::{Duration, Instant};
4
5static ACTIVATION: AtomicBool = AtomicBool::new(false);
6static COMMANDS: Mutex<Vec<String>> = Mutex::new(Vec::new());
7
8const RETRY_INTERVAL: Duration = Duration::from_millis(200);
9const RETRY_TIMEOUT: Duration = Duration::from_secs(15);
10
11#[derive(Debug, PartialEq, Eq)]
12pub enum Claim {
13 Primary,
14 Forwarded,
15}
16
17pub fn take_activation() -> bool {
18 ACTIVATION.swap(false, Ordering::AcqRel)
19}
20
21pub fn queue_command(command: &str) {
22 if !command.is_empty() {
23 COMMANDS.lock().unwrap().push(command.to_owned());
24 }
25}
26
27pub fn take_commands() -> Vec<String> {
28 std::mem::take(&mut *COMMANDS.lock().unwrap())
29}
30
31fn received(message: &[u8]) {
32 queue_command(String::from_utf8_lossy(message).trim());
33 ACTIVATION.store(true, Ordering::Release);
34}
35
36/// `command` travels to the running instance, which queues it for `take_commands`.
37pub fn claim(name: &str, wait_for_previous: bool, command: &str) -> Claim {
38 let started = Instant::now();
39 loop {
40 if platform::try_become_primary(name) {
41 queue_command(command);
42 return Claim::Primary;
43 }
44 if !wait_for_previous {
45 platform::notify_primary(name, command);
46 return Claim::Forwarded;
47 }
48 if started.elapsed() >= RETRY_TIMEOUT {
49 return Claim::Primary;
50 }
51 std::thread::sleep(RETRY_INTERVAL);
52 }
53}
54
55fn user_name() -> String {
56 std::env::var("USERNAME")
57 .or_else(|_| std::env::var("USER"))
58 .unwrap_or_default()
59}
60
61#[cfg(windows)]
62mod platform {
63 use std::fs::{File, OpenOptions};
64 use std::io::{Read, Write};
65 use std::mem::ManuallyDrop;
66 use std::os::windows::io::{AsRawHandle, FromRawHandle};
67 use std::time::Duration;
68
69 use windows::Win32::Foundation::{
70 ERROR_ACCESS_DENIED, ERROR_NO_DATA, ERROR_PIPE_BUSY, ERROR_PIPE_CONNECTED, GetLastError,
71 HANDLE, INVALID_HANDLE_VALUE,
72 };
73 use windows::Win32::Storage::FileSystem::{
74 FILE_FLAG_FIRST_PIPE_INSTANCE, FlushFileBuffers, PIPE_ACCESS_INBOUND,
75 };
76 use windows::Win32::System::Pipes::{
77 ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, PIPE_REJECT_REMOTE_CLIENTS,
78 PIPE_TYPE_BYTE, PIPE_WAIT,
79 };
80 use windows::Win32::UI::WindowsAndMessaging::{ASFW_ANY, AllowSetForegroundWindow};
81 use windows::core::PCWSTR;
82
83 use super::{received, user_name};
84
85 const CONNECT_ATTEMPTS: u32 = 20;
86 const CONNECT_INTERVAL: Duration = Duration::from_millis(100);
87
88 fn pipe_path(name: &str) -> String {
89 format!(r"\\.\pipe\{name}-{}", user_name())
90 }
91
92 pub fn try_become_primary(name: &str) -> bool {
93 let wide_path: Vec<u16> = pipe_path(name)
94 .encode_utf16()
95 .chain(std::iter::once(0))
96 .collect();
97 let handle = unsafe {
98 CreateNamedPipeW(
99 PCWSTR(wide_path.as_ptr()),
100 PIPE_ACCESS_INBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE,
101 PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
102 1,
103 0,
104 0,
105 0,
106 None,
107 )
108 };
109 if handle == INVALID_HANDLE_VALUE {
110 let error = unsafe { GetLastError() };
111 return error != ERROR_ACCESS_DENIED && error != ERROR_PIPE_BUSY;
112 }
113 let raw_handle = handle.0 as usize;
114 std::thread::spawn(move || {
115 let handle = HANDLE(raw_handle as *mut _);
116 loop {
117 let connected = unsafe { ConnectNamedPipe(handle, None) }.is_ok()
118 || matches!(
119 unsafe { GetLastError() },
120 ERROR_PIPE_CONNECTED | ERROR_NO_DATA
121 );
122 if connected {
123 let mut pipe = ManuallyDrop::new(unsafe { File::from_raw_handle(handle.0) });
124 let mut message = Vec::new();
125 let _ = pipe.read_to_end(&mut message);
126 received(&message);
127 } else {
128 std::thread::sleep(CONNECT_INTERVAL);
129 }
130 let _ = unsafe { DisconnectNamedPipe(handle) };
131 }
132 });
133 true
134 }
135
136 pub fn notify_primary(name: &str, command: &str) {
137 let path = pipe_path(name);
138 let _ = unsafe { AllowSetForegroundWindow(ASFW_ANY) };
139 for _ in 0..CONNECT_ATTEMPTS {
140 if let Ok(mut pipe) = OpenOptions::new().write(true).open(&path) {
141 let _ = pipe.write_all(command.as_bytes());
142 let _ = unsafe { FlushFileBuffers(HANDLE(pipe.as_raw_handle())) };
143 return;
144 }
145 std::thread::sleep(CONNECT_INTERVAL);
146 }
147 }
148}
149
150#[cfg(unix)]
151mod platform {
152 use std::io::{ErrorKind, Read, Write};
153 use std::os::unix::net::{UnixListener, UnixStream};
154 use std::path::PathBuf;
155 use std::time::Duration;
156
157 use super::{received, user_name};
158
159 const READ_TIMEOUT: Duration = Duration::from_secs(1);
160
161 pub(super) fn socket_path(name: &str) -> PathBuf {
162 let directory = std::env::var_os("XDG_RUNTIME_DIR")
163 .map(PathBuf::from)
164 .unwrap_or_else(std::env::temp_dir);
165 directory.join(format!("{name}-{}.sock", user_name()))
166 }
167
168 enum Bound {
169 Listening(UnixListener),
170 Taken,
171 Unavailable,
172 }
173
174 fn bind(path: &PathBuf) -> Bound {
175 match UnixListener::bind(path) {
176 Ok(listener) => Bound::Listening(listener),
177 Err(error) if error.kind() == ErrorKind::AddrInUse => {
178 if UnixStream::connect(path).is_ok() {
179 return Bound::Taken;
180 }
181 let _ = std::fs::remove_file(path);
182 UnixListener::bind(path).map_or(Bound::Unavailable, Bound::Listening)
183 }
184 Err(_) => Bound::Unavailable,
185 }
186 }
187
188 pub fn try_become_primary(name: &str) -> bool {
189 let listener = match bind(&socket_path(name)) {
190 Bound::Listening(listener) => listener,
191 Bound::Taken => return false,
192 Bound::Unavailable => return true,
193 };
194 std::thread::spawn(move || {
195 for mut connection in listener.incoming().flatten() {
196 let _ = connection.set_read_timeout(Some(READ_TIMEOUT));
197 let mut message = Vec::new();
198 let _ = connection.read_to_end(&mut message);
199 received(&message);
200 }
201 });
202 true
203 }
204
205 pub fn notify_primary(name: &str, command: &str) {
206 if let Ok(mut stream) = UnixStream::connect(socket_path(name)) {
207 let _ = stream.write_all(command.as_bytes());
208 }
209 }
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215
216 #[test]
217 fn second_claim_forwards_and_stale_socket_is_reclaimed() {
218 let name = format!("rusty-teams-test-{}", std::process::id());
219 assert_eq!(
220 claim(&name, false, "join https://example/meet"),
221 Claim::Primary
222 );
223 assert_eq!(take_commands(), ["join https://example/meet"]);
224 assert_eq!(claim(&name, false, "hang-up"), Claim::Forwarded);
225 let started = Instant::now();
226 let mut commands = Vec::new();
227 while commands.is_empty() {
228 assert!(started.elapsed() < Duration::from_secs(1));
229 std::thread::sleep(Duration::from_millis(10));
230 commands = take_commands();
231 }
232 assert_eq!(commands, ["hang-up"]);
233 assert!(take_activation());
234
235 let stale_name = format!("{name}-stale");
236 #[cfg(unix)]
237 {
238 let path = platform::socket_path(&stale_name);
239 drop(std::os::unix::net::UnixListener::bind(&path).unwrap());
240 assert!(path.exists());
241 }
242 assert_eq!(claim(&stale_name, false, ""), Claim::Primary);
243 assert_eq!(
244 claim("missing-directory/rusty-teams", false, ""),
245 Claim::Primary
246 );
247 assert!(take_commands().is_empty());
248
249 #[cfg(unix)]
250 for leftover in [&name, &stale_name] {
251 let _ = std::fs::remove_file(platform::socket_path(leftover));
252 }
253 }
254}