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::panic::{AssertUnwindSafe, catch_unwind, panic_any};
13
use std::pin::{Pin, pin};
14
use std::sync::{Arc, Mutex, MutexGuard, Weak};
15
use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
16

            
17
use futures::FutureExt as _;
18
use futures::pin_mut;
19
use futures::task::{FutureObj, Spawn, SpawnError};
20

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

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

            
35
use oneshot_fused_workaround::{self as oneshot, Canceled};
36
use tor_error::error_report;
37
use tor_rtcompat::{Blocking, ToplevelBlockOn};
38

            
39
use Poll::*;
40
use TaskState::*;
41

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

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

            
48
//---------- principal data structures ----------
49

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

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

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

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

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

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

            
157
    /// Scheduling policy
158
    scheduling: SchedulingPolicy,
159

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

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

            
191
/// Record of a single task
192
///
193
/// Tracks a spawned task, or the main task (the argument to `block_on`).
194
///
195
/// Stored in [`Data`]`.tasks`.
196
struct Task {
197
    /// For debugging output
198
    desc: String,
199
    /// Has this been woken via a waker?  (And is it in `Data.awake`?)
200
    ///
201
    /// **Set to `Awake` only by [`Task::set_awake`]**,
202
    /// preserving the invariant that
203
    /// every `Awake` task is in [`Data.awake`](struct.Data.html#structfield.awake).
204
    state: TaskState,
205
    /// The actual future (or a placeholder for it)
206
    ///
207
    /// May be `None` briefly in the executor main loop, because we've
208
    /// temporarily moved it out so we can poll it,
209
    /// or if this is a Subthread task which is currently running sync code
210
    /// (in which case we're blocked in the executor waiting to be
211
    /// woken up by [`thread_context_switch`](Shared::thread_context_switch).
212
    ///
213
    /// Note that the `None` can be observed outside the main loop, because
214
    /// the main loop unlocks while it polls, so other (non-main-loop) code
215
    /// might see it.
216
    fut: Option<TaskFutureInfo>,
217
}
218

            
219
/// A future as stored in our record of a [`Task`]
220
#[derive(Educe)]
221
#[educe(Debug)]
222
enum TaskFutureInfo {
223
    /// The [`Future`].  All is normal.
224
    Normal(#[educe(Debug(ignore))] TaskFuture),
225
    /// The future isn't here because this task is the main future for `block_on`
226
    Main,
227
    /// This task is actually a [`Subthread`](MockExecutor::subthread_spawn)
228
    ///
229
    /// Instead of polling it, we'll switch to it with
230
    /// [`thread_context_switch`](Shared::thread_context_switch).
231
    Subthread,
232
}
233

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

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

            
264
    /// Which task this is
265
    id: TaskId,
266
}
267

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

            
291
    /// Waker
292
    ///
293
    /// Signalled by special code in the executor loop
294
    waker: Option<Waker>,
295
}
296

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

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

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

            
340
/// [`Shared::subthread_yield`] should set our task awake before switching to the executor
341
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
342
struct SetAwake;
343

            
344
thread_local! {
345
    /// Identifies this thread.
346
    pub static THREAD_DESCRIPTOR: Cell<ThreadDescriptor> = const {
347
        Cell::new(ThreadDescriptor::Foreign)
348
    };
349
}
350

            
351
//---------- creation ----------
352

            
353
impl MockExecutor {
354
    /// Make a `MockExecutor` with default parameters
355
2
    pub fn new() -> Self {
356
2
        Self::default()
357
2
    }
358

            
359
    /// Make a `MockExecutor` with a specific `SchedulingPolicy`
360
15137
    pub fn with_scheduling(scheduling: SchedulingPolicy) -> Self {
361
15137
        Data {
362
15137
            scheduling,
363
15137
            ..Default::default()
364
15137
        }
365
15137
        .into()
366
15137
    }
367
}
368

            
369
impl From<Data> for MockExecutor {
370
15137
    fn from(data: Data) -> MockExecutor {
371
15137
        let shared = Shared {
372
15137
            data: Mutex::new(data),
373
15137
            thread_condvar: std::sync::Condvar::new(),
374
15137
        };
375
15137
        MockExecutor {
376
15137
            shared: Arc::new(shared),
377
15137
        }
378
15137
    }
379
}
380

            
381
//---------- spawning ----------
382

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

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

            
421
    /// Spawn a task and return its `TaskId`
422
    ///
423
    /// Convenience method for use by `spawn_identified` and `spawn_obj`.
424
    /// The future passed to `block_on` is not handled here.
425
91002
    fn spawn_internal(&self, desc: String, fut: TaskFuture) -> TaskId {
426
91002
        let mut data = self.shared.lock();
427
91002
        data.insert_task(desc, TaskFutureInfo::Normal(fut))
428
91002
    }
