Skip to main content

kora_lib/usage_limit/rules/
usage_rule.rs

1use super::{super::limiter::LimiterContext, InstructionRule, TransactionRule};
2
3macro_rules! delegate {
4    ($self:expr, $method:ident $(, $arg:expr)*) => {
5        match $self {
6            UsageRule::Transaction(r) => r.$method($($arg),*),
7            UsageRule::Instruction(r) => r.$method($($arg),*),
8        }
9    };
10}
11
12#[derive(Debug)]
13pub enum UsageRule {
14    Transaction(TransactionRule),
15    Instruction(InstructionRule),
16}
17
18impl UsageRule {
19    pub fn rule_type(&self) -> &'static str {
20        match self {
21            Self::Transaction(_) => "transaction",
22            Self::Instruction(_) => "instruction",
23        }
24    }
25
26    pub fn storage_key(&self, user_id: &str, timestamp: u64) -> String {
27        delegate!(self, storage_key, user_id, timestamp)
28    }
29
30    pub fn count_increment(&self, ctx: &mut LimiterContext<'_>) -> u64 {
31        delegate!(self, count_increment, ctx)
32    }
33
34    pub fn max(&self) -> u64 {
35        delegate!(self, max)
36    }
37
38    pub fn window_seconds(&self) -> Option<u64> {
39        delegate!(self, window_seconds)
40    }
41
42    pub fn description(&self) -> String {
43        delegate!(self, description)
44    }
45
46    pub fn as_instruction(&self) -> Option<&InstructionRule> {
47        match self {
48            Self::Instruction(r) => Some(r),
49            Self::Transaction(_) => None,
50        }
51    }
52}