summary refs log tree commit diff
path: root/src/librustuv/timer.rs
blob: 6cbba8e6fd452eaea47dec7f19d2498baaac6836 (plain)
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
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::libc::c_int;
use std::mem;
use std::rt::rtio::RtioTimer;
use std::rt::task::BlockedTask;

use homing::{HomeHandle, HomingIO};
use super::{UvHandle, ForbidUnwind, ForbidSwitch, wait_until_woken_after};
use uvio::UvIoFactory;
use uvll;

pub struct TimerWatcher {
    handle: *uvll::uv_timer_t,
    home: HomeHandle,
    action: Option<NextAction>,
    blocker: Option<BlockedTask>,
    id: uint, // see comments in timer_cb
}

pub enum NextAction {
    WakeTask,
    SendOnce(Sender<()>),
    SendMany(Sender<()>, uint),
}

impl TimerWatcher {
    pub fn new(io: &mut UvIoFactory) -> ~TimerWatcher {
        let handle = UvHandle::alloc(None::<TimerWatcher>, uvll::UV_TIMER);
        assert_eq!(unsafe {
            uvll::uv_timer_init(io.uv_loop(), handle)
        }, 0);
        let me = ~TimerWatcher {
            handle: handle,
            action: None,
            blocker: None,
            home: io.make_handle(),
            id: 0,
        };
        return me.install();
    }

    fn start(&mut self, msecs: u64, period: u64) {
        assert_eq!(unsafe {
            uvll::uv_timer_start(self.handle, timer_cb, msecs, period)
        }, 0)
    }

    fn stop(&mut self) {
        assert_eq!(unsafe { uvll::uv_timer_stop(self.handle) }, 0)
    }
}

impl HomingIO for TimerWatcher {
    fn home<'r>(&'r mut self) -> &'r mut HomeHandle { &mut self.home }
}

impl UvHandle<uvll::uv_timer_t> for TimerWatcher {
    fn uv_handle(&self) -> *uvll::uv_timer_t { self.handle }
}

impl RtioTimer for TimerWatcher {
    fn sleep(&mut self, msecs: u64) {
        // As with all of the below functions, we must be extra careful when
        // destroying the previous action. If the previous action was a channel,
        // destroying it could invoke a context switch. For these situtations,
        // we must temporarily un-home ourselves, then destroy the action, and
        // then re-home again.
        let missile = self.fire_homing_missile();
        self.id += 1;
        self.stop();
        let _missile = match mem::replace(&mut self.action, None) {
            None => missile, // no need to do a homing dance
            Some(action) => {
                drop(missile);      // un-home ourself
                drop(action);       // destroy the previous action
                self.fire_homing_missile()  // re-home ourself
            }
        };

        // If the descheduling operation unwinds after the timer has been
        // started, then we need to call stop on the timer.
        let _f = ForbidUnwind::new("timer");

        self.action = Some(WakeTask);
        wait_until_woken_after(&mut self.blocker, &self.uv_loop(), || {
            self.start(msecs, 0);
        });
        self.stop();
    }

    fn oneshot(&mut self, msecs: u64) -> Receiver<()> {
        let (tx, rx) = channel();

        // similarly to the destructor, we must drop the previous action outside
        // of the homing missile
        let _prev_action = {
            let _m = self.fire_homing_missile();
            self.id += 1;
            self.stop();
            self.start(msecs, 0);
            mem::replace(&mut self.action, Some(SendOnce(tx)))
        };

        return rx;
    }

    fn period(&mut self, msecs: u64) -> Receiver<()> {
        let (tx, rx) = channel();

        // similarly to the destructor, we must drop the previous action outside
        // of the homing missile
        let _prev_action = {
            let _m = self.fire_homing_missile();
            self.id += 1;
            self.stop();
            self.start(msecs, msecs);
            mem::replace(&mut self.action, Some(SendMany(tx, self.id)))
        };

        return rx;
    }
}

extern fn timer_cb(handle: *uvll::uv_timer_t, status: c_int) {
    let _f = ForbidSwitch::new("timer callback can't switch");
    assert_eq!(status, 0);
    let timer: &mut TimerWatcher = unsafe { UvHandle::from_uv_handle(&handle) };

    match timer.action.take_unwrap() {
        WakeTask => {
            let task = timer.blocker.take_unwrap();
            let _ = task.wake().map(|t| t.reawaken());
        }
        SendOnce(chan) => { let _ = chan.try_send(()); }
        SendMany(chan, id) => {
            let _ = chan.try_send(());

            // Note that the above operation could have performed some form of
            // scheduling. This means that the timer may have decided to insert
            // some other action to happen. This 'id' keeps track of the updates
            // to the timer, so we only reset the action back to sending on this
            // channel if the id has remained the same. This is essentially a
            // bug in that we have mutably aliasable memory, but that's libuv
            // for you. We're guaranteed to all be running on the same thread,
            // so there's no need for any synchronization here.
            if timer.id == id {
                timer.action = Some(SendMany(chan, id));
            }
        }
    }
}