429
}
430

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

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

            
453
impl Blocking for MockExecutor {
454
    type ThreadHandle<T: Send + 'static> = Pin<Box<dyn Future<Output = T>>>;
455

            
456
30
    fn spawn_blocking<F, T>(&self, f: F) -> Self::ThreadHandle<T>
457
30
    where
458
30
        F: FnOnce() -> T + Send + 'static,
459
30
        T: Send + 'static,
460
    {
461
        assert_matches!(
462
30
            THREAD_DESCRIPTOR.get(),
463
            ThreadDescriptor::Executor | ThreadDescriptor::Subthread(_),
464
            "MockExecutor::spawn_blocking_io only allowed from future or subthread, being run by this executor"
465
        );
466
30
        Box::pin(
467
30
            self.subthread_spawn("spawn_blocking", f)
468
30
                .map(|x| x.expect("Error in spawn_blocking subthread.")),
469
        )
470
30
    }
471

            
472
902
    fn reenter_block_on<F>(&self, future: F) -> F::Output
473
902
    where
474
902
        F: Future,
475
902
        F::Output: Send + 'static,
476
    {
477
902
        self.subthread_block_on_future(future)
478
902
    }
479
}
480

            
481
//---------- block_on ----------
482

            
483
impl ToplevelBlockOn for MockExecutor {
484
303
    fn block_on<F>(&self, input_fut: F) -> F::Output
485
303
    where
486
303
        F: Future,
487
    {
488
303
        let mut value: Option<F::Output> = None;
489

            
490
        // Box this just so that we can conveniently control precisely when it's dropped.
491
        // (We could do this with Option and Pin::set but that seems clumsier.)
492
303
        let mut input_fut = Box::pin(input_fut);
493

            
494
303
        let run_store_fut = {
495
303
            let value = &mut value;
496
303
            let input_fut = &mut input_fut;
497
303
            async {
498
303
                trace!("MockExecutor block_on future...");
499
303
                let t = input_fut.await;
500
303
                trace!("MockExecutor block_on future returned...");
501
303
                *value = Some(t);
502
303
                trace!("MockExecutor block_on future exiting.");
503
303
            }
504
        };
505

            
506
        {
507
303
            pin_mut!(run_store_fut);
508

            
509
303
            let main_id = self
510
303
                .shared
511
303
                .lock()
512
303
                .insert_task("main".into(), TaskFutureInfo::Main);
513
303
            trace!("MockExecutor {main_id:?} is task for block_on");
514
303
            self.execute_to_completion(run_store_fut);
515
        }
516

            
517
        #[allow(clippy::let_and_return)] // clarity
518
303
        let value = value.take().unwrap_or_else(|| {
519
            // eprintln can be captured by libtest, but the debug_dump goes to io::stderr.
520
            // use the latter, so that the debug dump is prefixed by this message.
521
            let _: io::Result<()> = writeln!(io::stderr(), "all futures blocked, crashing...");
522
            // write to tracing too, so the tracing log is clear about when we crashed
523
            error!("all futures blocked, crashing...");
524

            
525
            // Sequencing here is subtle.
526
            //
527
            // We should do the dump before dropping the input future, because the input
528
            // future is likely to own things that, when dropped, wake up other tasks,
529
            // rendering the dump inaccurate.
530
            //
531
            // But also, dropping the input future may well drop a ProgressUntilStalledFuture
532
            // which then reenters us.  More generally, we mustn't call user code
533
            // with the lock held.
534
            //
535
            // And, we mustn't panic with the data lock held.
536
            //
537
            // If value was Some, then this closure is dropped without being called,
538
            // which drops the future after it has yielded the value, which is correct.
539
            {
540
                let mut data = self.shared.lock();
541
                data.debug_dump();
542
            }
543
            drop(input_fut);
544

            
545
            panic!(
546
                r"
547
all futures blocked. waiting for the real world? or deadlocked (waiting for each other) ?
548
"
549
            );
550
        });
551

            
552
303
        value
553
303
    }
554
}
555

            
556
//---------- execution - core implementation ----------
557

            
558
impl MockExecutor {
559
    /// Keep polling tasks until nothing more can be done
560
    ///
561
    /// Ie, stop when `awake` is empty and `progressing_until_stalled` is `None`.
562
15747
    fn execute_to_completion(&self, mut main_fut: MainFuture) {
563
15747
        trace!("MockExecutor execute_to_completion...");
564
        loop {
565
4046640
            self.execute_until_first_stall(main_fut.as_mut());
566

            
567
            // Handle `progressing_until_stalled`
568
4030893
            let pus_waker = {
569
4046640
                let mut data = self.shared.lock();
570
4046640
                let pus = &mut data.progressing_until_stalled;
571
4046640
                trace!("MockExecutor execute_to_completion PUS={:?}", &pus);
572
4046640
                let Some(pus) = pus else {
573
                    // No progressing_until_stalled, we're actually done.
574
15747
                    break;
575
                };
576
4030893
                assert_eq!(
577
                    pus.finished, Pending,
578
                    "ProgressingUntilStalled finished twice?!"
579
                );
580
4030893
                pus.finished = Ready(());
581

            
582
                // Release the lock temporarily so that ActualWaker::clone doesn't deadlock
583
4030893
                let waker = pus
584
4030893
                    .waker
585
4030893
                    .take()
586
4030893
                    .expect("ProgressUntilStalledFuture not ever polled!");
587
4030893
                drop(data);
588
4030893
                let waker_copy = waker.clone();
589
4030893
                let mut data = self.shared.lock();
590

            
591
4030893
                let pus = &mut data.progressing_until_stalled;
592
4030893
                if let Some(double) = pus
593
4030893
                    .as_mut()
594
4030893
                    .expect("progressing_until_stalled updated under our feet!")
595
4030893
                    .waker
596
4030893
                    .replace(waker)
597
                {
598
                    panic!("double progressing_until_stalled.waker! {double:?}");
599
4030893
                }
600

            
601
4030893
                waker_copy
602
            };
603
4030893
            pus_waker.wake();
604
        }
605
15747
        trace!("MockExecutor execute_to_completion done");
606
15747
    }
607

            
608
    /// Keep polling tasks until `awake` is empty
609
    ///
610
    /// (Ignores `progressing_until_stalled` - so if one is active,
611
    /// will return when all other tasks have blocked.)
612
    ///
613
    /// # Panics
614
    ///
615
    /// Might malfunction or panic if called reentrantly
616
4046640
    fn execute_until_first_stall(&self, main_fut: MainFuture) {
617
4046640
        trace!("MockExecutor execute_until_first_stall ...");
618

            
619
4046640
        assert_eq!(
620
4046640
            THREAD_DESCRIPTOR.get(),
621
            ThreadDescriptor::Foreign,
622
            "MockExecutor executor re-entered"
623
        );
624
4046640
        THREAD_DESCRIPTOR.set(ThreadDescriptor::Executor);
625

            
626
4046640
        let r = catch_unwind(AssertUnwindSafe(|| self.executor_main_loop(main_fut)));
627

            
628
4046640
        THREAD_DESCRIPTOR.set(ThreadDescriptor::Foreign);
629

            
630
4046640
        match r {
631
4046640
            Ok(()) => trace!("MockExecutor execute_until_first_stall done."),
632
            Err(e) => {
633
                trace!("MockExecutor executor, or async task, panicked!");
634
                panic_any(e)
635
            }
636
        }
637
4046640
    }
638

            
639
    /// Keep polling tasks until `awake` is empty (inner, executor main loop)
640
    ///
641
    /// This is only called from [`MockExecutor::execute_until_first_stall`],
642
    /// so it could also be called `execute_until_first_stall_inner`.
643
4046640
    fn executor_main_loop(&self, mut main_fut: MainFuture) {
644
        'outer: loop {
645
            // Take a `Awake` task off `awake` and make it `Asleep`
646
5861201
            let (id, mut fut) = 'inner: loop {
647
9911417
                let mut data = self.shared.lock();
648
9911417
                let Some(id) = data.schedule() else {
649
4046640
                    break 'outer;
650
                };
651
5864777
                let Some(task) = data.tasks.get_mut(id) else {
652
3576
                    trace!("MockExecutor {id:?} vanished");
653
3576
                    continue;
654
                };
655
5861201
                task.state = Asleep(vec![]);
656
5861201
                let fut = task.fut.take().expect("future missing from task!");
657
5861201
                break 'inner (id, fut);
658
            };
659

            
660
            // Poll the selected task
661
5861201
            trace!("MockExecutor {id:?} polling...");
662
5861201
            let waker = ActualWaker::make_waker(&self.shared, id);
663
5861201
            let mut cx = Context::from_waker(&waker);
664
5861201
            let r: Either<Poll<()>, IsSubthread> = match &mut fut {
665
4122918
                TaskFutureInfo::Normal(fut) => Left(fut.poll_unpin(&mut cx)),
666
1630726
                TaskFutureInfo::Main => Left(main_fut.as_mut().poll(&mut cx)),
667
107557
                TaskFutureInfo::Subthread => Right(IsSubthread),
668
            };
669

            
670
            // Deal with the returned `Poll`
671
            let _fut_drop_late;
672
            {
673
5861201
                let mut data = self.shared.lock();
674
5861201
                let task = data
675
5861201
                    .tasks
676
5861201
                    .get_mut(id)
677
5861201
                    .expect("task vanished while we were polling it");
678

            
679
5753644
                match r {
680
                    Left(Pending) => {
681
5687597
                        trace!("MockExecutor {id:?} -> Pending");
682
5687597
                        if task.fut.is_some() {
683
                            panic!("task reinserted while we polled it?!");
684
5687597
                        }
685
                        // The task might have been woken *by its own poll method*.
686
                        // That's why we set it to `Asleep` *earlier* rather than here.
687
                        // All we need to do is put the future back.
688
5687597
                        task.fut = Some(fut);
689
                    }
690
                    Left(Ready(())) => {
691
66047
                        trace!("MockExecutor {id:?} -> Ready");
692
                        // Oh, it finished!
693
                        // It might be in `awake`, but that's allowed to contain stale tasks,
694
                        // so we *don't* need to scan that list and remove it.
695
66047
                        data.tasks.remove(id);
696
                        // It is important that we don't drop `fut` until we have released
697
                        // the data lock, since it is an external type and might try to reenter
698
                        // us (eg by calling spawn).  If we do that here, we risk deadlock.
699
                        // So, move `fut` to a variable with scope outside the block with `data`.
700
66047
                        _fut_drop_late = fut;
701
                    }
702
                    Right(IsSubthread) => {
703
107557
                        trace!("MockExecutor {id:?} -> Ready, waking Subthread");
704
                        // Task is a subthread, which has called thread_context_switch
705
                        // to switch to us.  We "poll" it by switching back.
706

            
707
                        // Put back `TFI::Subthread`, which was moved out temporarily, above.
708
107557
                        task.fut = Some(fut);
709

            
710
107557
                        self.shared.thread_context_switch(
711
107557
                            data,
712
107557
                            ThreadDescriptor::Executor,
713
107557
                            ThreadDescriptor::Subthread(id),
714
107557
                        );
715

            
716
                        // Now, if the Subthread still exists, that's because it's switched
717
                        // back to us, and is waiting in subthread_block_on_future again.
718
                        // Or it might have ended, in which case it's not in `tasks` any more.
719
                        // In any case we can go back to scheduling futures.
720
                    }
721
                }
722
            }
723
        }
