asupersync 0.3.4

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! Stream adapter for watch receivers.

use crate::channel::watch;
use crate::cx::Cx;
use crate::stream::Stream;
use std::pin::Pin;
use std::task::{Context, Poll};

/// Stream that yields when watch value changes.
#[derive(Debug)]
pub struct WatchStream<T> {
    inner: watch::Receiver<T>,
    cx: Cx,
    has_seen_initial: bool,
    terminated: bool,
}

impl<T: Clone> WatchStream<T> {
    /// Create from watch receiver.
    #[inline]
    #[must_use]
    pub fn new(cx: Cx, recv: watch::Receiver<T>) -> Self {
        Self {
            inner: recv,
            cx,
            has_seen_initial: false,
            terminated: false,
        }
    }

    /// Create, skipping the initial value.
    #[inline]
    #[must_use]
    pub fn from_changes(cx: Cx, recv: watch::Receiver<T>) -> Self {
        let mut stream = Self::new(cx, recv);
        // Skip whatever value/version is current at construction time.
        stream.inner.mark_seen();
        stream.has_seen_initial = true;
        stream
    }

    /// Returns a reference to the underlying watch receiver.
    #[inline]
    #[must_use]
    pub fn get_ref(&self) -> &watch::Receiver<T> {
        &self.inner
    }

    /// Returns a mutable reference to the underlying watch receiver.
    #[inline]
    pub fn get_mut(&mut self) -> &mut watch::Receiver<T> {
        &mut self.inner
    }

    /// Consumes the stream, returning the underlying watch receiver.
    #[inline]
    #[must_use]
    pub fn into_inner(self) -> watch::Receiver<T> {
        self.inner
    }
}

impl<T: Clone> Stream for WatchStream<T> {
    type Item = T;

    fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        if this.terminated {
            return Poll::Ready(None);
        }

        // Keep the initial snapshot path consistent with the change-wait path:
        // a pre-requested cancellation terminates the stream instead of yielding
        // one last snapshot.
        if !this.has_seen_initial {
            if this.cx.checkpoint().is_err() {
                this.terminated = true;
                return Poll::Ready(None);
            }
            this.has_seen_initial = true;
            // The initial snapshot counts as observed by this stream.
            return Poll::Ready(Some(this.inner.borrow_and_update_clone()));
        }

