ambient_sys 0.3.1

A system abstraction for Ambient; abstracts over desktop and web. Host-only.
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
use std::{
    collections::BTreeSet,
    marker::PhantomPinned,
    pin::Pin,
    sync::{
        atomic::{AtomicBool, AtomicUsize, Ordering},
        Arc,
    },
    task::{Context, Poll, Waker},
    thread::{self, Thread},
    time::Duration,
};

use futures::{
    task::{ArcWake, AtomicWaker},
    Future,
};
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use pin_project::{pin_project, pinned_drop};
use slotmap::new_key_type;
mod interval;

pub use crate::platform::time::{Instant, SystemTime};

pub use interval::{interval, interval_at, Interval};

pub static GLOBAL_TIMER: Lazy<TimersHandle> = Lazy::new(Timers::start);

pub fn sleep_label(duration: Duration, label: &'static str) -> Sleep {
    Sleep::new(&GLOBAL_TIMER, Instant::now() + duration, label)
}

pub fn sleep_until_label(deadline: Instant, label: &'static str) -> Sleep {
    Sleep::new(&GLOBAL_TIMER, deadline, label)
}

struct TimerEntry {
    waker: AtomicWaker,
    finished: AtomicBool,
    _pinned: PhantomPinned,
    label: &'static str,
}

new_key_type! {
    pub struct TimerKey;
}

#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone)]
struct Entry {
    deadline: Instant,
    timer: *const TimerEntry,
}

unsafe impl Send for Entry {}
unsafe impl Sync for Entry {}

struct ThreadWaker {
    thread_id: Thread,
}

impl ArcWake for ThreadWaker {
    fn wake_by_ref(arc_self: &Arc<Self>) {
        arc_self.thread_id.unpark()
    }
}

struct Inner {
    /// Invoked when there is a new timer
    waker: AtomicWaker,
    heap: Mutex<BTreeSet<Entry>>,
    handle_count: AtomicUsize,
}

impl Inner {
    pub fn register(&self, deadline: Instant, timer: *const TimerEntry) {
        self.heap.lock().insert(Entry { deadline, timer });

        self.waker.wake();
    }

    fn remove(&self, deadline: Instant, timer: *const TimerEntry) {
        self.heap.lock().remove(&Entry { deadline, timer });
    }
}

pub struct TimersHandle {
    inner: Arc<Inner>,
}

impl Clone for TimersHandle {
    fn clone(&self) -> Self {
        self.inner.handle_count.fetch_add(1, Ordering::Relaxed);

        Self {
            inner: self.inner.clone(),
        }
    }
}

impl Drop for TimersHandle {
    fn drop(&mut self) {
        let count = self.inner.handle_count.fetch_sub(1, Ordering::Relaxed);
        if count == 1 {
            self.inner.waker.wake();
        }
    }
}

pub struct Timers {
    inner: Arc<Inner>,
}

pub struct TimersFinished;

impl Timers {
    pub fn new() -> (Self, TimersHandle) {
        let inner = Arc::new(Inner {
            heap: Mutex::new(BTreeSet::new()),
            waker: AtomicWaker::new(),
            handle_count: AtomicUsize::new(1),
        });

        (
            Self {
                inner: inner.clone(),
            },
            TimersHandle { inner },
        )
    }

    /// Advances the timers, returning the next deadline
    fn tick(&mut self, time: Instant, waker: &Waker) -> Result<Option<Instant>, TimersFinished> {
        self.inner.waker.register(waker);

        let mut heap = self.inner.heap.lock();

        tracing::debug!(count = heap.len(), "Timers::tick");
        let time_end = time + Duration::from_millis(10);
        let mut count = 0;
        while let Some(entry) = heap.first() {
            // All deadlines before now have been handled
            if entry.deadline > time_end {
                tracing::debug!(?count, "expired timers this tick");
                return Ok(Some(entry.deadline));
            }
            count += 1;

            let entry = heap.pop_first().unwrap();
            // Fire and wake the timer
            // # Safety
            // Sleep removes the timer when dropped
            // Drop is guaranteed due to Sleep being pinned when registered
            let timer = unsafe { &*(entry.timer) };

            tracing::debug!(label=?timer.label, deadline=?entry.deadline, ?time, "Timer expired" );
            // Wake the future waiting on the timer
            timer.finished.store(true, Ordering::SeqCst);
            timer.waker.wake();
        }

        tracing::debug!(?count, "expired timers this tick");

        if self.inner.handle_count.load(Ordering::SeqCst) == 0 {
            return Err(TimersFinished);
        }

        Ok(None)
    }