724
4046640
    }
725
}
726

            
727
impl Data {
728
    /// Return the next task to run
729
    ///
730
    /// The task is removed from `awake`, but **`state` is not set to `Asleep`**.
731
    /// The caller must restore the invariant!
732
9911417
    fn schedule(&mut self) -> Option<TaskId> {
733
        use SchedulingPolicy as SP;
734
9911417
        match self.scheduling {
735
4974294
            SP::Stack => self.awake.pop_back(),
736
4937123
            SP::Queue => self.awake.pop_front(),
737
        }
738
9911417
    }
739
}
740

            
741
impl ActualWaker {
742
    /// Obtain a strong reference to the executor's data
743
23884178
    fn upgrade_data(&self) -> Option<Arc<Shared>> {
744
23884178
        self.data.upgrade()
745
23884178
    }
746

            
747
    /// Wake the task corresponding to this `ActualWaker`
748
    ///
749
    /// This is like `<Self as std::task::Wake>::wake()` but takes `&self`, not `Arc`
750
6596255
    fn wake(&self) {
751
6596255
        let Some(data) = self.upgrade_data() else {
752
            // The executor is gone!  Don't try to wake.
753
2
            return;
754
        };
755
6596253
        let mut data = data.lock();
756
6596253
        let data = &mut *data;
757
6596253
        trace!("MockExecutor {:?} wake", &self.id);
758
6596253
        let Some(task) = data.tasks.get_mut(self.id) else {
759
16170
            return;
760
        };
761
6580083
        task.set_awake(self.id, &mut data.awake);
762
6596255
    }
763

            
764
    /// Create and return a `Waker` for task `id`
765
5918360
    fn make_waker(shared: &Arc<Shared>, id: TaskId) -> Waker {
766
5918360
        ActualWaker {
767
5918360
            data: Arc::downgrade(shared),
768
5918360
            id,
769
5918360
        }
770
5918360
        .new_waker()
771
5918360
    }
772
}
773

            
774
//---------- "progress until stalled" functionality ----------
775

            
776
impl MockExecutor {
777
    /// Run tasks in the current executor until every other task is waiting
778
    ///
779
    /// # Panics
780
    ///
781
    /// Might malfunction or panic if more than one such call is running at once.
782
    ///
783
    /// (Ie, you must `.await` or drop the returned `Future`
784
    /// before calling this method again.)
785
    ///
786
    /// Must be called and awaited within a future being run by `self`.
787
4030893
    pub fn progress_until_stalled(&self) -> impl Future<Output = ()> + use<> {
788
4030893
        let mut data = self.shared.lock();
789
4030893
        assert!(
790
4030893
            data.progressing_until_stalled.is_none(),
791
            "progress_until_stalled called more than once"
792
        );
793
4030893
        trace!("MockExecutor progress_until_stalled...");
794
4030893
        data.progressing_until_stalled = Some(ProgressingUntilStalled {
795
4030893
            finished: Pending,
796
4030893
            waker: None,
797
4030893
        });
798
4030893
        ProgressUntilStalledFuture {
799
4030893
            shared: self.shared.clone(),
800
4030893
        }
801
4030893
    }
802
}
803

            
804
impl Future for ProgressUntilStalledFuture {
805
    type Output = ();
806

            
807
8062061
    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
808
8062061
        let waker = cx.waker().clone();
809
8062061
        let mut data = self.shared.lock();
810
8062061
        let pus = data.progressing_until_stalled.as_mut();
811
8062061
        trace!("MockExecutor progress_until_stalled polling... {:?}", &pus);
812
8062061
        let pus = pus.expect("ProgressingUntilStalled missing");
813
8062061
        pus.waker = Some(waker);
814
8062061
        pus.finished
815
8062061
    }
