Rate limit guard - Lazy rate limit semaphore implementation to control your asynchronous code frequency execution

Overview

Rate limit guard

Lazy rate limit semaphore (a.k.a fixed window algorithm without queueing) implementation to control your asynchronous code frequency execution


Documentation: lib.rs/raliguard

Overview

use std::{thread, sync, time};

use raliguard::Semaphore;


// Create a semaphore with restriction `5 tasks per 1 second`
let originl_sem = Semaphore::new(5, time::Duration::from_secs(1));

// Make it sharable between treads (or you can share between tasks)
let shared_sem = sync::Arc::new(
    sync::Mutex::new(originl_sem)
);

// This is a counter that increments when a thread completed
let shared_done_count = sync::Arc::new(sync::Mutex::new(0));

// Spawn 15 threads
for _ in 0..15 {
    let cloned_sem = shared_sem.clone();
    let cloned_done_state = shared_done_count.clone();
    let thread = thread::spawn(move || {
        let mut local_sem = cloned_sem.lock().unwrap();

        // Get required delay
        let calculated_delay = local_sem.calc_delay();
        drop(local_sem);

        // If delay exists, sleep it
        if let Some(delay) = calculated_delay {
            dbg!(&delay);
            thread::sleep(delay);
        }

        // Mark the thread is done
        let mut local_done_count = cloned_done_state.lock().unwrap();
        *local_done_count += 1;

    });
}

// So sleep 1 second (add some millis to let threads complete incrementing)
thread::sleep(time::Duration::from_secs(1) + time::Duration::from_millis(50));
let cloned_done_count = shared_done_count.clone();
let current_done = cloned_done_count.lock().unwrap();

// And then maximum 10 threads should be completed
// after 1 second sleeping
// (the first 5 with no delay and the another 5 after 1 second)
assert_eq!(*current_done, 10);

Features

  • Calculated delay for sleep can be used with any async/await runtime backend or with threads
  • Minimum memory used to save calls data
You might also like...
Asynchronous runtime abstractions for implicit function decoloring.
Asynchronous runtime abstractions for implicit function decoloring.

decolor Asynchronous runtime abstractions for implicit function decoloring. Decolor is in beta Install | User Docs | Crate Docs | Reference | Contribu

A simple, efficient Rust library for handling asynchronous job processing and task queuing.

job_queue Setup cargo add job_queue Usage Create a job use job_queue::{Error, Job, typetag, async_trait, serde}; #[derive(Debug, serde::Deserialize,

Clean up the lines of files in your code repository

lineman Clean up the lines of files in your code repository NOTE: While lineman does have tests in place to ensure it operates in a specific way, I st

Tagref helps you maintain cross-references in your code.

Tagref helps you maintain cross-references in your code. You can use it to help keep things in sync, document assumptions, manage invariants, etc. Airbnb uses it for their front-end monorepo. You should use it too!

Twidge is a fresh approach to productivity. It integrates with your workflow and allows you to be your most productive self.

Twidge A productivity app which is an extension to your mind Twidge is a cross platform productivity app, powered by rust, tauri, prisma-client-rust T

Migrate C code to Rust
Migrate C code to Rust

C2Rust helps you migrate C99-compliant code to Rust. The translator (or transpiler) produces unsafe Rust code that closely mirrors the input C code. T

Mix async code with CPU-heavy thread pools using Tokio + Rayon

tokio-rayon Mix async code with CPU-heavy thread pools using Tokio + Rayon Resources Documentation crates.io TL;DR Sometimes, you're doing async stuff

Minimal, flexible framework for implementing solutions to Advent of Code in Rust

This is advent_of_code_traits, a minimal, flexible framework for implementing solutions to Advent of Code in Rust.

Waits until the exit code of a program is zero

Waitz A rust utility to wait that a program exits with 0. You need to wait for something to start up and don't know when it finishes?

Comments
  • Fix initial excess delay

    Fix initial excess delay

    There was an excess delay when semaphore's state at renewed boundary stamp. Now it was fixed, so first access_times requests will be executed with no delay, and next will have delay only when they exceed limit

    opened by deknowny 0
Releases(v0.1.1)
Owner
Yan Kurbatov
Open source, backend and a little bit frontend developer
Yan Kurbatov
🦀 Rust support library for semaphore

?? semaphore-rs Rust support library for using semaphore. It's mostly a Rust rewrite of zk-kit, but just focuses on semaphore (for now) and still cove

Worldcoin 31 Dec 21, 2022
Malloc frequency profiler

Malloc frequency profiler This malloc frequency profiler helps detect program hotspots that perform a large number of memory allocations.

Leonid Ryzhyk 7 Jan 7, 2022
Arduino Nano frequency counter with atomic clock accuracy

Arduino Nano frequency counter with atomic clock accuracy Project description and test setup With this project you can measure a frequency from less t

Frank Buss 24 Apr 3, 2022
Measure the execution time of an application

Execution Timer Drag an executable file on the binary or enter the path as an argument to measure the execution time of the program. Building cargo bu

Flux Industries 2 Nov 16, 2021
dark-std an Implementation of asynchronous containers build on tokio

dark-std dark-std is an Implementation of asynchronous containers build on tokio. It uses a read-write separation design borrowed from Golang SyncHash

darkrpc 4 Dec 13, 2022
Simple interoperability between C++ coroutines and asynchronous Rust

cxx-async Overview cxx-async is a Rust crate that extends the cxx library to provide seamless interoperability between asynchronous Rust code using as

Patrick Walton 180 Dec 16, 2022
An asynchronous Hardware Abstraction Layer (HAL) for embedded systems

embedded-hal-async An asynchronous Hardware Abstraction Layer (HAL) for embedded systems. This crate contains asynchronous versions of the embedded-ha

Diego Barrios Romero 3 Jan 22, 2022
An asynchronous IO utilities crate powered by tokio.

An asynchronous IO utilities crate powered by tokio.

Harry 2 Aug 18, 2022
Various extention traits for providing asynchronous higher-order functions

async-hofs Various extention traits for providing asynchronous higher-order functions. // This won't make any name conflicts since all imports inside

かわえもん 5 Jun 28, 2022
prelate-rs is an idiomatic, asynchronous Rust wrapper around the aoe4world API. Very much a WIP at this stage.

prelate-rs is an idiomatic, asynchronous Rust wrapper around the aoe4world API. Very much a WIP at this stage. Project Status We currently support the

William Findlay 4 Dec 29, 2022