1
//! Executor for running tests with mocked environment
2
//!
3
//! See [`MockExecutor`]
4

            
5
use std::any::Any;
6
use std::cell::Cell;
7
use std::collections::VecDeque;
8
use std::fmt::{self, Debug, Display};
9
use std::future::Future;
10
use std::io::{self, Write as _};
11
use std::iter;
12
use std::mem;
13
use std::panic::{catch_unwind, panic_any, AssertUnwindSafe};
14
use std::pin::Pin;
15
use std::sync::{Arc, Mutex, MutexGuard, Weak};
16
use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
17

            
18
use futures::future::Map;
19
use futures::pin_mut;
20
use futures::task::{FutureObj, Spawn, SpawnError};
21
use futures::FutureExt as _;
22

            
23
use assert_matches::assert_matches;
24
use educe::Educe;
25
use itertools::Either;
26
use itertools::{chain, izip};
27
use slotmap_careful::DenseSlotMap;
28
use std::backtrace::Backtrace;
29
use strum::EnumIter;
30

            
31
// NB: when using traced_test, the trace! and error! output here is generally suppressed
32
// in tests of other crates.  To see it, you can write something like this
33
// (in the dev-dependencies of the crate whose tests you're running):
34
//    tracing-test = { version = "0.2.4", features = ["no-env-filter"] }
35
use tracing::{error, trace};
36

            
37
use oneshot_fused_workaround::{self as oneshot, Canceled, Receiver};
38
use tor_error::error_report;
39
use tor_rtcompat::{Blocking, ToplevelBlockOn};
40

            
41
use Poll::*;
42
use TaskState::*;
43

            
44
/// Type-erased future, one for each of our (normal) tasks
45
type TaskFuture = FutureObj<'static, ()>;
46

            
47
/// Future for the argument to `block_on`, which is handled specially
48
type MainFuture<'m> = Pin<&'m mut dyn Future<Output = ()>>;
49

            
50
//---------- principal data structures ----------
51

            
52
/// Executor for running tests with mocked environment
53
///
54
/// For test cases which don't actually wait for anything in the real world.
55
///
56
/// This is the executor.
57
/// It implements [`Spawn`] and [`ToplevelBlockOn`]
58
///
59
/// It will usually be used as part of a `MockRuntime`.
60
///
61
/// To run futures, call [`ToplevelBlockOn::block_on`]
62
///
63
/// # Restricted environment
64
///
65
/// Tests run with this executor must not attempt to block
66
/// on anything "outside":
67
/// every future that anything awaits must (eventually) be woken directly
68
/// *by some other task* in the same test case.
69
///
70
/// (By directly we mean that the [`Waker::wake`] call is made
71
/// by that waking future, before that future itself awaits anything.)
72
///
73
/// # Panics
74
///
75
/// The executor will panic
76
/// if the toplevel future (passed to `block_on`)
77
/// doesn't complete (without externally blocking),
78
/// but instead waits for something.
79
///
80
/// The executor will malfunction or panic if reentered.
81
/// (Eg, if `block_on` is reentered.)
82
#[derive(Clone, Default, Educe)]
83
#[educe(Debug)]
84
pub struct MockExecutor {
85
    /// Mutable state
86
    #[educe(Debug(ignore))]
87
    shared: Arc<Shared>,
88
}
89

            
90
/// Shared state and ancillary information
91
///
92
/// This is always within an `Arc`.
93
#[derive(Default)]
94
struct Shared {
95
    /// Shared state
96
    data: Mutex<Data>,
97
    /// Condition variable for thread scheduling
98
    ///
99
    /// Signaled when [`Data.thread_to_run`](struct.Data.html#structfield.thread_to_run)
100
    /// is modified.
101
    thread_condvar: std::sync::Condvar,
102
}
103

            
104
/// Task id, module to hide `Ti` alias
105
mod task_id {
106
    slotmap_careful::new_key_type! {
107
        /// Task ID, usually called `TaskId`
108
        ///
109
        /// Short name in special `task_id` module so that [`Debug`] is nice
110
        pub(super) struct Ti;
111
    }
112
}
113
use task_id::Ti as TaskId;
114

            
115
/// Executor's state
116
///
117
/// ### Task state machine
118
///
119
/// A task is created in `tasks`, `Awake`, so also in `awake`.
120
///
121
/// When we poll it, we take it out of `awake` and set it to `Asleep`,
122
/// and then call `poll()`.
123
/// Any time after that, it can be made `Awake` again (and put back onto `awake`)
124
/// by the waker ([`ActualWaker`], wrapped in [`Waker`]).
125
///
126
/// The task's future is of course also present here in this data structure.
127
/// However, during poll we must release the lock,
128
/// so we cannot borrow the future from `Data`.
129
/// Instead, we move it out.  So `Task.fut` is an `Option`.
130
///
131
/// ### "Main" task - the argument to `block_on`
132
///
133
/// The signature of `BlockOn::block_on` accepts a non-`'static` future
134
/// (and a non-`Send`/`Sync` one).
135
///
136
/// So we cannot store that future in `Data` because `Data` is `'static`.
137
/// Instead, this main task future is passed as an argument down the call stack.
138
/// In the data structure we simply store a placeholder, `TaskFutureInfo::Main`.
139
50918
#[derive(Educe, derive_more::Debug)]
140
#[educe(Default)]
141
struct Data {
142
    /// Tasks
143
    ///
144
    /// Includes tasks spawned with `spawn`,
145
    /// and also the future passed to `block_on`.
146
2
    #[debug("{:?}", DebugTasks(self, || tasks.keys()))]
147
    tasks: DenseSlotMap<TaskId, Task>,
148

            
149
    /// `awake` lists precisely: tasks that are `Awake`, plus maybe stale `TaskId`s
150
    ///
151
    /// Tasks are pushed onto the *back* when woken,
152
    /// so back is the most recently woken.
153
2
    #[debug("{:?}", DebugTasks(self, || awake.iter().cloned()))]
154
    awake: VecDeque<TaskId>,
155

            
156
    /// If a future from `progress_until_stalled` exists
157
    progressing_until_stalled: Option<ProgressingUntilStalled>,
158

            
159
    /// Scheduling policy
160
    scheduling: SchedulingPolicy,
161

            
162
    /// (Sub)thread we want to run now
163
    ///
164
    /// At any one time only one thread is meant to be running.
165
    /// Other threads are blocked in condvar wait, waiting for this to change.
166
    ///
167
    /// **Modified only** within
168
    /// [`thread_context_switch_send_instruction_to_run`](Shared::thread_context_switch_send_instruction_to_run),
169
    /// which takes responsibility for preserving the following **invariants**:
170
    ///
171
    ///  1. no-one but the named thread is allowed to modify this field.
172
    ///  2. after modifying this field, signal `thread_condvar`
173
    #[educe(Default(expression = "ThreadDescriptor::Executor"))]
174
    thread_to_run: ThreadDescriptor,
175
}
176

            
177
/// How we should schedule?
178
15690
#[derive(Debug, Clone, Default, EnumIter)]
179
#[non_exhaustive]
180
pub enum SchedulingPolicy {
181
    /// Task *most* recently woken is run
182
    ///
183
    /// This is the default.
184
    ///
185
    /// It will expose starvation bugs if a task never sleeps.
186
    /// (Which is a good thing in tests.)
187
    #[default]
188
    Stack,
189
    /// Task *least* recently woken is run.
190
    Queue,
191
}
192

            
193
/// Record of a single task
194
///
195
/// Tracks a spawned task, or the main task (the argument to `block_on`).
196
///
197
/// Stored in [`Data`]`.tasks`.
198
struct Task {
199
    /// For debugging output
200
    desc: String,
201
    /// Has this been woken via a waker?  (And is it in `Data.awake`?)
202
    ///
203
    /// **Set to `Awake` only by [`Task::set_awake`]**,
204
    /// preserving the invariant that
205
    /// every `Awake` task is in [`Data.awake`](struct.Data.html#structfield.awake).
206
    state: TaskState,
207
    /// The actual future (or a placeholder for it)
208
    ///
209
    /// May be `None` because we've temporarily moved it out so we can poll it,
210
    /// or if this is a Subthread task which is currently running sync code
211
    /// (in which case we're blocked in the executor waiting to be
212
    /// woken up by [`thread_context_switch`](Shared::thread_context_switch).
213
    fut: Option<TaskFutureInfo>,
214
    /// Is this task actually a [`Subthread`](MockExecutor::subthread_spawn)?
215
    ///
216
    /// Subthread tasks do not end when `fut` is `Ready` -
217
    /// instead, `fut` is `Some` when the thread is within `subthread_block_on_future`.
218
    /// The rest of the time this is `None`, but we don't run the executor,
219
    /// because `Data.thread_to_run` is `ThreadDescriptor::Task(this_task)`.
220
    is_subthread: Option<IsSubthread>,
221
}
222

            
223
/// A future as stored in our record of a [`Task`]
224
enum TaskFutureInfo {
225
    /// The [`Future`].  All is normal.
226
    Normal(TaskFuture),
227
    /// The future isn't here because this task is the main future for `block_on`
228
    Main,
229
}
230

            
231
/// State of a task - do we think it needs to be polled?
232
///
233
/// Stored in [`Task`]`.state`.
234
#[derive(Debug)]
235
enum TaskState {
236
    /// Awake - needs to be polled
237
    ///
238
    /// Established by [`waker.wake()`](Waker::wake)
239
    Awake,
240
    /// Asleep - does *not* need to be polled
241
    ///
242
    /// Established each time just before we call the future's [`poll`](Future::poll)
243
    Asleep(Vec<SleepLocation>),
244
}
245

            
246
/// Actual implementor of `Wake` for use in a `Waker`
247
///
248
/// Futures (eg, channels from [`futures`]) will use this to wake a task
249
/// when it should be polled.
250
///
251
/// This type must not be `Cloned` with the `Data` lock held.
252
/// Consequently, a `Waker` mustn't either.
253
struct ActualWaker {
254
    /// Executor state
255
    ///
256
    /// The Waker mustn't to hold a strong reference to the executor,
257
    /// since typically a task holds a future that holds a Waker,
258
    /// and the executor holds the task - so that would be a cycle.
259
    data: Weak<Shared>,
260

            
261
    /// Which task this is
262
    id: TaskId,
263
}
264

            
265
/// State used for an in-progress call to
266
/// [`progress_until_stalled`][`MockExecutor::progress_until_stalled`]
267
///
268
/// If present in [`Data`], an (async) call to `progress_until_stalled`
269
/// is in progress.
270
///
271
/// The future from `progress_until_stalled`, [`ProgressUntilStalledFuture`]
272
/// is a normal-ish future.
273
/// It can be polled in the normal way.
274
/// When it is polled, it looks here, in `finished`, to see if it's `Ready`.
275
///
276
/// The future is made ready, and woken (via `waker`),
277
/// by bespoke code in the task executor loop.
278
///
279
/// When `ProgressUntilStalledFuture` (maybe completes and) is dropped,
280
/// its `Drop` impl is used to remove this from `Data.progressing_until_stalled`.
281
#[derive(Debug)]
282
struct ProgressingUntilStalled {
283
    /// Have we, in fact, stalled?
284
    ///
285
    /// Made `Ready` by special code in the executor loop
286
    finished: Poll<()>,
287

            
288
    /// Waker
289
    ///
290
    /// Signalled by special code in the executor loop
291
    waker: Option<Waker>,
292
}
293

            
294
/// Future from
295
/// [`progress_until_stalled`][`MockExecutor::progress_until_stalled`]
296
///
297
/// See [`ProgressingUntilStalled`] for an overview of this aspect of the contraption.
298
///
299
/// Existence of this struct implies `Data.progressing_until_stalled` is `Some`.
300
/// There can only be one at a time.
301
#[derive(Educe)]
302
#[educe(Debug)]
303
struct ProgressUntilStalledFuture {
304
    /// Executor's state; this future's state is in `.progressing_until_stalled`
305
    #[educe(Debug(ignore))]
306
    shared: Arc<Shared>,
307
}
308

            
309
/// Identifies a thread we know about - the executor thread, or a Subthread
310
///
311
/// Not related to `std::thread::ThreadId`.
312
///
313
/// See [`spawn_subthread`](MockExecutor::subthread_spawn) for definition of a Subthread.
314
///
315
/// This being a thread-local and not scoped by which `MockExecutor` we're talking about
316
/// means that we can't cope if there are multiple `MockExecutor`s involved in the same thread.
317
/// That's OK (and documented).
318
#[derive(Copy, Clone, Eq, PartialEq, derive_more::Debug)]
319
enum ThreadDescriptor {
320
    /// Foreign - neither the (running) executor, nor a Subthread
321
    #[debug("FOREIGN")]
322
    Foreign,
323
    /// The executor.
324
    #[debug("Exe")]
325
    Executor,
326
    /// This task, which is a Subthread.
327
    #[debug("{_0:?}")]
328
    Subthread(TaskId),
329
}
330

            
331
/// Marker indicating that this task is a Subthread, not an async task.
332
///
333
/// See [`spawn_subthread`](MockExecutor::subthread_spawn) for definition of a Subthread.
334
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
335
struct IsSubthread;
336

            
337
thread_local! {
338
    /// Identifies this thread.
339
    pub static THREAD_DESCRIPTOR: Cell<ThreadDescriptor> = const {
340
        Cell::new(ThreadDescriptor::Foreign)
341
    };
342
}
343

            
344
//---------- creation ----------
345

            
346
impl MockExecutor {
347
    /// Make a `MockExecutor` with default parameters
348
4
    pub fn new() -> Self {
349
4
        Self::default()
350
4
    }
351

            
352
    /// Make a `MockExecutor` with a specific `SchedulingPolicy`
353
6414
    pub fn with_scheduling(scheduling: SchedulingPolicy) -> Self {
354
6414
        Data {
355
6414
            scheduling,
356
6414
            ..Default::default()
357
6414
        }
358
6414
        .into()
359
6414
    }
360
}
361

            
362
impl From<Data> for MockExecutor {
363
6414
    fn from(data: Data) -> MockExecutor {
364
6414
        let shared = Shared {
365
6414
            data: Mutex::new(data),
366
6414
            thread_condvar: std::sync::Condvar::new(),
367
6414
        };
368
6414
        MockExecutor {
369
6414
            shared: Arc::new(shared),
370
6414
        }
371
6414
    }
372
}
373

            
374
//---------- spawning ----------
375

            
376
impl MockExecutor {
377
    /// Spawn a task and return something to identify it
378
    ///
379
    /// `desc` should `Display` as some kind of short string (ideally without spaces)
380
    /// and will be used in the `Debug` impl and trace log messages from `MockExecutor`.
381
    ///
382
    /// The returned value is an opaque task identifier which is very cheap to clone
383
    /// and which can be used by the caller in debug logging,
384
    /// if it's desired to correlate with the debug output from `MockExecutor`.
385
    /// Most callers will want to ignore it.
386
    ///
387
    /// This method is infallible.  (The `MockExecutor` cannot be shut down.)
388
186
    pub fn spawn_identified(
389
186
        &self,
390
186
        desc: impl Display,
391
186
        fut: impl Future<Output = ()> + Send + 'static,
392
186
    ) -> impl Debug + Clone + Send + 'static {
393
186
        self.spawn_internal(desc.to_string(), FutureObj::from(Box::new(fut)))
394
186
    }
