Last active
April 28, 2022 16:28
-
-
Save jayhuang75/61f4ebfcee0290336129b3e6e837fc78 to your computer and use it in GitHub Desktop.
rust-velocity-limit-worker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #[derive(Debug)] | |
| pub struct Limit { | |
| pub daily_max_amount: f64, | |
| pub weekly_max_amount: f64, | |
| pub daily_max_load: i32, | |
| } | |
| pub struct Worker { | |
| velocity_limit: Limit, | |
| transactions: Vec<Transaction>, | |
| output: Vec<Output>, | |
| } | |
| impl Worker { | |
| pub fn new(limit: Limit) -> Self{ | |
| Worker { | |
| velocity_limit: limit, | |
| transactions: Vec::new(), | |
| output: Vec::new(), | |
| } | |
| } | |
| pub fn load_transactions(&mut self, path: &'static str) { | |
| let file = File::open(&path).unwrap(); | |
| let file = BufReader::new(file); | |
| for (_, line) in file.lines().enumerate() { | |
| let line_item = line.unwrap(); | |
| let txn: Transaction = serde_json::from_str(&line_item).unwrap(); | |
| self.transactions.push(txn); | |
| } | |
| } | |
| pub fn process(&mut self) { | |
| self.output = self.transactions.iter().filter(|txn| { | |
| !txn.is_duplicate() | |
| }) | |
| .map(|txn| { | |
| let mut is_accepted = true; | |
| // A maximum of $5,000 can be loaded per day | |
| if !txn.by_max_amount_transactions_per_day(self.velocity_limit.daily_max_amount) { | |
| is_accepted = false; | |
| } | |
| // A maximum of $20,000 can be loaded per week | |
| if !txn.by_week_transactions(self.velocity_limit.weekly_max_amount) { | |
| is_accepted = false; | |
| } | |
| // // A maximum of 3 loads can be performed per day, regardless of amount | |
| if !txn.by_day_transactions(self.velocity_limit.daily_max_load) { | |
| is_accepted = false; | |
| } | |
| Output{ | |
| id: txn.id.clone(), | |
| customer_id: txn.customer_id.clone(), | |
| accept: is_accepted | |
| } | |
| }).collect::<Vec<Output>>(); | |
| } | |
| pub fn file_writer(&mut self, path: &'static str) { | |
| let mut f = File::create(path).expect("Unable to create file"); | |
| for line in &self.output{ | |
| let serialized = serde_json::to_string(&line).unwrap(); | |
| writeln!(&mut f, "{}", serialized).unwrap(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment