Move the session handler to a dedicated file

This commit is contained in:
Rodolphe Breard 2019-07-11 12:25:19 +02:00
parent a9e4a697f7
commit eed8f88e2b
2 changed files with 53 additions and 35 deletions

View file

@ -10,8 +10,10 @@ mod entry;
mod errors; mod errors;
mod event_handlers; mod event_handlers;
mod logger; mod logger;
mod session_handler;
use log::{debug, error, warn}; use crate::session_handler::SessionHandler;
use log::{error, warn};
use std::collections::HashMap; use std::collections::HashMap;
use std::io; use std::io;
use std::str::FromStr; use std::str::FromStr;
@ -44,40 +46,6 @@ pub enum Response {
#[derive(Clone, Default)] #[derive(Clone, Default)]
pub struct NoContext; pub struct NoContext;
struct SessionHandler<T> {
entry_rx: mpsc::Receiver<Entry>,
event_handlers: Vec<EventHandler<T>>,
}
impl<T: Clone + Default> SessionHandler<T> {
fn new(entry_rx: mpsc::Receiver<Entry>, handlers_rx: &mpsc::Receiver<EventHandler<T>>) -> Self {
debug!(
"New thread for session {}",
thread::current().name().unwrap()
);
let mut event_handlers = Vec::new();
for h in handlers_rx.iter() {
debug!("Event handler registered");
event_handlers.push(h);
}
SessionHandler {
entry_rx,
event_handlers,
}
}
fn read_entries(&self) {
let mut context: T = Default::default();
for e in self.entry_rx.iter() {
for h in self.event_handlers.iter() {
if h.is_callable(&e.event) {
h.call(&e, &mut context);
}
}
}
}
}
#[derive(Default)] #[derive(Default)]
pub struct SmtpIn<T> { pub struct SmtpIn<T> {
sessions: HashMap<u64, (mpsc::Sender<Entry>, thread::JoinHandle<()>)>, sessions: HashMap<u64, (mpsc::Sender<Entry>, thread::JoinHandle<()>)>,

View file

@ -0,0 +1,50 @@
// Copyright (c) 2019 Rodolphe Bréard
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use crate::entry::Entry;
use crate::event_handlers::EventHandler;
use log::debug;
use std::sync::mpsc;
use std::thread;
pub struct SessionHandler<T> {
entry_rx: mpsc::Receiver<Entry>,
event_handlers: Vec<EventHandler<T>>,
}
impl<T: Clone + Default> SessionHandler<T> {
pub fn new(
entry_rx: mpsc::Receiver<Entry>,
handlers_rx: &mpsc::Receiver<EventHandler<T>>,
) -> Self {
debug!(
"New thread for session {}",
thread::current().name().unwrap()
);
let mut event_handlers = Vec::new();
for h in handlers_rx.iter() {
debug!("Event handler registered");
event_handlers.push(h);
}
SessionHandler {
entry_rx,
event_handlers,
}
}
pub fn read_entries(&self) {
let mut context: T = Default::default();
for e in self.entry_rx.iter() {
for h in self.event_handlers.iter() {
if h.is_callable(&e.event) {
h.call(&e, &mut context);
}
}
}
}
}