This commit is contained in:
Jeff Baskin 2024-03-29 07:51:14 -04:00
parent ba41b311ab
commit ca26efca6e
2 changed files with 46 additions and 27 deletions

View File

@ -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<String>,
rx: Receiver<SendMsg>,
}
impl Cache {
fn new(recv: Receiver<SendMsg>) -> 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<String>) -> 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<SendMsg>,
@ -33,32 +73,8 @@ impl MoreThanText {
pub fn new() -> Self {
let (tx, rx) = channel();
spawn(move || {
let mut ids: Vec<String> = 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 }
}

View File

@ -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)]