luciola-cli 0.15.0

Command-line interface and diagnostic radar for the Luciola P2P discovery engine
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
//! Cross-platform dynamic idle-sleep guard for active transfers and tunnels.
//!
//! Prevents system idle sleep (while still allowing display sleep) ONLY while
//! an active transfer, forward, or agent session is running, releasing the
//! assertion after a configurable idle grace period or immediately on drop.

use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};

/// Default grace period before releasing an idle-sleep assertion after activity stops.
pub const DEFAULT_RELEASE_GRACE: Duration = Duration::from_secs(120);

/// Platform-specific idle-sleep inhibitor backend.
pub trait PowerBackend: Send + Sync {
    /// Human-readable backend name.
    fn name(&self) -> &'static str;
    /// Whether this backend is usable on the current host.
    fn available(&self) -> bool;
    /// Acquire an idle-sleep assertion.
    fn acquire(&self) -> Result<(), String>;
    /// Release the currently held idle-sleep assertion.
    fn release(&self) -> Result<(), String>;
}

struct GuardState {
    held: bool,
    active: bool,
    closed: bool,
    release_deadline: Option<Instant>,
    waiter_running: bool,
}

/// Dynamic host idle-sleep inhibitor with cancellable grace-period release and RAII cleanup.
pub struct PowerGuard {
    backend: Arc<dyn PowerBackend>,
    release_grace: Duration,
    shared: Arc<(Mutex<GuardState>, Condvar)>,
}

impl PowerGuard {
    /// Create a guard backed by the current platform's default inhibitor.
    pub fn system(release_grace: Duration) -> Self {
        Self::new(Arc::new(SystemPowerBackend::new()), release_grace)
    }

    /// Create a guard with an explicit backend (used by unit tests).
    pub fn new(backend: Arc<dyn PowerBackend>, release_grace: Duration) -> Self {
        let release_grace = if release_grace.is_zero() {
            DEFAULT_RELEASE_GRACE
        } else {
            release_grace
        };
        Self {
            backend,
            release_grace,
            shared: Arc::new((
                Mutex::new(GuardState {
                    held: false,
                    active: false,
                    closed: false,
                    release_deadline: None,
                    waiter_running: false,
                }),
                Condvar::new(),
            )),
        }
    }

    /// Name of the active platform backend.
    #[allow(dead_code)]
    pub fn backend_name(&self) -> &'static str {
        self.backend.name()
    }

    /// Whether an idle-sleep assertion is currently held.
    #[allow(dead_code)]
    pub fn is_held(&self) -> bool {
        self.shared.0.lock().map(|s| s.held).unwrap_or(false)
    }

    /// Mark work active (`true` acquires immediately) or idle (`false` schedules
    /// release after `release_grace`, cancelled immediately if reactivated or dropped).
    pub fn set_active(&self, active: bool) {
        if !self.backend.available() {
            return;
        }
        let (lock, cvar) = &*self.shared;
        let mut st = match lock.lock() {
            Ok(s) => s,
            Err(_) => return,
        };
        if st.closed {
            return;
        }

        if active {
            st.active = true;
            st.release_deadline = None;
            cvar.notify_all();
            if st.held {
                return;
            }
            if let Err(err) = self.backend.acquire() {
                tracing::warn!(backend = self.backend.name(), error = %err, "failed to acquire idle-sleep guard");
                return;
            }
            st.held = true;
            tracing::debug!(backend = self.backend.name(), "acquired idle-sleep guard");
            return;
        }

        if !st.active {
            return;
        }
        st.active = false;
        if !st.held {
            return;
        }
        st.release_deadline = Some(Instant::now() + self.release_grace);
        cvar.notify_all();
        if st.waiter_running {
            return;
        }
        st.waiter_running = true;

        let shared_ref = Arc::clone(&self.shared);
        let backend_ref = Arc::clone(&self.backend);
        drop(st);

        std::thread::spawn(move || {
            let (lock, cvar) = &*shared_ref;
            let mut st = match lock.lock() {
                Ok(s) => s,
                Err(_) => return,
            };
            loop {
                if st.closed || st.active || !st.held {
                    st.waiter_running = false;
                    return;
                }
                let Some(deadline) = st.release_deadline else {
                    st.waiter_running = false;
                    return;
                };
                let now = Instant::now();
                if now >= deadline {
                    st.release_deadline = None;
                    st.waiter_running = false;
                    if let Err(err) = backend_ref.release() {
                        tracing::warn!(backend = backend_ref.name(), error = %err, "failed to release idle-sleep guard");
                    }
                    st.held = false;
                    tracing::debug!(
                        backend = backend_ref.name(),
                        "released idle-sleep guard after idle grace"
                    );
                    return;
                }
                let remaining = deadline.saturating_duration_since(now);
                st = match cvar.wait_timeout(st, remaining) {
                    Ok((guard, _)) => guard,
                    Err(_) => return,
                };
            }
        });
    }

    /// Permanently close the guard and release any held assertion immediately.
    pub fn close(&self) {
        let (lock, cvar) = &*self.shared;
        let mut st = match lock.lock() {
            Ok(s) => s,
            Err(_) => return,
        };
        if st.closed {
            return;
        }
        st.closed = true;
        st.active = false;
        st.release_deadline = None;
        cvar.notify_all();
        if st.held {
            let _ = self.backend.release();
            st.held = false;
        }
    }
}

impl Drop for PowerGuard {
    fn drop(&mut self) {
        self.close();
    }
}

/// Platform-native idle-sleep backend (`caffeinate` on macOS, `systemd-inhibit` on Linux).
struct SystemPowerBackend {
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    child: Mutex<Option<std::process::Child>>,
    #[cfg(target_os = "linux")]
    available_cache: std::sync::OnceLock<bool>,
}

impl SystemPowerBackend {
    fn new() -> Self {
        Self {
            #[cfg(any(target_os = "macos", target_os = "linux"))]
            child: Mutex::new(None),
            #[cfg(target_os = "linux")]
            available_cache: std::sync::OnceLock::new(),
        }
    }
}

impl PowerBackend for SystemPowerBackend {
    fn name(&self) -> &'static str {
        #[cfg(target_os = "macos")]
        {
            "macos-caffeinate"
        }
        #[cfg(target_os = "linux")]
        {
            "linux-systemd-inhibit"
        }
        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
        {
            "noop"
        }
    }

    fn available(&self) -> bool {
        #[cfg(target_os = "macos")]
        {
            std::path::Path::new("/usr/bin/caffeinate").exists()
        }
        #[cfg(target_os = "linux")]
        {
            *self.available_cache.get_or_init(|| {
                std::process::Command::new("systemd-inhibit")
                    .arg("--version")
                    .stdout(std::process::Stdio::null())
                    .stderr(std::process::Stdio::null())
                    .status()
                    .map(|s| s.success())
                    .unwrap_or(false)
            })
        }
        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
        {
            false
        }
    }

    fn acquire(&self) -> Result<(), String> {
        #[cfg(target_os = "macos")]
        {
            let mut slot = self.child.lock().map_err(|e| e.to_string())?;
            if slot.is_some() {
                return Ok(());
            }
            let pid = std::process::id().to_string();
            let child = std::process::Command::new("/usr/bin/caffeinate")
                .args(["-i", "-w", &pid])
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn()
                .map_err(|e| format!("spawn caffeinate: {e}"))?;
            *slot = Some(child);
            Ok(())
        }
        #[cfg(target_os = "linux")]
        {
            let mut slot = self.child.lock().map_err(|e| e.to_string())?;
            if slot.is_some() {
                return Ok(());
            }
            let pid = std::process::id().to_string();
            // Self-terminating child bound to parent PID so even an abrupt
            // SIGKILL never orphans an immortal `sleep infinity` grandchild.
            let child = std::process::Command::new("systemd-inhibit")
                .args([
                    "--what=idle",
                    "--who=luciola",
                    "--why=Active Luciola transfer or tunnel",
                    "--mode=block",
                    "/bin/sh",
                    "-c",
                    "trap 'exit 0' TERM INT; while kill -0 \"$1\" 2>/dev/null; do sleep 2; done",
                    "_",
                    &pid,
                ])
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn()
                .map_err(|e| format!("spawn systemd-inhibit: {e}"))?;
            *slot = Some(child);
            Ok(())
        }
        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
        {
            Ok(())
        }
    }

    fn release(&self) -> Result<(), String> {
        #[cfg(target_os = "macos")]
        {
            let mut slot = self.child.lock().map_err(|e| e.to_string())?;
            if let Some(mut child) = slot.take() {
                let _ = child.kill();
                let _ = child.wait();
            }
            Ok(())
        }
        #[cfg(target_os = "linux")]
        {
            let mut slot = self.child.lock().map_err(|e| e.to_string())?;
            if let Some(mut child) = slot.take() {
                // Send SIGTERM first so systemd-inhibit cleanly terminates its
                // shell child without orphaning it; fall back to SIGKILL.
                let _ = std::process::Command::new("kill")
                    .args(["-TERM", &child.id().to_string()])
                    .stdout(std::process::Stdio::null())
                    .stderr(std::process::Stdio::null())
                    .status();
                for _ in 0..10 {
                    if let Ok(Some(_)) = child.try_wait() {
                        return Ok(());
                    }
                    std::thread::sleep(Duration::from_millis(20));
                }
                let _ = child.kill();
                let _ = child.wait();
            }
            Ok(())
        }
        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
        {
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    struct MockBackend {
        acquires: AtomicUsize,
        releases: AtomicUsize,
    }

    impl MockBackend {
        fn new() -> Self {
            Self {
                acquires: AtomicUsize::new(0),
                releases: AtomicUsize::new(0),
            }
        }
    }

    impl PowerBackend for MockBackend {
        fn name(&self) -> &'static str {
            "mock"
        }
        fn available(&self) -> bool {
            true
        }
        fn acquire(&self) -> Result<(), String> {
            self.acquires.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
        fn release(&self) -> Result<(), String> {
            self.releases.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }

    #[test]
    fn guard_acquires_holds_through_reactivation_and_releases_after_grace() {
        let backend = Arc::new(MockBackend::new());
        let guard = PowerGuard::new(backend.clone(), Duration::from_millis(60));

        guard.set_active(true);
        assert!(guard.is_held());
        assert_eq!(backend.acquires.load(Ordering::SeqCst), 1);

        // Become inactive, then reactivate before grace expires: must NOT release.
        guard.set_active(false);
        std::thread::sleep(Duration::from_millis(20));
        guard.set_active(true);
        std::thread::sleep(Duration::from_millis(70));
        assert!(guard.is_held());
        assert_eq!(backend.releases.load(Ordering::SeqCst), 0);

        // Become inactive and let grace elapse: must release cleanly.
        guard.set_active(false);
        std::thread::sleep(Duration::from_millis(120));
        assert!(!guard.is_held());
        assert_eq!(backend.releases.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn drop_releases_held_assertion_immediately() {
        let backend = Arc::new(MockBackend::new());
        {
            let guard = PowerGuard::new(backend.clone(), Duration::from_secs(60));
            guard.set_active(true);
            assert!(guard.is_held());
        }
        assert_eq!(backend.releases.load(Ordering::SeqCst), 1);
    }
}