Coverage Report

Created: 2026-12-05 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
super-voice-daemon/src/daemon/recording/state.rs
Line
Count
Source
1
// SPDX-License-Identifier: GPL-3.0-only
2
//! The daemon's one microphone recording: whether there is one, how far it
3
//! has got, and how to stop it.
4
//!
5
//! This used to be three records that had to agree: a `busy` flag, the stop
6
//! channel, and the reservation of a recording not yet capturing. Each was
7
//! claimed and cleared in a different place, and they did not agree:
8
//!
9
//! - The stop channel was installed only once the recorder was built, a second
10
//!   or so after `busy`, so a stop in between reached nothing and the
11
//!   microphone opened anyway.
12
//! - The reservation had no owner. A second recording could take it, or clear
13
//!   it, and the first then failed its own claim and cleared the second's
14
//!   `busy` under its live take.
15
//! - A recording dropped while it waited kept its reservation, so every start
16
//!   was refused until the daemon restarted.
17
//!
18
//! A [`Claim`] is the one record now. It belongs to the recording that made it,
19
//! it carries the stop channel from the moment the recording holds the
20
//! microphone, and dropping it, however the recording ends, frees the
21
//! microphone.
22
23
use super::RecordingCancelled;
24
use std::sync::atomic::{AtomicU64, Ordering};
25
use std::sync::{Mutex, MutexGuard, PoisonError};
26
use tokio::sync::{broadcast, oneshot};
27
28
/// Where the recording is, if there is one.
29
#[derive(Debug, Default)]
30
pub(crate) struct RecordingState {
31
    phase: Mutex<Phase>,
32
    next_id: AtomicU64,
33
}
34
35
#[derive(Debug, Default)]
36
enum Phase {
37
    #[default]
38
    Idle,
39
    /// Reserved, and starting: not yet holding the microphone. `cancel` is
40
    /// taken by the stop that cancels it.
41
    Starting {
42
        id: u64,
43
        cancel: Option<oneshot::Sender<()>>,
44
    },
45
    /// Holds the microphone: building the recorder, capturing, or
46
    /// transcribing what it captured. `stop` reaches the recorder until
47
    /// capture ends.
48
    Active {
49
        id: u64,
50
        stop: Option<broadcast::Sender<()>>,
51
    },
52
}
53
54
impl Phase {
55
37
    fn id(&self) -> Option<u64> {
56
37
        match self {
57
0
            Self::Idle => None,
58
37
            Self::Starting { id, .. } | Self::Active { id, .. } => Some(*id),
59
        }
60
37
    }
61
}
62
63
/// What [`RecordingState::stop`] did.
64
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65
pub(crate) enum Stopped {
66
    /// There was no recording.
67
    NothingToStop,
68
    /// The recording had not yet taken the microphone, and will not.
69
    Cancelled,
70
    /// The recorder was told to stop capturing.
71
    Signalled,
72
    /// Capture had ended: the take is being transcribed, which a stop does
73
    /// not interrupt.
74
    Transcribing,
75
}
76
77
impl RecordingState {
78
    /// Whether a recording is under way: starting, or holding the
79
    /// microphone.
80
191
    pub(crate) fn is_busy(&self) -> bool {
81
191
        !matches!(*self.phase(), Phase::Idle)
82
191
    }
83
84
    /// Whether a recording is starting: reserved, not yet holding the
85
    /// microphone.
86
13
    pub(crate) fn is_starting(&self) -> bool {
87
13
        matches!(*self.phase(), Phase::Starting { .. })
88
13
    }
89
90
    /// Whether a recording holds the microphone and its take is being
91
    /// transcribed, so there is no capture left to stop.
92
12
    pub(crate) fn is_transcribing(&self) -> bool {
93
12
        matches!(*self.phase(), Phase::Active { stop: None, .. })
94
12
    }
95
96
    /// Whether a recording is starting or capturing: the microphone is open,
97
    /// or about to be. Not once capture has ended and the take is only being
98
    /// transcribed.
99
27
    pub(crate) fn is_capturing(&self) -> bool {
100
27
        matches!(
101
27
            *self.phase(),
102
            Phase::Starting { .. } | Phase::Active { stop: Some(_), .. }
103
        )
104
27
    }
105
106
    /// Reserve the microphone for a new recording. `None` when one is under
107
    /// way: one at a time.
108
    ///
109
    /// The recording starts out starting; it takes the microphone with
110
    /// [`Claim::start`]. The receiver resolves when a stop cancels it before
111
    /// then.
112
37
    pub(crate) fn reserve(&self) -> Option<(Claim<'_>, oneshot::Receiver<()>)> {
113
37
        let mut phase = self.phase();
114
37
        if !matches!(*phase, Phase::Idle) {
115
1
            return None;
116
36
        }
117
36
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
118
36
        let (cancel, cancelled) = oneshot::channel();
119
36
        *phase = Phase::Starting {
120
36
            id,
121
36
            cancel: Some(cancel),
122
36
        };
123
36
        Some((Claim { state: self, id }, cancelled))
124
37
    }
125
126
    /// Stop the recording: cancel one starting, or tell the recorder of one
127
    /// capturing to stop.
128
14
    pub(crate) fn stop(&self) -> Stopped {
129
14
        match &mut *self.phase() {
130
6
            Phase::Idle => Stopped::NothingToStop,
131
            // Marked rather than ended: the recording ends itself on seeing
132
            // the cancel, so no other can take its place before it has.
133
            Phase::Starting { cancel, .. } => {
134
3
                if let Some(cancel) = cancel.take() {
135
                    // Usually unreceived: the mark is what `Claim::start`
136
                    // then finds.
137
3
                    let _ = cancel.send(());
138
0
                }
139
3
                Stopped::Cancelled
140
            }
141
            Phase::Active {
142
                stop: Some(stop), ..
143
            } => {
144
4
                let _ = stop.send(());
145
4
                Stopped::Signalled
146
            }
147
1
            Phase::Active { stop: None, .. } => Stopped::Transcribing,
148
        }
149
14
    }
150
151
355
    fn phase(&self) -> MutexGuard<'_, Phase> {
152
355
        self.phase.lock().unwrap_or_else(PoisonError::into_inner)
153
355
    }
