crux_time/
command.rs

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
use std::{future::Future, marker::PhantomData};

use crux_core::{command::RequestBuilder, Command, Request};
use futures::{
    channel::oneshot::{self, Sender},
    select, FutureExt,
};

use crate::{get_timer_id, Duration, Instant, TimeRequest, TimeResponse, TimerId};

pub struct Time<Effect, Event> {
    // Allow impl level trait bounds to avoid repetition
    effect: PhantomData<Effect>,
    event: PhantomData<Event>,
}

impl<Effect, Event> Time<Effect, Event>
where
    Effect: Send + From<Request<TimeRequest>> + 'static,
    Event: Send + 'static,
{
    pub fn now() -> RequestBuilder<Effect, Event, impl Future<Output = TimeResponse>> {
        Command::request_from_shell(TimeRequest::Now)
    }

    pub fn notify_at(
        instant: Instant,
    ) -> (
        RequestBuilder<Effect, Event, impl Future<Output = TimeResponse>>,
        TimerHandle,
    ) {
        let id = get_timer_id();
        let (sender, mut receiver) = oneshot::channel();

        let builder = RequestBuilder::new(move |ctx| async move {
            select! {
                response = ctx.request_from_shell(TimeRequest::NotifyAt { id, instant }).fuse() => return response,
                cleared = receiver => {
                    // The Err variant would mean the sender was dropped, but `receiver` is a fused future,
                    // which signals `is_terminated` true in that case, so this branch of the select will
                    // never run for the Err case

                    let id = cleared.unwrap();
                    return ctx.request_from_shell(TimeRequest::Clear { id }).await;
                }
            }
        });

        let handle = TimerHandle {
            timer_id: id,
            abort: sender,
        };

        (builder, handle)
    }

    pub fn notify_after(
        duration: Duration,
    ) -> (
        RequestBuilder<Effect, Event, impl Future<Output = TimeResponse>>,
        TimerHandle,
    ) {
        let id = get_timer_id();
        let (sender, mut receiver) = oneshot::channel();

        let builder = RequestBuilder::new(move |ctx| async move {
            select! {
                response = ctx.request_from_shell(TimeRequest::NotifyAfter { id, duration }).fuse() => return response,
                cleared = receiver => {
                    // The Err variant would mean the sender was dropped, but `receiver` is a fused future,
                    // which signals `is_terminated` true in that case, so this branch of the select will
                    // never run for the Err case
                    let id = cleared.unwrap();
                    ctx.request_from_shell(TimeRequest::Clear { id }).await
                }
            }
        });

        let handle = TimerHandle {
            timer_id: id,
            abort: sender,
        };

        (builder, handle)
    }
}

/// A handle to a requested timer. Allows the timer to be cleared. The handle is safe to drop,
/// in which case the original timer is no longer abortable
#[derive(Debug)]
pub struct TimerHandle {
    timer_id: TimerId,
    abort: Sender<TimerId>,
}

impl TimerHandle {
    /// Clear the associated timer request. The original task will resolve with `TimeResponse::Cleared`
    /// and the shell will be notified that the timer has been cleared with `TimeRequest::Cleared { id }`,
    /// so it can clean up associated resources
    pub fn clear(self) {
        let _ = self.abort.send(self.timer_id);
    }
}

#[cfg(test)]
mod tests {
    use crux_core::Request;

    use super::Time;
    use crate::{Duration, TimeRequest, TimeResponse};

    enum Effect {
        Time(Request<TimeRequest>),
    }

    impl From<Request<TimeRequest>> for Effect {
        fn from(value: Request<TimeRequest>) -> Self {
            Self::Time(value)
        }
    }

    #[derive(Debug, PartialEq)]
    enum Event {
        Elapsed(TimeResponse),
    }

    #[test]
    fn timer_can_be_cleared() {
        let (cmd, handle) = Time::notify_after(Duration::from_secs(2).unwrap());
        let mut cmd = cmd.then_send(Event::Elapsed);

        let effect = cmd.effects().next();

        assert!(cmd.events().next().is_none());

        let Some(Effect::Time(_request)) = effect else {
            panic!("should get an effect");
        };

        handle.clear();

        let effect = cmd.effects().next();
        assert!(cmd.events().next().is_none());

        let Some(Effect::Time(mut request)) = effect else {
            panic!("should get an effect");
        };

        let TimeRequest::Clear { id } = request.operation else {
            panic!("expected a Clear request");
        };

        request
            .resolve(TimeResponse::Cleared { id })
            .expect("should resolve");

        let event = cmd.events().next();

        assert!(matches!(
            event,
            Some(Event::Elapsed(TimeResponse::Cleared { .. }))
        ));
    }

    #[test]
    fn dropping_a_timer_handle_does_not_clear_the_request() {
        let (cmd, handle) = Time::notify_after(Duration::from_secs(2).unwrap());
        drop(handle);

        let mut cmd = cmd.then_send(Event::Elapsed);
        let effect = cmd.effects().next();

        assert!(cmd.events().next().is_none());

        let Some(Effect::Time(mut request)) = effect else {
            panic!("should get an effect");
        };

        let TimeRequest::NotifyAfter { id, .. } = request.operation else {
            panic!("Expected a NotifyAfter");
        };

        request
            .resolve(TimeResponse::DurationElapsed { id })
            .expect("should resolve");

        let event = cmd.events().next();

        assert_eq!(
            event,
            Some(Event::Elapsed(TimeResponse::DurationElapsed { id }))
        );
    }
}