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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
// Copyright 2019 Federico Fissore
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! # Shorty
//!
//! `shorty` is a URL shortener: it assigns a short ID to a URL of any length, and when people will access the URL with that short ID, they will be redirected to the original URL.
//!
#[macro_use]
extern crate serde_derive;

use core::fmt;
use std::error::Error;
use std::fmt::{Display, Formatter};

#[cfg(not(test))]
use crate::redis_facade::RedisFacade;
use redis::{ErrorKind, RedisError};
#[cfg(test)]
use tests::StubRedisFacade as RedisFacade;

#[cfg(not(test))]
pub mod redis_facade;

#[derive(Debug)]
pub struct ShortenerError {
    message: &'static str,
    cause: Option<Box<Error>>,
}

impl ShortenerError {
    fn new(message: &'static str) -> ShortenerError {
        ShortenerError {
            message,
            cause: None,
        }
    }
    fn new_with_cause(message: &'static str, error: Box<Error>) -> ShortenerError {
        ShortenerError {
            message,
            cause: Some(error),
        }
    }
}

impl Display for ShortenerError {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        f.write_str(&self.message)?;

        if let Some(err) = &self.cause {
            return f.write_str(&format!(" - {}", &err));
        }

        Ok(())
    }
}

impl Error for ShortenerError {}

/// `Shortener` is the struct exposing methods `lookup` and `shorten`.
///
/// `lookup` attempts to resolve an ID to a URL. If no URL is found or an error occurs, it returns `None`, otherwise it returns `Some(url)`.
///
/// `shorten` takes an optional API key and a URL to shorten. If the API key is present, it will validate it and shorten the URL only if validation passes. Otherwise, it will just shorten the URL.
///
/// `Shortener` interacts with a `RedisFacade`, which makes it easier to work with the `redis` crate and simplifies testing.
///
pub struct Shortener {
    id_length: usize,
    id_alphabet: Vec<char>,
    redis: RedisFacade,
    rate_limit_period: usize,
    rate_limit: i64,
}

/// A struct with the successful result of a URL shortening. It holds the original `url` and the resulting `id`
#[derive(Serialize)]
pub struct ShortenerResult {
    id: String,
    url: String,
}

impl Shortener {
    /// Creates a new Shortener
    ///
    /// `id_length` is the length of the generated ID.
    ///
    /// `id_alphabet` is the alphabet used in the ID: a decent one is `a-zA-Z0-9` as each entry has 62 possible values and is ASCII
    ///
    /// `redis` is a `RedisFacade` instance.
    ///
    /// `rate_limit_period` is the amount of seconds during which calls to `shorten` will be counted.
    ///
    /// `rate_limit` is the max number of calls that can be made to `shorten` in a period.
    pub fn new(
        id_length: usize,
        id_alphabet: Vec<char>,
        redis: RedisFacade,
        rate_limit_period: usize,
        rate_limit: i64,
    ) -> Shortener {
        Shortener {
            id_length,
            id_alphabet,
            redis,
            rate_limit_period,
            rate_limit,
        }
    }

    /// Looks up a URL by the given ID. If no URL is found or an error occurs, it returns `None`, otherwise it returns `Some(url)`.
    pub fn lookup(&self, id: &str) -> Option<String> {
        match self.redis.get_string(id) {
            Ok(url) => Some(url),
            Err(_) => None,
        }
    }

    fn verify_api_key(&self, api_key: &str) -> Result<(), ShortenerError> {
        let api_key = format!("API_KEY_{}", api_key);
        log::trace!("verifying api key '{}'", api_key);

        let verify_and_increment = self.redis.get_bool(&api_key).and_then(|valid| {
            if !valid {
                return Err(RedisError::from((
                    ErrorKind::ExtensionError,
                    "API key expired",
                )));
            }

            if self.rate_limit <= 0 {
                return Ok(-1);
            }

            let rate_key = format!("RATE_{}", api_key);
            log::trace!("verifying rate key '{}'", rate_key);

            self.redis.exists(&rate_key).and_then(|exists| {
                log::trace!("rate key exists {}", exists);

                self.redis.increment(&rate_key).and_then(|number_of_calls| {
                    log::trace!("rate key {} number of calls {}", rate_key, number_of_calls);

                    if !exists {
                        self.redis
                            .expire(&rate_key, self.rate_limit_period)
                            .unwrap();
                    }

                    Ok(number_of_calls)
                })
            })
        });

        match verify_and_increment {
            Ok(call_rate) if self.rate_limit > 0 && call_rate > self.rate_limit => {
                Err(ShortenerError::new("Rate limit exceeded"))
            }
            Ok(_) => Ok(()),
            Err(err) => Err(ShortenerError::new_with_cause(
                "Invalid API key",
                Box::new(err),
            )),
        }
    }