816
}
817

            
818
impl Drop for ProgressUntilStalledFuture {
819
4030893
    fn drop(&mut self) {
820
4030893
        self.shared.lock().progressing_until_stalled = None;
821
4030893
    }
822
}
823

            
824
//---------- (sub)threads ----------
825

            
826
impl MockExecutor {
827
    /// Spawn a "Subthread", for processing in a sync context
828
    ///
829
    /// `call` will be run on a separate thread, called a "Subthread".
830
    ///
831
    /// But it will **not run simultaneously** with the executor,
832
    /// nor with other Subthreads.
833
    /// So Subthreads are somewhat like coroutines.
834
    ///
835
    /// `call` must be capable of making progress without waiting for any other Subthreads.
836
    /// `call` may wait for async futures, using
837
    /// [`subthread_block_on_future`](MockExecutor::subthread_block_on_future).
838
    ///
839
    /// Subthreads may be used for cpubound activity,
840
    /// or synchronous IO (such as large volumes of disk activity),
841
    /// provided that the synchronous code will reliably make progress,
842
    /// without waiting (directly or indirectly) for any async task or Subthread -
843
    /// except via `subthread_block_on_future`.
844
    ///
845
    /// # Subthreads vs raw `std::thread` threads
846
    ///
847
    /// Programs using `MockExecutor` may use `std::thread` threads directly.
848
    /// However, this is not recommended.  There are severe limitations:
849
    ///
850
    ///  * Only a Subthread can re-enter the async context from sync code:
851
    ///    this must be done with
852
    ///    using [`subthread_block_on_future`](MockExecutor::subthread_block_on_future).
853
    ///    (Re-entering the executor with
854
    ///    [`block_on`](tor_rtcompat::ToplevelBlockOn::block_on)
855
    ///    is not allowed.)
856
    ///  * If async tasks want to suspend waiting for synchronous code,
857
    ///    the synchronous code must run on a Subthread.
858
    ///    This allows the `MockExecutor` to know when
859
    ///    that synchronous code is still making progress.
860
    ///    (This is needed for
861
    ///    [`progress_until_stalled`](MockExecutor::progress_until_stalled)
862
    ///    and the facilities which use it, such as
863
    ///    [`MockRuntime::advance_until_stalled`](crate::MockRuntime::advance_until_stalled).)
864
    ///  * Subthreads never run in parallel -
865
    ///    they only run as scheduled deterministically by the `MockExecutor`.
866
    ///    So using Subthreads eliminates a source of test nonndeterminism.
867
    ///    (Execution order is still varied due to explicitly varying the scheduling policy.)
868
    ///
869
    /// # Panics, abuse, and malfunctions
870
    ///
871
    /// If `call` panics and unwinds, `spawn_subthread` yields `Err`.
872
    /// The application code should to do something about it if this happens,
873
    /// typically, logging errors, tearing things down, or failing a test case.
874
    ///
875
    /// If the executor doesn't run, the subthread will not run either, and will remain stuck.
876
    /// (So, typically, if the thread supposed to run the executor panics,
877
    /// for example because a future or the executor itself panics,
878
    /// all the subthreads will become stuck - effectively, they'll be leaked.)
879
    ///
880
    /// `spawn_subthread` panics if OS thread spawning fails.
881
    /// (Like `std::thread::spawn()` does.)
882
    ///
883
    /// `MockExecutor`s will malfunction or panic if
884
    /// any executor invocation method (eg `block_on`) is called on a Subthread.
885
34
    pub fn subthread_spawn<T: Send + 'static>(
886
34
        &self,
887
34
        desc: impl Display,
888
34
        call: impl FnOnce() -> T + Send + 'static,
889
34
    ) -> impl Future<Output = Result<T, Box<dyn Any + Send>>> + Unpin + Send + Sync + 'static {
