summaryrefslogtreecommitdiff
path: root/exes/ratelimit/src/grpc.rs
blob: 9e5d31c71992bb3982df9f19e839e6ed09f5f97a (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
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use opentelemetry::global;
use opentelemetry::propagation::Extractor;
use proto::nova::ratelimit::ratelimiter::HeadersSubmitRequest;
use proto::nova::ratelimit::ratelimiter::{
    ratelimiter_server::Ratelimiter, BucketSubmitTicketRequest,
};
use tokio::sync::RwLock;
use tonic::Response;
use tracing::debug;
use tracing_opentelemetry::OpenTelemetrySpanExt;
use twilight_http_ratelimiting::RatelimitHeaders;

use crate::buckets::bucket::Bucket;
use crate::buckets::redis_lock::RedisLock;
use crate::buckets::GlobalLock;

pub struct RLServer {
    global: Arc<RedisLock>,
    buckets: RwLock<HashMap<String, Arc<Bucket>>>,
}

impl RLServer {
    pub fn new(redis_lock: Arc<RedisLock>) -> Self {
        Self {
            global: redis_lock,
            buckets: RwLock::new(HashMap::new()),
        }
    }
}

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

impl<'a> Extractor for MetadataMap<'a> {
    /// Get a value for a key from the `MetadataMap`.  If the value can't be converted to &str, returns None
    fn get(&self, key: &str) -> Option<&str> {
        self.0.get(key).and_then(|metadata| metadata.to_str().ok())
    }

    /// Collect all the keys from the `MetadataMap`.
    fn keys(&self) -> Vec<&str> {
        self.0
            .keys()
            .map(|key| match key {
                tonic::metadata::KeyRef::Ascii(v) => v.as_str(),
                tonic::metadata::KeyRef::Binary(v) => v.as_str(),
            })
            .collect::<Vec<_>>()
    }
}

#[tonic::async_trait]
impl Ratelimiter for RLServer {
    async fn submit_headers(
        &self,
        request: tonic::Request<HeadersSubmitRequest>,
    ) -> Result<tonic::Response<()>, tonic::Status> {
        let parent_cx =
            global::get_text_map_propagator(|prop| prop.extract(&MetadataMap(request.metadata())));
        // Generate a tracing span as usual
        let span = tracing::span!(tracing::Level::INFO, "request process");
        span.set_parent(parent_cx);

        let data = request.into_inner();

        let ratelimit_headers = RatelimitHeaders::from_pairs(
            data.headers.iter().map(|f| (f.0 as &str, f.1.as_bytes())),
        )
        .unwrap();

        if let Some(duration) = self.global.is_locked().await {
            tokio::time::sleep(duration).await;
        }

        let bucket: Arc<Bucket> = if self.buckets.read().await.contains_key(&data.path) {
            self.buckets
                .read()
                .await
                .get(&data.path)
                .expect("impossible")
                .clone()
        } else {
            let bucket = Bucket::new();
            self.buckets.write().await.insert(data.path, bucket.clone());
            bucket
        };

        match ratelimit_headers {
            RatelimitHeaders::Global(global) => {
                // If we are globally ratelimited, we lock using the redis lock
                // This is using redis because a global ratelimit should be executed in all
                // ratelimit workers.
                debug!(
                    "global ratelimit headers detected: {}",
                    global.retry_after()
                );
                self.global
                    .clone()
                    .lock_for(Duration::from_secs(global.retry_after()))
                    .await;
            }
            RatelimitHeaders::None => {}
            RatelimitHeaders::Present(present) => {
                // we should update the bucket.
                bucket.update(&present, data.precise_time);
            }
            _ => unreachable!(),
        };

        Ok(Response::new(()))
    }

    async fn submit_ticket(
        &self,
        request: tonic::Request<BucketSubmitTicketRequest>,
    ) -> Result<tonic::Response<()>, tonic::Status> {
        let parent_cx =
            global::get_text_map_propagator(|prop| prop.extract(&MetadataMap(request.metadata())));
        // Generate a tracing span as usual
        let span = tracing::span!(tracing::Level::INFO, "request process");
        span.set_parent(parent_cx);

        let data = request.into_inner();

        let bucket: Arc<Bucket> = if self.buckets.read().await.contains_key(&data.path) {
            self.buckets
                .read()
                .await
                .get(&data.path)
                .expect("impossible")
                .clone()
        } else {
            let bucket = Bucket::new();
            self.buckets.write().await.insert(data.path, bucket.clone());
            bucket
        };

        // wait for the ticket to be accepted
        let _ = bucket.ticket().await;

        Ok(Response::new(()))
    }
}