Skip to content

Commit

Permalink
Fix taking session and writing at the same time. Fixes tomhoule#3
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathanKingston committed May 28, 2019
1 parent 5010d33 commit 38f75f9
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,16 @@ pub trait ContextExt {

impl<AppData> ContextExt for tide::Context<AppData> {
fn set_session<T: 'static + Sync + Send + Default>(&mut self, new_session: T) -> Result<(), StringError> {
// Handle old session if hasn't been taken
let session = self
.extensions_mut()
.remove::<Session<T>>()
.remove::<Session<T>>();

let sender = self
.extensions_mut()
.remove::<oneshot::Sender<T>>()
.ok_or_else(|| StringError(MIDDLEWARE_MISSING_MSG.to_owned()))?;
session
.sender
sender
.send(new_session)
.map_err(|_| StringError("Unable to handle session".to_owned()))
}
Expand All @@ -50,16 +54,15 @@ impl<AppData> ContextExt for tide::Context<AppData> {
/// copied often, so it is preferrable not to store large amounts of data in the session.
pub struct Session<Shape> {
data: Shape,
sender: oneshot::Sender<Shape>,
}

impl<SessionShape> Session<SessionShape>
where
SessionShape: Default,
{
fn new(data: SessionShape) -> (Self, oneshot::Receiver<SessionShape>) {
fn new(data: SessionShape) -> (Self, oneshot::Sender<SessionShape>, oneshot::Receiver<SessionShape>) {
let (sender, receiver) = oneshot::channel();
(Session { data, sender }, receiver)
(Session { data }, sender, receiver)
}
}

Expand Down Expand Up @@ -117,8 +120,9 @@ where
.and_then(|a| a)
.unwrap_or_default();

let (session, mut receiver) = Session::new(session_shape);
let (session, sender, mut receiver) = Session::new(session_shape);
ctx.extensions_mut().insert::<Session<Shape>>(session);
ctx.extensions_mut().insert::<oneshot::Sender<Shape>>(sender);

let mut session_cookie = Cookie::new(self.cookie_name.clone(), session_id.clone());
session_cookie.set_path("/");
Expand Down

0 comments on commit 38f75f9

Please sign in to comment.