395

            
396
    /// Spawn a task and return its output for further usage
397
    ///
398
    /// `desc` should `Display` as some kind of short string (ideally without spaces)
399
    /// and will be used in the `Debug` impl and trace log messages from `MockExecutor`.
400
16
    pub fn spawn_join<T: Debug + Send + 'static>(
401
16
        &self,
402
16
        desc: impl Display,
403
16
        fut: impl Future<Output = T> + Send + 'static,
404
16
    ) -> impl Future<Output = T> {
405
16
        let (tx, rx) = oneshot::channel();
406
16
        self.spawn_identified(desc, async move {
407
16
            let res = fut.await;
408
16
            tx.send(res)
409
16
                .expect("Failed to send future's output, did future panic?");
410
16
        });
411
16
        rx.map(|m| m.expect("Failed to receive future's output"))
412
16
    }
413

            
414
    /// Spawn a task and return its `TaskId`
415
    ///
416
    /// Convenience method for use by `spawn_identified` and `spawn_obj`.
417
    /// The future passed to `block_on` is not handled here.
418
61248
    fn spawn_internal(&self, desc: String, fut: TaskFuture) -> TaskId {
419
61248
        let mut data = self.shared.lock();
420
61248
        data.insert_task(desc, TaskFutureInfo::Normal(fut), None)
421
61248
    }
