-
Notifications
You must be signed in to change notification settings - Fork 385
/
server.rs
59 lines (49 loc) · 1.97 KB
/
server.rs
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
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use opentelemetry::{
global,
sdk::export::trace::stdout,
sdk::trace as sdktrace,
trace::{Span, Tracer},
};
use opentelemetry_contrib::trace::propagator::XrayPropagator;
use std::{convert::Infallible, net::SocketAddr};
async fn handle(req: Request<Body>) -> Result<Response<Body>, Infallible> {
let parent_context =
global::get_text_map_propagator(|propagator| propagator.extract(req.headers()));
let x_amzn_trace_id = req
.headers()
.get("x-amzn-trace-id")
.unwrap()
.to_str()
.unwrap();
let span = global::tracer("example/server").start_with_context("hello", parent_context);
span.add_event(format!("Handling - {}", x_amzn_trace_id), Vec::new());
Ok(Response::new(
format!("Hello!, X-Ray Trace Header: {}", x_amzn_trace_id).into(),
))
}
fn init_tracer() -> (sdktrace::Tracer, stdout::Uninstall) {
global::set_text_map_propagator(XrayPropagator::new());
// Install stdout exporter pipeline to be able to retrieve the collected spans.
// For the demonstration, use `Sampler::AlwaysOn` sampler to sample all traces. In a production
// application, use `Sampler::ParentBased` or `Sampler::TraceIdRatioBased` with a desired ratio.
stdout::new_pipeline()
.with_trace_config(sdktrace::Config {
default_sampler: Box::new(sdktrace::Sampler::AlwaysOn),
id_generator: Box::new(sdktrace::XrayIdGenerator::default()),
..Default::default()
})
.install()
}
#[tokio::main]
async fn main() {
let _guard = init_tracer();
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let make_svc = make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn(handle)) });
let server = Server::bind(&addr).serve(make_svc);
println!("Listening on {}", addr);
if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
}