    /// Starts executing the timers in the background
    pub fn start() -> TimersHandle {
        let (timers, handle) = Timers::new();
        #[cfg(target_os = "unknown")]
        wasm_bindgen_futures::spawn_local(timers.run_wasm());

        #[cfg(not(target_os = "unknown"))]
        std::thread::spawn(move || timers.run_blocking());

        handle
    }

    pub fn run_blocking(mut self) {
        let waker = Arc::new(ThreadWaker {
            thread_id: thread::current(),
        });

        let waker = futures::task::waker(waker);

        loop {
            let now = Instant::now();
            let next = match self.tick(now, &waker) {
                Ok(v) => v,
                Err(_) => {
                    break;
                }
            };

            if let Some(next) = next {
                let dur = next - now;
                thread::park_timeout(dur)
            } else {
                thread::park();
            }
        }
    }

    #[cfg(target_os = "unknown")]
    pub fn run_wasm(self) -> impl Future<Output = ()> {
        let reactor = AsyncReactor {
            timers: self,
            timeout: None,
        };

        reactor
    }
}

#[cfg(target_os = "unknown")]
struct AsyncReactor {
    timers: Timers,
    timeout: Option<gloo_timers::callback::Timeout>,
}

#[cfg(target_os = "unknown")]
impl Future for AsyncReactor {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let now = Instant::now();

        let next = match self.timers.tick(now, cx.waker()) {
            Ok(v) => v,
            Err(_) => {
                return Poll::Ready(());
            }
        };

        if let Some(next) = next {
            let dur = next - now;
            tracing::debug!(?dur, "schedule wakeup");

            let waker = cx.waker().clone();
            let timer = gloo_timers::callback::Timeout::new(
                dur.as_millis().try_into().unwrap(),
                move || {
                    tracing::debug!("wake after timeout");
                    waker.wake_by_ref();
                },
            );

            self.timeout = Some(timer);

            Poll::Pending
        } else {
            tracing::debug!("no timers, yield until a new timer is added");
            Poll::Pending
        }
    }
}

#[pin_project(PinnedDrop)]
/// Sleep future
pub struct Sleep {
    shared: Arc<Inner>,
    timer: Box<TimerEntry>,
    deadline: Instant,
    registered: bool,
    label: &'static str,
}

impl std::fmt::Debug for Sleep {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Sleep")
            .field("deadline", &self.deadline)
            .finish()
    }
}

impl Sleep {
    pub(crate) fn new(handle: &TimersHandle, deadline: Instant, label: &'static str) -> Self {
        Self {
            shared: handle.inner.clone(),
            timer: Box::new(TimerEntry {
                waker: AtomicWaker::new(),
                finished: AtomicBool::new(false),
                _pinned: PhantomPinned,
                label,
            }),
            deadline,
            registered: false,
            label,
        }
    }

    /// Set the label
    pub fn with_label(mut self, label: &'static str) -> Self {
        self.label = label;
        self
    }

    pub fn reset(self: Pin<&mut Self>, deadline: Instant) {
        let (timer, cur_deadline) = self.unregister();
        *cur_deadline = deadline;
        timer.finished.store(false, Ordering::SeqCst);
    }

    pub fn deadline(&self) -> Instant {
        self.deadline
    }

    /// Removes the timer entry from the timers queue.
    ///
    /// The TimerEntry is no longer aliased and is safe to modify.
    fn unregister(self: Pin<&mut Self>) -> (&mut TimerEntry, &mut Instant) {
        let p = self.project();
        // This removes any existing reference to the TimerEntry pointer
        let shared = p.shared;
        shared.remove(*p.deadline, &**p.timer);

        *p.registered = false;
        (p.timer, p.deadline)
    }

    fn register_deadline(self: Pin<&mut Self>) {
        let p = self.project();
        p.shared.register(*p.deadline, &**p.timer);
        *p.registered = true;
    }
}

impl Future for Sleep {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if self
            .timer
            .finished
            .compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
            .is_ok()
        {
            Poll::Ready(())
        } else if !self.registered {
            self.timer.waker.register(cx.waker());
            self.register_deadline();

            Poll::Pending
        } else {
            self.timer.waker.register(cx.waker());
            Poll::Pending
        }
    }
}

#[pinned_drop]
impl PinnedDrop for Sleep {
    fn drop(self: Pin<&mut Self>) {
        if self.registered {
            self.unregister();
        }
    }
}

