Skip to main content

sentry_tower/
lib.rs

1//! Adds support for automatic hub binding for each request received by the Tower server (or client,
2//! though usefulness is limited in this case).
3//!
4//! This allows breadcrumbs collected during the request handling to land in a specific hub, and
5//! avoid having them mixed across requests should a new hub be bound at each request.
6//!
7//! # Examples
8//!
9//! ```rust
10//! # use tower::ServiceBuilder;
11//! # use std::time::Duration;
12//! # type Request = String;
13//! use sentry_tower::NewSentryLayer;
14//!
15//! // Compose a Tower service where each request gets its own Sentry hub
16//! let service = ServiceBuilder::new()
17//!     .layer(NewSentryLayer::<Request>::new_from_top())
18//!     .timeout(Duration::from_secs(30))
19//!     .service(tower::service_fn(|req: Request| format!("hello {}", req)));
20//! ```
21//!
22//! More customization can be achieved through the `new` function, such as passing a [`Hub`]
23//! directly.
24//!
25//! ```rust
26//! # use tower::ServiceBuilder;
27//! # use std::{sync::Arc, time::Duration};
28//! # type Request = String;
29//! use sentry::Hub;
30//! use sentry_tower::SentryLayer;
31//!
32//! // Create a hub dedicated to web requests
33//! let hub = Arc::new(Hub::with(|hub| Hub::new_from_top(hub)));
34//!
35//! // Compose a Tower service
36//! let service = ServiceBuilder::new()
37//!     .layer(SentryLayer::<_, _, Request>::new(hub))
38//!     .timeout(Duration::from_secs(30))
39//!     .service(tower::service_fn(|req: Request| format!("hello {}", req)));
40//! ```
41//!
42//! The layer can also accept a closure to return a hub depending on the incoming request.
43//!
44//! ```rust
45//! # use tower::ServiceBuilder;
46//! # use std::{sync::Arc, time::Duration};
47//! # type Request = String;
48//! use sentry::Hub;
49//! use sentry_tower::SentryLayer;
50//!
51//! // Compose a Tower service
52//! let hello = Arc::new(Hub::with(|hub| Hub::new_from_top(hub)));
53//! let other = Arc::new(Hub::with(|hub| Hub::new_from_top(hub)));
54//!
55//! let service = ServiceBuilder::new()
56//!     .layer(SentryLayer::new(|req: &Request| match req.as_str() {
57//!         "hello" => hello.clone(),
58//!         _ => other.clone(),
59//!     }))
60//!     .timeout(Duration::from_secs(30))
61//!     .service(tower::service_fn(|req: Request| format!("{} world", req)));
62//! ```
63//!
64//! When using Tonic, the layer can be used directly by the Tonic stack:
65//!
66//! ```rust,no_run
67//! # use anyhow::{anyhow, Result};
68//! # use sentry_anyhow::capture_anyhow;
69//! # use tonic::{Request, Response, Status, transport::Server};
70//! # mod hello_world {
71//! #     include!("helloworld.rs");
72//! # }
73//! use hello_world::{greeter_server::*, *};
74//! use sentry_tower::NewSentryLayer;
75//!
76//! struct GreeterService;
77//!
78//! #[tonic::async_trait]
79//! impl Greeter for GreeterService {
80//!     async fn say_hello(
81//!         &self,
82//!         req: Request<HelloRequest>,
83//!     ) -> Result<Response<HelloReply>, Status> {
84//!         let HelloRequest { name } = req.into_inner();
85//!         if name == "world" {
86//!             capture_anyhow(&anyhow!("Trying to greet a planet"));
87//!             return Err(Status::invalid_argument("Cannot greet a planet"));
88//!         }
89//!         Ok(Response::new(HelloReply {
90//!             message: format!("Hello {}", name),
91//!         }))
92//!     }
93//! }
94//!
95//! # #[tokio::main]
96//! # async fn main() -> Result<()> {
97//! Server::builder()
98//!     .layer(NewSentryLayer::new_from_top())
99//!     .add_service(GreeterServer::new(GreeterService))
100//!     .serve("127.0.0.1:50051".parse().unwrap())
101//!     .await?;
102//! #     Ok(())
103//! # }
104//! ```
105//!
106//! ## Usage with `tower-http`
107//!
108//! The `http` feature of the `sentry-tower` crate offers another layer which will attach
109//! request details onto captured events, and optionally start a new performance monitoring
110//! transaction based on the incoming HTTP headers.  When using the tower integration via
111//! `sentry::integrations::tower`, this feature can also be enabled using the `tower-http`
112//! feature of the `sentry` crate instead of the `tower` feature.
113//!
114//! The created transaction will automatically use the request URI as its name.
115//! This is sometimes not desirable in case the request URI contains unique IDs
116//! or similar. In this case, users should manually override the transaction name
117//! in the request handler using the [`Scope::set_transaction`](sentry_core::Scope::set_transaction)
118//! method.
119//!
120//! When combining both layers, take care of the ordering of both. For example
121//! with [`tower::ServiceBuilder`], always define the `Hub` layer before the `Http`
122//! one, like so:
123//!
124//! ```rust
125//! # #[cfg(feature = "http")] {
126//! # type Request = http::Request<String>;
127//! let layer = tower::ServiceBuilder::new()
128//!     .layer(sentry_tower::NewSentryLayer::<Request>::new_from_top())
129//!     .layer(sentry_tower::SentryHttpLayer::new().enable_transaction());
130//! # }
131//! ```
132//!
133//! When using `axum`, either use [`tower::ServiceBuilder`] as shown above, or make sure you
134//! reorder the layers, like so:
135//!
136//! ```ignore
137//! let app = Router::new()
138//!     .route("/", get(handler))
139//!     .layer(sentry_tower::SentryHttpLayer::new().enable_transaction())
140//!     .layer(sentry_tower::NewSentryLayer::<Request>::new_from_top())
141//! ```
142//!
143//! This is because `axum` applies middleware in the opposite order as [`tower::ServiceBuilder`].
144//! Applying the layers in the wrong order can result in memory leaks.
145//!
146//! [`tower::ServiceBuilder`]: https://docs.rs/tower/latest/tower/struct.ServiceBuilder.html
147
148#![doc(html_favicon_url = "https://sentry-brand.storage.googleapis.com/favicon.ico")]
149#![doc(html_logo_url = "https://sentry-brand.storage.googleapis.com/sentry-glyph-black.png")]
150
151use std::marker::PhantomData;
152use std::sync::Arc;
153use std::task::{Context, Poll};
154
155use sentry_core::{Hub, SentryFuture, SentryFutureExt};
156use tower_layer::Layer;
157use tower_service::Service;
158
159#[cfg(feature = "http")]
160mod http;
161#[cfg(feature = "http")]
162pub use crate::http::*;
163
164/// Provides a hub for each request
165pub trait HubProvider<H, Request>
166where
167    H: Into<Arc<Hub>>,
168{
169    /// Returns a hub to be bound to the request
170    fn hub(&self, request: &Request) -> H;
171}
172
173impl<H, F, Request> HubProvider<H, Request> for F
174where
175    F: Fn(&Request) -> H,
176    H: Into<Arc<Hub>>,
177{
178    fn hub(&self, request: &Request) -> H {
179        (self)(request)
180    }
181}
182
183impl<Request> HubProvider<Arc<Hub>, Request> for Arc<Hub> {
184    fn hub(&self, _request: &Request) -> Arc<Hub> {
185        self.clone()
186    }
187}
188
189/// Provides a new hub made from the currently active hub for each request
190#[derive(Clone, Copy)]
191pub struct NewFromTopProvider;
192
193impl<Request> HubProvider<Arc<Hub>, Request> for NewFromTopProvider {
194    fn hub(&self, _request: &Request) -> Arc<Hub> {
195        Hub::new_from_top(Hub::current()).into()
196    }
197}
198
199/// Tower layer that binds a specific Sentry hub for each request made.
200pub struct SentryLayer<P, H, Request>
201where
202    P: HubProvider<H, Request>,
203    H: Into<Arc<Hub>>,
204{
205    provider: P,
206    _hub: PhantomData<(H, fn() -> Request)>,
207}
208
209impl<S, P, H, Request> Layer<S> for SentryLayer<P, H, Request>
210where
211    P: HubProvider<H, Request> + Clone,
212    H: Into<Arc<Hub>>,
213{
214    type Service = SentryService<S, P, H, Request>;
215
216    fn layer(&self, service: S) -> Self::Service {
217        SentryService {
218            service,
219            provider: self.provider.clone(),
220            _hub: PhantomData,
221        }
222    }
223}
224
225impl<P, H, Request> Clone for SentryLayer<P, H, Request>
226where
227    P: HubProvider<H, Request> + Clone,
228    H: Into<Arc<Hub>>,
229{
230    fn clone(&self) -> Self {
231        Self {
232            provider: self.provider.clone(),
233            _hub: PhantomData,
234        }
235    }
236}
237
238impl<P, H, Request> SentryLayer<P, H, Request>
239where
240    P: HubProvider<H, Request> + Clone,
241    H: Into<Arc<Hub>>,
242{
243    /// Build a new layer with the given Layer provider
244    pub fn new(provider: P) -> Self {
245        Self {
246            provider,
247            _hub: PhantomData,
248        }
249    }
250}
251
252/// Tower service that binds a specific Sentry hub for each request made.
253pub struct SentryService<S, P, H, Request>
254where
255    P: HubProvider<H, Request>,
256    H: Into<Arc<Hub>>,
257{
258    service: S,
259    provider: P,
260    _hub: PhantomData<(H, fn() -> Request)>,
261}
262
263impl<S, Request, P, H> Service<Request> for SentryService<S, P, H, Request>
264where
265    S: Service<Request>,
266    P: HubProvider<H, Request>,
267    H: Into<Arc<Hub>>,
268{
269    type Response = S::Response;
270    type Error = S::Error;
271    type Future = SentryFuture<S::Future>;
272
273    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
274        self.service.poll_ready(cx)
275    }
276
277    fn call(&mut self, request: Request) -> Self::Future {
278        let hub = self.provider.hub(&request).into();
279        let fut = Hub::run(hub.clone(), || self.service.call(request));
280        fut.bind_hub(hub)
281    }
282}
283
284impl<S, P, H, Request> Clone for SentryService<S, P, H, Request>
285where
286    S: Clone,
287    P: HubProvider<H, Request> + Clone,
288    H: Into<Arc<Hub>>,
289{
290    fn clone(&self) -> Self {
291        Self {
292            service: self.service.clone(),
293            provider: self.provider.clone(),
294            _hub: PhantomData,
295        }
296    }
297}
298
299impl<S, P, H, Request> SentryService<S, P, H, Request>
300where
301    P: HubProvider<H, Request> + Clone,
302    H: Into<Arc<Hub>>,
303{
304    /// Wrap a Tower service with a Tower layer that binds a Sentry hub for each request made.
305    pub fn new(provider: P, service: S) -> Self {
306        SentryLayer::<P, H, Request>::new(provider).layer(service)
307    }
308}
309
310/// Tower layer that binds a new Sentry hub for each request made
311pub type NewSentryLayer<Request> = SentryLayer<NewFromTopProvider, Arc<Hub>, Request>;
312
313impl<Request> NewSentryLayer<Request> {
314    /// Create a new Sentry layer that binds a new Sentry hub for each request made
315    pub fn new_from_top() -> Self {
316        Self {
317            provider: NewFromTopProvider,
318            _hub: PhantomData,
319        }
320    }
321}
322
323/// Tower service that binds a new Sentry hub for each request made.
324pub type NewSentryService<S, Request> = SentryService<S, NewFromTopProvider, Arc<Hub>, Request>;
325
326impl<S, Request> NewSentryService<S, Request> {
327    /// Wrap a Tower service with a Tower layer that binds a Sentry hub for each request made.
328    pub fn new_from_top(service: S) -> Self {
329        Self {
330            provider: NewFromTopProvider,
331            service,
332            _hub: PhantomData,
333        }
334    }
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340    use std::rc::Rc;
341
342    fn assert_sync<T: Sync>() {}
343
344    #[test]
345    fn test_layer_is_sync_when_request_isnt() {
346        assert_sync::<NewSentryLayer<Rc<()>>>(); // Rc<()> is not Sync
347    }
348
349    #[test]
350    fn test_service_is_sync_when_request_isnt() {
351        assert_sync::<NewSentryService<(), Rc<()>>>(); // Rc<()> is not Sync
352    }
353}