Skip to main content

BrokerLimits

Struct BrokerLimits 

Source
pub struct BrokerLimits {
    pub buckets: HashMap<BucketId, BucketCfg>,
    pub route: HashMap<MethodId, Vec<BucketId>>,
    pub conns: ConnQuota,
}
Expand description

The full limit policy of one broker user: token buckets, routes and connection quotas.

Normally read from the [broker] section of a limits file by from_toml_str or from_toml_section, then handed to BrokerLimiter::new.

Limits belong to the broker user (the token or account), not to a connector. Build one BrokerLimiter per user and share it between all connectors of that user. Two limiters for one broker limit would each allow the full rate, so together they would exceed the quota the broker gave.

§Examples

use brokapi_runtime::BrokerLimits;

let raw = r#"
[demo.buckets.orders]
rate = 10
per = "1s"
burst = 3

[demo.route]
PlaceOrder = ["orders"]

[demo.conns]
max_conns = 2
max_subs_per_conn = 50
supports_multiplex = false
"#;
let limits = BrokerLimits::from_toml_str(raw)?;
assert_eq!(limits.buckets["orders"].burst, 3);
assert_eq!(limits.buckets_for("PlaceOrder"), vec!["orders".to_string()]);

Fields§

§buckets: HashMap<BucketId, BucketCfg>

The token buckets by name.

§route: HashMap<MethodId, Vec<BucketId>>

For each method name, the buckets one call spends from (one token from each). A bucket named here that is missing from buckets is a configuration error found at BrokerLimiter::acquire.

§conns: ConnQuota

Connection and subscription quotas.

Implementations§

Source§

impl BrokerLimits

Source

pub fn from_toml_str(raw: &str) -> Result<Self, ConfigError>

Reads a limits file that holds exactly one broker section.

The file layout is one top-level table per broker, with buckets, route and conns below it: [bcs.buckets.global], [bcs.route], [bcs.conns]. A per value is an integer followed by ms, s, m, h or d ("250ms", "1s", "24h"). Zero, fractions ("1.5s"), other units ("1w") and spaces inside ("1 s") are refused. buckets and route must be present. Keys the parser does not know are ignored (an older file with dedicated_command_conns still reads), so a misspelled optional key is silently lost.

Use from_toml_section for a file that holds several brokers.

§Errors

Returns [brokapi_core::ConfigError::Message] when the text is not valid TOML, when a required key is missing or has the wrong type, when per cannot be parsed, or when the file has zero or several broker sections.

§Examples
use brokapi_runtime::BrokerLimits;

let raw = r#"
[demo.buckets.global]
rate = 100
per = "1s"
burst = 20
[demo.route]
"*" = ["global"]
[demo.conns]
max_conns = 4
max_subs_per_conn = 50
supports_multiplex = false
"#;
let limits = BrokerLimits::from_toml_str(raw)?;
assert_eq!(limits.conns.max_conns, 4);

// An unsupported duration unit is a configuration error, not a silent default.
let bad = raw.replace("\"1s\"", "\"1w\"");
assert!(BrokerLimits::from_toml_str(&bad).is_err());

// Two broker sections: pick one with `from_toml_section`.
let two = format!("{raw}\n{}", raw.replace("demo", "other"));
assert!(BrokerLimits::from_toml_str(&two).is_err());
assert!(BrokerLimits::from_toml_section(&two, "other").is_ok());
Source

pub fn from_toml_section(raw: &str, section: &str) -> Result<Self, ConfigError>

Reads one named broker section (for example "tbank") of a limits file.

Other sections are parsed too, so they must be valid, but they are not returned. The format is the same as in from_toml_str.

§Errors

Returns [brokapi_core::ConfigError::Message] for invalid TOML or an invalid section, and when the file has no [section].

§Examples
use brokapi_runtime::BrokerLimits;

let raw = r#"
[a.buckets.g]
rate = 1
per = "1s"
burst = 1
[a.route]
"*" = ["g"]
[a.conns]
max_conns = 1
max_subs_per_conn = 1
supports_multiplex = false
"#;
assert!(BrokerLimits::from_toml_section(raw, "a").is_ok());
assert!(BrokerLimits::from_toml_section(raw, "b").is_err());
Source

pub fn from_toml_path(path: &str) -> Result<Self, ConfigError>

Reads a limits file from disk. The file must hold exactly one broker section.

Same as from_toml_str after reading the file.

§Errors

Returns [brokapi_core::ConfigError::Message] when the file cannot be read (the message names the path), and for every reason from_toml_str lists.

§Examples
use brokapi_runtime::BrokerLimits;

let err = BrokerLimits::from_toml_path("/definitely/not/here.toml").unwrap_err();
assert!(err.to_string().contains("/definitely/not/here.toml"));
Source

pub fn buckets_for(&self, method: &str) -> Vec<BucketId> ⓘ

The buckets a call to method spends from: its own route, else the DEFAULT_ROUTE route, else none.

The ids come back sorted and without repeats. This is the order in which BrokerLimiter::acquire takes the tokens. The ids are not checked against buckets.

§Examples
use std::collections::HashMap;
use brokapi_runtime::{BrokerLimits, ConnQuota, DEFAULT_ROUTE};

let limits = BrokerLimits {
    buckets: HashMap::new(),
    route: HashMap::from([
        ("PlaceOrder".to_string(), vec!["orders".to_string(), "global".to_string()]),
        (DEFAULT_ROUTE.to_string(), vec!["global".to_string()]),
    ]),
    conns: ConnQuota::default(),
};
assert_eq!(limits.buckets_for("PlaceOrder"), ["global", "orders"]);
assert_eq!(limits.buckets_for("SomethingNew"), ["global"]);

Trait Implementations§

Source§

impl Clone for BrokerLimits

Source§

fn clone(&self) -> BrokerLimits

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for BrokerLimits

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for BrokerLimits

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for BrokerLimits

Source§

fn eq(&self, other: &BrokerLimits) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for BrokerLimits

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more