422
}
423

            
424
impl Data {
425
    /// Insert a task given its `TaskFutureInfo` and return its `TaskId`.
426
68182
    fn insert_task(
427
68182
        &mut self,
428
68182
        desc: String,
429
68182
        fut: TaskFutureInfo,
430
68182
        is_subthread: Option<IsSubthread>,
431
68182
    ) -> TaskId {
432
68182
        let state = Awake;
433
68182
        let id = self.tasks.insert(Task {
434
68182
            state,
435
68182
            desc,
436
68182
            fut: Some(fut),
437
68182
            is_subthread,
438
68182
        });
439
68182
        self.awake.push_back(id);
440
68182
        trace!("MockExecutor spawned {:?}={:?}", id, self.tasks[id]);
441
68182
        id
442
68182
    }
443
}
444

            
445
impl Spawn for MockExecutor {
446
58466
    fn spawn_obj(&self, future: TaskFuture) -> Result<(), SpawnError> {
447
58466
        self.spawn_internal("spawn_obj".into(), future);
448
58466
        Ok(())
449
58466
    }
450
}
451

            
452
impl MockExecutor {
453
    /// Implementation of `spawn_blocking` and `blocking_io`
454
4
    fn spawn_thread_inner<F, T>(&self, f: F) -> <Self as Blocking>::ThreadHandle<T>
455
4
    where
456
4
        F: FnOnce() -> T + Send + 'static,
457
4
        T: Send + 'static,
458
4
    {
459
4
        // For the mock executor, everything runs on the same thread.
460
4
        // If we need something more complex in the future, we can change this.
461
4
        let (tx, rx) = oneshot::channel();
462
4
        self.spawn_identified("Blocking".to_string(), async move {
463
4
            match tx.send(f()) {
464
4
                Ok(()) => (),
465
                Err(_) => panic!("Failed to send future's output, did future panic?"),
466
            }
467
4
        });
468
4
        rx.map(Box::new(|m| m.expect("Failed to receive future's output")))
469
4
    }
470
}
471

            
472
impl Blocking for MockExecutor {
473
    type ThreadHandle<T: Send + 'static> =
474
        Map<Receiver<T>, Box<dyn FnOnce(Result<T, Canceled>) -> T>>;
475

            
476
4
    fn spawn_blocking<F, T>(&self, f: F) -> Self::ThreadHandle<T>
477
4
    where
478
4
        F: FnOnce() -> T + Send + 'static,
479
4
        T: Send + 'static,
480
4
    {
481
        assert_matches!(
482
4
            THREAD_DESCRIPTOR.get(),
483
            ThreadDescriptor::Executor | ThreadDescriptor::Subthread(_),
484
 "MockExecutor::spawn_blocking_io only allowed from future or subthread, being run by this executor"
485
        );
486
4
        self.spawn_thread_inner(f)
487
4
    }
488

            
489
    fn reenter_block_on<F>(&self, future: F) -> F::Output
490
    where
491
        F: Future + Send + 'static,
492
        F::Output: Send + 'static,
493
    {
494
        self.subthread_block_on_future(future)
495
    }
496

            
497
    fn blocking_io<F, T>(&self, f: F) -> impl Future<Output = T>
498
    where
499
        F: FnOnce() -> T + Send + 'static,
500
        T: Send + 'static,
501
    {
502
        assert_eq!(
503
            THREAD_DESCRIPTOR.get(),
504
            ThreadDescriptor::Executor,
505
            "MockExecutor::blocking_io only allowed from future being polled by this executor"
506
        );
507
        self.spawn_thread_inner(f)
508
    }
509
}
510

            
511
//---------- block_on ----------
512

            
513
impl ToplevelBlockOn for MockExecutor {
514
330
    fn block_on<F>(&self, input_fut: F) -> F::Output
515
330
    where
516
330
        F: Future,
517
330
    {
518
330
        let mut value: Option<F::Output> = None;
519
330

            
520
330
        // Box this just so that we can conveniently control precisely when it's dropped.
521
330
        // (We could do this with Option and Pin::set but that seems clumsier.)
522
330
        let mut input_fut = Box::pin(input_fut);
523
330

            
524
330
        let run_store_fut = {
525
330
            let value = &mut value;
526
330
            let input_fut = &mut input_fut;
527
330
            async {
528
330
                trace!("MockExecutor block_on future...");
529
330
                let t = input_fut.await;
530
330
                trace!("MockExecutor block_on future returned...");
531
330
                *value = Some(t);
532
330
                trace!("MockExecutor block_on future exiting.");
533
330
            }
534
        };
535

            
536
        {
537
330
            pin_mut!(run_store_fut);
538
330

            
539
330
            let main_id = self
540
330
                .shared
541
330
                .lock()
542
330
                .insert_task("main".into(), TaskFutureInfo::Main, None);
543
330
            trace!("MockExecutor {main_id:?} is task for block_on");
544
330
            self.execute_to_completion(run_store_fut);
545
330
        }
546
330

            
547
330
        #[allow(clippy::let_and_return)] // clarity
548
330
        let value = value.take().unwrap_or_else(|| {
549
            // eprintln can be captured by libtest, but the debug_dump goes to io::stderr.
550
            // use the latter, so that the debug dump is prefixed by this message.
551
            let _: io::Result<()> = writeln!(io::stderr(), "all futures blocked, crashing...");
552
            // write to tracing too, so the tracing log is clear about when we crashed
553
            error!("all futures blocked, crashing...");
554

            
555
            // Sequencing here is subtle.
556
            //
557
            // We should do the dump before dropping the input future, because the input
558
            // future is likely to own things that, when dropped, wake up other tasks,
559
            // rendering the dump inaccurate.
560
            //
561
            // But also, dropping the input future may well drop a ProgressUntilStalledFuture
562
            // which then reenters us.  More generally, we mustn't call user code
563
            // with the lock held.
564
            //
565
            // And, we mustn't panic with the data lock held.
566
            //
567
            // If value was Some, then this closure is dropped without being called,
568
            // which drops the future after it has yielded the value, which is correct.
569
            {
570
                let mut data = self.shared.lock();
571
                data.debug_dump();
572
            }
573
            drop(input_fut);
574

            
575
            panic!(
576
                r"
577
all futures blocked. waiting for the real world? or deadlocked (waiting for each other) ?
578
"
579
            );
580
330
        });
581
330

            
582
330
        value
583
330
    }
584
}
585

            
586
//---------- execution - core implementation ----------
587

            
588
impl MockExecutor {
589
    /// Keep polling tasks until nothing more can be done
590
    ///
591
    /// Ie, stop when `awake` is empty and `progressing_until_stalled` is `None`.
592
6930
    fn execute_to_completion(&self, mut main_fut: MainFuture) {
593
6930
        trace!("MockExecutor execute_to_completion...");
594
        loop {
595
952382
            self.execute_until_first_stall(main_fut.as_mut());
596

            
597
            // Handle `progressing_until_stalled`
598
945452
            let pus_waker = {
599
952382
                let mut data = self.shared.lock();
600
952382
                let pus = &mut data.progressing_until_stalled;
601
952382
                trace!("MockExecutor execute_to_completion PUS={:?}", &pus);
602
952382
                let Some(pus) = pus else {
603
                    // No progressing_until_stalled, we're actually done.
604
6930
                    break;
605
                };
606
945452
                assert_eq!(
607
                    pus.finished, Pending,
608
                    "ProgressingUntilStalled finished twice?!"
609
                );
610
945452
                pus.finished = Ready(());
611
945452

            
612
945452
                // Release the lock temporarily so that ActualWaker::clone doesn't deadlock
613
945452
                let waker = pus
614
945452
                    .waker
615
945452
                    .take()
616
945452
                    .expect("ProgressUntilStalledFuture not ever polled!");
617
945452
                drop(data);
618
945452
                let waker_copy = waker.clone();
619
945452
                let mut data = self.shared.lock();
620
945452

            
621
945452
                let pus = &mut data.progressing_until_stalled;
622
945452
                if let Some(double) = mem::replace(
623
945452
                    &mut pus
624
945452
                        .as_mut()
625
945452
                        .expect("progressing_until_stalled updated under our feet!")
626
945452
                        .waker,
627
945452
                    Some(waker),
628
945452
                ) {
629
                    panic!("double progressing_until_stalled.waker! {double:?}");
630
945452
                }
631
945452

            
632
945452
                waker_copy
633
945452
            };
634
945452
            pus_waker.wake();
635
        }
636
6930
        trace!("MockExecutor execute_to_completion done");
637
6930
    }
638

            
639
    /// Keep polling tasks until `awake` is empty
640
    ///
641
    /// (Ignores `progressing_until_stalled` - so if one is active,
642
    /// will return when all other tasks have blocked.)
643
    ///
644
    /// # Panics
645
    ///
646
    /// Might malfunction or panic if called reentrantly
647
952382
    fn execute_until_first_stall(&self, main_fut: MainFuture) {
648
952382
        trace!("MockExecutor execute_until_first_stall ...");
649

            
650
952382
        assert_eq!(
651
952382
            THREAD_DESCRIPTOR.get(),
652
            ThreadDescriptor::Foreign,
653
            "MockExecutor executor re-entered"
654
        );
655
952382
        THREAD_DESCRIPTOR.set(ThreadDescriptor::Executor);
656
952382

            
657
973151
        let r = catch_unwind(AssertUnwindSafe(|| self.executor_main_loop(main_fut)));
658
952382

            
659
952382
        THREAD_DESCRIPTOR.set(ThreadDescriptor::Foreign);
660
952382

            
661
952382
        match r {
662
952382
            Ok(()) => trace!("MockExecutor execute_until_first_stall done."),
663
            Err(e) => {
664
                trace!("MockExecutor executor, or async task, panicked!");
665
                panic_any(e)
666
            }
667
        }
668
952382
    }
669

            
670
    /// Keep polling tasks until `awake` is empty (inner, executor main loop)
671
    ///
672
    /// This is only called from [`MockExecutor::execute_until_first_stall`],
673
    /// so it could also be called `execute_until_first_stall_inner`.
674
    #[allow(clippy::cognitive_complexity)]
675
952382
    fn executor_main_loop(&self, mut main_fut: MainFuture) {
676
        'outer: loop {
677
            // Take a `Awake` task off `awake` and make it `Asleep`
678
1250574
            let (id, mut fut) = 'inner: loop {
679
2203924
                let mut data = self.shared.lock();
680
2203924
                let Some(id) = data.schedule() else {
681
952382
                    break 'outer;
682
                };
683
1251542
                let Some(task) = data.tasks.get_mut(id) else {
684
968
                    trace!("MockExecutor {id:?} vanished");
685
968
                    continue;
686
                };
687
1250574
                task.state = Asleep(vec![]);
688
1250574
                let fut = task.fut.take().expect("future missing from task!");
689
1250574
                break 'inner (id, fut);
690
1250574
            };
691
1250574

            
692
1250574
            // Poll the selected task
693
1250574
            let waker = ActualWaker {
694
1250574
                data: Arc::downgrade(&self.shared),
695
1250574
                id,
696
1250574
            }
697
1250574
            .new_waker();
698
1250574
            trace!("MockExecutor {id:?} polling...");
699
1250574
            let mut cx = Context::from_waker(&waker);
700
1250574
            let r = match &mut fut {
701
77096
                TaskFutureInfo::Normal(fut) => fut.poll_unpin(&mut cx),
702
1173478
                TaskFutureInfo::Main => main_fut.as_mut().poll(&mut cx),
703
            };
704

            
705
            // Deal with the returned `Poll`
706
            let _fut_drop_late;
707
            {
708
1250574
                let mut data = self.shared.lock();
709
1250574
                let task = data
710
1250574
                    .tasks
711
1250574
                    .get_mut(id)
712
1250574
                    .expect("task vanished while we were polling it");
713
1250574

            
714
1250574
                match (r, task.is_subthread) {
715
                    (Pending, _) => {
716
1216340
                        trace!("MockExecutor {id:?} -> Pending");
717
1216340
                        if task.fut.is_some() {
718
                            panic!("task reinserted while we polled it?!");
719
1216340
                        }
720
1216340
                        // The task might have been woken *by its own poll method*.
721
1216340
                        // That's why we set it to `Asleep` *earlier* rather than here.
722
1216340
                        // All we need to do is put the future back.
723
1216340
                        task.fut = Some(fut);
724
                    }
725
                    (Ready(()), None) => {
726
34226
                        trace!("MockExecutor {id:?} -> Ready");
727
                        // Oh, it finished!
728
                        // It might be in `awake`, but that's allowed to contain stale tasks,
729
                        // so we *don't* need to scan that list and remove it.
730
34226
                        data.tasks.remove(id);
731
34226
                        // It is important that we don't drop `fut` until we have released
732
34226
                        // the data lock, since it is an external type and might try to reenter
733
34226
                        // us (eg by calling spawn).  If we do that here, we risk deadlock.
734
34226
                        // So, move `fut` to a variable with scope outside the block with `data`.
735
34226
                        _fut_drop_late = fut;
736
                    }
737
                    (Ready(()), Some(IsSubthread)) => {
738
8
                        trace!("MockExecutor {id:?} -> Ready, waking Subthread");
739
                        // Task was blocking on the future given to .subthread_block_on_future().
740
                        // That future has completed and stored its result where the Subthread
741
                        // can see it.  Now we need to wake up that thread, and let it run
742
                        // until it blocks again.
743
                        //
744
                        // We leave `.fut` as `None`.
745
                        // subthread_block_on_future is responsible for filling it in again.
746

            
747
8
                        self.shared.thread_context_switch(
748
8
                            data,
749
8
                            ThreadDescriptor::Executor,
750
8
                            ThreadDescriptor::Subthread(id),
751
8
                        );
752
8

            
753
8
                        // Now, if the Subthread still exists, that's because it's waiting
754
8
                        // in subthread_block_on_future again, in which case `fut` is `Some`.
755
8
                        // Or it might have ended, in which case it's not in `tasks` any more.
756
8
                        // We can go back to scheduling futures.
757
8

            
758
8
                        // `fut` contains the future passed to `subthread_block_on_future`,
759
8
                        // ie it owns an external type.  See above.
760
8
                        _fut_drop_late = fut;
761
                    }
762
                }
763
            }
764
        }
