rmux-server 0.9.1

Tokio daemon and request dispatcher for the RMUX terminal multiplexer.
Documentation
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
#[cfg(unix)]
use super::STATUS_JOB_OUTPUT_LIMIT;
use super::{
    ensure_status_job_cache_capacity, run_status_job, ActiveStatusJob, StatusJobCacheEntry,
    StatusJobKey, StatusJobRuntime, STATUS_JOB_ACTIVE_LIMIT, STATUS_JOB_CACHE_LIMIT,
};
use std::collections::HashMap;
#[cfg(unix)]
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::{Duration, Instant};
#[cfg(unix)]
use std::time::{SystemTime, UNIX_EPOCH};

#[cfg(windows)]
#[test]
fn windows_status_job_preserves_quoted_command_arguments() {
    assert_eq!(
        run_status_job(r#"echo "RMUX STATUS JOB""#, None),
        r#""RMUX STATUS JOB""#
    );
}

#[cfg(unix)]
#[test]
fn status_job_key_canonicalizes_profile_environment_order() {
    let profile = test_profile(&[("RMUX_STATUS_KEY", "shared")]);
    let key = StatusJobKey::new("printf probe", Some(&profile));
    let environment = key.environment.as_ref().expect("profile environment key");
    let mut sorted = environment.as_ref().clone();

    sorted.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1)));
    assert_eq!(environment.as_ref(), &sorted);
}

#[test]
fn status_job_cache_evicts_old_completed_entries() {
    let now = Instant::now();
    let mut jobs = HashMap::new();
    for index in 0..STATUS_JOB_CACHE_LIMIT {
        jobs.insert(
            StatusJobKey::new(&format!("job-{index}"), None),
            StatusJobCacheEntry {
                output: String::new(),
                updated_at: Some(now + Duration::from_millis(index as u64)),
                in_flight: false,
            },
        );
    }

    ensure_status_job_cache_capacity(&mut jobs, &StatusJobKey::new("job-new", None), now);

    assert_eq!(jobs.len(), STATUS_JOB_CACHE_LIMIT - 1);
    assert!(!jobs.contains_key(&StatusJobKey::new("job-0", None)));
}

#[test]
fn status_job_cache_honors_render_ttl() {
    let runtime = StatusJobRuntime::new();
    let command = format!("ttl-job-{}", std::process::id());
    let key = StatusJobKey::new(&command, None);
    runtime.seed_cache(
        key.clone(),
        StatusJobCacheEntry {
            output: "cached".to_owned(),
            updated_at: Some(Instant::now()),
            in_flight: false,
        },
    );

    let rendered = runtime.cached_output(&command, None, Duration::from_secs(3600));

    assert_eq!(rendered, "cached");
    assert!(
        !runtime.cache_entry_in_flight(&key),
        "fresh cache entries must not spawn a replacement job"
    );
}

#[test]
fn status_job_runtime_bounds_active_workers() {
    let runtime = StatusJobRuntime::new();
    {
        let mut state = runtime.inner.lock_state();
        for job_id in 0..u64::try_from(STATUS_JOB_ACTIVE_LIMIT).expect("limit fits u64") {
            state.active.insert(
                job_id,
                ActiveStatusJob {
                    cancellation: Arc::new(AtomicBool::new(false)),
                    worker: None,
                    completed: false,
                },
            );
        }
    }
    let command = format!("bounded-job-{}", std::process::id());
    let key = StatusJobKey::new(&command, None);

    assert_eq!(runtime.cached_output(&command, None, Duration::ZERO), "");
    assert_eq!(runtime.active_job_count(), STATUS_JOB_ACTIVE_LIMIT);
    assert!(
        !runtime.cache_entry_in_flight(&key),
        "the active limit must reject rather than detach an untracked worker"
    );
}

#[cfg(unix)]
#[test]
fn status_job_drains_stdout_while_child_is_running() {
    let output = run_status_job("printf '%70000s' x", None);

    assert_eq!(output.len(), STATUS_JOB_OUTPUT_LIMIT);
}

#[cfg(unix)]
#[test]
fn status_job_timeout_kills_descendants_holding_stdout() {
    let started = Instant::now();
    let output = run_status_job("sleep 5 &", None);

    assert_eq!(output, "");
    assert!(
        started.elapsed() < Duration::from_secs(2),
        "status job should time out instead of waiting for background descendants"
    );
}

