summaryrefslogtreecommitdiff
path: root/exes/rest/src/ratelimit_client/remote_hashring.rs
blob: b99276d25166f424ee98aa235e0bc6dd429e24c8 (plain)
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
use core::fmt::Debug;
use opentelemetry::propagation::Injector;
use proto::nova::ratelimit::ratelimiter::ratelimiter_client::RatelimiterClient;
use std::convert::TryFrom;
use std::hash::Hash;
use std::ops::Deref;
use std::ops::DerefMut;
use tonic::transport::Channel;
use tracing::debug;

#[derive(Debug, Clone)]
pub struct VNode {
    address: String,

    client: RatelimiterClient<Channel>,
}

impl Deref for VNode {
    type Target = RatelimiterClient<Channel>;

    fn deref(&self) -> &Self::Target {
        &self.client
    }
}

impl DerefMut for VNode {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.client
    }
}

impl Hash for VNode {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.address.hash(state);
    }
}

pub struct MetadataMap<'a>(pub &'a mut tonic::metadata::MetadataMap);

impl<'a> Injector for MetadataMap<'a> {
    /// Set a key and value in the `MetadataMap`.  Does nothing if the key or value are not valid inputs
    fn set(&mut self, key: &str, value: String) {
        if let Ok(key) = tonic::metadata::MetadataKey::from_bytes(key.as_bytes()) {
            if let Ok(val) = tonic::metadata::MetadataValue::try_from(&value) {
                self.0.insert(key, val);
            }
        }
    }
}

impl VNode {
    pub async fn new(address: String, port: u16) -> Result<Self, tonic::transport::Error> {
        let host = format!("http://{}:{port}", address.clone());
        debug!("connecting to {}", host);
        let client = RatelimiterClient::connect(host).await?;

        Ok(Self { address, client })
    }
}

#[repr(transparent)]
#[derive(Default)]
pub struct HashRingWrapper(hashring::HashRing<VNode>);

impl Deref for HashRingWrapper {
    type Target = hashring::HashRing<VNode>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for HashRingWrapper {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl Debug for HashRingWrapper {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("HashRing").finish()
    }
}