utopia_span/storage.rs
1//! Where the current span is kept.
2
3use std::cell::RefCell;
4use std::future::Future;
5use std::sync::Mutex;
6
7use crate::Span;
8
9/// Keeps the current span of an execution context, so [`Span::add`] and
10/// [`Span::current`] work without passing spans around.
11///
12/// Implement it to keep spans elsewhere (a thread-local, a request
13/// extension); register it with [`Span::set_storage`].
14///
15/// PHP: `Utopia\Span\Storage\Storage`.
16pub trait Storage: Send + Sync {
17 /// The current span of this context, if any.
18 ///
19 /// PHP: `get()`.
20 fn get(&self) -> Option<Span>;
21
22 /// Sets (or clears, with `None`) the current span of this context.
23 ///
24 /// PHP: `set($span)`.
25 fn set(&self, span: Option<Span>);
26}
27
28/// One current span for the whole process.
29///
30/// PHP: `Utopia\Span\Storage\Memory`, for FPM and CLI processes that handle
31/// one request at a time.
32///
33/// ```
34/// use utopia_span::{Memory, Span, Storage};
35///
36/// let storage = Memory::new();
37/// assert!(storage.get().is_none());
38///
39/// let span = Span::new("job");
40/// storage.set(Some(span.clone()));
41/// assert_eq!(storage.get(), Some(span));
42/// storage.set(None);
43/// assert!(storage.get().is_none());
44/// ```
45///
46/// ```php
47/// use Utopia\Span\Span;
48/// use Utopia\Span\Storage\Memory;
49///
50/// $storage = new Memory();
51/// var_dump($storage->get()); // NULL
52///
53/// $span = new Span('job');
54/// $storage->set($span);
55/// var_dump($storage->get() === $span); // bool(true)
56/// $storage->set(null);
57/// var_dump($storage->get()); // NULL
58/// ```
59#[derive(Debug, Default)]
60pub struct Memory {
61 span: Mutex<Option<Span>>,
62}
63
64impl Memory {
65 /// An empty storage.
66 ///
67 /// PHP: `new Memory()`.
68 pub fn new() -> Self {
69 Self::default()
70 }
71}
72
73impl Storage for Memory {
74 fn get(&self) -> Option<Span> {
75 self.span.lock().unwrap_or_else(|e| e.into_inner()).clone()
76 }
77
78 fn set(&self, span: Option<Span>) {
79 *self.span.lock().unwrap_or_else(|e| e.into_inner()) = span;
80 }
81}
82
83tokio::task_local! {
84 static CURRENT: RefCell<Option<Span>>;
85}
86
87/// One current span per task.
88///
89/// A task gets its own slot by running inside [`Task::scope`]; outside a
90/// scope there is no current span and [`Storage::set`] does nothing.
91///
92/// PHP: `Utopia\Span\Storage\Coroutine`, which keeps the span in the Swoole
93/// coroutine's context (`Coroutine::getContext()`); a scope is a coroutine.
94///
95/// ```
96/// use utopia_span::{Span, Storage, Task};
97///
98/// # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
99/// let storage = Task::new();
100/// storage.set(Some(Span::new("ignored")));
101/// assert!(storage.get().is_none()); // outside a scope
102///
103/// Task::scope(async {
104/// let storage = Task::new();
105/// let span = Span::new("request");
106/// storage.set(Some(span.clone()));
107/// assert_eq!(storage.get(), Some(span));
108/// })
109/// .await;
110/// # });
111/// ```
112///
113/// ```php
114/// use Utopia\Span\Span;
115/// use Utopia\Span\Storage\Coroutine;
116///
117/// $storage = new Coroutine();
118/// $storage->set(new Span('ignored'));
119/// var_dump($storage->get()); // NULL: outside a coroutine
120///
121/// \Swoole\Coroutine\run(function () {
122/// $storage = new Coroutine();
123/// $span = new Span('request');
124/// $storage->set($span);
125/// var_dump($storage->get() === $span); // bool(true)
126/// });
127/// ```
128#[derive(Debug, Default, Clone, Copy)]
129pub struct Task;
130
131impl Task {
132 /// The task storage.
133 ///
134 /// PHP: `new Coroutine()`.
135 pub fn new() -> Self {
136 Task
137 }
138
139 /// Runs `future` with its own current-span slot, initially empty.
140 ///
141 /// PHP: running code in a new Swoole coroutine.
142 pub fn scope<F: Future>(future: F) -> impl Future<Output = F::Output> {
143 CURRENT.scope(RefCell::new(None), future)
144 }
145
146 /// Runs `f` synchronously with its own current-span slot.
147 pub fn sync_scope<R>(f: impl FnOnce() -> R) -> R {
148 CURRENT.sync_scope(RefCell::new(None), f)
149 }
150
151 /// Whether the caller runs inside a [`Task::scope`].
152 ///
153 /// PHP: `Coroutine::getCid() !== -1`.
154 pub fn in_scope() -> bool {
155 CURRENT.try_with(|_| ()).is_ok()
156 }
157}
158
159impl Storage for Task {
160 fn get(&self) -> Option<Span> {
161 CURRENT.try_with(|c| c.borrow().clone()).ok().flatten()
162 }
163
164 fn set(&self, span: Option<Span>) {
165 let _ = CURRENT.try_with(|c| *c.borrow_mut() = span);
166 }
167}
168
169/// The task's span inside a [`Task::scope`], the process's span outside.
170///
171/// PHP: `Utopia\Span\Storage\Auto`, which uses the coroutine storage inside
172/// a Swoole coroutine and the memory storage elsewhere.
173///
174/// ```
175/// use utopia_span::{Auto, Span, Storage};
176///
177/// let storage = Auto::new();
178/// let span = Span::new("cli");
179/// storage.set(Some(span.clone()));
180/// assert_eq!(storage.get(), Some(span));
181/// ```
182///
183/// ```php
184/// use Utopia\Span\Span;
185/// use Utopia\Span\Storage\Auto;
186///
187/// $storage = new Auto();
188/// $span = new Span('cli');
189/// $storage->set($span);
190/// var_dump($storage->get() === $span); // bool(true)
191/// ```
192#[derive(Debug, Default)]
193pub struct Auto {
194 memory: Memory,
195}
196
197impl Auto {
198 /// An empty storage.
199 ///
200 /// PHP: `new Auto()`.
201 pub fn new() -> Self {
202 Self::default()
203 }
204}
205
206impl Storage for Auto {
207 fn get(&self) -> Option<Span> {
208 match CURRENT.try_with(|c| c.borrow().clone()) {
209 Ok(span) => span,
210 Err(_) => self.memory.get(),
211 }
212 }
213
214 fn set(&self, span: Option<Span>) {
215 if let Err(_outside) = CURRENT.try_with(|c| *c.borrow_mut() = span.clone()) {
216 self.memory.set(span);
217 }
218 }
219}