Compiling with a MPSC channel

This commit is contained in:
Quentin 2022-06-09 10:43:38 +02:00
parent cbcc339d50
commit 1e4d5eb8f1
Signed by: quentin
GPG key ID: E9602264D639FF68
2 changed files with 51 additions and 36 deletions

View file

@ -12,15 +12,14 @@ use crate::mailstore::Mailstore;
use crate::mailbox::Mailbox; use crate::mailbox::Mailbox;
use crate::service::Session; use crate::service::Session;
pub struct Command { pub struct Command<'a> {
tag: Tag, tag: Tag,
mailstore: Arc<Mailstore>, session: &'a mut Session,
session: Arc<Mutex<Session>>,
} }
impl Command { impl<'a> Command<'a> {
pub fn new(tag: Tag, mailstore: Arc<Mailstore>, session: Arc<Mutex<Session>>) -> Self { pub fn new(tag: Tag, session: &'a mut Session) -> Self {
Self { tag, mailstore, session } Self { tag, session }
} }
pub async fn capability(&self) -> Result<Response, BalError> { pub async fn capability(&self) -> Result<Response, BalError> {
@ -31,24 +30,19 @@ impl Command {
Ok(r) Ok(r)
} }
pub async fn login(&self, username: AString, password: AString) -> Result<Response, BalError> { pub async fn login(&mut self, username: AString, password: AString) -> Result<Response, BalError> {
let (u, p) = match (String::try_from(username), String::try_from(password)) { let (u, p) = match (String::try_from(username), String::try_from(password)) {
(Ok(u), Ok(p)) => (u, p), (Ok(u), Ok(p)) => (u, p),
_ => return Response::bad("Invalid characters"), _ => return Response::bad("Invalid characters"),
}; };
tracing::debug!(user = %u, "command.login"); tracing::debug!(user = %u, "command.login");
let creds = match self.mailstore.login_provider.login(&u, &p).await { let creds = match self.session.mailstore.login_provider.login(&u, &p).await {
Err(_) => return Response::no("[AUTHENTICATIONFAILED] Authentication failed."), Err(_) => return Response::no("[AUTHENTICATIONFAILED] Authentication failed."),
Ok(c) => c, Ok(c) => c,
}; };
let mut session = match self.session.lock() { self.session.creds = Some(creds);
Err(_) => return Response::bad("[AUTHENTICATIONFAILED] Unable to acquire lock on session."),
Ok(s) => s,
};
session.creds = Some(creds);
drop(session);
Response::ok("Logged in") Response::ok("Logged in")
} }
@ -61,16 +55,10 @@ impl Command {
Response::bad("Not implemented") Response::bad("Not implemented")
} }
pub async fn select(&self, mailbox: MailboxCodec) -> Result<Response, BalError> { pub async fn select(&mut self, mailbox: MailboxCodec) -> Result<Response, BalError> {
let mut session = match self.session.lock() { let mb = Mailbox::new(self.session.creds.as_ref().unwrap(), "TestMailbox".to_string()).unwrap();
Err(_) => return Response::no("[SELECTFAILED] Unable to acquire lock on session."), self.session.selected = Some(mb);
Ok(s) => s,
};
let mb = Mailbox::new(session.creds.as_ref().unwrap(), "TestMailbox".to_string()).unwrap();
session.selected = Some(mb);
drop(session);
Response::bad("Not implemented") Response::bad("Not implemented")
} }

View file

@ -6,7 +6,10 @@ use boitalettres::server::accept::addr::AddrStream;
use boitalettres::errors::Error as BalError; use boitalettres::errors::Error as BalError;
use boitalettres::proto::{Request, Response}; use boitalettres::proto::{Request, Response};
use futures::future::BoxFuture; use futures::future::BoxFuture;
use futures::future::FutureExt;
use imap_codec::types::command::CommandBody; use imap_codec::types::command::CommandBody;
use tokio::sync::mpsc;
use tokio::sync::mpsc::error::TrySendError;
use tower::Service; use tower::Service;
use crate::command; use crate::command;
@ -14,6 +17,8 @@ use crate::login::Credentials;
use crate::mailstore::Mailstore; use crate::mailstore::Mailstore;
use crate::mailbox::Mailbox; use crate::mailbox::Mailbox;
const MAX_PIPELINED_COMMANDS: usize = 10;
pub struct Instance { pub struct Instance {
pub mailstore: Arc<Mailstore>, pub mailstore: Arc<Mailstore>,
} }
@ -38,18 +43,17 @@ impl<'a> Service<&'a AddrStream> for Instance {
} }
} }
pub struct Session {
pub creds: Option<Credentials>,
pub selected: Option<Mailbox>,
}
pub struct Connection { pub struct Connection {
pub mailstore: Arc<Mailstore>, pub tx: mpsc::Sender<Request>,
pub session: Arc<Mutex<Session>>,
} }
impl Connection { impl Connection {
pub fn new(mailstore: Arc<Mailstore>) -> Self { pub fn new(mailstore: Arc<Mailstore>) -> Self {
Self { mailstore, session: Arc::new(Mutex::new(Session { creds: None, selected: None, })) } let (tx, mut rx) = mpsc::channel(MAX_PIPELINED_COMMANDS);
tokio::spawn(async move {
let mut session = Session::new(mailstore, rx);
session.run().await;
});
Self { tx }
} }
} }
impl Service<Request> for Connection { impl Service<Request> for Connection {
@ -63,9 +67,32 @@ impl Service<Request> for Connection {
fn call(&mut self, req: Request) -> Self::Future { fn call(&mut self, req: Request) -> Self::Future {
tracing::debug!("Got request: {:#?}", req); tracing::debug!("Got request: {:#?}", req);
let cmd = command::Command::new(req.tag, self.mailstore.clone(), self.session.clone()); match self.tx.try_send(req) {
Box::pin(async move { Ok(()) => return async { Response::ok("Ok") }.boxed(),
match req.body { Err(TrySendError::Full(_)) => return async { Response::bad("Too fast! Send less pipelined requests!") }.boxed(),
Err(TrySendError::Closed(_)) => return async { Response::bad("The session task has exited") }.boxed(),
}
// send a future that await here later a oneshot command
}
}
pub struct Session {
pub mailstore: Arc<Mailstore>,
pub creds: Option<Credentials>,
pub selected: Option<Mailbox>,
rx: mpsc::Receiver<Request>,
}
impl Session {
pub fn new(mailstore: Arc<Mailstore>, rx: mpsc::Receiver<Request>) -> Self {
Self { mailstore, rx, creds: None, selected: None, }
}
pub async fn run(&mut self) {
while let Some(req) = self.rx.recv().await {
let mut cmd = command::Command::new(req.tag, self);
let _ = match req.body {
CommandBody::Capability => cmd.capability().await, CommandBody::Capability => cmd.capability().await,
CommandBody::Login { username, password } => cmd.login(username, password).await, CommandBody::Login { username, password } => cmd.login(username, password).await,
CommandBody::Lsub { reference, mailbox_wildcard } => cmd.lsub(reference, mailbox_wildcard).await, CommandBody::Lsub { reference, mailbox_wildcard } => cmd.lsub(reference, mailbox_wildcard).await,
@ -73,8 +100,8 @@ impl Service<Request> for Connection {
CommandBody::Select { mailbox } => cmd.select(mailbox).await, CommandBody::Select { mailbox } => cmd.select(mailbox).await,
CommandBody::Fetch { sequence_set, attributes, uid } => cmd.fetch(sequence_set, attributes, uid).await, CommandBody::Fetch { sequence_set, attributes, uid } => cmd.fetch(sequence_set, attributes, uid).await,
_ => Response::bad("Error in IMAP command received by server."), _ => Response::bad("Error in IMAP command received by server."),
};
} }
})
} }
} }