-
-
Notifications
You must be signed in to change notification settings - Fork 188
feat(core): Stream extension trait #1214
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
lcian
wants to merge
7
commits into
master
Choose a base branch
from
lcian/feat/stream-ext
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+142
−1
Draft
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
abe6c9c
feat: futures::Stream extension
lcian 8af241c
Merge branch 'master' into lcian/feat/stream-ext
lcian 6c52b02
improve
lcian dc753c9
improve
lcian 52a238e
improve
lcian 0f6454c
Merge branch 'master' into lcian/feat/stream-ext
lcian ea7d7cf
Merge branch 'master' into lcian/feat/stream-ext
lcian File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| use std::pin::Pin; | ||
| use std::sync::Arc; | ||
| use std::task::{Context, Poll}; | ||
|
|
||
| use futures_core::Stream; | ||
|
|
||
| use crate::Hub; | ||
|
|
||
| /// A stream that binds a `Hub` to its polling. | ||
| /// | ||
| /// This activates the given hub for the duration of the inner stream's `poll_next` | ||
| /// method. Users usually do not need to construct this type manually, but | ||
| /// rather use the [`StreamExt::bind_hub`] method instead. | ||
| /// | ||
| /// [`StreamExt::bind_hub`]: trait.StreamExt.html#method.bind_hub | ||
| #[derive(Debug)] | ||
| pub struct SentryStream<S> { | ||
| hub: Arc<Hub>, | ||
| stream: S, | ||
| } | ||
|
|
||
| impl<S> SentryStream<S> { | ||
| /// Creates a new bound stream with a `Hub`. | ||
| pub fn new(hub: Arc<Hub>, stream: S) -> Self { | ||
| Self { hub, stream } | ||
| } | ||
| } | ||
|
|
||
| impl<S> Stream for SentryStream<S> | ||
| where | ||
| S: Stream, | ||
| { | ||
| type Item = S::Item; | ||
|
|
||
| fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { | ||
| let hub = self.hub.clone(); | ||
| // https://doc.rust-lang.org/std/pin/index.html#pinning-is-structural-for-field | ||
| let stream = unsafe { self.map_unchecked_mut(|s| &mut s.stream) }; | ||
| #[cfg(feature = "client")] | ||
| { | ||
| let _guard = crate::hub_impl::SwitchGuard::new(hub); | ||
| stream.poll_next(cx) | ||
| } | ||
| #[cfg(not(feature = "client"))] | ||
| { | ||
| let _ = hub; | ||
| stream.poll_next(cx) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Stream extensions for Sentry. | ||
| pub trait SentryStreamExt: Sized { | ||
| /// Binds a hub to this stream. | ||
| /// | ||
| /// This ensures that the stream is polled within the given hub. | ||
| fn bind_hub<H>(self, hub: H) -> SentryStream<Self> | ||
| where | ||
| H: Into<Arc<Hub>>, | ||
| { | ||
| SentryStream { | ||
| stream: self, | ||
| hub: hub.into(), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<S> SentryStreamExt for S where S: Stream {} | ||
|
|
||
| #[cfg(all(test, feature = "test"))] | ||
| mod tests { | ||
| use crate::test::with_captured_events; | ||
| use crate::{capture_error, capture_message, configure_scope, Hub, Level, SentryStreamExt}; | ||
| use futures::StreamExt; | ||
| use tokio::runtime::Runtime; | ||
|
|
||
| #[derive(Debug)] | ||
| struct TestError(&'static str); | ||
|
|
||
| impl std::fmt::Display for TestError { | ||
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| write!(f, "{}", self.0) | ||
| } | ||
| } | ||
|
|
||
| impl std::error::Error for TestError {} | ||
|
|
||
| #[test] | ||
| fn test_streams() { | ||
| let mut events = with_captured_events(|| { | ||
| let runtime = Runtime::new().unwrap(); | ||
|
|
||
| // Two real streams, each bound to its own hub. The work inside each | ||
| // stream runs during `poll_next`, so the captured errors must end up | ||
| // tagged with the scope of the hub the stream was bound to. | ||
| runtime.block_on(async { | ||
| let stream1 = futures::stream::once(async { | ||
| configure_scope(|scope| scope.set_transaction(Some("transaction1"))); | ||
| capture_error(&TestError("oh no from 1")); | ||
| }) | ||
| .bind_hub(Hub::new_from_top(Hub::current())); | ||
|
|
||
| let stream2 = futures::stream::once(async { | ||
| configure_scope(|scope| scope.set_transaction(Some("transaction2"))); | ||
| capture_error(&TestError("oh no from 2")); | ||
| }) | ||
| .bind_hub(Hub::new_from_top(Hub::current())); | ||
|
|
||
| stream1.collect::<Vec<_>>().await; | ||
| stream2.collect::<Vec<_>>().await; | ||
| }); | ||
|
|
||
| capture_message("oh hai from outside", Level::Info); | ||
| }); | ||
|
|
||
| events.sort_by(|a, b| a.transaction.cmp(&b.transaction)); | ||
| assert_eq!(events.len(), 3); | ||
|
|
||
| // The message captured outside any bound stream has no transaction and no | ||
| // exception, and sorts first. | ||
| assert_eq!(events[0].transaction, None); | ||
| assert!(events[0].exception.is_empty()); | ||
|
|
||
| // The errors captured inside `poll_next` carry the scope of their bound | ||
| // hub and the expected exception payload. | ||
| assert_eq!(events[1].transaction, Some("transaction1".into())); | ||
| assert_eq!(events[1].exception[0].value, Some("oh no from 1".into())); | ||
| assert_eq!(events[2].transaction, Some("transaction2".into())); | ||
| assert_eq!(events[2].exception[0].value, Some("oh no from 2".into())); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It is possible to avoid this direct usage of
unsafe(and the one inSentryFuture) by adding a dependency topin-project-lite.