Skip to main content

gwr_components/flow_controls/
limiter.rs

1// Copyright (c) 2023 Graphcore Ltd. All rights reserved.
2
3//! This component can be placed between two components in order to limit the
4//! bandwidth between them.
5//!
6//! # Ports
7//!
8//! This component has the following ports:
9//!  - One [input port](gwr_engine::port::InPort): `rx`
10//!  - One [output port](gwr_engine::port::OutPort): `tx`
11
12use std::cell::RefCell;
13use std::rc::Rc;
14
15use async_trait::async_trait;
16use gwr_engine::engine::Engine;
17use gwr_engine::port::{InPort, OutPort, PortStateResult};
18use gwr_engine::time::clock::Clock;
19use gwr_engine::traits::{Runnable, SimObject};
20use gwr_engine::types::{SimError, SimResult};
21use gwr_model_builder::{EntityDisplay, EntityGet};
22use gwr_track::entity::Entity;
23use gwr_track::tracker::aka::Aka;
24
25use super::rate_limiter::RateLimiter;
26use crate::{connect_tx, port_rx, take_option};
27
28/// The [`Limiter`] is a component that will allow data through at a
29/// specified rate.
30///
31/// The supplied [`RateLimiter`] defines the rate in bits per clock tick.
32/// Downstream backpressure overlaps the packet's service interval. The upstream
33/// handoff completes once both service and downstream acceptance have finished.
34#[derive(EntityGet, EntityDisplay)]
35pub struct Limiter<T>
36where
37    T: SimObject,
38{
39    entity: Rc<Entity>,
40    limiter: Rc<RateLimiter<T>>,
41    tx: RefCell<Option<OutPort<T>>>,
42    rx: RefCell<Option<InPort<T>>>,
43}
44
45impl<T> Limiter<T>
46where
47    T: SimObject,
48{
49    pub fn new_and_register_with_renames(
50        engine: &Engine,
51        clock: &Clock,
52        parent: &Rc<Entity>,
53        name: &str,
54        aka: Option<&Aka>,
55        limiter: Rc<RateLimiter<T>>,
56    ) -> Rc<Self> {
57        let entity = Rc::new(Entity::new(parent, name));
58        let tx = OutPort::new_with_renames(&entity, "tx", aka);
59        let rx = InPort::new_with_renames(engine, clock, &entity, "rx", aka);
60        let rc_self = Rc::new(Self {
61            entity,
62            limiter,
63            tx: RefCell::new(Some(tx)),
64            rx: RefCell::new(Some(rx)),
65        });
66        engine.register(rc_self.clone());
67        rc_self
68    }
69
70    pub fn new_and_register(
71        engine: &Engine,
72        clock: &Clock,
73        parent: &Rc<Entity>,
74        name: &str,
75        limiter: Rc<RateLimiter<T>>,
76    ) -> Rc<Self> {
77        Self::new_and_register_with_renames(engine, clock, parent, name, None, limiter)
78    }
79
80    pub fn connect_port_tx(&self, port_state: PortStateResult<T>) -> SimResult {
81        connect_tx!(self.tx, connect ; port_state)
82    }
83
84    pub fn port_rx(&self) -> PortStateResult<T> {
85        port_rx!(self.rx, state)
86    }
87}
88
89#[async_trait(?Send)]
90impl<T> Runnable for Limiter<T>
91where
92    T: SimObject,
93{
94    async fn run(&self) -> SimResult {
95        let mut rx = take_option!(self.rx);
96        let mut tx = take_option!(self.tx);
97        let limiter = &self.limiter;
98        let clock = limiter.clock();
99        loop {
100            // Get the value but without letting the OutPort complete
101            let value = rx.start_get()?.await;
102
103            let value_id = value.id();
104            let ticks = limiter.ticks(&value)?;
105            let service_end_tick = clock.tick_now().tick().checked_add(ticks).ok_or_else(|| {
106                SimError(format!(
107                    "{}: limiter service deadline overflows",
108                    self.entity
109                ))
110            })?;
111            self.entity.track_enter(value_id);
112
113            tx.put(value)?.await;
114            let remaining_ticks = service_end_tick.saturating_sub(clock.tick_now().tick());
115            if remaining_ticks > 0 {
116                clock.wait_ticks(remaining_ticks)?.await;
117            }
118            self.entity.track_exit(value_id);
119
120            // Allow the OutPort to complete
121            rx.finish_get();
122        }
123    }
124}