890
34
        let desc = desc.to_string();
891
34
        let (output_tx, output_rx) = oneshot::channel();
892

            
893
        // NB: we don't know which thread we're on!
894
        // In principle we might be on another Subthread.
895
        // So we can't context switch here.  That would be very confusing.
896
        //
897
        // Instead, we prepare the new Subthread as follows:
898
        //   - There is a task in the executor
899
        //   - The task is ready to be polled, whenever the executor decides to
900
        //   - The thread starts running right away, but immediately waits until it is scheduled
901
        // See `subthread_entrypoint`.
902

            
903
        {
904
34
            let mut data = self.shared.lock();
905
34
            let id = data.insert_task(desc.clone(), TaskFutureInfo::Subthread);
906

            
907
34
            let _: std::thread::JoinHandle<()> = std::thread::Builder::new()
908
34
                .name(desc)
909
34
                .spawn({
910
34
                    let shared = self.shared.clone();
911
34
                    move || shared.subthread_entrypoint(id, call, output_tx)
912
                })
913
34
                .expect("spawn failed");
914
        }
915

            
916
34
        output_rx.map(|r| {
917
6
            r.unwrap_or_else(|_: Canceled| panic!("Subthread cancelled but should be impossible!"))
918
6
        })
919
34
    }
920

            
921
    /// Call an async `Future` from a Subthread
922
    ///
923
    /// Blocks the Subthread, and arranges to run async tasks,
924
    /// including `fut`, until `fut` completes.
925
    ///
926
    /// `fut` is polled on the executor thread, not on the Subthread.
927
    /// (We may change that in the future, allowing passing a non-`Send` future.)
928
    ///
929
    /// # Panics, abuse, and malfunctions
930
    ///
931
    /// `subthread_block_on_future` will malfunction or panic
932
    /// if called on a thread that isn't a Subthread from the same `MockExecutor`
933
    /// (ie a thread made with [`spawn_subthread`](MockExecutor::subthread_spawn)).
934
    ///
935
    /// If `fut` itself panics, the executor will panic.
936
    ///
937
    /// If the executor isn't running, `subthread_block_on_future` will hang indefinitely.
938
    /// See `spawn_subthread`.
939
914
    pub fn subthread_block_on_future<T: Send + 'static>(&self, fut: impl Future<Output = T>) -> T {
940
914
        let id = match THREAD_DESCRIPTOR.get() {
941
914
            ThreadDescriptor::Subthread(id) => id,
942
            ThreadDescriptor::Executor => {
943
                panic!("subthread_block_on_future called from MockExecutor thread (async task?)")
944
            }
945
            ThreadDescriptor::Foreign => panic!(
946
                "subthread_block_on_future called on foreign thread (not spawned with spawn_subthread)"
947
            ),
948
        };
