Skip to content

Commit

Permalink
Fix bug that can cause key to never expire
Browse files Browse the repository at this point in the history
  • Loading branch information
jacob-pro committed Jan 21, 2024
1 parent 82cf6b6 commit c91e611
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "actix-extensible-rate-limit"
version = "0.3.0"
version = "0.3.1"
edition = "2021"
license = "MIT OR Apache-2.0"
description = "Rate limiting middleware for actix-web"
Expand Down
20 changes: 15 additions & 5 deletions src/backend/redis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::backend::{Backend, Decision, SimpleBackend, SimpleInput, SimpleOutput
use actix_web::rt::time::Instant;
use actix_web::{HttpResponse, ResponseError};
use redis::aio::ConnectionManager;
use redis::{AsyncCommands, Cmd};
use redis::AsyncCommands;
use std::borrow::Cow;
use std::time::Duration;
use thiserror::Error;
Expand Down Expand Up @@ -146,17 +146,26 @@ impl Backend<SimpleInput> for RedisBackend {
let key = self.make_key(&token);

let mut con = self.connection.clone();
let mut cmd = Cmd::new();
cmd.arg("BITFIELD")

let mut pipe = redis::pipe();
pipe.atomic()
// Decrement the rate limit count
.cmd("BITFIELD")
.arg(key.as_ref())
.arg("OVERFLOW")
.arg("SAT")
.arg("INCRBY")
.arg(BITFIELD_ENCODING)
.arg(BITFIELD_OFFSET)
.arg(-1);
.arg(-1)
// Set the key to expire immediately, if it doesn't already have an expiry
.cmd("EXPIRE")
.arg(key.as_ref())
.arg(0)
.arg("NX")
.ignore();

cmd.query_async(&mut con).await?;
pipe.query_async(&mut con).await?;

Ok(())
}
Expand All @@ -177,6 +186,7 @@ impl SimpleBackend for RedisBackend {
mod tests {
use super::*;
use crate::HeaderCompatibleOutput;
use redis::Cmd;

const MINUTE: Duration = Duration::from_secs(60);

Expand Down

0 comments on commit c91e611

Please sign in to comment.