drmkit-session 0.1.2

Session and seat management: revocable devices across VT switches
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
// SPDX-FileCopyrightText: (c) 2026 Joel Winarske
// SPDX-License-Identifier: MIT

//! The session sequencing, against a seat that does what it is told.
//!
//! None of this can be tested against a real seat on the machines this is
//! built on: over SSH logind reports the session busy, seatd is not running,
//! and the builtin backend wants root and a TTY. That is exactly why the
//! sequencing lives above a trait.

use std::path::{Path, PathBuf};

use crate::session::{Backend, DeviceId, RawEvent};
use crate::{Session, SessionError, SessionEvent};

/// What the fake seat was asked to do, in order.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Call {
    Open(PathBuf),
    Close(DeviceId),
    Acknowledge,
    Switch(i32),
}

/// A seat that opens whatever it is asked for and records everything.
#[derive(Debug, Default)]
struct FakeSeat {
    calls: Vec<Call>,
    /// Handed out in order, so a reopen is visibly a different descriptor.
    next_id: i32,
    next_fd: i32,
    /// Queued to be delivered by the next dispatch.
    deliver: Vec<RawEvent>,
    /// Refuse the next open, to test a resume that cannot complete.
    fail_next_open: bool,
    fail_close: bool,
}

impl FakeSeat {
    fn new() -> Self {
        Self {
            next_id: 1,
            next_fd: 100,
            ..Self::default()
        }
    }

    fn queue(&mut self, event: RawEvent) {
        self.deliver.push(event);
    }

    fn opens(&self) -> Vec<&PathBuf> {
        self.calls
            .iter()
            .filter_map(|call| match call {
                Call::Open(path) => Some(path),
                _ => None,
            })
            .collect()
    }
}

impl Backend for FakeSeat {
    fn open_device(&mut self, path: &Path) -> Result<(DeviceId, i32), SessionError> {
        self.calls.push(Call::Open(path.to_path_buf()));
        if self.fail_next_open {
            self.fail_next_open = false;
            return Err(SessionError::Seat("refused".to_owned()));
        }
        let id = DeviceId(self.next_id);
        let fd = self.next_fd;
        self.next_id += 1;
        self.next_fd += 1;
        Ok((id, fd))
    }

    fn close_device(&mut self, id: DeviceId) -> Result<(), SessionError> {
        self.calls.push(Call::Close(id));
        if self.fail_close {
            return Err(SessionError::Seat("close refused".to_owned()));
        }
        Ok(())
    }

    fn acknowledge_pause(&mut self) -> Result<(), SessionError> {
        self.calls.push(Call::Acknowledge);
        Ok(())
    }

    fn switch_session(&mut self, session: i32) -> Result<(), SessionError> {
        self.calls.push(Call::Switch(session));
        Ok(())
    }

    fn poll_fd(&self) -> Option<i32> {
        Some(7)
    }

    fn dispatch(&mut self, _timeout: i32, events: &mut Vec<RawEvent>) -> Result<(), SessionError> {
        events.append(&mut self.deliver);
        Ok(())
    }
}

/// A session holding one card.
fn with_card() -> Session<FakeSeat> {
    let mut session = Session::new(FakeSeat::new());
    session.take_device("/dev/dri/card0").expect("take");
    session
}

#[test]
fn taking_a_device_records_it() {
    let mut session = Session::new(FakeSeat::new());
    let device = session.take_device("/dev/dri/card0").expect("take");

    assert_eq!(device.path, Path::new("/dev/dri/card0"));
    assert_eq!(device.fd, 100);
    assert_eq!(session.devices().len(), 1);
    assert!(session.is_active());
}

#[test]
fn taking_the_same_path_twice_holds_one_device() {
    // The seat would happily give a second descriptor, and then a resume has
    // two to reopen and the caller two to keep straight.
    let mut session = Session::new(FakeSeat::new());
    let first = session.take_device("/dev/dri/card0").expect("take");
    let again = session.take_device("/dev/dri/card0").expect("take again");

    assert_eq!(first, again);
    assert_eq!(session.devices().len(), 1);
}

#[test]
fn a_pause_is_acknowledged_and_reported() {
    let mut session = with_card();
    session.backend_mut().queue(RawEvent::Disable);
    session.dispatch(0).expect("dispatch");

    assert!(!session.is_active(), "the display is not ours any more");
    assert_eq!(session.next_event(), Some(SessionEvent::Paused));
    assert!(
        session.backend().calls.contains(&Call::Acknowledge),
        "an unacknowledged pause stalls the switch"
    );
}