765
952382
    }
766
}
767

            
768
impl Data {
769
    /// Return the next task to run
770
    ///
771
    /// The task is removed from `awake`, but **`state` is not set to `Asleep`**.
772
    /// The caller must restore the invariant!
773
2203924
    fn schedule(&mut self) -> Option<TaskId> {
774
        use SchedulingPolicy as SP;
775
2203924
        match self.scheduling {
776
1108722
            SP::Stack => self.awake.pop_back(),
777
1095202
            SP::Queue => self.awake.pop_front(),
778
        }
779
2203924
    }
780
}
781

            
782
impl ActualWaker {
783
    /// Obtain a strong reference to the executor's data
784
5476674
    fn upgrade_data(&self) -> Option<Arc<Shared>> {
785
5476674
        self.data.upgrade()
786
5476674
    }
787

            
788
    /// Wake the task corresponding to this `ActualWaker`
789
    ///
790
    /// This is like `<Self as std::task::Wake>::wake()` but takes `&self`, not `Arc`
791
1650904
    fn wake(&self) {
792
1650904
        let Some(data) = self.upgrade_data() else {
793
            // The executor is gone!  Don't try to wake.
794
4
            return;
795
        };
796
1650900
        let mut data = data.lock();
797
1650900
        let data = &mut *data;
798
1650900
        trace!("MockExecutor {:?} wake", &self.id);
799
1650900
        let Some(task) = data.tasks.get_mut(self.id) else {
800
2484
            return;
801
        };
802
1648416
        task.set_awake(self.id, &mut data.awake);
803
1650904
    }
804
}
805

            
806
//---------- "progress until stalled" functionality ----------
807

            
808
impl MockExecutor {
809
    /// Run tasks in the current executor until every other task is waiting
810
    ///
811
    /// # Panics
812
    ///
813
    /// Might malfunction or panic if more than one such call is running at once.
814
    ///
815
    /// (Ie, you must `.await` or drop the returned `Future`
816
    /// before calling this method again.)
817
    ///
818
    /// Must be called and awaited within a future being run by `self`.
819
945452
    pub fn progress_until_stalled(&self) -> impl Future<Output = ()> {
820
945452
        let mut data = self.shared.lock();
821
945452
        assert!(
822
945452
            data.progressing_until_stalled.is_none(),
823
            "progress_until_stalled called more than once"
824
        );
825
945452
        trace!("MockExecutor progress_until_stalled...");
826
945452
        data.progressing_until_stalled = Some(ProgressingUntilStalled {
827
945452
            finished: Pending,
828
945452
            waker: None,
829
945452
        });
830
945452
        ProgressUntilStalledFuture {
831
945452
            shared: self.shared.clone(),
832
945452
        }
833
945452
    }
834
}
835

            
836
impl Future for ProgressUntilStalledFuture {
837
    type Output = ();
838

            
839
1890904
    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
840
1890904
        let waker = cx.waker().clone();
841
1890904
        let mut data = self.shared.lock();
842
1890904
        let pus = data.progressing_until_stalled.as_mut();
843
1890904
        trace!("MockExecutor progress_until_stalled polling... {:?}", &pus);
844
1890904
        let pus = pus.expect("ProgressingUntilStalled missing");
845
1890904
        pus.waker = Some(waker);
846
1890904
        pus.finished
847
1890904
    }
