metering.rs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::collections::VecDeque;
  19. use tracing::debug;
  20. use crate::util::time::NanoTimestamp;
  21. /// Struct representing metering configuration parameters.
  22. #[derive(Clone, Debug)]
  23. pub struct MeteringConfiguration {
  24. /// Defines the threshold after which rate limit kicks in.
  25. /// Set to 0 for no threshold.
  26. ///
  27. /// If we don't use raw count as our metric, it should be calculated
  28. /// by multiplying the median increase of the measured item with the
  29. /// "max" number of items we want before rate limit starts.
  30. /// For example, if we measure some item that increases our total
  31. /// measurement by ~5 and want to rate limit after about 10, this
  32. /// should be set as 50.
  33. pub threshold: u64,
  34. /// Sleep time for each unit over the threshold, in milliseconds.
  35. ///
  36. /// This is used to calculate sleep time when ratelimit is active.
  37. /// The computed sleep time when we are over the threshold will be:
  38. /// sleep_time = (total - threshold) * sleep_step
  39. pub sleep_step: u64,
  40. /// Parameter defining the expiration of each item, for time based
  41. /// decay, in nano seconds. Set to 0 for no expiration.
  42. pub expiry_time: NanoTimestamp,
  43. }
  44. impl MeteringConfiguration {
  45. /// Generate a new `MeteringConfiguration` for provided threshold,
  46. /// sleep step and expiration time (seconds).
  47. pub fn new(threshold: u64, sleep_step: u64, expiry_time: u128) -> Self {
  48. Self { threshold, sleep_step, expiry_time: NanoTimestamp::from_secs(expiry_time) }
  49. }
  50. }
  51. impl Default for MeteringConfiguration {
  52. fn default() -> Self {
  53. Self { threshold: 0, sleep_step: 0, expiry_time: NanoTimestamp(0) }
  54. }
  55. }
  56. /// Default `MeteringConfiguration` as a constant,
  57. /// so it can be used in trait macros.
  58. pub const DEFAULT_METERING_CONFIGURATION: MeteringConfiguration =
  59. MeteringConfiguration { threshold: 0, sleep_step: 0, expiry_time: NanoTimestamp(0) };
  60. /// Struct to keep track of some sequential metered actions and compute
  61. /// rate limits.
  62. ///
  63. /// The queue uses a time based decay and prunes metering information
  64. /// after corresponding expiration time has passed.
  65. #[derive(Debug)]
  66. pub struct MeteringQueue {
  67. /// Metering configuration of the queue.
  68. config: MeteringConfiguration,
  69. /// Ring buffer keeping track of action execution timestamp and
  70. /// its metered value.
  71. queue: VecDeque<(NanoTimestamp, u64)>,
  72. }
  73. impl MeteringQueue {
  74. /// Generate a new `MeteringQueue` for provided `MeteringConfiguration`.
  75. pub fn new(config: MeteringConfiguration) -> Self {
  76. Self { config, queue: VecDeque::new() }
  77. }
  78. /// Prune expired metering information from the queue.
  79. pub fn clean(&mut self) {
  80. // Check if expiration has been set
  81. if self.config.expiry_time.0 == 0 {
  82. return
  83. }
  84. // Iterate the queue to cleanup expired elements
  85. while let Some((ts, _)) = self.queue.front() {
  86. // This is an edge case where system reports a future timestamp
  87. // therefore elapsed computation fails.
  88. let Ok(elapsed) = ts.elapsed() else {
  89. debug!(target: "net::metering::MeteringQueue::clean", "Timestamp [{ts}] is in future. Removing...");
  90. let _ = self.queue.pop_front();
  91. continue
  92. };
  93. // Check if elapsed time is over the expiration limit
  94. if elapsed < self.config.expiry_time {
  95. break
  96. }
  97. // Remove element
  98. let _ = self.queue.pop_front();
  99. }
  100. }
  101. /// Add new metering value to the queue, after
  102. /// prunning expired metering information.
  103. /// If no threshold has been set, the insert is
  104. /// ignored.
  105. pub fn push(&mut self, value: &u64) {
  106. // Check if threshold has been set
  107. if self.config.threshold == 0 {
  108. return
  109. }
  110. // Prune expired elements
  111. self.clean();
  112. // Push the new value
  113. self.queue.push_back((NanoTimestamp::current_time(), *value));
  114. }
  115. /// Compute the current metered values total.
  116. pub fn total(&self) -> u64 {
  117. let mut total = 0;
  118. for (_, value) in &self.queue {
  119. total += value;
  120. }
  121. total
  122. }
  123. /// Compute sleep time for current metered values total, based on
  124. /// the metering configuration.
  125. ///
  126. /// The sleep time increases linearly, based on configuration sleep
  127. /// step. For example, in a raw count metering model, if we set the
  128. /// configuration with threshold = 6 and sleep_step = 250, when
  129. /// total = 10, returned sleep time will be 1000 ms.
  130. ///
  131. /// Sleep times table for the above example:
  132. ///
  133. /// | Total | Sleep Time (ms) |
  134. /// |-------|-----------------|
  135. /// | 0 | 0 |
  136. /// | 4 | 0 |
  137. /// | 6 | 0 |
  138. /// | 7 | 250 |
  139. /// | 8 | 500 |
  140. /// | 9 | 750 |
  141. /// | 10 | 1000 |
  142. /// | 14 | 2000 |
  143. /// | 18 | 3000 |
  144. pub fn sleep_time(&self) -> Option<u64> {
  145. // Check if threshold has been set
  146. if self.config.threshold == 0 {
  147. return None
  148. }
  149. // Check if we are over the threshold
  150. let total = self.total();
  151. if total < self.config.threshold {
  152. return None
  153. }
  154. // Compute the actual sleep time
  155. Some((total - self.config.threshold) * self.config.sleep_step)
  156. }
  157. }
  158. #[test]
  159. fn test_net_metering_queue_default() {
  160. let mut queue = MeteringQueue::new(MeteringConfiguration::default());
  161. for _ in 0..100 {
  162. queue.push(&1);
  163. assert!(queue.queue.is_empty());
  164. assert_eq!(queue.total(), 0);
  165. assert!(queue.sleep_time().is_none());
  166. }
  167. }
  168. #[test]
  169. fn test_net_metering_queue_raw_count() {
  170. let threshold = 6;
  171. let sleep_step = 250;
  172. let metering_configuration = MeteringConfiguration::new(threshold, sleep_step, 0);
  173. let mut queue = MeteringQueue::new(metering_configuration);
  174. for i in 1..threshold {
  175. queue.push(&1);
  176. assert_eq!(queue.total(), i);
  177. assert!(queue.sleep_time().is_none());
  178. }
  179. for i in threshold..100 {
  180. queue.push(&1);
  181. assert_eq!(queue.total(), i);
  182. assert_eq!(queue.sleep_time(), Some((i - threshold) * sleep_step));
  183. }
  184. }
  185. #[test]
  186. fn test_net_metering_queue_sleep_time() {
  187. let metered_value_median = 5;
  188. let threshold_items = 10;
  189. let threshold = metered_value_median * threshold_items;
  190. let sleep_step = 50;
  191. let metering_configuration = MeteringConfiguration::new(threshold, sleep_step, 0);
  192. let mut queue = MeteringQueue::new(metering_configuration);
  193. for i in 1..threshold_items {
  194. queue.push(&metered_value_median);
  195. assert_eq!(queue.total(), (i * metered_value_median));
  196. assert!(queue.sleep_time().is_none());
  197. }
  198. for i in threshold_items..100 {
  199. queue.push(&metered_value_median);
  200. let expected_total = i * metered_value_median;
  201. assert_eq!(queue.total(), expected_total);
  202. assert_eq!(queue.sleep_time(), Some((expected_total - threshold) * sleep_step));
  203. }
  204. }