949
914
        trace!("MockExecutor thread {id:?}, subthread_block_on_future...");
950
914
        let mut fut = pin!(fut);
951

            
952
        // We yield once before the first poll, and once after Ready, to shake up the
953
        // execution order a bit, depending on the scheduling policy.
954
1967
        let yield_ = |set_awake| self.shared.subthread_yield(id, set_awake);
955
914
        yield_(Some(SetAwake));
956

            
957
914
        let ret = loop {
958
            // Poll the provided future
959
1053
            trace!("MockExecutor thread {id:?}, s.t._block_on_future polling...");
960
1053
            let waker = ActualWaker::make_waker(&self.shared, id);
961
1053
            let mut cx = Context::from_waker(&waker);
962
1053
            let r: Poll<T> = fut.as_mut().poll(&mut cx);
963

            
964
1053
            if let Ready(r) = r {
965
914
                trace!("MockExecutor thread {id:?}, s.t._block_on_future poll -> Ready");
966
914
                break r;
967
139
            }
968

            
969
            // Pending.  Switch back to the executor thread.
970
            // When the future becomes ready, the Waker will be woken, waking the task,
971
            // so that the executor will "poll" us again.
972
139
            trace!("MockExecutor thread {id:?}, s.t._block_on_future poll -> Pending");
973

            
974
139
            yield_(None);
975
        };
976

            
977
914
        yield_(Some(SetAwake));
978

            
979
914
        trace!("MockExecutor thread {id:?}, subthread_block_on_future complete.");
980

            
981
914
        ret
982
914
    }
983
}
984

            
985
impl Shared {
986
    /// Main entrypoint function for a Subthread
987
    ///
988
    /// Entered on a new `std::thread` thread created by
989
    /// [`subthread_spawn`](MockExecutor::subthread_spawn).
990
    ///
991
    /// When `call` completes, sends its returned value `T` to `output_tx`.
992
34
    fn subthread_entrypoint<T: Send + 'static>(
993
34
        self: Arc<Self>,
994
34
        id: TaskId,
995
34
        call: impl FnOnce() -> T + Send + 'static,
996
34
        output_tx: oneshot::Sender<Result<T, Box<dyn Any + Send>>>,
997
34
    ) {
998
34
        THREAD_DESCRIPTOR.set(ThreadDescriptor::Subthread(id));
999
34
        trace!("MockExecutor thread {id:?}, entrypoint");
        // We start out Awake, but we wait for the executor to tell us to run.
        // This will be done the first time the task is "polled".
34
        {
34
            let data = self.lock();
34
            self.thread_context_switch_waitfor_instruction_to_run(
34
                data,
34
                ThreadDescriptor::Subthread(id),
34
            );
34
        }
34
        trace!("MockExecutor thread {id:?}, entering user code");
        // Run the user's actual thread function.
        // This will typically reenter us via subthread_block_on_future.
34
        let ret = catch_unwind(AssertUnwindSafe(call));
34
        trace!("MockExecutor thread {id:?}, completed user code");
        // This makes the return value from subthread_spawn ready.
        // It will be polled by the executor in due course, presumably.
34
        output_tx.send(ret).unwrap_or_else(
            #[allow(clippy::unnecessary_lazy_evaluations)]
14
            |_| {}, // receiver dropped, maybe executor dropped or something?
        );
34
        {
34
            let mut data = self.lock();
34

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

            
34
            // Tell the executor it is scheduled now.
34
            // We carry on exiting, in parallel (holding the data lock).
34
            self.thread_context_switch_send_instruction_to_run(
34
                &mut data,
34
                ThreadDescriptor::Subthread(id),
34
                ThreadDescriptor::Executor,
34
            );
34
        }
34
    }
    /// Yield back to the executor from a subthread
    ///
    /// Checks that things are in order
    /// (in particular, that this task is in the data structure as a subhtread)
    /// and switches to the executor thread.
    ///
    /// The caller must arrange that the task gets woken.
    ///
    /// With [`SetAwake`], sets our task awake, so that we'll be polled
    /// again as soon as we get to the top of the executor's queue.
    /// Otherwise, we'll be reentered after someone wakes a [`Waker`] for the task.
106781
    fn subthread_yield(&self, us: TaskId, set_awake: Option<SetAwake>) {
106781
        let mut data = self.lock();
        {
106781
            let data = &mut *data;
106781
            let task = data.tasks.get_mut(us).expect("Subthread task vanished!");
106781
            match &task.fut {
106781
                Some(TaskFutureInfo::Subthread) => {}
                other => panic!("subthread_block_on_future but TFI {other:?}"),
            };
106781
            if let Some(SetAwake) = set_awake {
98474
                task.set_awake(us, &mut data.awake);
98474
            }
        }
106781
        self.thread_context_switch(
106781
            data,
106781
            ThreadDescriptor::Subthread(us),
106781
            ThreadDescriptor::Executor,
        );
106781
    }
    /// Switch from (sub)thread `us` to (sub)thread `them`
    ///
    /// Returns when someone calls `thread_context_switch(.., us)`.