848
}
849

            
850
impl Drop for ProgressUntilStalledFuture {
851
945452
    fn drop(&mut self) {
852
945452
        self.shared.lock().progressing_until_stalled = None;
853
945452
    }
854
}
855

            
856
//---------- (sub)threads ----------
857

            
858
impl MockExecutor {
859
    /// Spawn a "Subthread", for processing in a sync context
860
    ///
861
    /// `call` will be run on a separate thread, called a "Subthread".
862
    ///
863
    /// But it will **not run simultaneously** with the executor,
864
    /// nor with other Subthreads.
865
    /// So Subthreads are somewhat like coroutines.
866
    ///
867
    /// `call` must be capable of making progress without waiting for any other Subthreads.
868
    /// `call` may wait for async futures, using
869
    /// [`subthread_block_on_future`](MockExecutor::subthread_block_on_future).
870
    ///
871
    /// Subthreads may be used for cpubound activity,
872
    /// or synchronous IO (such as large volumes of disk activity),
873
    /// provided that the synchronous code will reliably make progress,
874
    /// without waiting (directly or indirectly) for any async task or Subthread -
875
    /// except via `subthread_block_on_future`.
876
    ///
877
    /// # Subthreads vs raw `std::thread` threads
878
    ///
879
    /// Programs using `MockExecutor` may use `std::thread` threads directly.
880
    /// However, this is not recommended.  There are severe limitations:
881
    ///
882
    ///  * Only a Subthread can re-enter the async context from sync code:
883
    ///    this must be done with
884
    ///    using [`subthread_block_on_future`](MockExecutor::subthread_block_on_future).
885
    ///    (Re-entering the executor with
886
    ///    [`block_on`](tor_rtcompat::ToplevelBlockOn::block_on)
887
    ///    is not allowed.)
888
    ///  * If async tasks want to suspend waiting for synchronous code,
889
    ///    the synchronous code must run on a Subthread.
890
    ///    This allows the `MockExecutor` to know when
891
    ///    that synchronous code is still making progress.
892
    ///    (This is needed for
893
    ///    [`progress_until_stalled`](MockExecutor::progress_until_stalled)
894
    ///    and the facilities which use it, such as
895
    ///    [`MockRuntime::advance_until_stalled`](crate::MockRuntime::advance_until_stalled).)
896
    ///  * Subthreads never run in parallel -
897
    ///    they only run as scheduled deterministically by the `MockExecutor`.
898
    ///    So using Subthreads eliminates a source of test nonndeterminism.
899
    ///    (Execution order is still varied due to explicitly varying the scheduling policy.)
900
    ///
901
    /// # Panics, abuse, and malfunctions
902
    ///
903
    /// If `call` panics and unwinds, `spawn_subthread` yields `Err`.
904
    /// The application code should to do something about it if this happens,
905
    /// typically, logging errors, tearing things down, or failing a test case.
906
    ///
907
    /// If the executor doesn't run, the subthread will not run either, and will remain stuck.
908
    /// (So, typically, if the thread supposed to run the executor panics,
909
    /// for example because a future or the executor itself panics,
910
    /// all the subthreads will become stuck - effectively, they'll be leaked.)
911
    ///
912
    /// `spawn_subthread` panics if OS thread spawning fails.
913
    /// (Like `std::thread::spawn()` does.)
914
    ///
915
    /// `MockExecutor`s will malfunction or panic if
916
    /// any executor invocation method (eg `block_on`) is called on a Subthread.
917
4
    pub fn subthread_spawn<T: Send + 'static>(
918
4
        &self,
919
4
        desc: impl Display,
920
4
        call: impl FnOnce() -> T + Send + 'static,
921
4
    ) -> impl Future<Output = Result<T, Box<dyn Any + Send>>> + Unpin + Send + Sync + 'static {
922
4
        let desc = desc.to_string();
923
4
        let (output_tx, output_rx) = oneshot::channel();
924
4

            
925
4
        // NB: we don't know which thread we're on!
926
4
        // In principle we might be on another Subthread.
927
4
        // So we can't context switch here.  That would be very confusing.
928
4
        //
929
4
        // Instead, we prepare the new Subthread as follows:
930
4
        //   - There is a task in the executor
931
4
        //   - The task is ready to be polled, whenever the executor decides to
932
4
        //   - The thread starts running right away, but immediately waits until it is scheduled
933
4
        // See `subthread_entrypoint`.
934
4

            
935
4
        {
936
4
            let mut data = self.shared.lock();
937
4
            let fut = TaskFutureInfo::Normal(
938
4
                Box::new(
939
4
                    // When the executor decides that this new task is to be polled,
940
4
                    // its future (this future) returns Ready immediately,
941
4
                    // and the executor mainloop will context switch to the new thread.
942
4
                    futures::future::ready(()),
943
4
                )
944
4
                .into(),
945
4
            );
946
4
            let id = data.insert_task(desc.clone(), fut, Some(IsSubthread));
947
4

            
948
4
            let _: std::thread::JoinHandle<()> = std::thread::Builder::new()
949
4
                .name(desc)
950
4
                .spawn({
951
4
                    let shared = self.shared.clone();
952
4
                    move || shared.subthread_entrypoint(id, call, output_tx)
953
4
                })
954
4
                .expect("spawn failed");
955
4
        }
956
4

            
957
4
        output_rx.map(|r| {
958
4
            r.unwrap_or_else(|_: Canceled| panic!("Subthread cancelled but should be impossible!"))
959
4
        })
960
4
    }
961

            
962
    /// Call an async `Future` from a Subthread
963
    ///
964
    /// Blocks the Subthread, and arranges to run async tasks,
965
    /// including `fut`, until `fut` completes.
966
    ///
967
    /// `fut` is polled on the executor thread, not on the Subthread.
968
    /// (We may change that in the future, allowing passing a non-`Send` future.)
969
    ///
970
    /// # Panics, abuse, and malfunctions
971
    ///
972
    /// `subthread_block_on_future` will malfunction or panic
973
    /// if called on a thread that isn't a Subthread from the same `MockExecutor`
974
    /// (ie a thread made with [`spawn_subthread`](MockExecutor::subthread_spawn)).
975
    ///
976
    /// If `fut` itself panics, the executor will panic.
977
    ///
978
    /// If the executor isn't running, `subthread_block_on_future` will hang indefinitely.
979
    /// See `spawn_subthread`.
980
4
    pub fn subthread_block_on_future<T: Send + 'static>(
981
4
        &self,
982
4
        fut: impl Future<Output = T> + Send + 'static,
983
4
    ) -> T {
984
4
        let ret = Arc::new(Mutex::new(None));
985
4
        let fut = {
986
4
            let ret = ret.clone();
987
4
            async move {
988
4
                let t = fut.await;
989
4
                *ret.lock().expect("poison") = Some(t);
990
4
            }
991
        };
992
4
        let fut = TaskFutureInfo::Normal(Box::new(fut).into());
993

            
994
4
        let id = match THREAD_DESCRIPTOR.get() {
995
4
            ThreadDescriptor::Subthread(id) => id,
996
            ThreadDescriptor::Executor => {
997
                panic!("subthread_block_on_future called from MockExecutor thread (async task?)")
998
            }
999
            ThreadDescriptor::Foreign => panic!(
    "subthread_block_on_future called on foreign thread (not spawned with spawn_subthread)"
            ),
        };
4
        trace!("MockExecutor thread {id:?}, subthread_block_on_future...");
4
        {
4
            let mut data = self.shared.lock();
4
            let data_ = &mut *data;
4
            let task = data_.tasks.get_mut(id).expect("Subthread task vanished!");
4
            task.fut = Some(fut);
4
            task.set_awake(id, &mut data_.awake);
4

            
4
            self.shared.thread_context_switch(
4
                data,
4
                ThreadDescriptor::Subthread(id),
4
                ThreadDescriptor::Executor,
4
            );
4
        }
4

            
4
        let ret = ret.lock().expect("poison").take();
4
        ret.expect("fut completed but didn't store")
4
    }
}
impl Shared {
    /// Main entrypoint function for a Subthread
    ///
    /// Entered on a new `std::thread` thread created by
    /// [`subthread_spawn`](MockExecutor::subthread_spawn).
    ///
    /// When `call` completes, sends its returned value `T` to `output_tx`.
4
    fn subthread_entrypoint<T: Send + 'static>(
4
        self: Arc<Self>,
4
        id: TaskId,
4
        call: impl FnOnce() -> T + Send + 'static,
4
        output_tx: oneshot::Sender<Result<T, Box<dyn Any + Send>>>,
4
    ) {
4
        THREAD_DESCRIPTOR.set(ThreadDescriptor::Subthread(id));
4
        trace!("MockExecutor thread {id:?}, entrypoint");
        // Wait for the executor to tell us to run.
        // This will be done the first time the task is polled.
4
        {
4
            let data = self.lock();
4
            self.thread_context_switch_waitfor_instruction_to_run(
4
                data,
4
                ThreadDescriptor::Subthread(id),
4
            );
4
        }
4

            
4
        trace!("MockExecutor thread {id:?}, entering user code");
        // Run the user's actual thread function.
        // This will typically reenter us via subthread_block_on_future.
4
        let ret = catch_unwind(AssertUnwindSafe(call));
4

            
4
        trace!("MockExecutor thread {id:?}, completed user code");
        // This makes SubthreadFuture ready.
        // It will be polled by the executor in due course, presumably.
4
        output_tx.send(ret).unwrap_or_else(
4
            #[allow(clippy::unnecessary_lazy_evaluations)]
4
            |_| {}, // receiver dropped, maybe executor dropped or something?
4
        );
4

            
4
        {
4
            let mut data = self.lock();
4

            
4
            // Never poll this task again (so never schedule this thread)
4
            let _: Task = data.tasks.remove(id).expect("Subthread task vanished!");
4

            
4
            // Tell the executor it is scheduled now.
4
            // We carry on exiting, in parallel (holding the data lock).
4
            self.thread_context_switch_send_instruction_to_run(
4
                &mut data,
4
                ThreadDescriptor::Subthread(id),
4
                ThreadDescriptor::Executor,
4
            );
4
        }
4
    }
    /// Switch from (sub)thread `us` to (sub)thread `them`
    ///
    /// Returns when someone calls `thread_context_switch(.., us)`.
12
    fn thread_context_switch(
12
        &self,
12
        mut data: MutexGuard<Data>,
12
        us: ThreadDescriptor,
12
        them: ThreadDescriptor,
12
    ) {
12
        trace!("MockExecutor thread {us:?}, switching to {them:?}");
12
        self.thread_context_switch_send_instruction_to_run(&mut data, us, them);
12
        self.thread_context_switch_waitfor_instruction_to_run(data, us);
12
    }
    /// Instruct the (sub)thread `them` to run
    ///
    /// Update `thread_to_run`, which will wake up `them`'s
    /// call to `thread_context_switch_waitfor_instruction_to_run`.
    ///
    /// Must be called from (sub)thread `us`.
    /// Part of `thread_context_switch`, not normally called directly.
16
    fn thread_context_switch_send_instruction_to_run(
16
        &self,
16
        data: &mut MutexGuard<Data>,
16
        us: ThreadDescriptor,
16
        them: ThreadDescriptor,
16
    ) {
16
        assert_eq!(data.thread_to_run, us);
16
        data.thread_to_run = them;
16
        self.thread_condvar.notify_all();
16
    }
    /// Await an instruction for this thread, `us`, to run
    ///
    /// Waits for `thread_to_run` to be `us`,
    /// waiting for `thread_condvar` as necessary.
    ///
    /// Part of `thread_context_switch`, not normally called directly.