154
}
155
156
/// One recording's hold on the microphone. Dropping it frees the microphone.
157
#[derive(Debug)]
158
pub(crate) struct Claim<'a> {
159
    state: &'a RecordingState,
160
    id: u64,
161
}
162
163
impl Claim<'_> {
164
    /// Take the microphone. Returns the receiver the recorder stops on, which
165
    /// a stop reaches from now on.
166
    ///
167
    /// # Errors
168
    /// [`RecordingCancelled`] when a stop cancelled the recording before
169
    /// then.
170
20
    pub(crate) fn start(&self) -> Result<broadcast::Receiver<()>, RecordingCancelled> {
171
20
        let mut phase = self.state.phase();
172
20
        match &*phase {
173
            Phase::Starting {
174
                id,
175
                cancel: Some(_),
176
18
            } if *id == self.id => {
177
18
                let (stop, stopped) = broadcast::channel(1);
178
18
                *phase = Phase::Active {
179
18
                    id: self.id,
180
18
                    stop: Some(stop),
181
18
                };
182
18
                Ok(stopped)
183
            }
184
2
            _ => Err(RecordingCancelled),
185
        }
186
20
    }
187
188
    /// Capture has ended: a stop now finds the take being transcribed.
189
4
    pub(crate) fn capture_ended(&self) {
190
4
        if let Phase::Active { id, stop } = &mut *self.state.phase()
191
4
            && *id == self.id
192
        {
193
4
            *stop = None;
194
0
        }
195
4
    }
196
}
197
198
impl Drop for Claim<'_> {
199
37
    fn drop(&mut self) {
200
37
        let mut phase = self.state.phase();
201
37
        if phase.id() == Some(self.id) {
202
36
            *phase = Phase::Idle;
203
1
        }
204
37
    }
