1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/* Copyright 2016 Joshua Gentry
 *
 * 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 std::any::Any;
use std::fmt::Write;
use std::sync::{Arc, Mutex, MutexGuard};
use time::Timespec;

use iron::typemap::Key;

use FeSessionState;

//*************************************************************************************************
/// This object holds information about the session for the current request.
///
/// FeSession can either be pulled directly out of the request or you can use the convenience
/// functions in FeSessionRequest.
///
/// # Examples
///
/// Accessing from directly from the request.
///
/// ```
/// # extern crate iron;
/// # extern crate fe_session;
/// # extern crate time;
/// use std::sync::{Arc, Mutex};
/// use std::fmt::Write;
/// use iron::{Iron, Chain, Request, Response};
/// use iron::status::Status;
/// use fe_session::{FeSessionStorage, FeSession, FeConnection, FeSessionState};
/// use time::*;
///
/// # fn main() {
/// let mut chain = Chain::new(|req : &mut Request| {
///     let mut session = req.extensions.get_mut::<FeSession<usize>>().unwrap().clone();
///     let mut result  = String::new();
///
///     match session.state() {
///         FeSessionState::Expired => { // Old session expired, create a new one.
///             req.extensions.insert::<FeSession<usize>>(
///                 FeSession::new(
///                     None,
///                     FeSessionState::Active,
///                     get_time(),
///                     Some(Arc::new(Mutex::new(0)))
///                     )
///                 );
////            write!(result, "{}", 0).unwrap();
///         },
///         FeSessionState::None => { // No session, create a new one.
///             req.extensions.insert::<FeSession<usize>>(
///                 FeSession::new(
///                     None,
///                     FeSessionState::Active,
///                     get_time(),
///                     Some(Arc::new(Mutex::new(0)))
///                     )
///                 );
///            write!(result, "{}", 0).unwrap();
///         },
///         FeSessionState::Active => {
///             let mut count = session.get();
///
///             *count += 1;
///             write!(result, "{}", *count).unwrap();
///         }
///     }
///     Ok(Response::with((Status::Ok, result)))
/// });
///
/// chain.around(FeSessionStorage::<usize>::new());
///
/// let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();
///
/// let mut conn1 = FeConnection::new("localhost", 3000);
/// let mut conn2 = FeConnection::new("localhost", 3000);
///
/// assert_eq!(conn1.get_string("/"), "0");
/// assert_eq!(conn2.get_string("/"), "0");
/// assert_eq!(conn1.get_string("/"), "1");
/// assert_eq!(conn1.get_string("/"), "2");
/// assert_eq!(conn2.get_string("/"), "1");
///
/// iron.close().unwrap();
/// # }
/// ```
///
/// Or the recommended way using FeSessionRequest.
///
/// ```
/// # extern crate iron;
/// # extern crate fe_session;
/// use std::fmt::Write;
/// use iron::{Iron, Chain, Request, Response};
/// use iron::status::Status;
/// use fe_session::{FeSessionStorage, FeConnection, FeSessionRequest, FeSessionState};
///
/// # fn main() {
/// let mut chain = Chain::new(|req : &mut Request| {
///     let mut session = req.get_session::<usize>();
///     let mut result  = String::new();
///
///     match session.state() {
///         FeSessionState::Expired => { // Old session expired, create a new one.
///             req.create_session(0 as usize);
////            write!(result, "{}", 0).unwrap();
///         },
///         FeSessionState::None => { // No session, create a new one.
///            req.create_session(0 as usize);
///            write!(result, "{}", 0).unwrap();
///         },
///         FeSessionState::Active => {
///             let mut count = session.get();
///
///             *count += 1;
///             write!(result, "{}", *count).unwrap();
///         }
///     }
///     Ok(Response::with((Status::Ok, result)))
/// });
///
/// chain.around(FeSessionStorage::<usize>::new());
///
/// let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();
///
/// let mut conn1 = FeConnection::new("localhost", 3000);
/// let mut conn2 = FeConnection::new("localhost", 3000);
///
/// assert_eq!(conn1.get_string("/"), "0");
/// assert_eq!(conn2.get_string("/"), "0");
/// assert_eq!(conn1.get_string("/"), "1");
/// assert_eq!(conn1.get_string("/"), "2");
/// assert_eq!(conn2.get_string("/"), "1");
///
/// iron.close().unwrap();
/// # }
/// ```
#[derive(Debug)]
pub struct FeSession<T : 'static>
{
    //---------------------------------------------------------------------------------------------
    /// The session key for the session if it's defined.  Newly created sessions don't get a
    /// session key until the request has been handled and the session key sent back to the client.
    key : Option<u32>,

    //---------------------------------------------------------------------------------------------
    /// The curren state of the session active/none/expired.
    state : FeSessionState,

    //---------------------------------------------------------------------------------------------
    /// The last time we handled a request for the session.
    last_accessed : Timespec,

    //---------------------------------------------------------------------------------------------
    /// The session for this request if it exists.  If the state is none or expired this will be
    /// none.
    session : Option<Arc<Mutex<T>>>,

    //---------------------------------------------------------------------------------------------
    /// If the client panics while holding the mutex for the session, this flag will be set.  This
    /// value is initialized to false when we start handing a request.  When the clients goes to
    /// get the mutex if it's poisoned this flag will then be set.
    poisoned : bool
}

impl<T> FeSession<T>
{
    //*********************************************************************************************
    /// Creates a new instance of the object.
    ///
    /// Most clients probably won't need to use this function.  Intead they should use the
    /// method exported by FeSessionRequest.
    ///
    /// If you are calling this function manually the key should be set to None.  If this is not
    /// set to None then there is a chance the session won't be saved.
    ///
    /// For the state only only FeSessionState::None and FeSessionState::Active make sense
    /// however setting it to FeSessionState::Expired will not cause any issues.
    ///
    /// # Examples
    ///
    /// Manually changing the session.
    ///
    /// ```
    /// # extern crate iron;
    /// # extern crate fe_session;
    /// # extern crate time;
    /// use std::sync::{Arc, Mutex};
    /// use iron::{Iron, Chain, Request, Response};
    /// use iron::status::Status;
    /// use fe_session::{FeSessionStorage, FeSession, FeConnection, FeSessionState};
    /// use time::get_time;
    ///
    /// struct MySession;
    ///
    /// # fn main() {
    /// let mut chain = Chain::new(|req : &mut Request| {
    ///
    ///     if req.url.path()[0] == "clear" {
    ///         req.extensions.insert::<FeSession<MySession>>(
    ///             FeSession::new(None, FeSessionState::None, get_time(), None)
    ///             );
    ///         Ok(Response::with((Status::Ok, "cleared")))
    ///     }
    ///     else {
    ///         req.extensions.insert::<FeSession<MySession>>(
    ///             FeSession::new(
    ///                 None,
    ///                 FeSessionState::Active,
    ///                 get_time(),
    ///                 Some(Arc::new(Mutex::new(MySession)))
    ///                 )
    ///             );
    ///         Ok(Response::with((Status::Ok, "new")))
    ///     }
    /// });
    ///
    /// chain.around(FeSessionStorage::<usize>::new());
    ///
    /// let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();
    ///
    /// let mut conn = FeConnection::new("localhost", 3000);
    ///
    /// assert_eq!(conn.get_string("/clear"), "cleared");
    /// assert_eq!(conn.get_string("/"), "new");
    ///
    /// iron.close().unwrap();
    /// # }
    /// ```
    ///
    /// Recommended way of changing the session.
    ///
    /// ```
    /// # extern crate iron;
    /// # extern crate fe_session;
    /// use iron::{Iron, Chain, Request, Response};
    /// use iron::status::Status;
    /// use fe_session::{FeSessionStorage, FeConnection, FeSessionRequest};
    ///
    /// struct MySession;
    ///
    /// # fn main() {
    /// let mut chain = Chain::new(|req : &mut Request| {
    ///
    ///     if req.url.path()[0] == "clear" {
    ///         req.clear_session::<MySession>();
    ///         Ok(Response::with((Status::Ok, "cleared")))
    ///     }
    ///     else {
    ///         req.create_session(MySession);
    ///         Ok(Response::with((Status::Ok, "new")))
    ///     }
    /// });
    ///
    /// chain.around(FeSessionStorage::<usize>::new());
    ///
    /// let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();
    ///
    /// let mut conn = FeConnection::new("localhost", 3000);
    ///
    /// assert_eq!(conn.get_string("/clear"), "cleared");
    /// assert_eq!(conn.get_string("/"), "new");
    ///
    /// iron.close().unwrap();
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// If the state is set to FeSessionState::Active but the session is None this method will
    /// panic.
    pub fn new(
        key           : Option<u32>,
        state         : FeSessionState,
        last_accessed : Timespec,
        session       : Option<Arc<Mutex<T>>>
        ) -> FeSession<T>
    {
        if state.is_active() && session.is_none()
        {
            panic!("State is Active but there no session.");
        }

        FeSession {
            key           : key,
            state         : state,
            last_accessed : last_accessed,
            session       : session,
            poisoned      : false
        }
    }

    //*********************************************************************************************
    /// Returns the session key for this session if it is defined.  This is normally defined for
    /// an active session.  However if a session is newly created it will not be created until the
    /// request has been completed.
    pub fn key(&self) -> Option<u32>
    {
        self.key
    }

    //*********************************************************************************************
    /// Returns the current state of the session.
    pub fn state(&self) -> FeSessionState
    {
        self.state
    }

    //*********************************************************************************************
    /// Returns the time we last processed a request for this session.
    pub fn last_accessed(&self) -> &Timespec
    {
        &self.last_accessed
    }

    //*********************************************************************************************
    /// Returns true if the mutex protecting the session is poisoned.  This means we've panicked
    /// while holding the session mutex.  This value does not get set in a reuqest until the
    /// get() method is called.
    pub fn poisoned(&self) -> bool
    {
        self.poisoned
    }

    //*********************************************************************************************
    /// Acquires the mutex for the session and returns the MutexGuard.  This means that any other
    /// requests that want to modify the session will be blocked until the MutexGuard is destroyed.
    ///
    /// # Examples
    /// ```
    /// # extern crate iron;
    /// # extern crate fe_session;
    /// use std::fmt::Write;
    /// use std::sync::{Arc, Mutex};
    /// use iron::{Iron, Chain, Request, Response};
    /// use iron::status::Status;
    /// use fe_session::{FeSessionStorage, FeSession, FeConnection, FeSessionRequest, FeSessionState};
    ///
    /// # fn main() {
    /// let mut chain = Chain::new(|req : &mut Request| {
    ///     let mut session = req.get_session::<usize>();
    ///     let mut result  = String::new();
    ///
    ///     match session.state() {
    ///         FeSessionState::Expired => { // Old session expired, create a new one.
    ///             req.create_session(0 as usize);
    ////            write!(result, "{}", 0).unwrap();
    ///         },
    ///         FeSessionState::None => { // No session, create a new one.
    ///            req.create_session(0 as usize);
    ///            write!(result, "{}", 0).unwrap();
    ///         },
    ///         FeSessionState::Active => {
    ///             let mut count = session.get();
    ///
    ///             *count += 1;
    ///             write!(result, "{}", *count).unwrap();
    ///         }
    ///     }
    ///     Ok(Response::with((Status::Ok, result)))
    /// });
    ///
    /// chain.around(FeSessionStorage::<usize>::new());
    ///
    /// let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();
    ///
    /// let mut conn1 = FeConnection::new("localhost", 3000);
    /// let mut conn2 = FeConnection::new("localhost", 3000);
    ///
    /// assert_eq!(conn1.get_string("/"), "0");
    /// assert_eq!(conn2.get_string("/"), "0");
    /// assert_eq!(conn1.get_string("/"), "1");
    /// assert_eq!(conn1.get_string("/"), "2");
    /// assert_eq!(conn2.get_string("/"), "1");
    ///
    /// iron.close().unwrap();
    /// # }
    /// ```
    /// # Panics
    ///
    /// This method will panic if the state is not FeSessionState::Active.
    pub fn get(&mut self) -> MutexGuard<T>
    {
        match self.session
        {
            //-------------------------------------------------------------------------------------
            // Got the mutex, lock it and return the MutexGuard.
            Some(ref mutex) => {
                match mutex.lock()
                {
                    //-----------------------------------------------------------------------------
                    // No problems return the MutexGuard.
                    Ok(guard) => {
                        guard
                    },
                    //-----------------------------------------------------------------------------
                    // The mutex is poisoned, log a warning, change the flag but still return
                    // the MutexGuard.
                    Err(poison) => {
                        let mut result = String::with_capacity(8);

                        if let Some(key) = self.key
                        {
                            write!(result, "{:x}", key).unwrap();
                        }
                        else
                        {
                            result.push_str("<new>");
                        }

                        warn!("Session {} poisoned.", result);
                        self.poisoned = true;
                        poison.into_inner()
                    }
                }
            },
            //-------------------------------------------------------------------------------------
            // There is no session, panic.
            None => {
                panic!("No session to return.");
            }
        }
    }

    //*********************************************************************************************
    /// Destroys the object and returns Arc<Mutex<T>> protecting the user's session.
    ///
    /// # Panics
    ///
    /// This method will panic if the state is not FeSessionState::Active.
    pub fn raw(self) -> Arc<Mutex<T>>
    {
        self.session.unwrap()
    }
}

impl<T> Clone for FeSession<T>
{
    //*********************************************************************************************
    /// Implementation of Clone.
    fn clone(&self) -> FeSession<T>
    {
        FeSession {
            key           : self.key.clone(),
            state         : self.state,
            last_accessed : self.last_accessed.clone(),
            session       : self.session.clone(),
            poisoned      : self.poisoned
        }
    }

    //*********************************************************************************************
    /// Implementation of Clone.
    fn clone_from(
        &mut self,
        source: &FeSession<T>
        )
    {
        self.key           = source.key.clone();
        self.state         = source.state;
        self.last_accessed = source.last_accessed.clone();
        self.session       = source.session.clone();
        self.poisoned      = source.poisoned;
    }
}

impl<T : Any> Key for FeSession<T>
{
    type Value = FeSession<T>;
}