#[cfg(unix)]
#[test]
fn status_job_normal_completion_reaps_background_descendants() {
    let probe = StatusJobProcessProbe::new("normal-completion");
    let command = probe.normal_completion_command();
    let started = Instant::now();

    let output = run_status_job(&command, None);

    assert_eq!(output, "complete");
    assert!(
        started.elapsed() < Duration::from_secs(2),
        "normal status completion should not wait for a detached background job"
    );
    assert_probe_processes_dead(
        &probe.wait_for_descendant_count(1),
        "normal status completion",
    );
}

#[cfg(unix)]
#[test]
fn status_job_normal_completion_does_not_join_an_escaped_stdout_writer() {
    let probe = EscapedStatusWriterProbe::new();
    let started = Instant::now();

    let output = run_status_job(&probe.command(), None);

    assert!(
        output.contains("complete"),
        "the direct shell output must be preserved: {output:?}"
    );
    assert!(
        started.elapsed() < Duration::from_secs(2),
        "an escaped descendant retaining stdout must not block status completion"
    );
}

#[cfg(unix)]
#[test]
fn status_job_timeout_force_kills_term_ignoring_descendants() {
    let probe = StatusJobProcessProbe::new("term-resistant");
    let started = Instant::now();

    let output = run_status_job(&probe.command(), None);

    assert_eq!(output, "");
    assert!(
        started.elapsed() < Duration::from_secs(2),
        "status job should escalate promptly after its TERM grace"
    );
    assert_probe_processes_dead(&probe.wait_for_descendant_count(1), "timeout cleanup");
}

#[cfg(unix)]
#[test]
fn status_job_cache_releases_only_after_process_tree_cleanup() {
    let runtime = StatusJobRuntime::new();
    let probe = StatusJobProcessProbe::new("cache-cleanup");
    let command = probe.command();
    let key = StatusJobKey::new(&command, None);

    let _ = runtime.cached_output(&command, None, Duration::ZERO);
    let first_generation = probe.wait_for_descendant_count(1);
    wait_for_status_job_in_flight(&runtime, &key, false);
    assert_probe_processes_dead(&first_generation, "first cache generation");

    let _ = runtime.cached_output(&command, None, Duration::ZERO);
    let second_generation = probe.wait_for_descendant_count(2);
    let live = second_generation
        .iter()
        .filter(|pid| rmux_os::process::is_live(**pid))
        .count();
    assert!(
        live <= 1,
        "status refresh accumulated {live} live TERM-resistant descendants: \
         {second_generation:?}"
    );

    wait_for_status_job_in_flight(&runtime, &key, false);
    assert_probe_processes_dead(&second_generation, "second cache generation");
}

#[cfg(unix)]
#[test]
fn daemon_shutdown_cancels_joins_and_reaps_status_job_tree() {
    let runtime = StatusJobRuntime::new();
    let probe = StatusJobProcessProbe::new("daemon-shutdown");
    let command = probe.command();

    let _ = runtime.cached_output(&command, None, Duration::ZERO);
    let descendants = probe.wait_for_descendant_count(1);
    assert_eq!(runtime.active_job_count(), 1);
    let started = Instant::now();

    runtime.shutdown_and_join();

    assert!(runtime.is_closing());
    assert_eq!(
        runtime.active_job_count(),
        0,
        "shutdown must join every worker"
    );
    assert!(
        started.elapsed() < Duration::from_secs(2),
        "daemon-owned status shutdown exceeded its bounded TERM/KILL cleanup"
    );
    assert_probe_processes_dead(&descendants, "daemon shutdown");

    let _ = runtime.cached_output(&command, None, Duration::ZERO);
    std::thread::sleep(Duration::from_millis(25));
    assert_eq!(
        runtime.active_job_count(),
        0,
        "a closing daemon must reject new status workers"
    );
}

#[cfg(unix)]
#[test]
fn dropping_status_runtime_cancels_and_reaps_owned_tree() {
    let probe = StatusJobProcessProbe::new("runtime-drop");
    let command = probe.command();
    let runtime = StatusJobRuntime::new();
    let _ = runtime.cached_output(&command, None, Duration::ZERO);
    let descendants = probe.wait_for_descendant_count(1);

    drop(runtime);

    assert_probe_processes_dead(&descendants, "runtime drop");
}

