1
//! Runtime side of the request / resume primitive.
2
//!
3
//! Every OS-facing operation the browser can only answer asynchronously is
4
//! split in two on every target:
5
//!
6
//! * **request** - `FileDialog::open_file(.., data, on_result) -> RequestId` registers `{RequestId,
7
//!   data, on_result}` here and returns the id.
8
//! * **resume** - once the result exists the *runtime* invokes `on_result(data, CallbackInfo,
9
//!   result)` as a fresh, ordinary callback activation. A resume may issue the next request, so a
10
//!   chain of awaits becomes a chain of resumes and the app's callbacks form a state machine over
11
//!   its own `RefAny`.
12
//!
13
//! This module is the one place where requests are parked. On desktop the
14
//! request function usually performs the (modal, blocking) OS call itself and
15
//! calls [`complete`] straight away; the completion is still queued rather
16
//! than invoked, which is what gives every target the same ordering
17
//! guarantee: *the result callback never runs re-entrantly inside the
18
//! requesting activation.* Mobile pickers, whose OS delegates answer later,
19
//! use [`defer`] with a poll closure the pump asks once per frame.
20
//!
21
//! The pump - [`take_completed`] - is driven by the shells after every
22
//! activation and from the per-frame timer/thread tick, and by the E2E runner
23
//! in the same places. `LayoutWindow::run_completed_requests` turns the drained
24
//! entries into callback invocations.
25
//!
26
//! ## Why a process-wide queue and not `CallbackInfo::push_change`
27
//!
28
//! The request functions are ordinary static API functions - they take no
29
//! `CallbackInfo`, because a `RequestId`-returning signature has to be
30
//! callable from anywhere (a timer, a thread writeback, another resume). The
31
//! queue is therefore owned by the runtime, not by an activation. It is the
32
//! single choke point a web host replaces: a lifted build classifies
33
//! [`complete_erased`] / [`defer`] / [`take_completed`] as boundary imports
34
//! and services them from JavaScript, and nothing else changes.
35
//!
36
//! ## Delivery order and ownership
37
//!
38
//! * FIFO. Nested completions (a resume that issues and immediately completes another request) are
39
//!   appended to the end, never recursed into.
40
//! * Entries are delivered by whichever window pumps next. Synchronous completions (every desktop
41
//!   dialog / file / http call) are pumped by the requesting window right after the requesting
42
//!   activation returns, so in practice a request resumes on the window that issued it.
43
//! * The queue holds a clone of the app's `data` until delivery, keeping the `RefAny` alive across
44
//!   the gap. There is no cancellation in v1.
45

            
46
use alloc::{boxed::Box, vec::Vec};
47

            
48
use azul_core::{refany::RefAny, task::RequestId};
49

            
50
use crate::callbacks::ResumeCallback;
51

            
52
/// A request whose result exists and whose callback has not run yet.
53
pub struct CompletedRequest {
54
    pub request_id: RequestId,
55
    /// The app's context, exactly as submitted to the request function.
56
    pub data: RefAny,
57
    pub callback: ResumeCallback,
58
    /// The per-operation result struct, type-erased.
59
    pub result: RefAny,
60
}
61

            
62
impl core::fmt::Debug for CompletedRequest {
63
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
64
        f.debug_struct("CompletedRequest")
65
            .field("request_id", &self.request_id)
66
            .field("callback", &self.callback)
67
            .finish_non_exhaustive()
68
    }
69
}
70

            
71
/// Asked by the pump once per frame; returns the type-erased result struct
72
/// once the platform has answered, `None` while the request is still open.
73
pub type PollFn = Box<dyn FnMut() -> Option<RefAny> + Send>;
74

            
75
/// A request the platform answers asynchronously (a mobile file picker whose
76
/// delegate fires later).
77
pub struct PendingRequest {
78
    pub request_id: RequestId,
79
    pub data: RefAny,
80
    pub callback: ResumeCallback,
81
    pub poll: PollFn,
82
}
83

            
84
impl core::fmt::Debug for PendingRequest {
85
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
86
        f.debug_struct("PendingRequest")
87
            .field("request_id", &self.request_id)
88
            .field("callback", &self.callback)
89
            .finish_non_exhaustive()
90
    }
