arty 0.6.0

Thread-aware async runtime that keeps each task on one worker thread.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use crate::runtime::builder::RuntimeBuilder;
use crate::runtime::dispatch::DispatcherClient;
use crate::runtime::error::Error;
use crate::runtime::worker::WorkerJoiner;
use crate::task::RuntimeScheduler;

/// Owns an Arty runtime's workers and their shutdown.
///
/// Use this type to run async tasks from synchronous code.
/// Arty assigns each async worker to an available processor. A fixed worker count
/// can assign multiple workers to one processor. A task stays on its worker
/// until it finishes or is cancelled.
///
/// Borrow its [`RuntimeScheduler`] through
/// [`scheduler`](Self::scheduler) to submit tasks or block on
/// tasks that borrow the caller's data.
/// When the required tasks finish, call [`stop`](Self::stop) to stop the runtime.
///
/// # Drop
///
/// Dropping this value requests shutdown and normally waits for workers to stop.
/// Arty cancels pending async tasks and queued blocking functions. Blocking
/// functions that already started can finish. A function that never returns can
/// prevent shutdown from completing.
///
/// Dropping the runtime cannot return shutdown errors. Call [`stop`](Self::stop)
/// to receive errors for worker panics or I/O driver failures during
/// startup or normal operation. I/O driver shutdown failures are not returned.
///
/// Dropping this value in an Arty task or on a blocking worker panics.
/// Keep it on a thread that is not an Arty worker.
/// From worker code, use
/// [`RuntimeControl::request_stop`](crate::runtime::RuntimeControl::request_stop).
///
/// Schedulers and [`Context`](crate::task::Context) values do not keep
/// the runtime running after this value is dropped.
///
/// # Examples
///
/// Submit a task from synchronous code and stop after receiving its result:
///
/// ```
/// use arty::runtime::Runtime;
///
/// let runtime = Runtime::new()?;
/// let task = runtime.scheduler().spawn_anywhere((), |_, ()| async { 42 });
/// assert_eq!(futures::executor::block_on(task)?, 42);
/// runtime.stop()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct Runtime {
    scheduler: RuntimeScheduler,
    worker_joiner: WorkerJoiner,
    shutdown_on_drop: bool,
}

