1use std::fmt;
8
9use serde::{Deserialize, Serialize};
10
11use crate::HttpLimitKind;
12
13#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
15#[serde(deny_unknown_fields)]
16pub struct HttpLimit {
17 pub kind: HttpLimitKind,
18 pub limit: u64,
19 pub actual: u64,
20 pub actual_is_lower_bound: bool,
21 #[serde(default, skip_serializing_if = "Option::is_none")]
22 pub executing_limit: Option<u64>,
23}
24
25impl HttpLimit {
26 pub(crate) fn matches_code(&self, code: &str) -> bool {
27 const MAX_SAFE_INTEGER: u64 = (1_u64 << 53) - 1;
28 self.kind.code() == code
29 && self.actual > self.limit
30 && (self.kind == HttpLimitKind::Parameters || self.limit > 0)
31 && self.actual <= MAX_SAFE_INTEGER
32 && self.limit <= MAX_SAFE_INTEGER
33 && if self.kind.is_admission() {
34 self.actual_is_lower_bound
35 && self
36 .executing_limit
37 .is_some_and(|value| value > 0 && value <= MAX_SAFE_INTEGER)
38 } else {
39 self.executing_limit.is_none()
40 && self.actual_is_lower_bound == (self.kind == HttpLimitKind::RequestBodyBytes)
41 }
42 }
43}
44
45impl fmt::Display for HttpLimit {
46 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47 write!(
48 formatter,
49 "{} limit {}; observed {}{}",
50 self.kind.as_str(),
51 self.limit,
52 if self.actual_is_lower_bound {
53 "at least "
54 } else {
55 ""
56 },
57 self.actual
58 )?;
59 if let Some(executing) = self.executing_limit {
60 write!(formatter, "; executing limit {executing}")?;
61 }
62 Ok(())
63 }
64}