#[test]
fn a_device_cannot_be_taken_while_paused() {
    // The seat would refuse anyway; failing here says why.
    let mut session = with_card();
    session.backend_mut().queue(RawEvent::Disable);
    session.dispatch(0).expect("dispatch");

    assert_eq!(
        session.take_device("/dev/dri/card1").unwrap_err(),
        SessionError::Inactive
    );
}

#[test]
fn a_resume_replaces_every_descriptor() {
    // Every per-descriptor kernel object is gone, so reusing the old one would
    // work from objects the kernel has forgotten.
    let mut session = with_card();
    let before = session.devices()[0].fd;

    session.backend_mut().queue(RawEvent::Disable);
    session.backend_mut().queue(RawEvent::Enable);
    session.dispatch(0).expect("dispatch");

    assert_eq!(session.next_event(), Some(SessionEvent::Paused));
    let Some(SessionEvent::Resumed { devices }) = session.next_event() else {
        panic!("expected a resume");
    };
    assert_eq!(devices.len(), 1);
    assert_ne!(devices[0].fd, before, "a fresh descriptor, not the old one");
    assert_eq!(devices[0].path, Path::new("/dev/dri/card0"));
    assert!(session.is_active());
}

#[test]
fn a_resume_closes_before_it_reopens() {
    // The seat tracks one open device per handle. Opening the same path again
    // without closing leaks its handle for as long as the session runs.
    let mut session = with_card();
    session.backend_mut().queue(RawEvent::Disable);
    session.backend_mut().queue(RawEvent::Enable);
    session.dispatch(0).expect("dispatch");

    let calls = &session.backend().calls;
    let close = calls
        .iter()
        .position(|call| matches!(call, Call::Close(_)))
        .expect("the old handle is closed");
    let reopen = calls
        .iter()
        .rposition(|call| matches!(call, Call::Open(_)))
        .expect("reopened");
    assert!(close < reopen, "closed before reopened: {calls:?}");
}

#[test]
fn every_held_device_comes_back() {
    let mut session = Session::new(FakeSeat::new());
    for path in ["/dev/dri/card0", "/dev/dri/card1", "/dev/input/event0"] {
        session.take_device(path).expect("take");
    }

    session.backend_mut().queue(RawEvent::Disable);
    session.backend_mut().queue(RawEvent::Enable);
    session.dispatch(0).expect("dispatch");
    session.next_event();

    let Some(SessionEvent::Resumed { devices }) = session.next_event() else {
        panic!("expected a resume");
    };
    assert_eq!(devices.len(), 3);
    let paths: Vec<&Path> = devices.iter().map(|d| d.path.as_path()).collect();
    assert_eq!(
        paths,
        vec![
            Path::new("/dev/dri/card0"),
            Path::new("/dev/dri/card1"),
            Path::new("/dev/input/event0"),
        ],
        "and in the order they were taken"
    );
}

#[test]
fn a_released_device_does_not_come_back() {
    let mut session = Session::new(FakeSeat::new());
    session.take_device("/dev/dri/card0").expect("take");
    session.take_device("/dev/dri/card1").expect("take");
    session.release_device("/dev/dri/card0").expect("release");

    session.backend_mut().queue(RawEvent::Disable);
    session.backend_mut().queue(RawEvent::Enable);
    session.dispatch(0).expect("dispatch");
    session.next_event();

    let Some(SessionEvent::Resumed { devices }) = session.next_event() else {
        panic!("expected a resume");
    };
    assert_eq!(devices.len(), 1);
    assert_eq!(devices[0].path, Path::new("/dev/dri/card1"));
}

#[test]
fn releasing_something_never_taken_is_an_error() {
    let mut session = with_card();
    assert_eq!(
        session.release_device("/dev/dri/card9").unwrap_err(),
        SessionError::UnknownDevice
    );
    assert_eq!(session.devices().len(), 1, "and holds what it had");
}

#[test]
fn a_repeated_pause_is_reported_once() {
    // A seat that says it twice is not a reason to tell the caller twice; they
    // have already stopped.
    let mut session = with_card();
    session.backend_mut().queue(RawEvent::Disable);
    session.backend_mut().queue(RawEvent::Disable);
    session.dispatch(0).expect("dispatch");

    assert_eq!(session.next_event(), Some(SessionEvent::Paused));
    assert_eq!(session.next_event(), None, "not twice");
}

