Skip to content

Commit

Permalink
fix: store 'block_until' in persistent storage (#133)
Browse files Browse the repository at this point in the history
  • Loading branch information
lemmih authored Feb 3, 2025
1 parent 3dd52e9 commit b49448a
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions src/rate_limiter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use worker::*;
#[durable_object]
pub struct RateLimiter {
state: State,
#[allow(unused)]
block_until: DateTime<Utc>,
}

Expand All @@ -18,21 +19,32 @@ impl DurableObject for RateLimiter {

async fn fetch(&mut self, _req: Request) -> Result<Response> {
let now = Utc::now();
let block_until = self
.state
.storage()
.get("block_until")
.await
.map(|v| DateTime::<Utc>::from_timestamp(v, 0).unwrap_or_default())
.unwrap_or(Utc::now());
console_log!(
"Rate limiter invoked: now={:?}, block_until={:?}, may_sign={:?}",
now,
self.block_until,
self.block_until <= now
block_until,
block_until <= now
);
if self.block_until <= now {
if block_until <= now {
// This Durable Object will be deleted after the alarm is triggered
self.state
.storage()
.set_alarm(std::time::Duration::from_secs(
crate::constants::RATE_LIMIT_SECONDS as u64 + 1,
))
.await?;
self.block_until = now + Duration::seconds(crate::constants::RATE_LIMIT_SECONDS);
let block_until = now + Duration::seconds(crate::constants::RATE_LIMIT_SECONDS);
self.state
.storage()
.put("block_until", block_until.timestamp())
.await?;

Response::from_json(&true)
} else {
Expand Down

0 comments on commit b49448a

Please sign in to comment.