#[cfg(unix)]
#[test]
fn status_job_uses_profile_environment() {
    let profile = test_profile(&[
        ("RMUX_STATUS_PROBE", "from-profile"),
        ("TMUX_PROGRAM", "/tmp/rmux-shim/tmux"),
    ]);

    let output = run_status_job(
        "printf '%s/%s' \"$RMUX_STATUS_PROBE\" \"$TMUX_PROGRAM\"",
        Some(&profile),
    );

    assert_eq!(output, "from-profile//tmp/rmux-shim/tmux");
}

#[cfg(unix)]
#[test]
fn status_job_cache_is_partitioned_by_profile_environment() {
    let first = test_profile(&[("TMUX_PANE", "%1")]);
    let second = test_profile(&[("TMUX_PANE", "%2")]);

    assert_ne!(
        StatusJobKey::new("printf probe", Some(&first)),
        StatusJobKey::new("printf probe", Some(&second))
    );
}

#[cfg(unix)]
fn test_profile(environment: &[(&str, &str)]) -> crate::terminal::TerminalProfile {
    use rmux_core::{EnvironmentStore, OptionStore};
    use rmux_proto::SessionName;

    let mut spawn_environment = HashMap::new();
    for (name, value) in environment {
        spawn_environment.insert((*name).to_owned(), (*value).to_owned());
    }
    let session_name = SessionName::new("alpha").expect("valid session name");
    crate::terminal::TerminalProfile::for_run_shell_with_base_environment(
        &EnvironmentStore::default(),
        &OptionStore::default(),
        Some(&session_name),
        Some(1),
        Path::new("/tmp/rmux-status-job-test.sock"),
        None,
        false,
        None,
        None,
    )
    .expect("profile")
    .with_test_environment(spawn_environment)
}

#[cfg(unix)]
struct StatusJobProcessProbe {
    root: PathBuf,
    process_groups: PathBuf,
    descendants: PathBuf,
}

#[cfg(unix)]
impl StatusJobProcessProbe {
    fn new(label: &str) -> Self {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time after Unix epoch")
            .as_nanos();
        let root = std::env::temp_dir().join(format!(
            "rmux-status-job-{label}-{}-{unique}",
            std::process::id()
        ));
        std::fs::create_dir_all(&root).expect("create status job probe root");
        Self {
            process_groups: root.join("groups.pid"),
            descendants: root.join("descendants.pid"),
            root,
        }
    }

    fn command(&self) -> String {
        format!(
            "printf '%s\\n' \"$$\" >> {}; \
             sh -c 'trap \"\" TERM; printf \"%s\\n\" \"$$\" >> \"$1\"; \
             while :; do sleep 30; done' sh {} & wait",
            shell_quote_path(&self.process_groups),
            shell_quote_path(&self.descendants),
        )
    }

    fn normal_completion_command(&self) -> String {
        format!(
            "sh -c 'trap \"\" TERM; printf \"%s\\n\" \"$$\" >> \"$1\"; \
             while :; do sleep 30; done' sh {} </dev/null >/dev/null 2>&1 & \
             while [ ! -s {} ]; do sleep 0.01; done; printf complete",
            shell_quote_path(&self.descendants),
            shell_quote_path(&self.descendants),
        )
    }

    fn wait_for_descendant_count(&self, expected: usize) -> Vec<u32> {
        let deadline = Instant::now() + Duration::from_secs(3);
        loop {
            let descendants = read_probe_pids(&self.descendants);
            if descendants.len() >= expected {
                return descendants;
            }
            assert!(
                Instant::now() < deadline,
                "status job did not record {expected} descendant pids; got {descendants:?}"
            );
            std::thread::sleep(Duration::from_millis(10));
        }
    }
}

#[cfg(unix)]
const ESCAPED_STATUS_WRITER_ENV: &str = "RMUX_TEST_ESCAPED_STATUS_WRITER_PID";

#[cfg(unix)]
const ESCAPED_STATUS_WRITER_TEST: &str = "status_jobs::tests::escaped_status_stdout_writer_helper";