205
}
206
207
#[cfg(test)]
208
mod tests {
209
    use super::{RecordingState, Stopped};
210
211
    /// One recording at a time, and the microphone is free again once it
212
    /// ends, however it ends.
213
    #[test]
214
1
    fn one_recording_at_a_time_until_its_claim_drops() {
215
1
        let state = RecordingState::default();
216
1
        let (claim, _cancelled) = state.reserve().expect("free");
217
1
        assert!(state.reserve().is_none(), "two recordings at once");
218
1
        assert!(state.is_busy());
219
220
1
        drop(claim);
221
1
        assert!(!state.is_busy());
222
1
        assert!(state.reserve().is_some());
223
1
    }
224
225
    /// A stop reaches a recording from the moment it takes the microphone,
226
    /// before its recorder is built.
227
    #[test]
228
1
    fn a_stop_reaches_a_recording_as_soon_as_it_starts() {
229
1
        let state = RecordingState::default();
230
1
        let (claim, _cancelled) = state.reserve().expect("free");
231
1
        let mut stopped = claim.start().expect("not cancelled");
232
233
1
        assert_eq!(state.stop(), Stopped::Signalled);
234
1
        assert!(stopped.try_recv().is_ok(), "the recorder never heard it");
235
1
    }
236
237
    /// A stop while the recording is starting cancels it, and the recording
238
    /// finds that when it would take the microphone.
239
    #[test]
240
1
    fn a_stop_while_starting_cancels_the_recording() {
241
1
        let state = RecordingState::default();
242
1
        let (claim, mut cancelled) = state.reserve().expect("free");
243
244
1
        assert_eq!(state.stop(), Stopped::Cancelled);
245
1
        assert!(cancelled.try_recv().is_ok());
246
1
        assert!(claim.start().is_err(), "a cancelled recording started");
247
1
        assert!(state.is_busy(), "freed before the recording saw its cancel");
248
1
        drop(claim);
249
1
        assert!(!state.is_busy());
250
1
    }
251
252
    /// Once capture has ended, a stop finds the take being transcribed.
253
    #[test]
254
1
    fn a_stop_after_capture_finds_the_take_transcribing() {
255
1
        let state = RecordingState::default();
256
1
        let (claim, _cancelled) = state.reserve().expect("free");
257
1
        let _stopped = claim.start().expect("not cancelled");
258
1
        claim.capture_ended();
259
260
1
        assert!(state.is_transcribing());
261
1
        assert_eq!(state.stop(), Stopped::Transcribing);
262
1
    }
263
264
    /// A claim only ever frees its own recording: a stale one dropping late
265
    /// leaves the next recording alone.
266
    #[test]
267
1
    fn a_claim_frees_only_its_own_recording() {
268
1
        let state = RecordingState::default();
269
1
        let (first, _) = state.reserve().expect("free");
270
        // The first is cancelled and freed by hand, as if it had ended, while
271
        // a value of it lingers.
272
1
        assert_eq!(state.stop(), Stopped::Cancelled);
273
1
        let stale = super::Claim {
274
1
            state: &state,
275
1
            id: first.id,
276
1
        };
277
1
        drop(first);
278
1
        let (second, _) = state.reserve().expect("free again");
279
280
1
        drop(stale);
281
1
        assert!(state.is_busy(), "a stale claim freed the next recording");
282
1
        assert!(second.start().is_ok());
283
1
    }
284
285
    /// Nothing to stop when no recording is under way.
286
    #[test]
287
1
    fn a_stop_with_no_recording_does_nothing() {
288
1
        assert_eq!(RecordingState::default().stop(), Stopped::NothingToStop);
289
1
    }
290
291
    /// A recording captures from the moment it is reserved, since the
292
    /// microphone is about to open, until capture ends. Its transcription is
293
    /// not capturing.
294
    #[test]
295
1
    fn a_recording_captures_until_its_capture_ends() {
296
1
        let state = RecordingState::default();
297
1
        assert!(!state.is_capturing(), "nothing is recording");
298
1
        let (claim, _cancelled) = state.reserve().expect("free");
299
1
        assert!(state.is_capturing(), "starting");
300
1
        let _stopped = claim.start().expect("not cancelled");
301
1
        assert!(state.is_capturing(), "holding the microphone");
302
1
        claim.capture_ended();
303
1
        assert!(!state.is_capturing(), "only transcribing");
304
1
        drop(claim);
305
1
        assert!(!state.is_capturing(), "over");
306
1
    }
307
}