    /// Shortens an URL, returning a `ShortenerResult` holding the provided URL and the generated ID.
    ///
    /// If the optional API key is present, it will validate it and shorten the URL only if validation passes. Otherwise, it will just shorten the URL.
    pub fn shorten(
        &self,
        api_key: &Option<&str>,
        url: &str,
    ) -> Result<ShortenerResult, ShortenerError> {
        let id = nanoid::custom(self.id_length, &self.id_alphabet);

        let verify_result = api_key
            .as_ref()
            .map(|api_key| self.verify_api_key(api_key))
            .unwrap_or(Ok(()));

        verify_result.and_then(|_| {
            let mut url = url.to_owned();
            if !url.to_lowercase().starts_with("http") {
                url = format!("http://{}", url);
            }

            self.redis
                .set(&id, url.as_str())
                .map(|_| ShortenerResult { id, url })
                .map_err(|err| ShortenerError::new_with_cause("redis error", Box::new(err)))
        })
    }
}

#[cfg(test)]
mod tests {
    use redis::RedisResult;

    use super::*;
    use std::cell::RefCell;

    pub struct StubRedisFacade {
        get_string_answers: RefCell<Vec<RedisResult<String>>>,
        get_bool_answers: RefCell<Vec<RedisResult<bool>>>,
        exists_answers: RefCell<Vec<RedisResult<bool>>>,
        set_answers: RefCell<Vec<RedisResult<()>>>,
        incr_answers: RefCell<Vec<RedisResult<i64>>>,
        expire_answers: RefCell<Vec<RedisResult<()>>>,
    }

    impl StubRedisFacade {
        fn new() -> Self {
            StubRedisFacade {
                get_string_answers: RefCell::new(vec![]),
                get_bool_answers: RefCell::new(vec![]),
                exists_answers: RefCell::new(vec![]),
                set_answers: RefCell::new(vec![]),
                incr_answers: RefCell::new(vec![]),
                expire_answers: RefCell::new(vec![]),
            }
        }

        pub fn get_string(&self, _key: &str) -> RedisResult<String> {
            match self.get_string_answers.borrow_mut().pop() {
                Some(s) => s,
                None => panic!("unexpected get_string call"),
            }
        }

        pub fn get_bool(&self, _key: &str) -> RedisResult<bool> {
            match self.get_bool_answers.borrow_mut().pop() {
                Some(s) => s,
                None => panic!("unexpected get call"),
            }
        }

        pub fn exists(&self, _key: &str) -> RedisResult<bool> {
            match self.exists_answers.borrow_mut().pop() {
                Some(s) => s,
                None => panic!("unexpected exists call"),
            }
        }

        pub fn set(&self, _key: &str, _value: &str) -> RedisResult<()> {
            match self.set_answers.borrow_mut().pop() {
                Some(s) => s,
                None => panic!("unexpected set call"),
            }
        }

        pub fn increment(&self, _key: &str) -> RedisResult<i64> {
            match self.incr_answers.borrow_mut().pop() {
                Some(s) => s,
                None => panic!("unexpected incr call"),
            }
        }

        pub fn expire(&self, _key: &str, _seconds: usize) -> RedisResult<()> {
            match self.expire_answers.borrow_mut().pop() {
                Some(s) => s,
                None => panic!("unexpected expire call"),
            }
        }
    }

    #[test]
    fn test_lookup() {
        let redis = StubRedisFacade::new();
        &redis
            .get_string_answers
            .borrow_mut()
            .push(Ok(String::from("test url")));

        let shortener = Shortener::new(10, vec!['a', 'b', 'c'], redis, 600, 10);
        assert_eq!(shortener.lookup("id").unwrap(), "test url");
    }

    #[test]
    fn test_shorten_happy_path_first_call() {
        let redis = StubRedisFacade::new();
        &redis.get_bool_answers.borrow_mut().push(Ok(true));
        &redis.exists_answers.borrow_mut().push(Ok(false));
        &redis.incr_answers.borrow_mut().push(Ok(1));
        &redis.expire_answers.borrow_mut().push(Ok(()));
        &redis.set_answers.borrow_mut().push(Ok(()));

        let shortener = Shortener::new(10, vec!['a', 'b', 'c'], redis, 600, 10);
        let shorten_result = shortener.shorten(&Some("api key"), "A url").unwrap();
        assert_eq!(10, shorten_result.id.len());
        assert_eq!("http://A url", shorten_result.url);
    }

