A Rust attribute macro to limit a function's number of runs over a specified period of time

Overview

throttle_my_fn: A Rust attribute macro to throttle the execution of functions

License Crates.io docs.rs

throttle_my_fn is a Rust attribute macro to limit a function's number of runs over a specified period of time, even when called from multiple threads.

The primary use-case for this attribute macro is rate-limiting, e.g. to avoid hammering an online service or to avoid serving too many requests over a period of time.

The macro works by rewriting the function and prefixing it with the necessary book-keeping for throttling (see Usage below). The resulting function is thread-safe.

Usage

Add the dependency to your Cargo.toml:

[dependencies]
throttle_my_fn = "0.2"

Or, using cargo add:

$ cargo add throttle_my_fn

Include the macro:

use throttle_my_fn::throttle;

Annotate the functions you want to throttle:

#[throttle(10, Duration::from_secs(1))]
pub(crate) fn run_10_times_per_second(arg: &str) -> String {
  ...
}

#[throttle(1, Duration::from_millis(100))]
pub(crate) fn run_once_per_100_milliseconds(arg: &str) -> String {
  ...
}

Note that the function signatures are modified to wrap the return type in an Option, like so:

pub(crate) fn run_10_times_per_second(arg: &str) -> Option<String> {
  ...
}

pub(crate) fn run_once_per_100_milliseconds(arg: &str) -> Option<String> {
  ...
}

The Option returned signifies whether the function executed or not.

Changelog

  • 0.2.3

    • Add this Changelog section to the README.
  • 0.2.2

    • Documentation updates regarding thread-safety.
  • 0.2.1

    • Documentation update about possible use cases for this crate.
    • Thanks go to @not-matthias from the Rust Linz Discord server for feedback.
  • 0.2.0

    • Replace the use of MaybeUninit and AtomicBool with parking_lot::Mutex and parking_lot::const_mutex.
    • Thanks go to @mejrs and @veber-alex from the Rust Discord server for feedback.
  • 0.1.0

    • Initial release
You might also like...
Machine Learning library for Rust

rusty-machine This library is no longer actively maintained. The crate is currently on version 0.5.4. Read the API Documentation to learn more. And he

Rust library for Self Organising Maps (SOM).
Rust library for Self Organising Maps (SOM).

RusticSOM Rust library for Self Organising Maps (SOM). Using this Crate Add rusticsom as a dependency in Cargo.toml [dependencies] rusticsom = "1.1.0"

Rust language bindings for TensorFlow
Rust language bindings for TensorFlow

TensorFlow Rust provides idiomatic Rust language bindings for TensorFlow. Notice: This project is still under active development and not guaranteed to

Machine learning crate for Rust

rustlearn A machine learning package for Rust. For full usage details, see the API documentation. Introduction This crate contains reasonably effectiv

Rust bindings for the C++ api of PyTorch.