16
    fn thread_context_switch_waitfor_instruction_to_run(
16
        &self,
16
        data: MutexGuard<Data>,
16
        us: ThreadDescriptor,
16
    ) {
16
        #[allow(let_underscore_lock)]
16
        let _: MutexGuard<_> = self
16
            .thread_condvar
38
            .wait_while(data, |data| {
30
                let live = data.thread_to_run;
30
                let resume = live == us;
30
                if resume {
16
                    trace!("MockExecutor thread {us:?}, resuming");
                } else {
14
                    trace!("MockExecutor thread {us:?}, waiting for {live:?}");
                }
                // We're in `.wait_while`, not `.wait_until`.  Confusing.
30
                !resume
38
            })
16
            .expect("data lock poisoned");
16
    }
}
//---------- ancillary and convenience functions ----------
/// Trait to let us assert at compile time that something is nicely `Sync` etc.
#[allow(dead_code)] // yes, we don't *use* anything from this trait
trait EnsureSyncSend: Sync + Send + 'static {}
impl EnsureSyncSend for ActualWaker {}
impl EnsureSyncSend for MockExecutor {}
impl MockExecutor {
    /// Return the number of tasks running in this executor
    ///
    /// One possible use is for a test case to check that task(s)
    /// that ought to have exited, have indeed done so.
    ///
    /// In the usual case, the answer will be at least 1,
    /// because it counts the future passed to
    /// [`block_on`](MockExecutor::block_on)
    /// (perhaps via [`MockRuntime::test_with_various`](crate::MockRuntime::test_with_various)).
184
    pub fn n_tasks(&self) -> usize {
184
        self.shared.lock().tasks.len()
184
    }
}
impl Shared {
    /// Lock and obtain the guard
    ///
    /// Convenience method which panics on poison
14679190
    fn lock(&self) -> MutexGuard<Data> {
14679190
        self.data.lock().expect("data lock poisoned")
14679190
    }
}
impl Task {
    /// Set task `id` to `Awake` and arrange that it will be polled.
1648420
    fn set_awake(&mut self, id: TaskId, data_awake: &mut VecDeque<TaskId>) {
1648420
        match self.state {
437000
            Awake => {}
1211420
            Asleep(_) => {
1211420
                self.state = Awake;
1211420
                data_awake.push_back(id);
1211420
            }
        }
1648420
    }
}
//---------- ActualWaker as RawWaker ----------
/// Using [`ActualWaker`] in a [`RawWaker`]
///
/// We need to make a
/// [`Waker`] (the safe, type-erased, waker, used by actual futures)
/// which contains an
/// [`ActualWaker`] (our actual waker implementation, also safe).
///
/// `std` offers `Waker::from<Arc<impl Wake>>`.
/// But we want a bespoke `Clone` implementation, so we don't want to use `Arc`.
///
/// So instead, we implement the `RawWaker` API in terms of `ActualWaker`.
/// We keep the `ActualWaker` in a `Box`, and actually `clone` it (and the `Box`).
///
/// SAFETY
///
///  * The data pointer is `Box::<ActualWaker>::into_raw()`
///  * We share these when we clone
///  * No-one is allowed `&mut ActualWaker` unless there are no other clones
///  * So we may make references `&ActualWaker`
impl ActualWaker {
    /// Wrap up an [`ActualWaker`] as a type-erased [`Waker`] for passing to futures etc.
1250574
    fn new_waker(self) -> Waker {
1250574
        unsafe { Waker::from_raw(self.raw_new()) }
1250574
    }
    /// Helper: wrap up an [`ActualWaker`] as a [`RawWaker`].
5076344
    fn raw_new(self) -> RawWaker {
5076344
        let self_: Box<ActualWaker> = self.into();
5076344
        let self_: *mut ActualWaker = Box::into_raw(self_);
5076344
        let self_: *const () = self_ as _;
5076344
        RawWaker::new(self_, &RAW_WAKER_VTABLE)
5076344
    }
    /// Implementation of [`RawWakerVTable`]'s `clone`
3825770
    unsafe fn raw_clone(self_: *const ()) -> RawWaker {
3825770
        let self_: *const ActualWaker = self_ as _;
3825770
        let self_: &ActualWaker = self_.as_ref().unwrap_unchecked();
3825770
        let copy: ActualWaker = self_.clone();
3825770
        copy.raw_new()
3825770
    }
    /// Implementation of [`RawWakerVTable`]'s `wake`
1210960
    unsafe fn raw_wake(self_: *const ()) {
1210960
        Self::raw_wake_by_ref(self_);
1210960
        Self::raw_drop(self_);
1210960
    }
    /// Implementation of [`RawWakerVTable`]'s `wake_ref_by`
1650904
    unsafe fn raw_wake_by_ref(self_: *const ()) {
1650904
        let self_: *const ActualWaker = self_ as _;
1650904
        let self_: &ActualWaker = self_.as_ref().unwrap_unchecked();
1650904
        self_.wake();
1650904
    }
    /// Implementation of [`RawWakerVTable`]'s `drop`
5047272
    unsafe fn raw_drop(self_: *const ()) {
5047272
        let self_: *mut ActualWaker = self_ as _;
5047272
        let self_: Box<ActualWaker> = Box::from_raw(self_);
5047272
        drop(self_);
5047272
    }
}
/// vtable for `Box<ActualWaker>` as `RawWaker`
//
// This ought to be in the impl block above, but
//   "associated `static` items are not allowed"
static RAW_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(
    ActualWaker::raw_clone,
    ActualWaker::raw_wake,
    ActualWaker::raw_wake_by_ref,
    ActualWaker::raw_drop,
);
//---------- Sleep location tracking and dumping ----------
/// We record "where a future went to sleep" as (just) a backtrace
///
/// This type alias allows us to mock `Backtrace` for miri.
/// (It also insulates from future choices about sleep location representation.0
#[cfg(not(miri))]
type SleepLocation = Backtrace;
impl Data {
    /// Dump tasks and their sleep location backtraces
2
    fn dump_backtraces(&self, f: &mut fmt::Formatter) -> fmt::Result {
8
        for (id, task) in self.tasks.iter() {
12
            let prefix = |f: &mut fmt::Formatter| write!(f, "{id:?}={task:?}: ");
8
            match &task.state {
                Awake => {
2
                    prefix(f)?;
2
                    writeln!(f, "awake")?;
                }
6
                Asleep(locs) => {
6
                    let n = locs.len();
6
                    for (i, loc) in locs.iter().enumerate() {
6
                        prefix(f)?;
6
                        writeln!(f, "asleep, backtrace {i}/{n}:\n{loc}",)?;
                    }
6
                    if n == 0 {
                        prefix(f)?;
                        writeln!(f, "asleep, no backtraces, Waker never cloned, stuck!",)?;
6
                    }
                }
            }
        }
2
        writeln!(
2
            f,
2
            "\nNote: there might be spurious traces, see docs for MockExecutor::debug_dump\n"
2
        )?;
2
        Ok(())
2
    }
}
/// Track sleep locations via `<Waker as Clone>`.
///
/// See [`MockExecutor::debug_dump`] for the explanation.
impl Clone for ActualWaker {
3825770
    fn clone(&self) -> Self {
3825770
        let id = self.id;
3825770
        if let Some(data) = self.upgrade_data() {
            // If the executor is gone, there is nothing to adjust
3825770
            let mut data = data.lock();
3825770
            if let Some(task) = data.tasks.get_mut(self.id) {
3825770
                match &mut task.state {
220892
                    Awake => trace!("MockExecutor cloned waker for awake task {id:?}"),
3604878
                    Asleep(locs) => locs.push(SleepLocation::force_capture()),
                }
            } else {
                trace!("MockExecutor cloned waker for dead task {id:?}");
            }
        }
3825770
        ActualWaker {
3825770
            data: self.data.clone(),
3825770
            id,
3825770
        }
3825770
    }
}
//---------- API for full debug dump ----------
/// Debugging dump of a `MockExecutor`'s state
///
/// Returned by [`MockExecutor::as_debug_dump`]
//
// Existence implies backtraces have been resolved
//
// We use `Either` so that we can also use this internally when we have &mut Data.
pub struct DebugDump<'a>(Either<&'a Data, MutexGuard<'a, Data>>);
impl MockExecutor {
    /// Dump the executor's state including backtraces of waiting tasks, to stderr
    ///
    /// This is considerably more extensive than simply
    /// `MockExecutor as Debug`.
    ///
    /// (This is a convenience method, which wraps
    /// [`MockExecutor::as_debug_dump()`].
    ///
    /// ### Backtrace salience (possible spurious traces)
    ///
    /// **Summary**
    ///
    /// The technique used to capture backtraces when futures sleep is not 100% exact.
    /// It will usually show all the actual sleeping sites,
    /// but it might also show other backtraces which were part of
    /// the implementation of some complex relevant future.
    ///
    /// **Details**
    ///
    /// When a future's implementation wants to sleep,
    /// it needs to record the [`Waker`] (from the [`Context`])
    /// so that the "other end" can call `.wake()` on it later,
    /// when the future should be woken.
    ///
    /// Since `Context.waker()` gives `&Waker`, borrowed from the `Context`,
    /// the future must clone the `Waker`,
    /// and it must do so in within the `poll()` call.
    ///
    /// A future which is waiting in a `select!` will typically
    /// show multiple traces, one for each branch.
    /// But,
    /// if a future sleeps on one thing, and then when polled again later,
    /// sleeps on something different, without waking up in between,
    /// both backtrace locations will be shown.
    /// And,
    /// a complicated future contraption *might* clone the `Waker` more times.
    /// So not every backtrace will necessarily be informative.
    ///
    /// ### Panics
    ///
    /// Panics on write errors.
2
    pub fn debug_dump(&self) {
2
        self.as_debug_dump().to_stderr();
2
    }
    /// Dump the executor's state including backtraces of waiting tasks
    ///
    /// This is considerably more extensive than simply
    /// `MockExecutor as Debug`.
    ///
    /// Returns an object for formatting with [`Debug`].
    /// To simply print the dump to stderr (eg in a test),
    /// use [`.debug_dump()`](MockExecutor::debug_dump).
    ///
    /// **Backtrace salience (possible spurious traces)** -
    /// see [`.debug_dump()`](MockExecutor::debug_dump).
2
    pub fn as_debug_dump(&self) -> DebugDump {
2
        let data = self.shared.lock();
2
        DebugDump(Either::Right(data))
2
    }
}
impl Data {
    /// Convenience function: dump including backtraces, to stderr
    fn debug_dump(&mut self) {
        DebugDump(Either::Left(self)).to_stderr();
    }
}
impl DebugDump<'_> {
    /// Convenience function: dump tasks and backtraces to stderr
    #[allow(clippy::wrong_self_convention)] // "to_stderr" doesn't mean "convert to stderr"
2
    fn to_stderr(self) {
2
        write!(io::stderr().lock(), "{:?}", self)
2
            .unwrap_or_else(|e| error_report!(e, "failed to write debug dump to stderr"));
2
    }
}
//---------- bespoke Debug impls ----------
impl Debug for DebugDump<'_> {
2
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2
        let self_: &Data = &self.0;
2

            
2
        writeln!(f, "MockExecutor state:\n{self_:#?}")?;
2
        writeln!(f, "MockExecutor task dump:")?;
2
        self_.dump_backtraces(f)?;
2
        Ok(())
