relay_cardinality/redis/
script.rs

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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
use relay_redis::{
    redis::{self, FromRedisValue, Script},
    Connection, RedisScripts,
};

use crate::Result;

/// Status wether an entry/bucket is accepted or rejected by the cardinality limiter.
#[derive(Debug, Clone, Copy)]
pub enum Status {
    /// Item is rejected.
    Rejected,
    /// Item is accepted.
    Accepted,
}

impl Status {
    /// Returns `true` if the status is [`Status::Rejected`].
    pub fn is_rejected(&self) -> bool {
        matches!(self, Self::Rejected)
    }
}

impl FromRedisValue for Status {
    fn from_redis_value(v: &redis::Value) -> redis::RedisResult<Self> {
        let accepted = bool::from_redis_value(v)?;
        Ok(if accepted {
            Self::Accepted
        } else {
            Self::Rejected
        })
    }
}

/// Result returned from [`CardinalityScript`].
#[derive(Debug)]
pub struct CardinalityScriptResult {
    /// Cardinality of the limit.
    pub cardinality: u32,
    /// Status for each hash passed to the script.
    pub statuses: Vec<Status>,
}

impl CardinalityScriptResult {
    /// Validates the result against the amount of hashes originally supplied.
    ///
    /// This is not necessarily required but recommended.
    pub fn validate(&self, num_hashes: usize) -> Result<()> {
        if num_hashes == self.statuses.len() {
            return Ok(());
        }

        Err(relay_redis::RedisError::Redis(redis::RedisError::from((
            redis::ErrorKind::ResponseError,
            "Script returned an invalid number of elements",
            format!("Expected {num_hashes} results, got {}", self.statuses.len()),
        )))
        .into())
    }
}

impl FromRedisValue for CardinalityScriptResult {
    fn from_redis_value(v: &redis::Value) -> redis::RedisResult<Self> {
        let Some(seq) = v.as_sequence() else {
            return Err(redis::RedisError::from((
                redis::ErrorKind::TypeError,
                "Expected a sequence from the cardinality script",
                format!("{v:?}"),
            )));
        };

        let mut iter = seq.iter();

        let cardinality = iter
            .next()
            .ok_or_else(|| {
                redis::RedisError::from((
                    redis::ErrorKind::TypeError,
                    "Expected cardinality as the first result from the cardinality script",
                ))
            })
            .and_then(FromRedisValue::from_redis_value)?;

        let mut statuses = Vec::with_capacity(iter.len());
        for value in iter {
            statuses.push(Status::from_redis_value(value)?);
        }

        Ok(Self {
            cardinality,
            statuses,
        })
    }
}

/// Abstraction over the `cardinality.lua` lua Redis script.
pub struct CardinalityScript(&'static Script);

impl CardinalityScript {
    /// Loads the script.
    ///
    /// This is somewhat costly and shouldn't be done often.
    pub fn load() -> Self {
        Self(RedisScripts::load_cardinality())
    }

    /// Creates a new pipeline to batch multiple script invocations.
    pub fn pipe(&self) -> CardinalityScriptPipeline<'_> {
        CardinalityScriptPipeline {
            script: self,
            pipe: redis::pipe(),
        }
    }

    /// Makes sure the script is loaded in Redis.
    fn load_redis(&self, con: &mut Connection) -> Result<()> {
        self.0
            .prepare_invoke()
            .load(con)
            .map_err(relay_redis::RedisError::Redis)?;

        Ok(())
    }

    /// Returns a [`redis::ScriptInvocation`] with all keys and arguments prepared.
    fn prepare_invocation(
        &self,
        limit: u32,
        expire: u64,
        hashes: impl Iterator<Item = u32>,
        keys: impl Iterator<Item = String>,
    ) -> redis::ScriptInvocation<'_> {
        let mut invocation = self.0.prepare_invoke();

        for key in keys {
            invocation.key(key);
        }

        invocation.arg(limit);
        invocation.arg(expire);

        for hash in hashes {
            invocation.arg(&hash.to_le_bytes());
        }

        invocation
    }
}

/// Pipeline to batch multiple [`CardinalityScript`] invocations.
pub struct CardinalityScriptPipeline<'a> {
    script: &'a CardinalityScript,
    pipe: redis::Pipeline,
}