impl Runtime {
    /// Creates and starts a runtime with the default configuration.
    ///
    /// Equivalent to [`Runtime::builder().build()`](RuntimeBuilder::build).
    /// See the [runtime defaults](crate::runtime#defaults) for the complete
    /// configuration.
    ///
    /// # Errors
    ///
    /// See [`RuntimeBuilder::build`] for configuration errors.
    /// The default configuration uses a valid worker count and blocking-pool limit.
    ///
    /// # Panics
    ///
    /// Panics if worker creation or initialization fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use arty::runtime::Runtime;
    ///
    /// let runtime = Runtime::new()?;
    /// assert_eq!(runtime.scheduler().block_on(async |_| 42)?, 42);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn new() -> Result<Self, Error> {
        RuntimeBuilder::new().build()
    }

    /// Returns a builder for configuring a runtime before starting its workers.
    ///
    /// See [`RuntimeBuilder`] for the defaults and available configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use arty::runtime::{BlockingPoolPolicy, Runtime};
    ///
    /// let builder = Runtime::builder().blocking_pool(BlockingPoolPolicy::shared().max(4));
    /// ```
    #[must_use]
    pub fn builder() -> RuntimeBuilder {
        RuntimeBuilder::new()
    }

    /// Borrows the scheduler that lets the runtime choose a worker for new tasks.
    ///
    /// Use it to submit tasks from outside the runtime and let the runtime
    /// choose a worker. In contrast,
    /// [`Context::scheduler`](crate::task::Context::scheduler) keeps child
    /// tasks on their parent's worker.
    ///
    /// You cannot clone the scheduler or keep it after this runtime is dropped.
    /// Tasks do not necessarily start or finish in the order you submit them.
    ///
    /// # Examples
    ///
    /// ```
    /// use arty::runtime::Runtime;
    ///
    /// let runtime = Runtime::new()?;
    /// let scheduler = runtime.scheduler();
    /// let first = scheduler.spawn_anywhere((), |_, ()| async { 20 });
    /// let second = scheduler.spawn_anywhere((), |_, ()| async { 22 });
    /// assert_eq!(
    ///     futures::executor::block_on(first)? + futures::executor::block_on(second)?,
    ///     42
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    #[inline]
    pub fn scheduler(&self) -> &RuntimeScheduler {
        &self.scheduler
    }

    /// Takes ownership of this runtime, requests shutdown, and waits for its workers to stop.
    ///
    /// Cancels pending async tasks and prevents queued blocking functions from
    /// starting. Blocking functions that already started can finish.
    /// `Ok(())` means shutdown is complete.
    ///
    /// Use [`Context::control`](crate::task::Context::control) to obtain
    /// runtime control and request shutdown without taking ownership of the runtime or
    /// blocking the caller.
    ///
    /// # Errors
    ///
    /// Returns an error if a worker panicked or an I/O driver failed during
    /// startup or normal operation. It does not return I/O driver shutdown
    /// failures. It waits for all workers to stop before it reports a failure.
    /// To receive a task failure, await its [`JoinHandle`](crate::task::JoinHandle).
    ///
    /// # Panics
    ///
    /// Panics if called from an Arty task or blocking worker. Use
    /// [`RuntimeControl::request_stop`](crate::runtime::RuntimeControl::request_stop)
    /// to request shutdown from worker code.
    ///
    /// # Examples
    ///
    /// ```
    /// use arty::runtime::Runtime;
    ///
    /// let runtime = Runtime::new()?;
    /// let error = runtime.scheduler().block_on(async |cx| {
    ///     cx.control().request_stop();
    ///     cx.scheduler()
    ///         .spawn(async |_| 42)
    ///         .await
    ///         .expect_err("submission follows shutdown")
    /// })?;
    /// runtime.stop()?;
    /// assert!(error.is_shutdown());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn stop(mut self) -> Result<(), Error> {
        if crate::runtime::worker::WorkerMarker::is_current() {
            let cause = self.scheduler.dispatcher.stop(arty_executor::ShutdownCause::default());
            crate::runtime::worker::asynchronous::LocalWorker::begin_executor_shutdown(&self.scheduler.dispatcher, cause);
            self.shutdown_on_drop = false;
            panic_shutdown_from_worker("Runtime::stop");
        }
        _ = self.scheduler.dispatcher.stop(arty_executor::ShutdownCause::default());
        self.shutdown_on_drop = false;
        self.wait()
    }

    fn wait(&self) -> Result<(), Error> {
        let wait_error = self.worker_joiner.join().err();
        if let Some(error) = self.scheduler.dispatcher.shutdown().error() {
            return Err(Error::shutdown_failure(error));
        }
        wait_error.map_or(Ok(()), Err)
    }

    pub(crate) const fn with_dispatcher(dispatcher: DispatcherClient, worker_joiner: WorkerJoiner) -> Self {
        Self {
            scheduler: RuntimeScheduler::new(dispatcher),
            worker_joiner,
            shutdown_on_drop: true,
        }
    }
}

impl Drop for Runtime {
    fn drop(&mut self) {
        if !self.shutdown_on_drop {
            return;
        }

        let cause = self.scheduler.dispatcher.stop(arty_executor::ShutdownCause::default());
        if crate::runtime::worker::WorkerMarker::is_current() {
            crate::runtime::worker::asynchronous::LocalWorker::begin_executor_shutdown(&self.scheduler.dispatcher, cause);
            if std::thread::panicking() {
                return;
            }
            panic_shutdown_from_worker("Runtime drop");
        }
        let _ = self.wait();
    }
}

