rmux-server 0.1.2

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
use std::time::{Duration, Instant};

use rmux_core::events::{
    OutputCursor, OutputCursorItem, OutputRing, PaneOutputSubscriptionKey, SubscriptionLimits,
};
use rmux_proto::{
    PaneId, PaneOutputCursorRequest, PaneOutputSubscriptionStart, PaneTarget, Response, RmuxError,
    SessionName, SubscribePaneOutputRequest,
};

use crate::daemon::ShutdownHandle;
use crate::pane_io::pane_output_channel_with_limits;

use super::{lag_dto, OutputSubscriptionState, RequestHandler, MAX_LAG_RECENT_BYTES};

#[test]
fn lag_dto_carries_recent_output_without_replaying_missed_bytes() {
    let mut ring = OutputRing::new(1, 8);
    let mut cursor = OutputCursor::new(0);
    ring.push(b"abcdef".to_vec());
    ring.push(b"ghijk".to_vec());

    let Some(OutputCursorItem::Gap(gap)) = ring.poll_cursor(&mut cursor) else {
        panic!("cursor should lag after output ring rotation");
    };
    let notice = lag_dto(&gap);

    assert_eq!(notice.expected_sequence, 0);
    assert_eq!(notice.resume_sequence, 1);
    assert_eq!(notice.missed_events, 1);
    assert_eq!(notice.newest_sequence, 1);
    assert_eq!(notice.recent.bytes, b"defghijk");
    assert_eq!(notice.recent.oldest_sequence, Some(0));
    assert_eq!(notice.recent.newest_sequence, Some(1));

    let Some(OutputCursorItem::Event(event)) = ring.poll_cursor(&mut cursor) else {
        panic!("cursor should resume at the oldest retained output event");
    };
    assert_eq!(event.sequence(), notice.resume_sequence);
    assert_eq!(event.bytes(), b"ghijk");
    assert_ne!(event.bytes(), notice.recent.bytes.as_slice());
}

#[test]
fn lag_dto_trims_recent_hint_under_detached_frame_limit() {
    let mut ring = OutputRing::new(1, MAX_LAG_RECENT_BYTES + 16);
    let mut cursor = OutputCursor::new(0);
    ring.push(vec![b'a'; 16]);
    ring.push(vec![b'b'; MAX_LAG_RECENT_BYTES + 16]);

    let Some(OutputCursorItem::Gap(gap)) = ring.poll_cursor(&mut cursor) else {
        panic!("cursor should lag after output ring rotation");
    };
    let notice = lag_dto(&gap);

    assert_eq!(notice.recent.bytes.len(), MAX_LAG_RECENT_BYTES);
    assert!(notice.recent.bytes.iter().all(|byte| *byte == b'b'));
    assert_eq!(notice.recent.oldest_sequence, None);
    assert_eq!(notice.recent.newest_sequence, Some(1));
    assert_eq!(notice.resume_sequence, 1);
}

#[tokio::test]
async fn cursor_handler_trims_lag_recent_hint_for_subscription_response() {
    let handler = RequestHandler::new();
    let connection_id = 77;
    let sender = pane_output_channel_with_limits(1, MAX_LAG_RECENT_BYTES + 32);
    let receiver = sender.subscribe();
    sender.send(vec![b'a'; 32]);
    sender.send(vec![b'b'; MAX_LAG_RECENT_BYTES + 32]);

    let subscription_id = {
        let mut subscriptions = handler
            .subscriptions
            .lock()
            .expect("subscription registry mutex must not be poisoned");
        let record = subscriptions
            .registry
            .subscribe(
                connection_id,
                PaneOutputSubscriptionKey::new(
                    SessionName::new("runtime").expect("valid session name"),
                    PaneId::new(1),
                ),
                Instant::now(),
            )
            .expect("subscription is within limits");
        let subscription_id = record.id();
        subscriptions.receivers.insert(subscription_id, receiver);
        subscription_id
    };

    let response = handler
        .handle_pane_output_cursor(
            connection_id,
            PaneOutputCursorRequest {
                subscription_id,
                max_events: Some(8),
            },
        )
        .await;
    let Response::PaneOutputLag(lag) = response else {
        panic!("lagged subscription should produce a lag response");
    };

    assert_eq!(lag.subscription_id, subscription_id);
    assert_eq!(lag.cursor.next_sequence, 1);
    assert_eq!(lag.cursor.missed_events, 1);
    assert_eq!(lag.lag.expected_sequence, 0);
    assert_eq!(lag.lag.resume_sequence, 1);
    assert_eq!(lag.lag.missed_events, 1);
    assert_eq!(lag.lag.recent.bytes.len(), MAX_LAG_RECENT_BYTES);
    assert!(lag.lag.recent.bytes.iter().all(|byte| *byte == b'b'));
    assert_eq!(lag.lag.recent.oldest_sequence, None);
    assert_eq!(lag.lag.recent.newest_sequence, Some(1));
}