2
    }
}
// See `impl Debug for Data` for notes on the output
impl Debug for Task {
114
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
114
        let Task {
114
            desc,
114
            state,
114
            fut,
114
            is_subthread,
114
        } = self;
114
        write!(f, "{:?}", desc)?;
114
        write!(f, "=")?;
114
        match is_subthread {
110
            None => {}
4
            Some(IsSubthread) => write!(f, "T")?,
        }
110
        match fut {
4
            None => write!(f, "P")?,
84
            Some(TaskFutureInfo::Normal(_)) => write!(f, "f")?,
26
            Some(TaskFutureInfo::Main) => write!(f, "m")?,
        }
114
        match state {
102
            Awake => write!(f, "W")?,
12
            Asleep(locs) => write!(f, "s{}", locs.len())?,
        };
114
        Ok(())
114
    }
}
/// Helper: `Debug`s as a list of tasks, given the `Data` for lookups and a list of the ids
///
/// `Task`s in `Data` are printed as `Ti(ID)"SPEC"=FLAGS"`.
///
/// `FLAGS` are:
///
///  * `T`: this task is for a Subthread (from subthread_spawn).
///  * `P`: this task is being polled (its `TaskFutureInfo` is absent)
///  * `f`: this is a normal task with a future and its future is present in `Data`
///  * `m`: this is the main task from `block_on`
///
///  * `W`: the task is awake
///  * `s<n>`: the task is asleep, and `<n>` is the number of recorded sleeping locations
//
// We do it this way because the naive dump from derive is very expansive
// and makes it impossible to see the wood for the trees.
// This very compact representation it easier to find a task of interest in the output.
//
// This is implemented in `impl Debug for Task`.
//
//
// rustc doesn't think automatically-derived Debug impls count for whether a thing is used.
// This has caused quite some fallout.  https://github.com/rust-lang/rust/pull/85200
// I think derive_more emits #[automatically_derived], so that even though we use this
// in our Debug impl, that construction is unused.
#[allow(dead_code)]
struct DebugTasks<'d, F>(&'d Data, F);
// See `impl Debug for Data` for notes on the output
impl<F, I> Debug for DebugTasks<'_, F>
where
    F: Fn() -> I,
    I: Iterator<Item = TaskId>,
{
4
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4
        let DebugTasks(data, ids) = self;
10
        for (id, delim) in izip!(ids(), chain!(iter::once(""), iter::repeat(" ")),) {
10
            write!(f, "{delim}{id:?}")?;
10
            match data.tasks.get(id) {
                None => write!(f, "-")?,
10
                Some(task) => write!(f, "={task:?}")?,
            }
        }
4
        Ok(())
4
    }
}
/// Mock `Backtrace` for miri
///
/// See also the not-miri `type SleepLocation`, alias above.
#[cfg(miri)]
mod miri_sleep_location {
    #[derive(Debug, derive_more::Display)]
    #[display("<SleepLocation>")]
    pub(super) struct SleepLocation {}
    impl SleepLocation {
        pub(super) fn force_capture() -> Self {
            SleepLocation {}
        }
    }
}
#[cfg(miri)]
use miri_sleep_location::SleepLocation;
#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_duration_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
    use super::*;
    use futures::channel::mpsc;
    use futures::{SinkExt as _, StreamExt as _};
    use strum::IntoEnumIterator;
    use tracing::info;
    #[cfg(not(miri))] // trace! asks for the time, which miri doesn't support
    use tracing_test::traced_test;
    fn various_mock_executors() -> impl Iterator<Item = MockExecutor> {
        // This duplicates the part of the logic in MockRuntime::test_with_various which
        // relates to MockExecutor, because we don't have a MockRuntime::builder.
        // The only parameter to MockExecutor is its scheduling policy, so this seems fine.
        SchedulingPolicy::iter().map(|scheduling| {
            eprintln!("===== MockExecutor::with_scheduling({scheduling:?}) =====");
            MockExecutor::with_scheduling(scheduling)
        })
    }
    #[cfg_attr(not(miri), traced_test)]
    #[test]
    fn simple() {
        let runtime = MockExecutor::default();
        let val = runtime.block_on(async { 42 });
        assert_eq!(val, 42);
    }
    #[cfg_attr(not(miri), traced_test)]
    #[test]
    fn stall() {
        let runtime = MockExecutor::default();
        runtime.block_on({
            let runtime = runtime.clone();
            async move {
                const N: usize = 3;
                let (mut txs, mut rxs): (Vec<_>, Vec<_>) =
                    (0..N).map(|_| mpsc::channel::<usize>(5)).unzip();
                let mut rx_n = rxs.pop().unwrap();
                for (i, mut rx) in rxs.into_iter().enumerate() {
                    runtime.spawn_identified(i, {
                        let mut txs = txs.clone();
                        async move {
                            loop {
                                eprintln!("task {i} rx...");
                                let v = rx.next().await.unwrap();
                                let nv = v + 1;
                                eprintln!("task {i} rx {v}, tx {nv}");
                                let v = nv;
                                txs[v].send(v).await.unwrap();
                            }
                        }
                    });
                }
                dbg!();
                let _: mpsc::TryRecvError = rx_n.try_next().unwrap_err();
                dbg!();
                runtime.progress_until_stalled().await;
                dbg!();
                let _: mpsc::TryRecvError = rx_n.try_next().unwrap_err();
                dbg!();
                txs[0].send(0).await.unwrap();
                dbg!();
                runtime.progress_until_stalled().await;
                dbg!();
                let r = rx_n.next().await;
                assert_eq!(r, Some(N - 1));
                dbg!();
                let _: mpsc::TryRecvError = rx_n.try_next().unwrap_err();
                runtime.spawn_identified("tx", {
                    let txs = txs.clone();
                    async {
                        eprintln!("sending task...");
                        for (i, mut tx) in txs.into_iter().enumerate() {
                            eprintln!("sending 0 to {i}...");
                            tx.send(0).await.unwrap();
                        }
                        eprintln!("sending task done");
                    }
                });
                runtime.debug_dump();
                for i in 0..txs.len() {
                    eprintln!("main {i} wait stall...");
                    runtime.progress_until_stalled().await;
                    eprintln!("main {i} rx wait...");
                    let r = rx_n.next().await;
                    eprintln!("main {i} rx = {r:?}");
                    assert!(r == Some(0) || r == Some(N - 1));
                }
                eprintln!("finishing...");
                runtime.progress_until_stalled().await;
                eprintln!("finished.");
            }
        });
    }
    #[cfg_attr(not(miri), traced_test)]
    #[test]
    fn spawn_blocking() {
        let runtime = MockExecutor::default();
        runtime.block_on({
            let runtime = runtime.clone();
            async move {
                let thr_1 = runtime.spawn_blocking(|| 42);
                let thr_2 = runtime.spawn_blocking(|| 99);
                assert_eq!(thr_2.await, 99);
                assert_eq!(thr_1.await, 42);
            }
        });
    }
    #[cfg_attr(not(miri), traced_test)]
    #[test]
    fn drop_reentrancy() {
        // Check that dropping a completed task future is done *outside* the data lock.
        // Involves a contrived future whose Drop impl reenters the executor.
        //
        // If `_fut_drop_late = fut` in execute_until_first_stall (the main loop)
        // is replaced with `drop(fut)` (dropping the future at the wrong moment),
        // we do indeed get deadlock, so this test case is working.
        struct ReentersOnDrop {
            runtime: MockExecutor,
        }
        impl Future for ReentersOnDrop {
            type Output = ();
            fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<()> {
                Poll::Ready(())
            }
        }
        impl Drop for ReentersOnDrop {
            fn drop(&mut self) {
                self.runtime
                    .spawn_identified("dummy", futures::future::ready(()));
            }
        }
        for runtime in various_mock_executors() {
            runtime.block_on(async {
                runtime.spawn_identified("trapper", {
                    let runtime = runtime.clone();
                    ReentersOnDrop { runtime }
                });
            });
        }
    }
    #[cfg_attr(not(miri), traced_test)]
    #[test]
    fn subthread() {
        for runtime in various_mock_executors() {
            runtime.block_on(async {
                let (tx, rx) = oneshot::channel();
                info!("spawning subthread");
                let thr = runtime.subthread_spawn("thr1", {
                    let runtime = runtime.clone();
                    move || {
                        info!("subthread_block_on_future...");
                        let i = runtime.subthread_block_on_future(rx).unwrap();
                        info!("subthread_block_on_future => {i}");
                        i + 1
                    }
                });
                info!("main task sending");
                tx.send(12).unwrap();
                info!("main task sent");
                let r = thr.await.unwrap();
                info!("main task thr => {r}");
                assert_eq!(r, 13);
            });
        }
    }
}