impl Drop for TimerWatcher {
    fn drop(&mut self) {
        // note that this drop is a little subtle. Dropping a channel which is
        // held internally may invoke some scheduling operations. We can't take
        // the channel unless we're on the home scheduler, but once we're on the
        // home scheduler we should never move. Hence, we take the timer's
        // action item and then move it outside of the homing block.
        let _action = {
            let _m = self.fire_homing_missile();
            self.stop();
            self.close();
            self.action.take()
        };
    }
}

#[cfg(test)]
mod test {
    use std::rt::rtio::RtioTimer;
    use super::super::local_loop;
    use super::TimerWatcher;

    #[test]
    fn oneshot() {
        let mut timer = TimerWatcher::new(local_loop());
        let port = timer.oneshot(1);
        port.recv();
        let port = timer.oneshot(1);
        port.recv();
    }

    #[test]
    fn override() {
        let mut timer = TimerWatcher::new(local_loop());
        let oport = timer.oneshot(1);
        let pport = timer.period(1);
        timer.sleep(1);
        assert_eq!(oport.recv_opt(), None);
        assert_eq!(pport.recv_opt(), None);
        timer.oneshot(1).recv();
    }

    #[test]
    fn period() {
        let mut timer = TimerWatcher::new(local_loop());
        let port = timer.period(1);
        port.recv();
        port.recv();
        let port2 = timer.period(1);
        port2.recv();
        port2.recv();
    }

    #[test]
    fn sleep() {
        let mut timer = TimerWatcher::new(local_loop());
        timer.sleep(1);
        timer.sleep(1);
    }

    #[test] #[should_fail]
    fn oneshot_fail() {
        let mut timer = TimerWatcher::new(local_loop());
        let _port = timer.oneshot(1);
        fail!();
    }

    #[test] #[should_fail]
    fn period_fail() {
        let mut timer = TimerWatcher::new(local_loop());
        let _port = timer.period(1);
        fail!();
    }

    #[test] #[should_fail]
    fn normal_fail() {
        let _timer = TimerWatcher::new(local_loop());
        fail!();
    }

    #[test]
    fn closing_channel_during_drop_doesnt_kill_everything() {
        // see issue #10375
        let mut timer = TimerWatcher::new(local_loop());
        let timer_port = timer.period(1000);

        spawn(proc() {
            let _ = timer_port.recv_opt();
        });

        // when we drop the TimerWatcher we're going to destroy the channel,
        // which must wake up the task on the other end
    }

    #[test]
    fn reset_doesnt_switch_tasks() {
        // similar test to the one above.
        let mut timer = TimerWatcher::new(local_loop());
        let timer_port = timer.period(1000);

        spawn(proc() {
            let _ = timer_port.recv_opt();
        });

        drop(timer.oneshot(1));
    }
    #[test]
    fn reset_doesnt_switch_tasks2() {
        // similar test to the one above.
        let mut timer = TimerWatcher::new(local_loop());
        let timer_port = timer.period(1000);

        spawn(proc() {
            let _ = timer_port.recv_opt();
        });

        timer.sleep(1);
    }

    #[test]
    fn sender_goes_away_oneshot() {
        let port = {
            let mut timer = TimerWatcher::new(local_loop());
            timer.oneshot(1000)
        };
        assert_eq!(port.recv_opt(), None);
    }

    #[test]
    fn sender_goes_away_period() {
        let port = {
            let mut timer = TimerWatcher::new(local_loop());
            timer.period(1000)
        };
        assert_eq!(port.recv_opt(), None);
    }

    #[test]
    fn receiver_goes_away_oneshot() {
        let mut timer1 = TimerWatcher::new(local_loop());
        drop(timer1.oneshot(1));
        let mut timer2 = TimerWatcher::new(local_loop());
        // while sleeping, the prevous timer should fire and not have its
        // callback do something terrible.
        timer2.sleep(2);
    }

    #[test]
    fn receiver_goes_away_period() {
        let mut timer1 = TimerWatcher::new(local_loop());
        drop(timer1.period(1));
        let mut timer2 = TimerWatcher::new(local_loop());
        // while sleeping, the prevous timer should fire and not have its
        // callback do something terrible.
        timer2.sleep(2);
    }
}