#[tokio::test]
async fn exited_pane_subscription_stays_alive_after_eof_until_cleanup() {
    let handler = RequestHandler::new();
    let connection_id = 88;
    let pane = PaneOutputSubscriptionKey::new(
        SessionName::new("runtime").expect("valid session name"),
        PaneId::new(7),
    );
    let sender = pane_output_channel_with_limits(8, 1024);
    let receiver = sender.subscribe_from_oldest();

    let subscription_id = {
        let mut subscriptions = handler
            .subscriptions
            .lock()
            .expect("subscription registry mutex must not be poisoned");
        let record = subscriptions
            .registry
            .subscribe(connection_id, pane.clone(), Instant::now())
            .expect("subscription is within limits");
        let subscription_id = record.id();
        subscriptions.receivers.insert(subscription_id, receiver);
        subscription_id
    };

    handler
        .drain_exited_pane_output_subscriptions(pane.clone())
        .await;

    let empty_before_eof = handler
        .handle_pane_output_cursor(
            connection_id,
            PaneOutputCursorRequest {
                subscription_id,
                max_events: Some(8),
            },
        )
        .await;
    let Response::PaneOutputCursor(empty_before_eof) = empty_before_eof else {
        panic!("draining subscription must stay alive before EOF");
    };
    assert!(empty_before_eof.events.is_empty());

    sender.send(b"final burst".to_vec());
    sender.send(Vec::new());

    let drained = handler
        .handle_pane_output_cursor(
            connection_id,
            PaneOutputCursorRequest {
                subscription_id,
                max_events: Some(8),
            },
        )
        .await;
    let Response::PaneOutputCursor(drained) = drained else {
        panic!("draining subscription should deliver retained bytes and EOF");
    };
    assert_eq!(drained.events.len(), 2);
    assert_eq!(drained.events[0].bytes, b"final burst");
    assert!(drained.events[1].bytes.is_empty());

    let idle_after_eof = handler
        .handle_pane_output_cursor(
            connection_id,
            PaneOutputCursorRequest {
                subscription_id,
                max_events: Some(8),
            },
        )
        .await;
    let Response::PaneOutputCursor(idle_after_eof) = idle_after_eof else {
        panic!("subscription should stay alive after EOF until explicit cleanup");
    };
    assert!(idle_after_eof.events.is_empty());

    handler
        .cleanup_connection_subscriptions(connection_id)
        .await;
    let closed = handler
        .handle_pane_output_cursor(
            connection_id,
            PaneOutputCursorRequest {
                subscription_id,
                max_events: Some(8),
            },
        )
        .await;
    let Response::Error(error) = closed else {
        panic!("subscription should close after connection cleanup");
    };
    assert_eq!(
        error.error,
        RmuxError::Server("subscription not found".to_owned())
    );
}

#[tokio::test]
async fn empty_server_shutdown_waits_for_exited_pane_subscription_drain() {
    let handler = RequestHandler::new();
    let (shutdown_handle, mut shutdown_rx) = ShutdownHandle::new();
    handler.install_shutdown_handle(shutdown_handle);
    let connection_id = 188;
    let pane = PaneOutputSubscriptionKey::new(
        SessionName::new("runtime").expect("valid session name"),
        PaneId::new(17),
    );
    let sender = pane_output_channel_with_limits(8, 1024);
    let receiver = sender.subscribe_from_oldest();

    let subscription_id = {
        let mut subscriptions = handler
            .subscriptions
            .lock()
            .expect("subscription registry mutex must not be poisoned");
        let record = subscriptions
            .registry
            .subscribe(connection_id, pane.clone(), Instant::now())
            .expect("subscription is within limits");
        let subscription_id = record.id();
        subscriptions.receivers.insert(subscription_id, receiver);
        subscription_id
    };

    handler
        .drain_exited_pane_output_subscriptions(pane.clone())
        .await;
    assert!(
        !handler.request_shutdown_if_server_empty().await,
        "active output drains must keep an otherwise empty server alive"
    );
    assert!(
        tokio::time::timeout(Duration::from_millis(50), &mut shutdown_rx)
            .await
            .is_err(),
        "shutdown must not fire before the SDK can drain retained output"
    );

    sender.send(b"final burst".to_vec());
    sender.send(Vec::new());
    let drained = handler
        .handle_pane_output_cursor(
            connection_id,
            PaneOutputCursorRequest {
                subscription_id,
                max_events: Some(8),
            },
        )
        .await;
    let Response::PaneOutputCursor(drained) = drained else {
        panic!("draining subscription should deliver retained bytes and EOF");
    };
    assert_eq!(drained.events.len(), 2);
    assert_eq!(drained.events[0].bytes, b"final burst");
    assert!(drained.events[1].bytes.is_empty());

    assert!(
        tokio::time::timeout(Duration::from_millis(50), &mut shutdown_rx)
            .await
            .is_err(),
        "the SDK connection must remain alive after EOF so callers can reconcile exit state"
    );

    handler
        .cleanup_connection_subscriptions(connection_id)
        .await;
    assert!(
        tokio::time::timeout(Duration::from_millis(50), shutdown_rx)
            .await
            .expect("shutdown should fire after the SDK connection closes")
            .is_ok(),
        "shutdown receiver should complete cleanly"
    );
}

