From ca26efca6e4b62d26599f7d99a10fa350c931927 Mon Sep 17 00:00:00 2001 From: Jeff Baskin Date: Fri, 29 Mar 2024 07:51:14 -0400 Subject: [PATCH] Refactor --- src/lib.rs | 70 ++++++++++++++++++++++++++++++++--------------------- src/main.rs | 3 +++ 2 files changed, 46 insertions(+), 27 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 3dec5d5..db8d25a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,6 @@ use rand::distributions::{Alphanumeric, DistString}; use std::{ - sync::mpsc::{channel, Sender}, + sync::mpsc::{channel, Receiver, Sender}, thread::spawn, }; @@ -24,6 +24,46 @@ enum SendMsg { ValidateSess(ValidateSession), } +struct Cache { + data: Vec, + rx: Receiver, +} + +impl Cache { + fn new(recv: Receiver) -> Self { + Self { + rx: recv, + data: Vec::new(), + } + } + + fn gen_id(&self) -> String { + Alphanumeric.sample_string(&mut rand::thread_rng(), 16) + } + + fn listen(&mut self) { + loop { + match self.rx.recv().unwrap() { + SendMsg::ValidateSess(vsess) => { + vsess.tx.send(self.validate_session(vsess.id)).unwrap() + } + } + } + } + + fn validate_session(&mut self, sess: Option) -> Session { + let session: Session; + if sess.is_some_and(|sess| self.data.contains(&sess)) { + session = Session::Ok; + } else { + let id = self.gen_id(); + self.data.push(id.clone()); + session = Session::New(id); + } + session + } +} + #[derive(Clone)] pub struct MoreThanText { tx: Sender, @@ -33,32 +73,8 @@ impl MoreThanText { pub fn new() -> Self { let (tx, rx) = channel(); spawn(move || { - let mut ids: Vec = Vec::new(); - loop { - match rx.recv().unwrap() { - SendMsg::ValidateSess(vsess) => { - let session: Session; - match vsess.id { - Some(id) => { - if ids.contains(&id) { - session = Session::Ok; - } else { - let sid = - Alphanumeric.sample_string(&mut rand::thread_rng(), 16); - ids.push(sid.clone()); - session = Session::New(sid); - } - } - None => { - let sid = Alphanumeric.sample_string(&mut rand::thread_rng(), 16); - ids.push(sid.clone()); - session = Session::New(sid); - } - } - vsess.tx.send(session).unwrap(); - } - } - } + let mut cache = Cache::new(rx); + cache.listen(); }); Self { tx: tx } } diff --git a/src/main.rs b/src/main.rs index 3302686..14eefe0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,6 +15,9 @@ struct Args { /// IP used #[arg(short, long, default_value_t = LOCALHOST.to_string())] address: String, + /// cluster host + #[arg(short, long, num_args(0..))] + cluster: String, } #[cfg(test)]