#[cfg(test)]
pub(crate) fn assert_dur(found: Duration, expected: Duration, msg: &str) {
    assert!(
        (found.as_millis().abs_diff(expected.as_millis())) < 10,
        "Expected {found:?} to be close to {expected:?}\n{msg}",
    )
}

#[cfg(test)]
fn setup_timers() -> (TimersHandle, thread::JoinHandle<()>) {
    let (timers, handle) = Timers::new();

    let thread = thread::Builder::new()
        .name("Timer".into())
        .spawn(move || timers.run_blocking())
        .unwrap();

    (handle, thread)
}

#[cfg(test)]
mod test {
    use std::{eprintln, time::Duration};

    use futures::{stream, FutureExt, StreamExt};

    use super::*;

    #[test]
    fn sleep() {
        let (handle, j) = setup_timers();
        let now = Instant::now();
        futures::executor::block_on(async move {
            Sleep::new(&handle, Instant::now() + Duration::from_millis(500), "a").await;

            eprintln!("Timer 1 finished");

            let now = Instant::now();
            Sleep::new(&handle, Instant::now() + Duration::from_millis(1000), "b").await;

            Sleep::new(&handle, now - Duration::from_millis(100), "b").await;

            eprintln!("Expired timer finished")
        });

        #[cfg(not(miri))]
        assert_dur(now.elapsed(), Duration::from_millis(500 + 1000), "seq");
        j.join().unwrap();
    }

    #[test]
    fn sleep_join() {
        let (handle, j) = setup_timers();

        let now = Instant::now();
        futures::executor::block_on(async move {
            let sleep_1 = Sleep::new(&handle, Instant::now() + Duration::from_millis(500), "a");

            eprintln!("Timer 1 finished");

            let now = Instant::now();
            let sleep_2 = Sleep::new(&handle, Instant::now() + Duration::from_millis(1000), "b");

            let sleep_3 = Sleep::new(&handle, now - Duration::from_millis(100), "c");

            futures::join!(sleep_1, sleep_2, sleep_3);

            eprintln!("Expired timer finished")
        });

        #[cfg(not(miri))]
        assert_dur(now.elapsed(), Duration::from_millis(1000), "join");
        j.join().unwrap();
    }

    #[test]
    fn sleep_race() {
        let (handle, j) = setup_timers();

        let now = Instant::now();
        futures::executor::block_on(async move {
            {
                let mut sleep_1 =
                    Sleep::new(&handle, Instant::now() + Duration::from_millis(500), "a").fuse();

                eprintln!("Timer 1 finished");

                let mut sleep_2 =
                    Sleep::new(&handle, Instant::now() + Duration::from_millis(1000), "b").fuse();

                futures::select!(_ = sleep_1 => {}, _ = sleep_2 => {});
            }

            Sleep::new(&handle, Instant::now() + Duration::from_millis(1500), "c").await;

            let _never_polled =
                Sleep::new(&handle, Instant::now() + Duration::from_millis(2000), "d");
            futures::pin_mut!(_never_polled);
        });

        #[cfg(not(miri))]
        assert_dur(now.elapsed(), Duration::from_millis(2000), "race");
        j.join().unwrap();
    }

    #[test]
    fn sleep_identical() {
        let (handle, j) = setup_timers();

        let now = Instant::now();
        futures::executor::block_on(async move {
            let deadline = now + Duration::from_millis(500);
            stream::iter(
                (0..100)
                    .map(|_| Sleep::new(&handle, deadline, "a"))
                    .collect::<Vec<_>>(),
            )
            .buffered(2048)
            .for_each(|_| async {
                // Sleep::new(&handle, Instant::now() + Duration::from_millis(100)).await;
            })
            .await;
        });

        #[cfg(not(miri))]
        assert_dur(now.elapsed(), Duration::from_millis(500), "seq");
        j.join().unwrap();
    }

    #[test]
    fn sleep_reset() {
        let (handle, j) = setup_timers();

        let now = Instant::now();
        futures::executor::block_on(async move {
            let sleep = Sleep::new(&handle, Instant::now() + Duration::from_millis(500), "a");

            futures::pin_mut!(sleep);
            sleep.as_mut().await;

            sleep
                .as_mut()
                .reset(Instant::now() + Duration::from_millis(1000));

            sleep.as_mut().await;
        });

        #[cfg(not(miri))]
        assert_dur(now.elapsed(), Duration::from_millis(1500), "seq");
        j.join().unwrap();
    }
}