91
}
92

            
93
#[cfg(feature = "std")]
94
mod queue {
95
    use std::sync::Mutex;
96

            
97
    use super::{CompletedRequest, PendingRequest};
98

            
99
    pub(super) struct RequestQueue {
100
        pub completed: Vec<CompletedRequest>,
101
        pub pending: Vec<PendingRequest>,
102
    }
103

            
104
    pub(super) static REQUEST_QUEUE: Mutex<RequestQueue> = Mutex::new(RequestQueue {
105
        completed: Vec::new(),
106
        pending: Vec::new(),
107
    });
108

            
109
676
    pub(super) fn with_queue<R>(f: impl FnOnce(&mut RequestQueue) -> R) -> R {
110
        // A poisoned lock only means a callback panicked while the queue was
111
        // held; the queue itself is still a plain Vec pair, so keep serving.
112
676
        let mut guard = REQUEST_QUEUE
113
676
            .lock()
114
676
            .unwrap_or_else(std::sync::PoisonError::into_inner);
115
676
        f(&mut guard)
116
676
    }
117
}
118

            
119
/// Registers a request whose result is already known and returns its id.
120
///
121
/// This is what every desktop request function calls after its synchronous
122
/// OS call: the callback runs on the next pump, never inside the caller.
123
2
pub fn complete<T: 'static>(data: RefAny, on_result: ResumeCallback, result: T) -> RequestId {
124
2
    complete_erased(data, on_result, RefAny::new(result))