#[cfg(unix)]
#[test]
fn escaped_status_stdout_writer_helper() {
    use std::io::Write as _;

    let Some(pid_path) = std::env::var_os(ESCAPED_STATUS_WRITER_ENV) else {
        return;
    };

    rustix::process::setsid().expect("escape the status process group");
    std::fs::write(pid_path, format!("{}\n", std::process::id()))
        .expect("record escaped status writer pid");
    let mut stdout = std::io::stdout().lock();
    loop {
        if stdout
            .write_all(b".")
            .and_then(|()| stdout.flush())
            .is_err()
        {
            return;
        }
        std::thread::sleep(Duration::from_millis(5));
    }
}

#[cfg(unix)]
struct EscapedStatusWriterProbe {
    root: PathBuf,
    pid_path: PathBuf,
}

#[cfg(unix)]
impl EscapedStatusWriterProbe {
    fn new() -> Self {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time after Unix epoch")
            .as_nanos();
        let root = std::env::temp_dir().join(format!(
            "rmux-status-job-escaped-{}-{unique}",
            std::process::id()
        ));
        std::fs::create_dir_all(&root).expect("create escaped status writer probe root");
        let pid_path = root.join("writer.pid");
        Self { root, pid_path }
    }

    fn command(&self) -> String {
        let executable = std::env::current_exe().expect("resolve current test executable");
        format!(
            "{}={} {} --exact {} --nocapture & \
             while [ ! -s {} ]; do sleep 0.01; done; printf complete",
            ESCAPED_STATUS_WRITER_ENV,
            shell_quote_path(&self.pid_path),
            shell_quote_path(&executable),
            ESCAPED_STATUS_WRITER_TEST,
            shell_quote_path(&self.pid_path),
        )
    }
}

#[cfg(unix)]
impl Drop for EscapedStatusWriterProbe {
    fn drop(&mut self) {
        use rustix::process::{kill_process, Pid, Signal};

        for pid in read_probe_pids(&self.pid_path) {
            if let Some(pid) = i32::try_from(pid).ok().and_then(Pid::from_raw) {
                let _ = kill_process(pid, Signal::KILL);
            }
        }
        let _ = std::fs::remove_dir_all(&self.root);
    }
}

#[cfg(unix)]
impl Drop for StatusJobProcessProbe {
    fn drop(&mut self) {
        use rustix::process::{kill_process, kill_process_group, Pid, Signal};

        for process_group in read_probe_pids(&self.process_groups) {
            if let Some(process_group) = i32::try_from(process_group).ok().and_then(Pid::from_raw) {
                let _ = kill_process_group(process_group, Signal::KILL);
            }
        }
        for descendant in read_probe_pids(&self.descendants) {
            if let Some(descendant) = i32::try_from(descendant).ok().and_then(Pid::from_raw) {
                let _ = kill_process(descendant, Signal::KILL);
            }
        }
        let _ = std::fs::remove_dir_all(&self.root);
    }
}

#[cfg(unix)]
fn assert_probe_processes_dead(pids: &[u32], stage: &str) {
    assert!(
        pids.iter().all(|pid| !rmux_os::process::is_live(*pid)),
        "TERM-resistant status descendants survived {stage}: {pids:?}"
    );
}

#[cfg(unix)]
fn read_probe_pids(path: &Path) -> Vec<u32> {
    let mut pids = std::fs::read_to_string(path)
        .unwrap_or_default()
        .lines()
        .filter_map(|line| line.trim().parse::<u32>().ok())
        .collect::<Vec<_>>();
    pids.sort_unstable();
    pids.dedup();
    pids
}

#[cfg(unix)]
fn shell_quote_path(path: &Path) -> String {
    format!("'{}'", path.display().to_string().replace('\'', "'\"'\"'"))
}

#[cfg(unix)]
fn wait_for_status_job_in_flight(runtime: &StatusJobRuntime, key: &StatusJobKey, expected: bool) {
    let deadline = Instant::now() + Duration::from_secs(3);
    loop {
        if runtime.cache_entry_in_flight(key) == expected {
            return;
        }
        assert!(
            Instant::now() < deadline,
            "status job in-flight state did not become {expected}"
        );
        std::thread::sleep(Duration::from_millis(10));
    }
}