mas_tower/
utils.rs

1// Copyright 2024 New Vector Ltd.
2// Copyright 2023, 2024 The Matrix.org Foundation C.I.C.
3//
4// SPDX-License-Identifier: AGPL-3.0-only
5// Please see LICENSE in the repository root for full details.
6
7use opentelemetry::{KeyValue, Value};
8use tower::{Layer, Service};
9
10/// A simple static key-value pair.
11#[derive(Clone, Debug)]
12pub struct KV<V>(pub &'static str, pub V);
13
14impl<V> From<KV<V>> for KeyValue
15where
16    V: Into<Value>,
17{
18    fn from(value: KV<V>) -> Self {
19        Self::new(value.0, value.1.into())
20    }
21}
22
23/// A wrapper around a function that can be used to generate a key-value pair,
24/// make or enrich spans.
25#[derive(Clone, Debug)]
26pub struct FnWrapper<F>(pub F);
27
28/// A no-op layer that has the request type bound.
29#[derive(Clone, Copy, Debug)]
30pub struct IdentityLayer<R> {
31    _request: std::marker::PhantomData<R>,
32}
33
34impl<R> Default for IdentityLayer<R> {
35    fn default() -> Self {
36        Self {
37            _request: std::marker::PhantomData,
38        }
39    }
40}
41
42/// A no-op service that has the request type bound.
43#[derive(Clone, Copy, Debug)]
44pub struct IdentityService<R, S> {
45    _request: std::marker::PhantomData<R>,
46    inner: S,
47}
48
49impl<R, S> Default for IdentityService<R, S>
50where
51    S: Default,
52{
53    fn default() -> Self {
54        Self {
55            _request: std::marker::PhantomData,
56            inner: S::default(),
57        }
58    }
59}
60
61impl<R, S> Layer<S> for IdentityLayer<R> {
62    type Service = IdentityService<R, S>;
63
64    fn layer(&self, inner: S) -> Self::Service {
65        IdentityService {
66            _request: std::marker::PhantomData,
67            inner,
68        }
69    }
70}
71
72impl<S, R> Service<R> for IdentityService<R, S>
73where
74    S: Service<R>,
75{
76    type Response = S::Response;
77    type Error = S::Error;
78    type Future = S::Future;
79
80    fn poll_ready(
81        &mut self,
82        cx: &mut std::task::Context<'_>,
83    ) -> std::task::Poll<Result<(), Self::Error>> {
84        self.inner.poll_ready(cx)
85    }
86
87    fn call(&mut self, req: R) -> Self::Future {
88        self.inner.call(req)
89    }
90}