summaryrefslogtreecommitdiff
path: root/exes/rest/src/ratelimit_client/mod.rs
blob: c9bd52eb824b19d14d96999ce752da2a63a9bbb3 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use crate::config::ReverseProxyConfig;

use self::remote_hashring::{HashRingWrapper, MetadataMap, VNode};
use anyhow::anyhow;
use opentelemetry::global;
use proto::nova::ratelimit::ratelimiter::{BucketSubmitTicketRequest, HeadersSubmitRequest};
use std::collections::HashMap;
use std::fmt::Debug;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use tokio::sync::{broadcast, RwLock};
use tonic::Request;
use tracing::{debug, error, info_span, instrument, trace_span, Instrument, Span};
use tracing_opentelemetry::OpenTelemetrySpanExt;

mod remote_hashring;

#[derive(Clone, Debug)]
pub struct RemoteRatelimiter {
    remotes: Arc<RwLock<HashRingWrapper>>,
    current_remotes: Vec<String>,

    stop: Arc<tokio::sync::broadcast::Sender<()>>,
    config: ReverseProxyConfig,
}

impl Drop for RemoteRatelimiter {
    fn drop(&mut self) {
        let _ = self
            .stop
            .clone()
            .send(())
            .map_err(|_| error!("ratelimiter was already stopped"));
    }
}

impl RemoteRatelimiter {
    async fn get_ratelimiters(&self) -> Result<(), anyhow::Error> {
        // get list of dns responses
        let responses: Vec<String> = dns_lookup::lookup_host(&self.config.ratelimiter_address)?
            .into_iter()
            .filter(|address| address.is_ipv4())
            .map(|address| address.to_string())
            .collect();

        let mut write = self.remotes.write().await;

        for ip in &responses {
            if !self.current_remotes.contains(&ip) {
                let a = VNode::new(ip.to_owned(), self.config.ratelimiter_port).await?;
                write.add(a.clone());
            }
        }

        Ok(())
    }

    #[must_use]
    pub fn new(config: ReverseProxyConfig) -> Self {
        let (rx, mut tx) = broadcast::channel(1);
        let obj = Self {
            remotes: Arc::new(RwLock::new(HashRingWrapper::default())),
            stop: Arc::new(rx),
            config,
            current_remotes: vec![]
        };

        let obj_clone = obj.clone();
        // Task to update the ratelimiters in the background
        tokio::spawn(async move {
            loop {
                debug!("refreshing");

                match obj_clone.get_ratelimiters().await {
                    Ok(_) => {
                        debug!("refreshed ratelimiting servers")
                    }
                    Err(err) => {
                        error!("refreshing ratelimiting servers failed {}", err);
                    }
                }

                let sleep = tokio::time::sleep(Duration::from_secs(5));
                tokio::pin!(sleep);
                tokio::select! {
                    () = &mut sleep => {
                        debug!("timer elapsed");
                    },
                    _ = tx.recv() => {}
                }
            }
        });

        obj
    }

    #[instrument(name = "ticket task")]
    pub fn ticket(
        &self,
        path: String,
    ) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'static>> {
        let remotes = self.remotes.clone();
        Box::pin(
            async move {
                // Getting the node managing this path
                let mut node = remotes
                    .write()
                    .instrument(trace_span!("acquiring ring lock"))
                    .await
                    .get(&path)
                    .cloned()
                    .ok_or_else(|| {
                        anyhow!(
                            "did not compute ratelimit because no ratelimiter nodes are detected"
                        )
                    })?;

                // Initialize span for tracing (headers injection)
                let span = info_span!("remote request");
                let context = span.context();
                let mut request = Request::new(BucketSubmitTicketRequest { path });
                global::get_text_map_propagator(|propagator| {
                    propagator.inject_context(&context, &mut MetadataMap(request.metadata_mut()))
                });

                // Requesting
                node.submit_ticket(request)
                    .instrument(info_span!("waiting for ticket response"))
                    .await?;

                Ok(())
            }
            .instrument(Span::current()),
        )
    }

    pub fn submit_headers(
        &self,
        path: String,
        headers: HashMap<String, String>,
    ) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'static>> {
        let remotes = self.remotes.clone();
        Box::pin(async move {
            let mut node = remotes
                .write()
                .instrument(trace_span!("acquiring ring lock"))
                .await
                .get(&path)
                .cloned()
                .ok_or_else(|| {
                    anyhow!("did not compute ratelimit because no ratelimiter nodes are detected")
                })?;

            let span = info_span!("remote request");
            let context = span.context();
            let time = SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)?
                .as_millis();
            let mut request = Request::new(HeadersSubmitRequest {
                path,
                precise_time: time as u64,
                headers,
            });
            global::get_text_map_propagator(|propagator| {
                propagator.inject_context(&context, &mut MetadataMap(request.metadata_mut()))
            });

            node.submit_headers(request).await?;

            Ok(())
        })
    }
}