1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
use cel_interpreter::CelExpression;
use derive_builder::Builder;
use serde::{Deserialize, Serialize};

pub use crate::{entity::*, param::definition::*};
pub use cala_types::{
    primitives::{Currency, VelocityLimitId},
    velocity::*,
};

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum VelocityLimitEvent {
    Initialized { values: VelocityLimitValues },
}

impl EntityEvent for VelocityLimitEvent {
    type EntityId = VelocityLimitId;
    fn event_table_name() -> &'static str {
        "cala_velocity_limit_events"
    }
}

#[derive(Builder)]
#[builder(pattern = "owned", build_fn(error = "EntityError"))]
pub struct VelocityLimit {
    _values: VelocityLimitValues,
    pub(super) _events: EntityEvents<VelocityLimitEvent>,
}

impl Entity for VelocityLimit {
    type Event = VelocityLimitEvent;
}

impl TryFrom<EntityEvents<VelocityLimitEvent>> for VelocityLimit {
    type Error = EntityError;

    fn try_from(events: EntityEvents<VelocityLimitEvent>) -> Result<Self, Self::Error> {
        let mut builder = VelocityLimitBuilder::default();
        for event in events.iter() {
            match event {
                VelocityLimitEvent::Initialized { values } => {
                    builder = builder._values(values.clone());
                }
            }
        }
        builder._events(events).build()
    }
}

/// Representation of a ***new*** velocity limit entity with required/optional properties and a builder.
#[derive(Builder, Debug)]
#[builder(build_fn(validate = "Self::validate"))]
pub struct NewVelocityLimit {
    #[builder(setter(into))]
    pub(super) id: VelocityLimitId,
    #[builder(setter(into))]
    pub(super) name: String,
    #[builder(setter(into))]
    description: String,
    window: Vec<NewPartitionKey>,
    #[builder(setter(strip_option, into), default)]
    condition: Option<String>,
    currency: Option<Currency>,
    #[builder(setter(strip_option), default)]
    params: Option<Vec<NewParamDefinition>>,
    limit: NewLimit,
}

impl NewVelocityLimit {
    pub fn builder() -> NewVelocityLimitBuilder {
        NewVelocityLimitBuilder::default()
    }

    pub(super) fn initial_events(self) -> EntityEvents<VelocityLimitEvent> {
        let limit = self.limit;
        EntityEvents::init(
            self.id,
            [VelocityLimitEvent::Initialized {
                values: VelocityLimitValues {
                    id: self.id,
                    name: self.name,
                    description: self.description,
                    currency: self.currency,
                    window: self
                        .window
                        .into_iter()
                        .map(|input| PartitionKey {
                            alias: input.alias,
                            value: CelExpression::try_from(input.value).expect("already validated"),
                        })
                        .collect(),
                    condition: self
                        .condition
                        .map(|expr| CelExpression::try_from(expr).expect("already validated")),
                    params: self
                        .params
                        .map(|params| params.into_iter().map(ParamDefinition::from).collect()),
                    limit: Limit {
                        timestamp_source: limit
                            .timestamp_source
                            .map(CelExpression::try_from)
                            .transpose()
                            .expect("already validated"),
                        balance: limit
                            .balance
                            .into_iter()
                            .map(|input| BalanceLimit {
                                layer: CelExpression::try_from(input.layer)
                                    .expect("already validated"),
                                amount: CelExpression::try_from(input.amount)
                                    .expect("already validated"),
                                enforcement_direction: CelExpression::try_from(
                                    input.enforcement_direction,
                                )
                                .expect("already validated"),
                            })
                            .collect(),
                    },
                },
            }],
        )
    }
}

impl NewVelocityLimitBuilder {
    fn validate(&self) -> Result<(), String> {
        validate_optional_expression(&self.condition)?;
        Ok(())
    }
}

#[derive(Clone, Builder, Debug)]
#[builder(build_fn(validate = "Self::validate"))]
pub struct NewPartitionKey {
    #[builder(setter(into))]
    alias: String,
    #[builder(setter(into))]
    value: String,
}
impl NewPartitionKey {
    pub fn builder() -> NewPartitionKeyBuilder {
        NewPartitionKeyBuilder::default()
    }
}
impl NewPartitionKeyBuilder {
    fn validate(&self) -> Result<(), String> {
        validate_expression(
            self.value
                .as_ref()
                .expect("Mandatory field 'value' not set"),
        )?;
        Ok(())
    }
}

#[derive(Clone, Builder, Debug)]
#[builder(build_fn(validate = "Self::validate"))]
pub struct NewLimit {
    #[builder(setter(strip_option, into), default)]
    timestamp_source: Option<String>,
    balance: Vec<NewBalanceLimit>,
}
impl NewLimit {
    pub fn builder() -> NewLimitBuilder {
        NewLimitBuilder::default()
    }
}
impl NewLimitBuilder {
    fn validate(&self) -> Result<(), String> {
        validate_optional_expression(&self.timestamp_source)
    }
}

#[derive(Clone, Builder, Debug)]
#[builder(build_fn(validate = "Self::validate"))]
pub struct NewBalanceLimit {
    #[builder(setter(into))]
    layer: String,
    #[builder(setter(into))]
    amount: String,
    #[builder(setter(into))]
    enforcement_direction: String,
}
impl NewBalanceLimit {
    pub fn builder() -> NewBalanceLimitBuilder {
        NewBalanceLimitBuilder::default()
    }
}
impl NewBalanceLimitBuilder {
    fn validate(&self) -> Result<(), String> {
        validate_expression(
            self.layer
                .as_ref()
                .expect("Mandatory field 'value' not set"),
        )?;
        validate_expression(
            self.amount
                .as_ref()
                .expect("Mandatory field 'value' not set"),
        )?;
        validate_expression(
            self.enforcement_direction
                .as_ref()
                .expect("Mandatory field 'value' not set"),
        )?;
        Ok(())
    }
}

fn validate_expression(expr: &str) -> Result<(), String> {
    CelExpression::try_from(expr).map_err(|e| e.to_string())?;
    Ok(())
}
fn validate_optional_expression(expr: &Option<Option<String>>) -> Result<(), String> {
    if let Some(Some(expr)) = expr.as_ref() {
        CelExpression::try_from(expr.as_str()).map_err(|e| e.to_string())?;
    }
    Ok(())
}