#[test]
fn a_resume_without_a_pause_changes_nothing() {
    // Seats send an enable at startup on some backends. The session is already
    // active, so there is nothing to rebuild and nothing to tell the caller.
    let mut session = with_card();
    let before = session.devices().to_vec();

    session.backend_mut().queue(RawEvent::Enable);
    session.dispatch(0).expect("dispatch");

    assert_eq!(session.next_event(), None);
    assert_eq!(session.devices(), before, "descriptors are untouched");
}

#[test]
fn a_resume_that_cannot_reopen_reports_it() {
    // The display is not coming back on its own, and a caller that never
    // learns is a caller that sits there. Reported for that device, as the
    // reference's `resume_failed_cb` does (drm-cxx#246), not as a failed
    // dispatch.
    let mut session = with_card();
    session.backend_mut().fail_next_open = true;
    session.backend_mut().queue(RawEvent::Disable);
    session.backend_mut().queue(RawEvent::Enable);

    session
        .dispatch(0)
        .expect("one lost device is not a failed dispatch");
    assert_eq!(session.next_event(), Some(SessionEvent::Paused));
    assert!(matches!(
        session.next_event(),
        Some(SessionEvent::DeviceLost { path, .. }) if path == Path::new("/dev/dri/card0")
    ));
    assert_eq!(
        session.next_event(),
        Some(SessionEvent::Resumed { devices: vec![] })
    );
    assert!(session.devices().is_empty(), "the lost device is not held");
}

/// One device that will not reopen costs that device, not the others: the
/// reference goes on to the rest, so every output but the lost one comes
/// back after the switch.
#[test]
fn a_device_that_cannot_reopen_does_not_cost_the_others() {
    let mut session = with_card();
    session.take_device("/dev/dri/card1").expect("take");
    // card0 reopens first, so this fails card0 and leaves card1 to come back.
    session.backend_mut().fail_next_open = true;
    session.backend_mut().queue(RawEvent::Disable);
    session.backend_mut().queue(RawEvent::Enable);
    session.dispatch(0).expect("dispatch");

    assert_eq!(session.next_event(), Some(SessionEvent::Paused));
    assert!(matches!(
        session.next_event(),
        Some(SessionEvent::DeviceLost { path, .. }) if path == Path::new("/dev/dri/card0")
    ));
    let Some(SessionEvent::Resumed { devices }) = session.next_event() else {
        panic!("the rest resume");
    };
    assert_eq!(devices.len(), 1);
    assert_eq!(devices[0].path, Path::new("/dev/dri/card1"));
    assert_eq!(session.devices(), devices.as_slice());
}

/// A seat that refuses to close a device is not a reason to give up on
/// reopening it; the reference ignores the close's result.
#[test]
fn a_refused_close_does_not_stop_the_reopen() {
    let mut session = with_card();
    session.backend_mut().fail_close = true;
    session.backend_mut().queue(RawEvent::Disable);
    session.backend_mut().queue(RawEvent::Enable);
    session.dispatch(0).expect("dispatch");

    assert_eq!(session.next_event(), Some(SessionEvent::Paused));
    let Some(SessionEvent::Resumed { devices }) = session.next_event() else {
        panic!("resumed");
    };
    assert_eq!(devices.len(), 1);
}

#[test]
fn events_arrive_in_the_order_they_happened() {
    let mut session = with_card();
    for _ in 0..3 {
        session.backend_mut().queue(RawEvent::Disable);
        session.backend_mut().queue(RawEvent::Enable);
    }
    session.dispatch(0).expect("dispatch");

    let mut seen = Vec::new();
    while let Some(event) = session.next_event() {
        seen.push(matches!(event, SessionEvent::Paused));
    }
    assert_eq!(
        seen,
        vec![true, false, true, false, true, false],
        "three switches away and back"
    );
}

#[test]
fn switching_asks_the_seat_and_waits() {
    // Asynchronous: the seat pauses when it honors the request. Nothing
    // changes at the moment of asking.
    let mut session = with_card();
    session.switch_session(3).expect("switch");

    assert!(session.backend().calls.contains(&Call::Switch(3)));
    assert!(
        session.is_active(),
        "still ours until the seat says otherwise"
    );
    assert_eq!(session.next_event(), None);
}

#[test]
fn the_poll_descriptor_comes_from_the_seat() {
    let session = with_card();
    assert_eq!(session.poll_fd(), Some(7));
}

#[test]
fn dispatching_nothing_is_quiet() {
    let mut session = with_card();
    session.dispatch(0).expect("dispatch");
    assert_eq!(session.next_event(), None);
    assert!(session.is_active());
    assert_eq!(
        session.backend().opens().len(),
        1,
        "an idle dispatch reopens nothing"
    );
}