impl CardinalityScriptPipeline<'_> {
    /// Adds another invocation of the script to the pipeline.
    pub fn add_invocation(
        &mut self,
        limit: u32,
        expire: u64,
        hashes: impl Iterator<Item = u32>,
        keys: impl Iterator<Item = String>,
    ) -> &mut Self {
        let invocation = self.script.prepare_invocation(limit, expire, hashes, keys);
        self.pipe.invoke_script(&invocation);
        self
    }

    /// Invokes the entire pipeline and returns the results.
    ///
    /// Returns one result for each script invocation.
    pub fn invoke(&self, con: &mut Connection<'_>) -> Result<Vec<CardinalityScriptResult>> {
        match self.pipe.query(con) {
            Ok(result) => Ok(result),
            Err(err) if err.kind() == redis::ErrorKind::NoScriptError => {
                relay_log::trace!("Redis script no loaded, loading it now");
                self.script.load_redis(con)?;
                self.pipe
                    .query(con)
                    .map_err(relay_redis::RedisError::Redis)
                    .map_err(Into::into)
            }
            Err(err) => Err(relay_redis::RedisError::Redis(err).into()),
        }
    }
}

#[cfg(test)]
mod tests {
    use relay_redis::{RedisConfigOptions, RedisPool};
    use uuid::Uuid;

    use super::*;

    impl CardinalityScript {
        fn invoke_one(
            &self,
            con: &mut Connection,
            limit: u32,
            expire: u64,
            hashes: impl Iterator<Item = u32>,
            keys: impl Iterator<Item = String>,
        ) -> Result<CardinalityScriptResult> {
            let mut results = self
                .pipe()
                .add_invocation(limit, expire, hashes, keys)
                .invoke(con)?;

            assert_eq!(results.len(), 1);
            Ok(results.pop().unwrap())
        }
    }

    fn build_redis() -> RedisPool {
        let url = std::env::var("RELAY_REDIS_URL")
            .unwrap_or_else(|_| "redis://127.0.0.1:6379".to_owned());

        let opts = RedisConfigOptions {
            max_connections: 1,
            ..Default::default()
        };
        RedisPool::single(&url, opts).unwrap()
    }

    fn keys(prefix: Uuid, keys: &[&str]) -> impl Iterator<Item = String> {
        keys.iter()
            .map(move |key| format!("{prefix}-{key}"))
            .collect::<Vec<_>>()
            .into_iter()
    }

    fn assert_ttls(connection: &mut Connection, prefix: Uuid) {
        let keys = redis::cmd("KEYS")
            .arg(format!("{prefix}-*"))
            .query::<Vec<String>>(connection)
            .unwrap();

        for key in keys {
            let ttl = redis::cmd("TTL")
                .arg(&key)
                .query::<i64>(connection)
                .unwrap();

            assert!(ttl >= 0, "Key {key} has no TTL");
        }
    }

    #[test]
    fn test_below_limit_perfect_cardinality_ttl() {
        let redis = build_redis();
        let mut client = redis.client().unwrap();
        let mut connection = client.connection().unwrap();

        let script = CardinalityScript::load();

        let prefix = Uuid::new_v4();
        let k1 = &["a", "b", "c"];
        let k2 = &["b", "c", "d"];

        script
            .invoke_one(&mut connection, 50, 3600, 0..30, keys(prefix, k1))
            .unwrap();

        script
            .invoke_one(&mut connection, 50, 3600, 0..30, keys(prefix, k2))
            .unwrap();

        assert_ttls(&mut connection, prefix);
    }

    #[test]
    fn test_load_script() {
        let redis = build_redis();
        let mut client = redis.client().unwrap();
        let mut connection = client.connection().unwrap();

        let script = CardinalityScript::load();
        let keys = keys(Uuid::new_v4(), &["a", "b", "c"]);

        redis::cmd("SCRIPT")
            .arg("FLUSH")
            .exec(&mut connection)
            .unwrap();
        script
            .invoke_one(&mut connection, 50, 3600, 0..30, keys)
            .unwrap();
    }

    #[test]
    fn test_multiple_calls_in_pipeline() {
        let redis = build_redis();
        let mut client = redis.client().unwrap();
        let mut connection = client.connection().unwrap();

        let script = CardinalityScript::load();
        let k2 = keys(Uuid::new_v4(), &["a", "b", "c"]);
        let k1 = keys(Uuid::new_v4(), &["a", "b", "c"]);

        let mut pipeline = script.pipe();
        let results = pipeline
            .add_invocation(50, 3600, 0..30, k1)
            .add_invocation(50, 3600, 0..30, k2)
            .invoke(&mut connection)
            .unwrap();

        assert_eq!(results.len(), 2);
    }
}