tch-rs Rust bindings for the C++ api of PyTorch. The goal of the tch crate is to provide some thin wrappers around the C++ PyTorch api (a.k.a. libtorc

个人的 rust 学习资料

🔝 通知: 项目文档迁移到: https://github.com/higker/learn-rust learning-rust-zh 个人的 rust 学习资料 学习目录 目录 源代码地址 相关解析 第一个rust程序 https://github.com/higker/learning-ru

Distributed compute platform implemented in Rust, and powered by Apache Arrow.
Distributed compute platform implemented in Rust, and powered by Apache Arrow.

Ballista: Distributed Compute Platform Overview Ballista is a distributed compute platform primarily implemented in Rust, powered by Apache Arrow. It

Tensors and differentiable operations (like TensorFlow) in Rust

autograd Differentiable operations and tensors backed by ndarray. Motivation Machine learning is one of the field where Rust lagging behind other lang

Rust numeric library with R, MATLAB & Python syntax

Peroxide Rust numeric library contains linear algebra, numerical analysis, statistics and machine learning tools with R, MATLAB, Python like macros. W

Comments
  • Requires `parking_lot` to be manually imported

    Requires `parking_lot` to be manually imported

    Great library! One thing I noticed when implementing this to my project was that the documentation says to just import the throttle_my_fn::throttle; but actually need to also import add parking_lot to dependencies and import it because this library itself is not doing that.

    documentation 
    opened by askonomm 5
  • Code doesn't compile if function has 2+ arguments

    Code doesn't compile if function has 2+ arguments

        #[throttle(1, std::time::Duration::from_millis(1000))]
        fn foo0() {}
    
        #[throttle(1, std::time::Duration::from_millis(1000))]
        fn foo1(a: i32) {}
    
        #[throttle(1, std::time::Duration::from_millis(1000))]
        fn foo2(a: i32, b: i32) {}
    

    First two examples work, but 3rd fails with the following:

    error: expected one of `!`, `)`, `,`, `.`, `::`, `?`, `{`, or an operator, found `b`
      --> src/lib.rs:23:21
       |
    23 |     fn foo2(a: i32, b: i32) {}
       |              -      ^ expected one of 8 possible tokens
       |              |
       |              help: missing `,`
    

    Not sure why it happens.

    bug 
    opened by rlidwka 2
  • Add support for debounce

    Add support for debounce

    This crate looks really nice. Would it be complex to add a feature to debounce?

    So you wait for the X time and run only the last one when the timeout is reached?

    enhancement 
    opened by johansmitsnl 6
Owner
Fred Morcos
Scuba diving, programming, software systems engineering & architecture
Fred Morcos
Signed distance functions + Rust (CPU & GPU) = ❤️❤️

sdf-playground Signed distance functions + Rust (CPU & GPU) = ❤️❤️ Platforms: Windows, Mac & Linux. About sdf-playground is a demo showcasing how you

Patryk Wychowaniec 5 Nov 16, 2023
Compile-time creation of neural networks with Rust

GAMMA Compile-time creation of neural networks with Rust Description This is for now just a showcase project of what can be done with const generics i

Aitor Ruano 354 Jan 1, 2023
A real-time implementation of "Ray Tracing in One Weekend" using nannou and rust-gpu.

Real-time Ray Tracing with nannou & rust-gpu An attempt at a real-time implementation of "Ray Tracing in One Weekend" by Peter Shirley. This was a per

null 89 Dec 23, 2022
Wonnx - a GPU-accelerated ONNX inference run-time written 100% in Rust, ready for the web

Wonnx is a GPU-accelerated ONNX inference run-time written 100% in Rust, ready for the web. Supported Platforms (enabled by wgpu) API Windows Linux &

WebONNX 354 Jan 6, 2023
Compile-time creation of neural networks

Mushin: Compile-time creation of neural networks Mushin is a Japanese term used in martial arts that refers to the state of mind obtained by practice.

Aitor Ruano 354 Jan 1, 2023
Msgpack serialization/deserialization library for Python, written in Rust using PyO3, and rust-msgpack. Reboot of orjson. msgpack.org[Python]

ormsgpack ormsgpack is a fast msgpack library for Python. It is a fork/reboot of orjson It serializes faster than msgpack-python and deserializes a bi

Aviram Hassan 139 Dec 30, 2022
Practice repo for learning Rust. Currently going through "Rust for JavaScript Developers" course.

rust-practice ?? Practice repo for learning Rust. Directories /rust-for-js-dev Files directed towards "Rust for JavaScript Developers" course. Thank y

Sammy Samkough 0 Dec 25, 2021
A Rust library with homemade machine learning models to classify the MNIST dataset. Built in an attempt to get familiar with advanced Rust concepts.

mnist-classifier Ideas UPDATED: Finish CLI Flags Parallelize conputationally intensive functions Class-based naive bayes README Image parsing Confusio

Neil Kaushikkar 0 Sep 2, 2021
🦀Rust Turkiye - Rust Dersleri

Rust Turkiye - Rust Dersleri CURIOSITY - Featuring Richard Feynman Bu repo Rust Turkiye tarafindan duzenlenen Rust Dersleri egitiminin alistirma ve ko

Theo M. Bulut 12 Jan 14, 2023
A Rust machine learning framework.

Linfa linfa (Italian) / sap (English): The vital circulating fluid of a plant. linfa aims to provide a comprehensive toolkit to build Machine Learning

Rust-ML 2.2k Jan 2, 2023