witchcraft_server/service/
trace_id_header.rs

1// Copyright 2022 Palantir Technologies, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14use crate::service::{Layer, Service};
15use http::header::HeaderName;
16use http::{HeaderValue, Response};
17
18#[allow(clippy::declare_interior_mutable_const)]
19const TRACE_ID: HeaderName = HeaderName::from_static("x-b3-traceid");
20
21/// A layer which adds an `X-B3-TraceId` header to responses.
22///
23/// It must be installed after trace propagation.
24pub struct TraceIdHeaderLayer;
25
26impl<S> Layer<S> for TraceIdHeaderLayer {
27    type Service = TraceIdHeaderService<S>;
28
29    fn layer(self, inner: S) -> Self::Service {
30        TraceIdHeaderService { inner }
31    }
32}
33
34pub struct TraceIdHeaderService<S> {
35    inner: S,
36}
37
38impl<S, R, B> Service<R> for TraceIdHeaderService<S>
39where
40    S: Service<R, Response = Response<B>> + Sync,
41    R: Send,
42{
43    type Response = S::Response;
44
45    async fn call(&self, req: R) -> Self::Response {
46        let mut response = self.inner.call(req).await;
47        let context = zipkin::current().expect("zipkin trace not initialized");
48        response.headers_mut().insert(
49            TRACE_ID,
50            HeaderValue::from_str(&context.trace_id().to_string()).unwrap(),
51        );
52        response
53    }
54}