        match this.inner.poll_changed(&this.cx, context) {
            Poll::Ready(Ok(())) => Poll::Ready(Some(this.inner.borrow_and_update_clone())),
            Poll::Ready(Err(_)) => {
                this.terminated = true;
                Poll::Ready(None)
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::*;
    use std::rc::Rc;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::task::{Context, Waker};

    fn noop_waker() -> Waker {
        std::task::Waker::noop().clone()
    }

    struct CountingWaker {
        wake_count: AtomicUsize,
    }

    use std::task::Wake;
    impl Wake for CountingWaker {
        fn wake(self: Arc<Self>) {
            self.wake_count.fetch_add(1, Ordering::SeqCst);
        }

        fn wake_by_ref(self: &Arc<Self>) {
            self.wake_count.fetch_add(1, Ordering::SeqCst);
        }
    }

    fn counting_waker() -> (Arc<CountingWaker>, Waker) {
        let state = Arc::new(CountingWaker {
            wake_count: AtomicUsize::new(0),
        });
        let waker = Waker::from(Arc::clone(&state));
        (state, waker)
    }

    fn init_test(name: &str) {
        crate::test_utils::init_test_logging();
        crate::test_phase!(name);
    }

    fn collect_closed_stream(mut stream: WatchStream<i32>) -> Vec<i32> {
        let waker = noop_waker();
        let mut task_cx = Context::from_waker(&waker);
        let mut out = Vec::new();

        loop {
            match Pin::new(&mut stream).poll_next(&mut task_cx) {
                Poll::Ready(Some(item)) => out.push(item),
                Poll::Ready(None) => return out,
                Poll::Pending => panic!("closed watch stream unexpectedly returned Pending"),
            }
        }
    }

    fn collect_new_after_sends(initial: i32, sends: &[i32]) -> Vec<i32> {
        let cx: Cx = Cx::for_testing();
        let (tx, rx) = watch::channel(initial);
        for &value in sends {
            tx.send(value)
                .expect("watch send before stream construction");
        }
        drop(tx);
        collect_closed_stream(WatchStream::new(cx, rx))
    }

    #[test]
    fn watch_stream_none_is_terminal_after_cancel() {
        init_test("watch_stream_none_is_terminal_after_cancel");
        let cx: Cx = Cx::for_testing();
        cx.set_cancel_requested(true);
        let (tx, rx) = watch::channel(0);
        let mut stream = WatchStream::from_changes(cx.clone(), rx);
        let waker = noop_waker();
        let mut task_cx = Context::from_waker(&waker);

        let poll = Pin::new(&mut stream).poll_next(&mut task_cx);
        let first_none = matches!(poll, Poll::Ready(None));
        crate::assert_with_log!(first_none, "first poll none", true, first_none);

        cx.set_cancel_requested(false);
        let send_result = tx.send(1);
        crate::assert_with_log!(
            send_result.is_ok(),
            "send after cancel clear succeeds",
            true,
            send_result.is_ok()
        );

        let poll = Pin::new(&mut stream).poll_next(&mut task_cx);
        let still_none = matches!(poll, Poll::Ready(None));
        crate::assert_with_log!(still_none, "stream remains terminated", true, still_none);
        crate::test_complete!("watch_stream_none_is_terminal_after_cancel");
    }

    #[test]
    fn watch_stream_new_none_is_terminal_after_cancel_before_initial_snapshot() {
        init_test("watch_stream_new_none_is_terminal_after_cancel_before_initial_snapshot");
        let cx: Cx = Cx::for_testing();
        cx.set_cancel_requested(true);
        let (tx, rx) = watch::channel(0);
        let mut stream = WatchStream::new(cx.clone(), rx);
        let waker = noop_waker();
        let mut task_cx = Context::from_waker(&waker);

        let poll = Pin::new(&mut stream).poll_next(&mut task_cx);
        let first_none = matches!(poll, Poll::Ready(None));
        crate::assert_with_log!(first_none, "first poll none", true, first_none);

        cx.set_cancel_requested(false);
        let send_result = tx.send(1);
        crate::assert_with_log!(
            send_result.is_ok(),
            "send after cancel clear succeeds",
            true,
            send_result.is_ok()
        );

        let poll = Pin::new(&mut stream).poll_next(&mut task_cx);
        let still_none = matches!(poll, Poll::Ready(None));
        crate::assert_with_log!(still_none, "stream remains terminated", true, still_none);
        crate::test_complete!(
            "watch_stream_new_none_is_terminal_after_cancel_before_initial_snapshot"
        );
    }

    #[test]
    fn mr_watch_stream_preconstruction_split_sends_coalesce_to_latest() {
        init_test("mr_watch_stream_preconstruction_split_sends_coalesce_to_latest");
        let sends = vec![1, 2, 3, 5, 8];
        let expected = collect_new_after_sends(0, &sends);

        for split in 0..=sends.len() {
            let mut split_sends = sends[..split].to_vec();
            split_sends.extend_from_slice(&sends[split..]);
            let actual = collect_new_after_sends(0, &split_sends);

            crate::assert_with_log!(
                actual == expected,
                format!("preconstruction split at {split}"),
                expected.clone(),
                actual
            );
        }

        crate::test_complete!("mr_watch_stream_preconstruction_split_sends_coalesce_to_latest");
    }

    #[test]
    fn mr_watch_stream_from_changes_output_is_prehistory_invariant() {
        init_test("mr_watch_stream_from_changes_output_is_prehistory_invariant");
        let future_change = 99;
        let prehistories: &[&[i32]] = &[&[], &[1], &[1, 2, 3], &[5, 8, 13, 21]];

        for &prehistory in prehistories {
            let cx: Cx = Cx::for_testing();
            let (tx, rx) = watch::channel(0);
            for &value in prehistory {
                tx.send(value).expect("watch prehistory send");
            }

            let mut stream = WatchStream::from_changes(cx, rx);
            let waker = noop_waker();
            let mut task_cx = Context::from_waker(&waker);
            let first = Pin::new(&mut stream).poll_next(&mut task_cx);
            crate::assert_with_log!(
                first.is_pending(),
                format!("prehistory length {} is skipped", prehistory.len()),
                true,
                first.is_pending()
            );

            tx.send(future_change).expect("watch future send");
            drop(tx);
            let actual = collect_closed_stream(stream);

            crate::assert_with_log!(
                actual == vec![future_change],
                format!(
                    "prehistory length {} yields only future change",
                    prehistory.len()
                ),
                vec![future_change],
                actual
            );
        }

        crate::test_complete!("mr_watch_stream_from_changes_output_is_prehistory_invariant");
    }

    #[test]
    fn watch_stream_initial_snapshot_does_not_duplicate_pending_update() {
        init_test("watch_stream_initial_snapshot_does_not_duplicate_pending_update");
        let cx: Cx = Cx::for_testing();
        let (tx, rx) = watch::channel(0);
        let send_result = tx.send(1);
        crate::assert_with_log!(
            send_result.is_ok(),
            "pre-send should succeed",
            true,
            send_result.is_ok()
        );

        let mut stream = WatchStream::new(cx, rx);
        let waker = noop_waker();
        let mut task_cx = Context::from_waker(&waker);

        let first = Pin::new(&mut stream).poll_next(&mut task_cx);
        crate::assert_with_log!(
            matches!(first, Poll::Ready(Some(1))),
            "first poll returns latest snapshot once",
            "Ready(Some(1))",
            format!("{first:?}")
        );

        let second = Pin::new(&mut stream).poll_next(&mut task_cx);
        crate::assert_with_log!(
            second.is_pending(),
            "second poll waits for a new change",
            true,
            second.is_pending()
        );
        crate::test_complete!("watch_stream_initial_snapshot_does_not_duplicate_pending_update");
    }

    #[test]
    fn watch_stream_from_changes_skips_current_value() {
        init_test("watch_stream_from_changes_skips_current_value");
        let cx: Cx = Cx::for_testing();
        let (tx, rx) = watch::channel(0);
        let send_result = tx.send(1);
        crate::assert_with_log!(
            send_result.is_ok(),
            "pre-send should succeed",
            true,
            send_result.is_ok()
        );

        let mut stream = WatchStream::from_changes(cx, rx);
        let waker = noop_waker();
        let mut task_cx = Context::from_waker(&waker);

        let first = Pin::new(&mut stream).poll_next(&mut task_cx);
        crate::assert_with_log!(
            first.is_pending(),
            "from_changes skips current value",
            true,
            first.is_pending()
        );

        let send_result = tx.send(2);
        crate::assert_with_log!(
            send_result.is_ok(),
            "second send should succeed",
            true,
            send_result.is_ok()
        );
        let second = Pin::new(&mut stream).poll_next(&mut task_cx);
        crate::assert_with_log!(
            matches!(second, Poll::Ready(Some(2))),
            "next change is yielded",
            "Ready(Some(2))",
            format!("{second:?}")
        );
        crate::test_complete!("watch_stream_from_changes_skips_current_value");
    }

    /// Invariant: stream terminates after sender is dropped.
    #[test]
    fn watch_stream_terminates_after_sender_drop() {
        init_test("watch_stream_terminates_after_sender_drop");
        let cx: Cx = Cx::for_testing();
        let (tx, rx) = watch::channel(42);
        let mut stream = WatchStream::new(cx, rx);
        let waker = noop_waker();
        let mut task_cx = Context::from_waker(&waker);

        // First poll: returns initial snapshot.
        let poll = Pin::new(&mut stream).poll_next(&mut task_cx);
        let got_42 = matches!(poll, Poll::Ready(Some(42)));
        crate::assert_with_log!(got_42, "initial snapshot", true, got_42);

        // Drop sender, then poll — should terminate.
        drop(tx);
        let poll = Pin::new(&mut stream).poll_next(&mut task_cx);
        let is_none = matches!(poll, Poll::Ready(None));
        crate::assert_with_log!(is_none, "terminated after sender drop", true, is_none);

        crate::test_complete!("watch_stream_terminates_after_sender_drop");
    }

    #[test]
    fn watch_stream_pending_poll_retains_waiter_registration() {
        init_test("watch_stream_pending_poll_retains_waiter_registration");
        let cx: Cx = Cx::for_testing();
        let (tx, rx) = watch::channel(0);
        let mut stream = WatchStream::from_changes(cx, rx);
        let (wake_state, waker) = counting_waker();
        let mut task_cx = Context::from_waker(&waker);

        let first = Pin::new(&mut stream).poll_next(&mut task_cx);
        crate::assert_with_log!(
            first.is_pending(),
            "initial poll waits for a change",
            true,
            first.is_pending()
        );
        let wake_count = wake_state.wake_count.load(Ordering::SeqCst);
        crate::assert_with_log!(wake_count == 0, "no wake before send", 0, wake_count);

        let send_result = tx.send(1);
        crate::assert_with_log!(
            send_result.is_ok(),
            "send after pending poll succeeds",
            true,
            send_result.is_ok()
        );
        let wake_count = wake_state.wake_count.load(Ordering::SeqCst);
        crate::assert_with_log!(
            wake_count > 0,
            "pending waiter is woken by send",
            "> 0",
            wake_count
        );

        let second = Pin::new(&mut stream).poll_next(&mut task_cx);
        crate::assert_with_log!(
            matches!(second, Poll::Ready(Some(1))),
            "woken poll yields new value",
            "Ready(Some(1))",
            format!("{second:?}")
        );
        crate::test_complete!("watch_stream_pending_poll_retains_waiter_registration");
    }

    #[test]
    fn watch_stream_accepts_non_send_non_sync_items() {
        init_test("watch_stream_accepts_non_send_non_sync_items");
        let cx: Cx = Cx::for_testing();
        let payload = Rc::new(String::from("local-only"));
        let (_tx, rx) = watch::channel(Rc::clone(&payload));
        let mut stream = WatchStream::new(cx, rx);
        let waker = noop_waker();
        let mut task_cx = Context::from_waker(&waker);

        let poll = Pin::new(&mut stream).poll_next(&mut task_cx);
        let got_initial = matches!(
            poll,
            Poll::Ready(Some(value)) if Rc::ptr_eq(&value, &payload)
        );
        crate::assert_with_log!(
            got_initial,
            "non-Send/non-Sync Rc payload is yielded",
            true,
            got_initial
        );

        crate::test_complete!("watch_stream_accepts_non_send_non_sync_items");
    }
}