#[cold]
#[inline(never)]
#[expect(clippy::panic, reason = "runtime ownership on a worker is a programming error")]
fn panic_shutdown_from_worker(operation: &str) -> ! {
    panic!("{operation} cannot run on an Arty worker; use RuntimeControl::request_stop")
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use std::cell::RefCell;
    use std::future::poll_fn;
    use std::task::{Poll, Waker};
    use std::thread;

    use performables::sync::channel;
    use thread_aware::ThreadBuilder;

    use super::*;
    use crate::runtime::dispatch::{DispatcherCore, WorkerEndpoint};
    use crate::runtime::worker::blocking::{PanicPolicy, Pool, Worker};
    use crate::task::JoinError;

    thread_local! {
        static SHUTDOWN_GUARD: RefCell<Option<ShutdownGuard>> = const { RefCell::new(None) };
    }

    struct ShutdownGuard(crate::runtime::RuntimeControl);

    impl Drop for ShutdownGuard {
        fn drop(&mut self) {
            self.0.request_stop();
        }
    }

    #[test]
    fn explicit_stop_reports_a_worker_panic_after_joining() {
        let worker = thread::spawn(|| panic!("worker shutdown failure"));
        let endpoint = WorkerEndpoint {
            command_tx: channel::unbounded().0,
            waker: Waker::noop().clone(),
            thread: ThreadBuilder::default().build(worker.thread().id()),
            blocking_worker: Worker::new(Pool::new(None), crate::runtime::shutdown::Shutdown::default(), PanicPolicy::Ignore),
        };
        let dispatcher = DispatcherClient::new(DispatcherCore::new(
            nonempty::NonEmpty::new(endpoint),
            crate::runtime::shutdown::Shutdown::default(),
        ));
        let runtime = Runtime::with_dispatcher(dispatcher, WorkerJoiner::new(vec![worker]));
        assert!(runtime.stop().unwrap_err().to_string().contains("panicked"));
    }

    #[test]
    fn authoritative_shutdown_failure_precedes_later_worker_panic() {
        let worker = thread::spawn(|| panic!("worker teardown failure"));
        let endpoint = WorkerEndpoint {
            command_tx: channel::unbounded().0,
            waker: Waker::noop().clone(),
            thread: ThreadBuilder::default().build(worker.thread().id()),
            blocking_worker: Worker::new(Pool::new(None), crate::runtime::shutdown::Shutdown::default(), PanicPolicy::Ignore),
        };
        let dispatcher = DispatcherClient::new(DispatcherCore::new(
            nonempty::NonEmpty::new(endpoint),
            crate::runtime::shutdown::Shutdown::default(),
        ));
        let runtime = Runtime::with_dispatcher(dispatcher.clone(), WorkerJoiner::new(vec![worker]));
        dispatcher.stop(Error::new(std::io::Error::other("first runtime failure")).into_shutdown_cause());

        assert_eq!(runtime.stop().unwrap_err().to_string(), "first runtime failure");
    }

    #[test]
    fn task_worker_stop_panics() {
        let runtime = single_worker_runtime();
        let joiner = runtime.worker_joiner.clone_for_test();
        let scheduler = worker_scheduler(&runtime);

        let error = scheduler.spawn(async move |_| runtime.stop()).join().unwrap_err();

        assert_programming_error(error, "Runtime::stop");
        joiner.join().unwrap();
    }

    #[test]
    fn ignored_task_worker_stop_skips_a_later_active_task() {
        let runtime = Runtime::builder()
            .workers(crate::runtime::WorkersPolicy::exactly(1))
            .panic(crate::runtime::PanicPolicy::ignore())
            .build()
            .unwrap();
        let joiner = runtime.worker_joiner.clone_for_test();
        let scheduler = worker_scheduler(&runtime);
        let (stopper_initialized, stopper_waker) = channel::unbounded();
        let (later_initialized, later_waker) = channel::unbounded();
        let invoked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let invoked_by_task = std::sync::Arc::clone(&invoked);
        let stopper = scheduler.spawn(move |_| {
            let mut runtime = Some(runtime);
            let mut initialized = Some(stopper_initialized);
            poll_fn(move |cx| {
                if let Some(initialized) = initialized.take() {
                    initialized.send(cx.waker().clone()).unwrap();
                    return Poll::<Result<(), Error>>::Pending;
                }
                runtime.take().unwrap().stop()?;
                Poll::Ready(Ok(()))
            })
        });
        let later = scheduler.spawn(move |_| {
            let mut initialized = Some(later_initialized);
            poll_fn(move |cx| {
                if let Some(initialized) = initialized.take() {
                    initialized.send(cx.waker().clone()).unwrap();
                    return Poll::Pending;
                }
                invoked_by_task.store(true, std::sync::atomic::Ordering::Release);
                Poll::Ready(())
            })
        });
        let stopper_waker = stopper_waker.recv().unwrap();
        let later_waker = later_waker.recv().unwrap();

        scheduler
            .spawn(move |_| async move {
                stopper_waker.wake_by_ref();
                later_waker.wake_by_ref();
            })
            .join()
            .unwrap();

        assert_programming_error(stopper.join().unwrap_err(), "Runtime::stop");
        assert!(later.join().unwrap_err().is_shutdown());
        assert!(!invoked.load(std::sync::atomic::Ordering::Acquire));
        joiner.join().unwrap();
    }

    #[test]
    fn ignored_task_worker_drop_skips_a_later_active_task() {
        let runtime = Runtime::builder()
            .workers(crate::runtime::WorkersPolicy::exactly(1))
            .panic(crate::runtime::PanicPolicy::ignore())
            .build()
            .unwrap();
        let joiner = runtime.worker_joiner.clone_for_test();
        let scheduler = worker_scheduler(&runtime);
        let (stopper_initialized, stopper_waker) = channel::unbounded();
        let (later_initialized, later_waker) = channel::unbounded();
        let invoked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let invoked_by_task = std::sync::Arc::clone(&invoked);
        let stopper = scheduler.spawn(move |_| {
            let mut runtime = Some(runtime);
            let mut initialized = Some(stopper_initialized);
            poll_fn(move |cx| {
                if let Some(initialized) = initialized.take() {
                    initialized.send(cx.waker().clone()).unwrap();
                    return Poll::Pending;
                }
                drop(runtime.take());
                Poll::Ready(())
            })
        });
        let later = scheduler.spawn(move |_| {
            let mut initialized = Some(later_initialized);
            poll_fn(move |cx| {
                if let Some(initialized) = initialized.take() {
                    initialized.send(cx.waker().clone()).unwrap();
                    return Poll::Pending;
                }
                invoked_by_task.store(true, std::sync::atomic::Ordering::Release);
                Poll::Ready(())
            })
        });
        let stopper_waker = stopper_waker.recv().unwrap();
        let later_waker = later_waker.recv().unwrap();

        scheduler
            .spawn(move |_| async move {
                stopper_waker.wake_by_ref();
                later_waker.wake_by_ref();
            })
            .join()
            .unwrap();

        assert_programming_error(stopper.join().unwrap_err(), "Runtime drop");
        assert!(later.join().unwrap_err().is_shutdown());
        assert!(!invoked.load(std::sync::atomic::Ordering::Acquire));
        joiner.join().unwrap();
    }

    #[test]
    fn blocking_worker_stop_panics() {
        let runtime = single_worker_runtime();
        let joiner = runtime.worker_joiner.clone_for_test();
        let scheduler = worker_scheduler(&runtime);

        let error = scheduler.spawn_blocking(move || runtime.stop()).join().unwrap_err();

        assert_programming_error(error, "Runtime::stop");
        joiner.join().unwrap();
    }

    #[test]
    fn task_worker_owner_drop_panics() {
        let runtime = single_worker_runtime();
        let joiner = runtime.worker_joiner.clone_for_test();
        let scheduler = worker_scheduler(&runtime);

        let error = scheduler.spawn(async move |_| drop(runtime)).join().unwrap_err();

        assert_programming_error(error, "Runtime drop");
        joiner.join().unwrap();
    }

    #[test]
    fn blocking_worker_owner_drop_panics() {
        let runtime = single_worker_runtime();
        let joiner = runtime.worker_joiner.clone_for_test();
        let scheduler = worker_scheduler(&runtime);

        let error = scheduler.spawn_blocking(move || drop(runtime)).join().unwrap_err();

        assert_programming_error(error, "Runtime drop");
        joiner.join().unwrap();
    }

    #[test]
    fn thread_local_shutdown_guard_survives_worker_slot_teardown() {
        thread::spawn(|| {
            let runtime = single_worker_runtime();
            let (control, scheduler) = runtime
                .scheduler()
                .block_on(async |cx| (cx.control().clone(), cx.scheduler().clone()))
                .unwrap();
            SHUTDOWN_GUARD.with(|guard| {
                assert!(guard.replace(Some(ShutdownGuard(control))).is_none());
            });
            scheduler.spawn(async |_| {}).join().unwrap();
            runtime.stop().unwrap();
        })
        .join()
        .unwrap();
    }

    fn assert_programming_error(error: JoinError, operation: &str) {
        assert!(error.is_panic());
        let panic = error.into_panic().expect("the join error was checked as a panic");
        let message = panic
            .downcast_ref::<String>()
            .map(String::as_str)
            .or_else(|| panic.downcast_ref::<&str>().copied())
            .expect("runtime ownership panic uses a string payload");
        assert!(message.contains(operation));
        assert!(message.contains("RuntimeControl::request_stop"));
    }

    fn worker_scheduler(runtime: &Runtime) -> crate::task::Scheduler {
        runtime
            .scheduler()
            .spawn_anywhere((), |cx, ()| async move { cx.scheduler().clone() })
            .join()
            .unwrap()
    }

    fn single_worker_runtime() -> Runtime {
        Runtime::builder()
            .workers(crate::runtime::WorkersPolicy::exactly(1))
            .blocking_pool(crate::runtime::BlockingPoolPolicy::shared().max(1))
            .build()
            .unwrap()
    }
}