-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathtrace.rs
More file actions
86 lines (75 loc) · 2.43 KB
/
Copy pathtrace.rs
File metadata and controls
86 lines (75 loc) · 2.43 KB
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
use tower::{Layer, Service};
use tracing::{instrument::Instrumented, Instrument};
use crate::{Context, LambdaInvocation};
use lambda_runtime_api_client::BoxError;
use std::task;
/// Tower middleware to create a tracing span for invocations of the Lambda function.
#[derive(Default)]
pub struct TracingLayer {}
impl TracingLayer {
/// Create a new tracing layer.
pub fn new() -> Self {
Self::default()
}
}
impl<S> Layer<S> for TracingLayer {
type Service = TracingService<S>;
fn layer(&self, inner: S) -> Self::Service {
TracingService { inner }
}
}
/// Tower service returned by [TracingLayer].
pub struct TracingService<S> {
inner: S,
}
impl<S> Service<LambdaInvocation> for TracingService<S>
where
S: Service<LambdaInvocation, Response = (), Error = BoxError>,
{
type Response = ();
type Error = BoxError;
type Future = Instrumented<S::Future>;
fn poll_ready(&mut self, cx: &mut task::Context<'_>) -> task::Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: LambdaInvocation) -> Self::Future {
let span = request_span(&req.context);
let future = {
// Enter the span before calling the inner service
// to ensure that it's assigned as parent of the inner spans.
let _guard = span.enter();
self.inner.call(req)
};
future.instrument(span)
}
}
/* ------------------------------------------- UTILS ------------------------------------------- */
pub fn request_span(ctx: &Context) -> tracing::Span {
match (&ctx.xray_trace_id, &ctx.tenant_id) {
(Some(trace_id), Some(tenant_id)) => {
tracing::info_span!(
"Lambda runtime invoke",
requestId = &ctx.request_id,
xrayTraceId = trace_id,
tenantId = tenant_id
)
}
(Some(trace_id), None) => {
tracing::info_span!(
"Lambda runtime invoke",
requestId = &ctx.request_id,
xrayTraceId = trace_id
)
}
(None, Some(tenant_id)) => {
tracing::info_span!(
"Lambda runtime invoke",
requestId = &ctx.request_id,
tenantId = tenant_id
)
}
(None, None) => {
tracing::info_span!("Lambda runtime invoke", requestId = &ctx.request_id)
}
}
}