214338
    fn thread_context_switch(
214338
        &self,
214338
        mut data: MutexGuard<Data>,
214338
        us: ThreadDescriptor,
214338
        them: ThreadDescriptor,
214338
    ) {
214338
        trace!("MockExecutor thread {us:?}, switching to {them:?}");
214338
        self.thread_context_switch_send_instruction_to_run(&mut data, us, them);
214338
        self.thread_context_switch_waitfor_instruction_to_run(data, us);
214338
    }
    /// 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.
215114
    fn thread_context_switch_send_instruction_to_run(
215114
        &self,
215114
        data: &mut MutexGuard<Data>,
215114
        us: ThreadDescriptor,
215114
        them: ThreadDescriptor,
215114
    ) {
215114
        assert_eq!(data.thread_to_run, us);
215114
        data.thread_to_run = them;
215114
        self.thread_condvar.notify_all();
215114
    }
    /// 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.
215884
    fn thread_context_switch_waitfor_instruction_to_run(
215884
        &self,
215884
        data: MutexGuard<Data>,
215884
        us: ThreadDescriptor,
215884
    ) {
        #[allow(let_underscore_lock)]
215884
        let _: MutexGuard<_> = self
215884
            .thread_condvar
572020
            .wait_while(data, |data| {
572020
                let live = data.thread_to_run;
572020
                let resume = live == us;
572020
                if resume {
215114
                    trace!("MockExecutor thread {us:?}, resuming");
                } else {
356906
                    trace!("MockExecutor thread {us:?}, waiting for {live:?}");
                }
                // We're in `.wait_while`, not `.wait_until`.  Confusing.
572020
                !resume
572020
            })
215884
            .expect("data lock poisoned");
215884
    }
}
//---------- 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)).
220
    pub fn n_tasks(&self) -> usize {
220
        self.shared.lock().tasks.len()
220
    }
}
impl Shared {
    /// Lock and obtain the guard
    ///
    /// Convenience method which panics on poison
64075793
    fn lock(&self) -> MutexGuard<Data> {
64075793
        self.data.lock().expect("data lock poisoned")
64075793
    }
}
impl Task {
    /// Set task `id` to `Awake` and arrange that it will be polled.
6678557
    fn set_awake(&mut self, id: TaskId, data_awake: &mut VecDeque<TaskId>) {
6678557
        match self.state {
888525
            Awake => {}
5790032
            Asleep(_) => {
5790032
                self.state = Awake;
5790032
                data_awake.push_back(id);
5790032
            }
        }
6678557
    }
}
//---------- 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.
5918360
    fn new_waker(self) -> Waker {
5918360
        unsafe { Waker::from_raw(self.raw_new()) }
5918360
    }
    /// Helper: wrap up an [`ActualWaker`] as a [`RawWaker`].
23206283
    fn raw_new(self) -> RawWaker {
23206283
        let self_: Box<ActualWaker> = self.into();
23206283
        let self_: *mut ActualWaker = Box::into_raw(self_);
23206283
        let self_: *const () = self_ as _;
23206283
        RawWaker::new(self_, &RAW_WAKER_VTABLE)
23206283
    }
    /// Implementation of [`RawWakerVTable`]'s `clone`
17287923
    unsafe fn raw_clone(self_: *const ()) -> RawWaker {
        unsafe {
17287923
            let self_: *const ActualWaker = self_ as _;
17287923
            let self_: &ActualWaker = self_.as_ref().unwrap_unchecked();
17287923
            let copy: ActualWaker = self_.clone();
17287923
            copy.raw_new()
        }
17287923
    }
    /// Implementation of [`RawWakerVTable`]'s `wake`
6010450
    unsafe fn raw_wake(self_: *const ()) {
6010450
        unsafe {
6010450
            Self::raw_wake_by_ref(self_);
6010450
            Self::raw_drop(self_);
6010450
        }
6010450
    }
    /// Implementation of [`RawWakerVTable`]'s `wake_ref_by`
6596255
    unsafe fn raw_wake_by_ref(self_: *const ()) {
6596255
        unsafe {
6596255
            let self_: *const ActualWaker = self_ as _;
6596255
            let self_: &ActualWaker = self_.as_ref().unwrap_unchecked();
6596255
            self_.wake();
6596255
        }
6596255
    }
    /// Implementation of [`RawWakerVTable`]'s `drop`
