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
#![doc = include_str!("../README.md")]
//!
//! ## Examples
//!
//! ### Tracing spans
//!
//! ```rust
#![doc = include_str!("../examples/context/mod.rs")]
//!
//! // Usage example
//!
//! async fn some_method(mut a: u64) -> u64 {
//!     TracerContext::on_enter(format!("`some_method` with params: a={a}"));
//!    
//!     // Some async computation
//!     
//!     TracerContext::on_exit("`some_method`");
//!     a * 32
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     let (trace, result) = TracerContext::in_scope(some_method(45)).await;
//!
//!     println!("answer: {result}");
//!     println!("trace: {trace:#?}");
//! }
//! ```
//!
//! [`tokio::task_local`]: https://docs.rs/tokio/latest/tokio/macro.task_local.html

use std::{fmt::Debug, future::Future};

use future::ScopedFutureWithValue;
use imp::FutureLocalKey;

pub mod future;
mod imp;

/// An init-once-per-future cell for thread-local values.
///
/// It uses thread local storage to ensure that the each polled future has its own local storage key.
/// Unlike the [`std::thread::LocalKey`] this cell will *not* lazily initialize the value on first access.
/// Instead, the value is first initialized when the future containing the future-local is first polled
/// by an executor.
///
/// After the execution finished the value moves from the future local cell to the future output.
pub struct FutureOnceCell<T>(imp::FutureLocalKey<T>);

impl<T> FutureOnceCell<T> {
    /// Creates an empty future once cell.
    #[must_use]
    pub const fn new() -> Self {
        Self(imp::FutureLocalKey::new())
    }
}

impl<T: Send + 'static> FutureOnceCell<T> {
    /// Acquires a reference to the value in this future local storage.
    ///
    /// Unlike the [`std::thread::LocalKey::with`] this method does not initialize the value
    /// when called.
    ///
    /// # Panics
    ///
    /// - This method will panic if the future local doesn't have a value set.
    ///
    /// - If you the returned future inside the a call to [`Self::with`] on the same cell, then the
    ///   call to `poll` will panic.
    #[inline]
    pub fn with<F, R>(&'static self, f: F) -> R
    where
        F: FnOnce(&T) -> R,
    {
        let value = self.0.local_key().borrow();
        f(value
            .as_ref()
            .expect("cannot access a future local value without setting it first"))
    }

    /// Returns a copy of the contained value.
    ///
    /// # Panics
    ///
    /// This method will panic if the future local doesn't have a value set.
    #[inline]
    pub fn get(&'static self) -> T
    where
        T: Copy,
    {
        self.0.local_key().borrow().unwrap()
    }

    /// Sets a value `T` as the future-local value for the future `F`.
    ///
    /// On completion of `scope`, the future-local value will be returned by the scoped future.
    ///
    /// ```rust
    /// use std::cell::Cell;
    ///
    /// use future_local_storage::FutureOnceCell;
    ///
    /// static VALUE: FutureOnceCell<Cell<u64>> = FutureOnceCell::new();
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let (output, answer) = VALUE.scope(Cell::from(0), async {
    ///         VALUE.with(|x| {
    ///             let value = x.get();
    ///             x.set(value + 1);
    ///         });
    ///
    ///         42
    ///     }).await;
    /// }
    /// ```
    #[inline]
    pub fn scope<F>(&'static self, value: T, future: F) -> ScopedFutureWithValue<T, F>
    where
        F: Future,
    {
        future.with_scope(self, value)
    }
}

impl<T: Debug + Send + 'static> Debug for FutureOnceCell<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("FutureOnceCell").field(&self.0).finish()
    }
}

impl<T> AsRef<FutureLocalKey<T>> for FutureOnceCell<T> {
    fn as_ref(&self) -> &FutureLocalKey<T> {
        &self.0
    }
}

/// Attaches future local storage values to a [`Future`].
///
/// Extension trait allowing futures to have their own static variables.
pub trait FutureLocalStorage: Future + Sized + private::Sealed {
    /// Sets a given value as the future local value of this future.
    ///
    /// Each future instance will have its own state of the attached value.
    ///
    /// ```rust
    /// use std::cell::Cell;
    ///
    /// use future_local_storage::{FutureOnceCell, FutureLocalStorage};
    ///
    /// static VALUE: FutureOnceCell<Cell<u64>> = FutureOnceCell::new();
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let (output, answer) = async {
    ///         VALUE.with(|x| {
    ///             let value = x.get();
    ///             x.set(value + 1);
    ///         });
    ///         
    ///         42
    ///     }.with_scope(&VALUE, Cell::from(0)).await;
    /// }
    /// ```
    fn with_scope<T, S>(self, scope: &'static S, value: T) -> ScopedFutureWithValue<T, Self>
    where
        T: Send,
        S: AsRef<FutureLocalKey<T>>;
}

mod private {
    use std::future::Future;

    pub trait Sealed {}

    impl<F: Future> Sealed for F {}
}

#[cfg(test)]
mod tests {
    use std::cell::{Cell, RefCell};

    use pretty_assertions::assert_eq;

    use super::*;
    use crate::FutureLocalStorage;

    #[test]
    fn test_once_cell_without_future() {
        static LOCK: FutureOnceCell<RefCell<String>> = FutureOnceCell::new();
        LOCK.0
            .local_key()
            .borrow_mut()
            .replace(RefCell::new("0".to_owned()));

        assert_eq!(LOCK.with(|x| x.borrow().clone()), "0".to_owned());
        LOCK.with(|x| x.replace("42".to_owned()));
        assert_eq!(LOCK.with(|x| x.borrow().clone()), "42".to_owned());
    }

    #[tokio::test]
    async fn test_future_once_cell_output() {
        static VALUE: FutureOnceCell<Cell<u64>> = FutureOnceCell::new();

        let (output, ()) = VALUE
            .scope(Cell::from(0), async {
                VALUE.with(|x| {
                    let value = x.get();
                    x.set(value + 1);
                });
            })
            .await;

        assert_eq!(output.into_inner(), 1);
    }

    #[tokio::test]
    async fn test_future_once_cell_discard_value() {
        static VALUE: FutureOnceCell<Cell<u64>> = FutureOnceCell::new();

        let fut_1 = async {
            for _ in 0..42 {
                VALUE.with(|x| {
                    let value = x.get();
                    x.set(value + 1);
                });
                tokio::task::yield_now().await;
            }

            VALUE.with(Cell::get)
        }
        .with_scope(&VALUE, Cell::new(0))
        .discard_value();

        let fut_2 = async { VALUE.with(Cell::get) }
            .with_scope(&VALUE, Cell::new(15))
            .discard_value();

        assert_eq!(fut_1.await, 42);
        assert_eq!(fut_2.await, 15);
        assert_eq!(
            tokio::spawn(
                async { VALUE.with(Cell::get) }
                    .with_scope(&VALUE, Cell::new(115))
                    .discard_value()
            )
            .await
            .unwrap(),
            115
        );
    }
}