    #[test]
    fn test_shorten_happy_path_no_rate_limit() {
        let redis = StubRedisFacade::new();
        &redis.get_bool_answers.borrow_mut().push(Ok(true));
        &redis.set_answers.borrow_mut().push(Ok(()));

        let shortener = Shortener::new(10, vec!['a', 'b', 'c'], redis, 600, -1);
        let shorten_result = shortener.shorten(&Some("api key"), "A url").unwrap();
        assert_eq!(10, shorten_result.id.len());
        assert_eq!("http://A url", shorten_result.url);
    }

    #[test]
    fn test_shorten_happy_path_second_call() {
        let redis = StubRedisFacade::new();
        &redis.get_bool_answers.borrow_mut().push(Ok(true));
        &redis.exists_answers.borrow_mut().push(Ok(true));
        &redis.incr_answers.borrow_mut().push(Ok(2));
        &redis.set_answers.borrow_mut().push(Ok(()));

        let shortener = Shortener::new(10, vec!['a', 'b', 'c'], redis, 600, 10);
        let shorten_result = shortener.shorten(&Some("api key"), "A url").unwrap();
        assert_eq!(10, shorten_result.id.len());
        assert_eq!("http://A url", shorten_result.url);
    }

    #[test]
    fn test_shorten_happy_path_no_api_key() {
        let redis = StubRedisFacade::new();
        &redis.get_bool_answers.borrow_mut().push(Ok(true));
        &redis.exists_answers.borrow_mut().push(Ok(false));
        &redis.incr_answers.borrow_mut().push(Ok(1));
        &redis.expire_answers.borrow_mut().push(Ok(()));
        &redis.set_answers.borrow_mut().push(Ok(()));

        let shortener = Shortener::new(10, vec!['a', 'b', 'c'], redis, 600, 10);
        let shorten_result = shortener.shorten(&None, "A url").unwrap();
        assert_eq!(10, shorten_result.id.len());
        assert_eq!("http://A url", shorten_result.url);
    }

    #[test]
    fn test_shorten_unhappy_path_rate_limit_exceeded() {
        let rate_limit = 10;
        let redis = StubRedisFacade::new();
        &redis.get_bool_answers.borrow_mut().push(Ok(true));
        &redis.exists_answers.borrow_mut().push(Ok(true));
        &redis.incr_answers.borrow_mut().push(Ok(rate_limit + 1));
        &redis.set_answers.borrow_mut().push(Ok(()));

        let shortener = Shortener::new(10, vec!['a', 'b', 'c'], redis, 600, rate_limit);
        let shorten_result_err = shortener.shorten(&Some("api key"), "A url").err().unwrap();
        assert_eq!("Rate limit exceeded", shorten_result_err.message);
    }

    #[test]
    fn test_shorten_happy_path_rate_limit_expired() {
        let redis = StubRedisFacade::new();

        &redis.get_bool_answers.borrow_mut().push(Ok(true));
        &redis.get_bool_answers.borrow_mut().push(Ok(true));

        &redis.exists_answers.borrow_mut().push(Ok(true));
        &redis.exists_answers.borrow_mut().push(Ok(false));

        &redis.expire_answers.borrow_mut().push(Ok(()));

        &redis.incr_answers.borrow_mut().push(Ok(1));
        &redis.incr_answers.borrow_mut().push(Ok(1));

        &redis.set_answers.borrow_mut().push(Ok(()));
        &redis.set_answers.borrow_mut().push(Ok(()));

        let shortener = Shortener::new(10, vec!['a', 'b', 'c'], redis, 600, 10);

        let shorten_result = shortener.shorten(&Some("api key"), "A url").unwrap();
        assert_eq!(10, shorten_result.id.len());
        assert_eq!("http://A url", shorten_result.url);

        let shorten_result = shortener.shorten(&Some("api key"), "Another url").unwrap();
        assert_eq!(10, shorten_result.id.len());
        assert_eq!("http://Another url", shorten_result.url);
    }

    #[test]
    fn test_shorten_unhappy_path_invalid_api_key() {
        let redis = StubRedisFacade::new();
        &redis.get_bool_answers.borrow_mut().push(Ok(false));

        let shortener = Shortener::new(10, vec!['a', 'b', 'c'], redis, 600, 10);
        let shorten_result_err = shortener.shorten(&Some("api key"), "A url").err().unwrap();
        assert_eq!("Invalid API key", shorten_result_err.message);
    }
}