gwr_components/flow_controls/rate_limiter.rs
1// Copyright (c) 2023 Graphcore Ltd. All rights reserved.
2
3//! Provide effective bandwidth limit for a component.
4//!
5//! A [RateLimiter] is a component that is given a
6//! [clock](gwr_engine::time::clock::Clock) and a rate in `bits per tick`.
7//! It uses this rate limit to enforce a delay determined by the object that is
8//! being rate limited.
9//!
10//! The [RateLimiter] therefore requires objects to implement the
11//! [TotalBytes] trait so that the number of bits of the object can be
12//! determined.
13//!
14//! # Ports
15//!
16//! This component has the following ports:
17//! - One [input port](gwr_engine::port::InPort): `rx`
18//! - One [output port](gwr_engine::port::OutPort): `tx`
19//!
20//! # Creating a Rate Limiter
21//!
22//! [RateLimiter]s should normally be constructed using the
23//! [rc_limiter!](crate::rc_limiter) macro. This returns an `Rc<RateLimiter>`
24//! because that is what components normally accept as a rate limiter argument.
25//! They are `Rc`ed because they are used immutably and as a result the same
26//! rate limiter can be shared by all components that have the same bandwidth.
27//!
28//! # Examples:
29//!
30//! Here is a basic example of a rate limiter being used by the
31//! [Limiter](crate::flow_controls::limiter) component which is connected
32//! between a source and sink.
33//!
34//! A [source](crate::source::Source) is used to produce 4-byte packets.
35//! The rate limiter is configured to run on a 1GHz clock at a rate of 16 bits
36//! per tick.
37//!
38//! As a result, the total time for the simulation should be `20.0ns` because
39//! each of the 10 packets should take 2 clock ticks to pass through the
40//! [Limiter](crate::flow_controls::limiter) and be consumed by the
41//! [Sink](crate::sink::Sink).
42//!
43//! ```rust
44//! # use gwr_components::flow_controls::limiter::Limiter;
45//! # use gwr_components::sink::Sink;
46//! # use gwr_components::source::Source;
47//! # use gwr_components::{connect_port, rc_limiter, option_box_repeat};
48//! # use gwr_engine::engine::Engine;
49//! # use gwr_engine::run_simulation;
50//!
51//! // Create the engine.
52//! let mut engine = Engine::default();
53//!
54//! // Create a 1GHz clock.
55//! let clock = engine.clock_ghz(1.0);
56//!
57//! // And build a 16 bits-per-tick rate limiter.
58//! let rate_limiter = rc_limiter!(&clock, 16);
59//!
60//! // Build the source (initially with no generator).
61//! let source = Source::new_and_register(&engine, engine.top(), "source", None);
62//!
63//! // Create a packet that uses the source as its trace-control entity.
64//! let packet = 0; // TODO implement a packet type to use here
65//!
66//! // Configure the source to produce ten of these packets.
67//! source.set_generator(option_box_repeat!(packet ; 10));
68//!
69//! // Create the a limiter component to enforce the limit
70//! let limiter = Limiter::new_and_register(&engine, &clock, engine.top(), "limit", rate_limiter);
71//!
72//! // Create the sink to accept these packets.
73//! let sink = Sink::new_and_register(&engine, &clock, engine.top(), "sink");
74//!
75//! // Connect the components.
76//! connect_port!(source, tx => limiter, rx)
77//! .expect("should be able to connect `Source` to `Limiter`");
78//! connect_port!(limiter, tx => sink, rx)
79//! .expect("should be able to connect `Limiter` to `Sink`");
80//!
81//! // Run the simulation.
82//! run_simulation!(engine);
83//!
84//! // Ensure the time is as expected.
85//! assert_eq!(engine.time_now_ns(), 20.0);
86//! ```
87
88use std::marker::PhantomData;
89
90use gwr_engine::time::clock::Clock;
91use gwr_engine::traits::TotalBytes;
92
93/// Create a [RateLimiter] wrapped in an [Rc](std::rc::Rc).
94///
95/// This is the most common form of [RateLimiter] used because all of its
96/// methods can be used immutably and therefore it can be shared by any number
97/// of components with the same bandwidth limit.
98#[macro_export]
99macro_rules! rc_limiter {
100 ($clock:expr, $bits_per_tick:expr) => {
101 std::rc::Rc::new($crate::flow_controls::rate_limiter::RateLimiter::new(
102 $clock,
103 $bits_per_tick,
104 ))
105 };
106}
107
108#[macro_export]
109macro_rules! option_rc_limiter {
110 ($clock:expr, $bits_per_tick:expr) => {
111 Some(std::rc::Rc::new(
112 $crate::flow_controls::rate_limiter::RateLimiter::new($clock, $bits_per_tick),
113 ))
114 };
115}
116
117#[derive(Clone)]
118pub struct RateLimiter<T>
119where
120 T: TotalBytes,
121{
122 /// Clock rate limiter is attached to.
123 clock: Clock,
124
125 /// Bits per tick that can pass through this interface.
126 bits_per_tick: usize,
127
128 phantom: PhantomData<T>,
129}
130
131impl<T> RateLimiter<T>
132where
133 T: TotalBytes,
134{
135 #[must_use]
136 pub fn new(clock: &Clock, bits_per_tick: usize) -> Self {
137 Self {
138 clock: clock.clone(),
139 bits_per_tick,
140 phantom: PhantomData,
141 }
142 }
143
144 pub async fn delay(&self, value: &T) {
145 let delay_ticks = self.ticks(value);
146 self.clock.wait_ticks(delay_ticks as u64).await;
147 }
148
149 pub async fn delay_ticks(&self, ticks: usize) {
150 self.clock.wait_ticks(ticks as u64).await;
151 }
152
153 pub fn ticks(&self, value: &T) -> usize {
154 let payload_bytes = value.total_bytes();
155 let payload_bits = payload_bytes * 8;
156 self.ticks_from_bits(payload_bits)
157 }
158
159 #[must_use]
160 pub fn ticks_from_bits(&self, bits: usize) -> usize {
161 bits.div_ceil(self.bits_per_tick)
162 }
163}