#![cfg_attr(not(feature = "boxed"), feature(type_alias_impl_trait))]
#![cfg_attr(test, feature(exit_status_error))]
extern crate self as async_local;
#[cfg(not(loom))]
use std::thread::LocalKey;
#[cfg(loom)]
use std::thread::LocalKey;
use std::{future::Future, marker::PhantomData, ops::Deref, ptr::addr_of};
pub use derive_async_local::AsContext;
use shutdown_barrier::{guard_thread_shutdown, suspend_until_shutdown};
pub struct Context<T: Sync>(T);
impl<T> Context<T>
where
T: Sync,
{
pub fn new(inner: T) -> Context<T> {
Context(inner)
}
}
impl<T> AsRef<Context<T>> for Context<T>
where
T: Sync,
{
fn as_ref(&self) -> &Context<T> {
self
}
}
impl<T> Deref for Context<T>
where
T: Sync,
{
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> Drop for Context<T>
where
T: Sync,
{
fn drop(&mut self) {
suspend_until_shutdown();
}
}
pub unsafe trait AsContext: AsRef<Context<Self::Target>> {
type Target: Sync;
}
unsafe impl<T> AsContext for Context<T>
where
T: Sync,
{
type Target = T;
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct LocalRef<T: Sync + 'static>(*const Context<T>);
impl<T> LocalRef<T>
where
T: Sync + 'static,
{
unsafe fn new(context: &Context<T>) -> Self {
guard_thread_shutdown();
LocalRef(addr_of!(*context))
}
pub unsafe fn guarded_ref<'a>(&self) -> RefGuard<'a, T> {
RefGuard {
inner: self.0,
_marker: PhantomData,
}
}
}
impl<T> Deref for LocalRef<T>
where
T: Sync,
{
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { (*self.0).deref() }
}
}
impl<T> Clone for LocalRef<T>
where
T: Sync + 'static,
{
fn clone(&self) -> Self {
LocalRef(self.0)
}
}
impl<T> Copy for LocalRef<T> where T: Sync + 'static {}
unsafe impl<T> Send for LocalRef<T> where T: Sync {}
unsafe impl<T> Sync for LocalRef<T> where T: Sync {}
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct RefGuard<'a, T: Sync + 'static> {
inner: *const Context<T>,
_marker: PhantomData<fn(&'a ()) -> &'a ()>,
}
impl<'a, T> RefGuard<'a, T>
where
T: Sync + 'static,
{
unsafe fn new(context: &Context<T>) -> Self {
guard_thread_shutdown();
RefGuard {
inner: addr_of!(*context),
_marker: PhantomData,
}
}
}
impl<'a, T> Deref for RefGuard<'a, T>
where
T: Sync,
{
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { (*self.inner).deref() }
}
}
impl<'a, T> Clone for RefGuard<'a, T>
where
T: Sync + 'static,
{
fn clone(&self) -> Self {
RefGuard {
inner: self.inner,
_marker: PhantomData,
}
}
}
impl<'a, T> Copy for RefGuard<'a, T> where T: Sync + 'static {}
unsafe impl<'a, T> Send for RefGuard<'a, T> where T: Sync {}
unsafe impl<'a, T> Sync for RefGuard<'a, T> where T: Sync {}
#[async_t::async_trait]
pub trait AsyncLocal<T>
where
T: 'static + AsContext,
{
async fn with_async<F, R, Fut>(&'static self, f: F) -> R
where
F: FnOnce(RefGuard<'async_trait, T::Target>) -> Fut + Send,
Fut: Future<Output = R> + Send;
unsafe fn local_ref(&'static self) -> LocalRef<T::Target>;
unsafe fn guarded_ref<'a>(&'static self) -> RefGuard<'a, T::Target>;
}
#[async_t::async_trait]
impl<T> AsyncLocal<T> for LocalKey<T>
where
T: AsContext,
{
async fn with_async<F, R, Fut>(&'static self, f: F) -> R
where
F: FnOnce(RefGuard<'async_trait, T::Target>) -> Fut + Send,
Fut: Future<Output = R> + Send,
{
let local_ref = unsafe { self.guarded_ref() };
f(local_ref).await
}
unsafe fn local_ref(&'static self) -> LocalRef<T::Target> {
self.with(|value| LocalRef::new(value.as_ref()))
}
unsafe fn guarded_ref<'a>(&'static self) -> RefGuard<'a, T::Target> {
self.with(|value| RefGuard::new(value.as_ref()))
}
}
#[cfg(all(test, not(loom)))]
mod tests {
use std::{
io,
process::{Command, Stdio},
sync::atomic::{AtomicUsize, Ordering},
};
use tokio::task::yield_now;
use super::*;
thread_local! {
static COUNTER: Context<AtomicUsize> = Context::new(AtomicUsize::new(0));
}
#[tokio::test(flavor = "multi_thread")]
async fn ref_spans_await() {
let counter = unsafe { COUNTER.local_ref() };
yield_now().await;
counter.deref().fetch_add(1, Ordering::Relaxed);
}
#[tokio::test(flavor = "multi_thread")]
async fn with_async() {
COUNTER
.with_async(|counter| async move {
yield_now().await;
counter.fetch_add(1, Ordering::Release);
})
.await;
}
#[tokio::test(flavor = "multi_thread")]
async fn bound_to_async_trait_lifetime() {
struct Counter;
#[async_t::async_trait]
trait Countable {
async fn add_one(ref_guard: RefGuard<'async_trait, AtomicUsize>) -> usize;
}
#[async_t::async_trait]
impl Countable for Counter {
async fn add_one(counter: RefGuard<'async_trait, AtomicUsize>) -> usize {
yield_now().await;
counter.fetch_add(1, Ordering::Release)
}
}
let counter = unsafe { COUNTER.guarded_ref() };
Counter::add_one(counter).await;
}
#[test]
fn tokio_safely_shuts_down() -> io::Result<()> {
Command::new("cargo")
.args(["run", "-p", "doomsday-clock"])
.stdout(Stdio::null())
.spawn()?
.wait()?
.exit_ok()
.expect("tokio failed to shutdown doomsday-clock");
Ok(())
}
#[test]
fn async_std_safely_shuts_down() -> io::Result<()> {
Command::new("cargo")
.args([
"run",
"-p",
"doomsday-clock",
"--no-default-features",
"--features",
"async-std-runtime",
])
.stdout(Stdio::null())
.spawn()?
.wait()?
.exit_ok()
.expect("async-std failed to shutdown doomsday-clock");
Ok(())
}
#[ignore]
#[test]
fn smol_safely_shuts_down() -> io::Result<()> {
Command::new("cargo")
.args([
"run",
"-p",
"doomsday-clock",
"--no-default-features",
"--features",
"smol-runtime",
])
.stdout(Stdio::null())
.spawn()?
.wait()?
.exit_ok()
.expect("smol to failed to shutdown doomsday-clock");
Ok(())
}
}