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
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use crate::Hub;
#[derive(Debug)]
pub struct SentryFuture<F> {
hub: Arc<Hub>,
future: F,
}
impl<F> SentryFuture<F> {
pub fn new(hub: Arc<Hub>, future: F) -> Self {
Self { hub, future }
}
}
impl<F> Future for SentryFuture<F>
where
F: Future,
{
type Output = F::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let hub = self.hub.clone();
let future = unsafe { self.map_unchecked_mut(|s| &mut s.future) };
#[cfg(feature = "client")]
{
Hub::run(hub, || future.poll(cx))
}
#[cfg(not(feature = "client"))]
{
let _ = hub;
future.poll(cx)
}
}
}
pub trait SentryFutureExt: Sized {
fn bind_hub<H>(self, hub: H) -> SentryFuture<Self>
where
H: Into<Arc<Hub>>,
{
SentryFuture {
future: self,
hub: hub.into(),
}
}
}
impl<F> SentryFutureExt for F where F: Future {}
#[cfg(all(test, feature = "test"))]
mod tests {
use crate::test::with_captured_events;
use crate::{capture_message, configure_scope, Hub, Level, SentryFutureExt};
use tokio::runtime::Runtime;
#[test]
fn test_futures() {
let mut events = with_captured_events(|| {
let runtime = Runtime::new().unwrap();
runtime.block_on(async {
let task1 = async {
configure_scope(|scope| scope.set_transaction(Some("transaction1")));
capture_message("oh hai from 1", Level::Info);
}
.bind_hub(Hub::new_from_top(Hub::current()));
let task1 = tokio::task::spawn(task1);
let task2 = async {
configure_scope(|scope| scope.set_transaction(Some("transaction2")));
capture_message("oh hai from 2", Level::Info);
}
.bind_hub(Hub::new_from_top(Hub::current()));
let task2 = tokio::task::spawn(task2);
task1.await.unwrap();
task2.await.unwrap();
});
capture_message("oh hai from outside", Level::Info);
});
events.sort_by(|a, b| a.transaction.cmp(&b.transaction));
assert_eq!(events.len(), 3);
assert_eq!(events[1].transaction, Some("transaction1".into()));
assert_eq!(events[2].transaction, Some("transaction2".into()));
}
}