125
2
}
126

            
127
/// [`complete`] with an already type-erased result struct.
128
#[must_use]
129
2
pub fn complete_erased(data: RefAny, on_result: ResumeCallback, result: RefAny) -> RequestId {
130
2
    let request_id = RequestId::unique();
131
    #[cfg(feature = "std")]
132
2
    queue::with_queue(|q| {
133
2
        q.completed.push(CompletedRequest {
134
2
            request_id,
135
2
            data,
136
2
            callback: on_result,
137
2
            result,
138
2
        });
139
2
    });
140
    #[cfg(not(feature = "std"))]
141
    {
142
        // Without std there is no runtime pump; the request is acknowledged
143
        // but never resumed. Every request function documents that no_std
144
        // builds have no OS-facing implementation.
145
        drop((data, on_result, result));
146
    }
147
2
    request_id
148
2
}
149

            
150
/// Registers a request the platform will answer later. `poll` is asked once
151
/// per frame until it returns `Some(result)`.
152
#[must_use]
153
1
pub fn defer(data: RefAny, on_result: ResumeCallback, poll: PollFn) -> RequestId {
154
1
    let request_id = RequestId::unique();
155
    #[cfg(feature = "std")]
156
1
    queue::with_queue(|q| {
157
1
        q.pending.push(PendingRequest {
158
1
            request_id,
159
1
            data,
160
1
            callback: on_result,
161
1
            poll,
162
1
        });
163
1
    });
164
    #[cfg(not(feature = "std"))]
165
    drop((data, on_result, poll));
166
1
    request_id
167
1
}
168

            
169
/// Drains every completed request, polling the pending ones first. Returns
170
/// them in the order they completed; an empty vector means nothing to do.
171
///
172
/// Called by the shells' pump. Resumes issued *during* delivery land in the
173
/// queue again and are picked up by the next call, which is how nested
174
/// completions stay FIFO instead of recursing.
175
#[must_use]
176
668
pub fn take_completed() -> Vec<CompletedRequest> {
177
    #[cfg(feature = "std")]
178
    {
179
668
        queue::with_queue(|q| {
180
668
            let mut still_pending = Vec::with_capacity(q.pending.len());
181
668
            for mut p in q.pending.drain(..) {
182
2
                match (p.poll)() {
183
1
                    Some(result) => q.completed.push(CompletedRequest {
184
1
                        request_id: p.request_id,
185
1
                        data: p.data,
186
1
                        callback: p.callback,
187
1
                        result,
188
1
                    }),
189
1
                    None => still_pending.push(p),
190
                }
191
            }
192
668
            q.pending = still_pending;
193
668
            core::mem::take(&mut q.completed)
194
668
        })
195
    }
196
    #[cfg(not(feature = "std"))]
197
    {
198
        Vec::new()
199
    }
200
668
}
201

            
202
/// `true` while any request is completed-but-undelivered or still pending.
203
/// Shells use it to keep their frame loop ticking until the queue is empty.
204
#[must_use]
205
2
pub fn has_work() -> bool {
206
    #[cfg(feature = "std")]
207
    {
208
2
        queue::with_queue(|q| !q.completed.is_empty() || !q.pending.is_empty())
209
    }
210
    #[cfg(not(feature = "std"))]
211
    {
212
        false
213
    }
214
2
}
215

            
216
/// Number of requests waiting on a platform answer - a debug probe for tests
217
/// that assert the queue does not grow without bound.
218
#[must_use]
219
3
pub fn pending_count() -> usize {
220
    #[cfg(feature = "std")]
221
    {
222
3
        queue::with_queue(|q| q.pending.len())
223
    }
224
    #[cfg(not(feature = "std"))]
225
    {
226
        0
227
    }
228
3
}
229

            
230
/// Deterministic answers for request functions under end-to-end tests.
231
///
232
/// A picker or a permission prompt cannot run inside an automated test - a
233
/// hanging modal is the worst outcome an e2e run can have - so every request
234
/// function asks this store FIRST. The store is *armed* under an e2e run
235
/// (`AZ_E2E` / `AZ_E2E_TEST` set, or `AZ_BACKEND=headless`; explicitly with
236
/// [`arm`]) and disarmed in production, where it costs one relaxed load.
237
///
238
/// * A **mocked** operation resumes immediately with the canned answer; the resume path is the
239
///   normal one, so a mocked test exercises the whole request / resume machinery except the OS call
240
///   itself.
241
/// * An **unmocked** picker under an armed store resolves as *cancelled* and is recorded (and
242
///   printed) as an unmocked request, so the scenario can assert on it
243
///   (`assert_no_unmocked_requests`) instead of hanging.
244
/// * Reads (`FilePath::read_*`) are served from the canned table when the path is registered and
245
///   from the real file system otherwise: files a scenario created are real, virtual `e2e://`
246
///   documents are canned.
247
/// * `FileDialog::save_bytes` never shows a dialog while armed: the bytes are recorded in
248
///   [`saved_files`] for `assert_saved_file`.
249
///
250
/// The JSON scenario op `{"op": "mock", "set": {...}}` fills the store; the
251
/// same op is what the browser lane maps onto `window.__az_e2e_mock`.
252
#[cfg(feature = "std")]
253
pub mod mock {
254
    use alloc::{
255
        collections::{BTreeMap, VecDeque},
256
        string::String,
257
        vec::Vec,
258
    };
259
    use std::sync::Mutex;
260

            
261
    use azul_css::{props::basic::color::ColorU, AzString};
262

            
263
    /// A canned HTTP answer.
264
    #[derive(Debug, Clone)]
265
    pub struct MockHttpResponse {
266
        pub status: u16,
267
        pub body: Vec<u8>,
268
        pub content_type: AzString,
269
    }
270

            
271
    /// What a mocked HTTP request resolves to.
272
    #[derive(Debug, Clone)]
273
    pub enum MockHttp {
274
        Response(MockHttpResponse),
275
        /// The transport failed (an `HttpError::Other` with this message).
276
        Error(AzString),
277
    }
278

            
279
    /// One `FileDialog::save_bytes` export recorded under an armed store.
280
    #[derive(Debug, Clone)]
281
    pub struct SavedFile {
282
        pub name: AzString,
283
        pub mime: AzString,
284
        pub bytes: Vec<u8>,
285
    }
286

            
287
    /// The store's verdict for one request.
288
    #[derive(Debug, Clone, PartialEq, Eq)]
289
    pub enum Answer<T> {
290
        /// Not an e2e run: perform the real OS call.
291
        NotArmed,
292
        /// Resume with this canned answer.
293
        Mocked(T),
294
        /// An e2e run with no answer queued: resolve as cancelled, loudly.
295
        Unmocked,
296
    }
297

            
298
    #[derive(Default)]
299
    struct MockState {
300
        /// `None` = decide from the environment on first use.
301
        armed: Option<bool>,
302
        file_open: VecDeque<Option<AzString>>,
303
        file_open_multi: VecDeque<Vec<AzString>>,
304
        color_pick: VecDeque<Option<ColorU>>,
305
        save_file: VecDeque<Option<AzString>>,
306
        save_bytes_accept: Option<bool>,
307
        file_reads: BTreeMap<String, Vec<u8>>,
308
        /// `(url pattern, answer)`: an exact URL, a prefix ending in `*`, or
309
        /// `*` for everything; first match wins.
310
        http: Vec<(String, MockHttp)>,
311
        audio_devices: Option<(Vec<AzString>, Vec<AzString>)>,
312
        video_decode_none: bool,
313
        saved_files: Vec<SavedFile>,
314
        unmocked: Vec<String>,
315
    }
316

            
317
    static STATE: Mutex<MockState> = Mutex::new(MockState {
318
        armed: None,
319
        file_open: VecDeque::new(),
320
        file_open_multi: VecDeque::new(),
321
        color_pick: VecDeque::new(),
322
        save_file: VecDeque::new(),
323
        save_bytes_accept: None,
324
        file_reads: BTreeMap::new(),
325
        http: Vec::new(),
326
        audio_devices: None,
327
        video_decode_none: false,
328
        saved_files: Vec::new(),
329
        unmocked: Vec::new(),
330
    });
331

            
332
20
    fn with<R>(f: impl FnOnce(&mut MockState) -> R) -> R {
333
20
        let mut guard = STATE
334
20
            .lock()
335
20
            .unwrap_or_else(std::sync::PoisonError::into_inner);
336
20
        f(&mut guard)
337
20
    }
338

            
339
1
    fn env_armed() -> bool {
340
2
        let set = |k: &str| std::env::var(k).map(|v| !v.is_empty()).unwrap_or(false);
341
1
        set("AZ_E2E")
342
1
            || set("AZ_E2E_TEST")
343
1
            || std::env::var("AZ_BACKEND").as_deref() == Ok("headless")
344
1
    }
345

            
346
20
    fn armed_in(s: &mut MockState) -> bool {
347
20
        *s.armed.get_or_insert_with(env_armed)
348
20
    }
349

            
350
    /// Arm the store explicitly (an e2e host that is not driven by the
351
    /// environment variables).
352
    pub fn arm() {
353
        with(|s| s.armed = Some(true));
354
    }
355

            
356
    /// Disarm the store: every request performs its real OS call again.
357
    pub fn disarm() {
358
        with(|s| s.armed = Some(false));
359
    }
360

            
361
    /// Whether requests are being answered from the store.
362
    #[must_use]
363
    pub fn is_armed() -> bool {
364
        with(armed_in)
365
    }
366

            
367
    /// Forget every queued answer, canned read and record; the armed state
368
    /// stays.
369
    pub fn reset() {
370
        with(|s| {
371
            let armed = s.armed;
372
            *s = MockState::default();
373
            s.armed = armed;
374
        });
375
    }
376

            
377
    /// The answer a scenario queued for `op`, or - when the queue is empty -
378
    /// the recorded "unmocked" fallback.
379
    fn answer<T>(s: &mut MockState, taken: Option<T>, op: &str) -> Answer<T> {
380
        if let Some(a) = taken {
381
            Answer::Mocked(a)
382
        } else {
383
            unmocked(s, op);
384
            Answer::Unmocked
385
        }
386
    }
387

            
388
    fn unmocked(s: &mut MockState, op: &str) {
389
        eprintln!("[azul][e2e] unmocked request under e2e: {op} (resolving as cancelled)");
390
        s.unmocked.push(String::from(op));
391
    }
392

            
393
    // ---- setters (the `mock` scenario op) ---------------------------------
394

            
395
    /// Queue the answer of the next `FileDialog::open_file` /
396
    /// `open_directory` (`None` = the user cancelled).
397
    pub fn push_file_open(path: Option<AzString>) {
398
        with(|s| s.file_open.push_back(path));
399
    }
400

            
401
    /// Queue the answer of the next `FileDialog::open_multiple_files`.
402
    pub fn push_file_open_multi(paths: Vec<AzString>) {
403
        with(|s| s.file_open_multi.push_back(paths));
404
    }
405

            
406
    /// Queue the answer of the next `ColorPickerDialog::open`.
407
    pub fn push_color_pick(color: Option<ColorU>) {
408
        with(|s| s.color_pick.push_back(color));
409
    }
410

            
411
    /// Queue the path the next `FileDialog::save_file` resolves to.
412
    pub fn push_save_file(path: Option<AzString>) {
413
        with(|s| s.save_file.push_back(path));
414
    }
415

            
416
    /// Whether `FileDialog::save_bytes` reports success while armed (default
417
    /// `true`); the bytes are recorded either way.
418
    pub fn set_save_bytes_accept(accept: bool) {
419
        with(|s| s.save_bytes_accept = Some(accept));
420
    }
421

            
422
    /// Serve `bytes` for every `FilePath::read_*` of `path`.
423
    pub fn set_file_read(path: impl Into<String>, bytes: Vec<u8>) {
424
        with(|s| {
425
            s.file_reads.insert(path.into(), bytes);
426
        });
427
    }
428

            
429
    /// Answer HTTP requests whose URL matches `pattern` (exact, `prefix*`,
430
    /// or `*`). Patterns are tried in registration order.
431
    pub fn add_http(pattern: impl Into<String>, answer: MockHttp) {
432
        with(|s| s.http.push((pattern.into(), answer)));
433
    }
434

            
435
    /// The device lists `AudioDeviceList::enumerate` resumes with.
436
    pub fn set_audio_devices(outputs: Vec<AzString>, inputs: Vec<AzString>) {
437
        with(|s| s.audio_devices = Some((outputs, inputs)));
438
    }
439

            
440
    /// Make `DecodedVideo::decode_mp4_h264` resume with `video: None`
441
    /// without touching a codec.
442
    pub fn set_video_decode_none(mocked: bool) {
443
        with(|s| s.video_decode_none = mocked);
444
    }
445

            
446
    // ---- consumers (the request functions) ---------------------------------
447

            
448
    /// `op` names the caller for the unmocked record, e.g.
449
    /// `"FileDialog::open_file"`.
450
    #[must_use]
451
    pub fn take_file_open(op: &str) -> Answer<Option<AzString>> {
452
        with(|s| {
453
            if !armed_in(s) {
454
                return Answer::NotArmed;
455
            }
456
            let taken = s.file_open.pop_front();
457
            answer(s, taken, op)
458
        })
459
    }
460

            
461
    #[must_use]
462
    pub fn take_file_open_multi() -> Answer<Vec<AzString>> {
463
        with(|s| {
464
            if !armed_in(s) {
465
                return Answer::NotArmed;
466
            }
467
            let taken = s.file_open_multi.pop_front();
468
            answer(s, taken, "FileDialog::open_multiple_files")
469
        })
470
    }
471

            
472
    #[must_use]
473
    pub fn take_color_pick() -> Answer<Option<ColorU>> {
474
        with(|s| {
475
            if !armed_in(s) {
476
                return Answer::NotArmed;
477
            }
478
            let taken = s.color_pick.pop_front();
479
            answer(s, taken, "ColorPickerDialog::open")
480
        })
481
    }
482

            
483
    #[must_use]
484
    pub fn take_save_file() -> Answer<Option<AzString>> {
485
        with(|s| {
486
            if !armed_in(s) {
487
                return Answer::NotArmed;
488
            }
489
            let taken = s.save_file.pop_front();
490
            answer(s, taken, "FileDialog::save_file")
491
        })
492
    }
493

            
494
    /// Canned bytes for `path`, if a scenario registered them. `None` means
495
    /// "read the real file" - reads never count as unmocked.
496
    #[must_use]
497
4
    pub fn take_file_read(path: &str) -> Option<Vec<u8>> {
498
4
        with(|s| {
499
4
            if !armed_in(s) {
500
4
                return None;
501
            }
502
            s.file_reads.get(path).cloned()
503
4
        })
504
4
    }
505

            
506
    #[must_use]
507
16
    pub fn take_http(url: &str) -> Answer<MockHttp> {
508
16
        with(|s| {
509
16
            if !armed_in(s) {
510
16
                return Answer::NotArmed;
511
            }
512
            let found = s.http.iter().find(|(pattern, _)| {
513
                pattern == "*"
514
                    || pattern == url
515
                    || pattern
516
                        .strip_suffix('*')
517
                        .is_some_and(|prefix| url.starts_with(prefix))
518
            });
519
            let taken = found.map(|(_, canned)| canned.clone());
520
            answer(s, taken, &alloc::format!("http {url}"))
521
16
        })
522
16
    }
523

            
524
    #[must_use]
525
    pub fn take_audio_devices() -> Answer<(Vec<AzString>, Vec<AzString>)> {
526
        with(|s| {
527
            if !armed_in(s) {
528
                return Answer::NotArmed;
529
            }
530
            let taken = s.audio_devices.clone();
531
            answer(s, taken, "AudioDeviceList::enumerate")
532
        })
533
    }
534

            
535
    /// `true` when an armed store asked for `decode_mp4_h264` to resume with
536
    /// `video: None`.
537
    #[must_use]
538
    pub fn video_decode_mocked() -> bool {
539
        with(|s| armed_in(s) && s.video_decode_none)
540
    }
541

            
542
    /// Records an export while armed; `None` when not armed (show the real
543
    /// dialog), `Some(accepted)` otherwise.
544
    #[must_use]
545
    pub fn record_saved_file(name: &AzString, mime: &AzString, bytes: &[u8]) -> Option<bool> {
546
        with(|s| {
547
            if !armed_in(s) {
548
                return None;
549
            }
550
            s.saved_files.push(SavedFile {
551
                name: name.clone(),
552
                mime: mime.clone(),
553
                bytes: bytes.to_vec(),
554
            });
555
            Some(s.save_bytes_accept.unwrap_or(true))
556
        })
557
    }
558

            
559
    // ---- records (the assertions) --------------------------------------------
560

            
561
    /// Every export recorded since the last [`reset`].
562
    #[must_use]
563
    pub fn saved_files() -> Vec<SavedFile> {
564
        with(|s| s.saved_files.clone())
565
    }
566

            
567
    /// Every request that ran without an answer since the last [`reset`].
568
    #[must_use]
569
    pub fn unmocked_requests() -> Vec<String> {
570
        with(|s| s.unmocked.clone())
571
    }
572
}
573

            
574
#[cfg(all(test, feature = "std"))]
575
mod tests {
576
    use core::sync::atomic::{AtomicUsize, Ordering};
577

            
578
    use azul_core::callbacks::Update;
579

            
580
    use super::*;
581
    use crate::callbacks::CallbackInfo;
582

            
583
    extern "C" fn noop(_: RefAny, _: CallbackInfo, _: RefAny) -> Update {
584
        Update::DoNothing
585
    }
586

            
587
    #[test]
588
1
    fn ids_are_unique_and_valid() {
589
1
        let a = RequestId::unique();
590
1
        let b = RequestId::unique();
591
1
        assert!(a.is_valid() && b.is_valid());
592
1
        assert_ne!(a, b);
593
1
        assert!(!RequestId::invalid().is_valid());
594
1
    }
595

            
596
    #[test]
597
1
    fn complete_is_delivered_fifo_and_defer_waits_for_its_poll() {
598
        // Other tests share the process-wide queue; drain whatever they left.
599
1
        let _ = take_completed();
600

            
601
1
        let cb = ResumeCallback::create(noop);
602
1
        let first = complete(RefAny::new(1u8), cb.clone(), 10u32);
603
1
        let second = complete(RefAny::new(2u8), cb.clone(), 20u32);
604

            
605
        static POLLS: AtomicUsize = AtomicUsize::new(0);
606
1
        let deferred = defer(
607
1
            RefAny::new(3u8),
608
1
            cb,
609
2
            Box::new(|| {
610
2
                if POLLS.fetch_add(1, Ordering::SeqCst) == 0 {
611
1
                    None
612
                } else {
613
1
                    Some(RefAny::new(30u32))
614
                }
615
2
            }),
616
        );
617
1
        assert!(has_work());
618
1
        assert_eq!(pending_count(), 1);
619

            
620
1
        let batch = take_completed();
621
1
        let ids: Vec<RequestId> = batch.iter().map(|c| c.request_id).collect();
622
1
        assert_eq!(ids, vec![first, second]);
623
1
        assert_eq!(pending_count(), 1, "poll answered None on the first pump");
624

            
625
1
        let batch = take_completed();
626
1
        assert_eq!(batch.len(), 1);
627
1
        assert_eq!(batch[0].request_id, deferred);
628
1
        let mut result = batch.into_iter().next().unwrap().result;
629
1
        assert_eq!(result.downcast_ref::<u32>().map(|r| *r), Some(30));
630
1
        assert_eq!(pending_count(), 0);
631
1
        assert!(!has_work());
632
1
    }
633
}