23169543
    unsafe fn raw_drop(self_: *const ()) {
23169543
        unsafe {
23169543
            let self_: *mut ActualWaker = self_ as _;
23169543
            let self_: Box<ActualWaker> = Box::from_raw(self_);
23169543
            drop(self_);
23169543
        }
23169543
    }
}
/// 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
1
    fn dump_backtraces(&self, f: &mut fmt::Formatter) -> fmt::Result {
4
        for (id, task) in self.tasks.iter() {
4
            let prefix = |f: &mut fmt::Formatter| write!(f, "{id:?}={task:?}: ");
4
            match &task.state {
                Awake => {
1
                    prefix(f)?;
1
                    writeln!(f, "awake")?;
                }
3
                Asleep(locs) => {
3
                    let n = locs.len();
3
                    for (i, loc) in locs.iter().enumerate() {
3
                        prefix(f)?;
3
                        writeln!(f, "asleep, backtrace {i}/{n}:\n{loc}",)?;
                    }
3
                    if n == 0 {
                        prefix(f)?;
                        writeln!(f, "asleep, no backtraces, Waker never cloned, stuck!",)?;
3
                    }
                }
            }
        }
1
        writeln!(
1
            f,
            "\nNote: there might be spurious traces, see docs for MockExecutor::debug_dump\n"
        )?;
1
        Ok(())
1
    }
}
/// Track sleep locations via `<Waker as Clone>`.
///
/// See [`MockExecutor::debug_dump`] for the explanation.
impl Clone for ActualWaker {
17287923
    fn clone(&self) -> Self {
17287923
        let id = self.id;
17287923
        if let Some(data) = self.upgrade_data() {
            // If the executor is gone, there is nothing to adjust
17287923
            let mut data = data.lock();
17287923
            if let Some(task) = data.tasks.get_mut(self.id) {
17287923
                match &mut task.state {
703120
                    Awake => trace!("MockExecutor cloned waker for awake task {id:?}"),
16584803
                    Asleep(locs) => locs.push(SleepLocation::force_capture()),
                }
            } else {
                trace!("MockExecutor cloned waker for dead task {id:?}");
            }
        }
17287923
        ActualWaker {
17287923
            data: self.data.clone(),
17287923
            id,
17287923
        }
17287923
    }
}
//---------- 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.
1
    pub fn debug_dump(&self) {
1
        self.as_debug_dump().to_stderr();
1
    }
    /// 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).
1
    pub fn as_debug_dump(&self) -> DebugDump {
1
        let data = self.shared.lock();
1
        DebugDump(Right(data))
1
    }
}
impl Data {
    /// Convenience function: dump including backtraces, to stderr
    fn debug_dump(&mut self) {
        DebugDump(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"
1
    fn to_stderr(self) {
1
        write!(io::stderr().lock(), "{:?}", self)
1
            .unwrap_or_else(|e| error_report!(e, "failed to write debug dump to stderr"));
1
    }
}
//---------- bespoke Debug impls ----------
impl Debug for DebugDump<'_> {
1
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1
        let self_: &Data = &self.0;
1
        writeln!(f, "MockExecutor state:\n{self_:#?}")?;
1
        writeln!(f, "MockExecutor task dump:")?;
1
        self_.dump_backtraces(f)?;
1
        Ok(())
1
    }
}
// See `impl Debug for Data` for notes on the output
impl Debug for Task {
61
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61
        let Task { desc, state, fut } = self;
61
        write!(f, "{:?}", desc)?;
61
        write!(f, "=")?;
59
        match fut {
2
            None => write!(f, "P")?,
38
            Some(TaskFutureInfo::Normal(_)) => write!(f, "f")?,
15
            Some(TaskFutureInfo::Main) => write!(f, "m")?,
6
            Some(TaskFutureInfo::Subthread) => write!(f, "T")?,
        }
61
        match state {
55
            Awake => write!(f, "W")?,
6
            Asleep(locs) => write!(f, "s{}", locs.len())?,
        };
61
        Ok(())
61
    }
}
/// 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>,
{
2
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2
        let DebugTasks(data, ids) = self;
5
        for (id, delim) in izip!(ids(), chain!(iter::once(""), iter::repeat(" ")),) {
5
            write!(f, "{delim}{id:?}")?;
5
            match data.tasks.get(id) {
                None => write!(f, "-")?,
5
                Some(task) => write!(f, "={task:?}")?,
            }
        }
2
        Ok(())
2
    }
}
/// 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_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    #![allow(clippy::string_slice)] // See arti#2571
    //! <!-- @@ 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!();
                #[allow(deprecated)] // TODO(#2386)
                let _: mpsc::TryRecvError = rx_n.try_next().unwrap_err();
                dbg!();
                runtime.progress_until_stalled().await;
                dbg!();
                #[allow(deprecated)] // TODO(#2386)
                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!();
                #[allow(deprecated)] // TODO(#2386)
                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_oneshot() {
        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);
            });
        }
    }
    #[cfg_attr(not(miri), traced_test)]
    #[test]
    fn subthread_pingpong() {
        for runtime in various_mock_executors() {
            runtime.block_on(async {
                let (mut i_tx, mut i_rx) = mpsc::channel(1);
                let (mut o_tx, mut o_rx) = mpsc::channel(1);
                info!("spawning subthread");
                let thr = runtime.subthread_spawn("thr", {
                    let runtime = runtime.clone();
                    move || {
                        while let Some(i) = {
                            info!("thread receiving ...");
                            runtime.subthread_block_on_future(i_rx.next())
                        } {
                            let o = i + 12;
                            info!("thread received {i}, sending {o}");
                            runtime.subthread_block_on_future(o_tx.send(o)).unwrap();
                            info!("thread sent {o}");
                        }
                        info!("thread exiting");
                        42
                    }
                });
                for i in 0..2 {
                    info!("main task sending {i}");
                    i_tx.send(i).await.unwrap();
                    info!("main task sent {i}");
                    let o = o_rx.next().await.unwrap();
                    info!("main task recv => {o}");
                    assert_eq!(o, i + 12);
                }
                info!("main task dropping sender");
                drop(i_tx);
                info!("main task awaiting thread");
                let r = thr.await.unwrap();
                info!("main task complete");
                assert_eq!(r, 42);
            });
        }
    }
}