#[test]
fn exited_pane_drain_idle_tracks_subscription_touch() {
    let mut subscriptions = OutputSubscriptionState::new(SubscriptionLimits::default());
    let pane = PaneOutputSubscriptionKey::new(
        SessionName::new("runtime").expect("valid session name"),
        PaneId::new(42),
    );
    let created = Instant::now();
    let record = subscriptions
        .registry
        .subscribe(5, pane.clone(), created)
        .expect("subscription is within limits");

    assert!(subscriptions.begin_pane_drain(pane.clone()));
    assert_eq!(
        subscriptions.pane_drain_idle_for(&pane, created),
        Some(Duration::ZERO)
    );

    let touched = created + Duration::from_secs(5);
    subscriptions
        .registry
        .touch(record.id(), touched)
        .expect("subscription should still be live");
    assert_eq!(
        subscriptions.pane_drain_idle_for(&pane, touched + Duration::from_millis(25)),
        Some(Duration::from_millis(25))
    );
}

#[tokio::test]
async fn exited_pane_subscription_auto_cleans_after_drain_timeout() {
    let handler = RequestHandler::new();
    let connection_id = 99;
    let pane = PaneOutputSubscriptionKey::new(
        SessionName::new("runtime").expect("valid session name"),
        PaneId::new(9),
    );
    let sender = pane_output_channel_with_limits(8, 1024);
    let receiver = sender.subscribe_from_oldest();
    let subscription_id = {
        let mut subscriptions = handler
            .subscriptions
            .lock()
            .expect("subscription registry mutex must not be poisoned");
        let record = subscriptions
            .registry
            .subscribe(connection_id, pane.clone(), Instant::now())
            .expect("subscription is within limits");
        let subscription_id = record.id();
        subscriptions.receivers.insert(subscription_id, receiver);
        subscription_id
    };

    handler
        .drain_exited_pane_output_subscriptions(pane.clone())
        .await;
    sender.send(b"tail".to_vec());
    sender.send(Vec::new());

    tokio::time::timeout(Duration::from_secs(3), async {
        loop {
            let removed = handler
                .subscriptions
                .lock()
                .expect("subscription registry mutex must not be poisoned")
                .registry
                .get(subscription_id)
                .is_none();
            if removed {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("undrained subscription should auto-clean after the drain timeout");
}

#[tokio::test]
async fn oldest_subscription_can_attach_to_retained_exited_pane_output() {
    let handler = RequestHandler::new();
    let connection_id = 55;
    let session_name = SessionName::new("gone").expect("valid session name");
    let target = PaneTarget::with_window(session_name.clone(), 0, 0);
    let pane = PaneOutputSubscriptionKey::new(session_name, PaneId::new(33));
    let sender = pane_output_channel_with_limits(8, 1024);
    sender.send(b"retained start".to_vec());
    sender.send(b"retained tail".to_vec());
    sender.send(Vec::new());

    handler.retain_exited_pane_output(target.clone(), pane, sender);

    let response = handler
        .handle_subscribe_pane_output(
            connection_id,
            SubscribePaneOutputRequest {
                target,
                start: PaneOutputSubscriptionStart::Oldest,
            },
        )
        .await;
    let Response::SubscribePaneOutput(subscribe) = response else {
        panic!("retained exited output should accept an Oldest subscription");
    };

    let response = handler
        .handle_pane_output_cursor(
            connection_id,
            PaneOutputCursorRequest {
                subscription_id: subscribe.subscription_id,
                max_events: Some(8),
            },
        )
        .await;
    let Response::PaneOutputCursor(cursor) = response else {
        panic!("retained subscription should return a cursor response");
    };
    assert_eq!(cursor.events.len(), 3);
    assert_eq!(cursor.events[0].bytes, b"retained start");
    assert_eq!(cursor.events[1].bytes, b"retained tail");
    assert!(cursor.events[2].bytes.is_empty());
}

#[tokio::test]
async fn kill_server_does_not_wait_for_retained_exited_pane_output() {
    let handler = RequestHandler::new();
    let (shutdown_handle, mut shutdown_rx) = ShutdownHandle::new();
    handler.install_shutdown_handle(shutdown_handle);
    let session_name = SessionName::new("gone").expect("valid session name");
    let target = PaneTarget::with_window(session_name.clone(), 0, 0);
    let pane = PaneOutputSubscriptionKey::new(session_name, PaneId::new(44));
    let sender = pane_output_channel_with_limits(8, 1024);
    sender.send(b"retained".to_vec());
    sender.send(Vec::new());
    handler.retain_exited_pane_output(target, pane, sender);

    let Response::KillServer(_) = handler.handle_kill_server().await else {
        panic!("kill-server should acknowledge shutdown");
    };
    assert!(
        handler.request_shutdown_if_pending(),
        "explicit kill-server must not wait for retained SDK output"
    );
    tokio::time::timeout(Duration::from_millis(50), &mut shutdown_rx)
        .await
        .expect("shutdown should be requested immediately")
        .expect("shutdown receiver should complete cleanly");
}