async_session

Struct Session

Source
pub struct Session { /* private fields */ }
Expand description

§The main session type.

§Cloning and Serialization

The cookie_value field is not cloned or serialized, and it can only be read through into_cookie_value. The intent of this field is that it is set either by initialization or by a session store, and read exactly once in order to set the cookie value.

§Change tracking session tracks whether any of its inner data

was changed since it was last serialized. Any sessoin store that does not undergo a serialization-deserialization cycle must call Session::reset_data_changed in order to reset the change tracker on an individual record.

§Change tracking example

let mut session = Session::new();
assert!(!session.data_changed());

session.insert("key", 1)?;
assert!(session.data_changed());

session.reset_data_changed();
assert_eq!(session.get::<usize>("key").unwrap(), 1);
assert!(!session.data_changed());

session.insert("key", 2)?;
assert!(session.data_changed());
assert_eq!(session.get::<usize>("key").unwrap(), 2);

session.insert("key", 1)?;
assert!(session.data_changed(), "reverting the data still counts as a change");

session.reset_data_changed();
assert!(!session.data_changed());
session.remove("nonexistent key");
assert!(!session.data_changed());
session.remove("key");
assert!(session.data_changed());

Implementations§

Source§

impl Session

Source

pub fn new() -> Self

Create a new session. Generates a random id and matching cookie value. Does not set an expiry by default

§Example
let session = Session::new();
assert_eq!(None, session.expiry());
assert!(session.into_cookie_value().is_some());

applies a cryptographic hash function on a cookie value returned by Session::into_cookie_value to obtain the session id for that cookie. Returns an error if the cookie format is not recognized

§Example
let session = Session::new();
let id = session.id().to_string();
let cookie_value = session.into_cookie_value().unwrap();
assert_eq!(id, Session::id_from_cookie_value(&cookie_value)?);
Source

pub fn destroy(&mut self)

mark this session for destruction. the actual session record is not destroyed until the end of this response cycle.

§Example
let mut session = Session::new();
assert!(!session.is_destroyed());
session.destroy();
assert!(session.is_destroyed());
Source

pub fn is_destroyed(&self) -> bool

returns true if this session is marked for destruction

§Example
let mut session = Session::new();
assert!(!session.is_destroyed());
session.destroy();
assert!(session.is_destroyed());
Source

pub fn id(&self) -> &str

Gets the session id

§Example
let session = Session::new();
let id = session.id().to_owned();
let cookie_value = session.into_cookie_value().unwrap();
assert_eq!(id, Session::id_from_cookie_value(&cookie_value)?);
Source

pub fn insert(&mut self, key: &str, value: impl Serialize) -> Result<(), Error>

inserts a serializable value into the session hashmap. returns an error if the serialization was unsuccessful.

§Example
#[derive(Serialize, Deserialize)]
struct User {
    name: String,
    legs: u8
}
let mut session = Session::new();
session.insert("user", User { name: "chashu".into(), legs: 4 }).expect("serializable");
assert_eq!(r#"{"name":"chashu","legs":4}"#, session.get_raw("user").unwrap());
Source

pub fn insert_raw(&mut self, key: &str, value: String)

inserts a string into the session hashmap

§Example
let mut session = Session::new();
session.insert_raw("ten", "10".to_string());
let ten: usize = session.get("ten").unwrap();
assert_eq!(ten, 10);
Source

pub fn get<T: DeserializeOwned>(&self, key: &str) -> Option<T>

deserializes a type T out of the session hashmap

§Example
let mut session = Session::new();
session.insert("key", vec![1, 2, 3]);
let numbers: Vec<usize> = session.get("key").unwrap();
assert_eq!(vec![1, 2, 3], numbers);
Source

pub fn get_raw(&self, key: &str) -> Option<String>

returns the String value contained in the session hashmap

§Example
let mut session = Session::new();
session.insert("key", vec![1, 2, 3]);
assert_eq!("[1,2,3]", session.get_raw("key").unwrap());
Source

pub fn remove(&mut self, key: &str)

removes an entry from the session hashmap

§Example
let mut session = Session::new();
session.insert("key", "value");
session.remove("key");
assert!(session.get_raw("key").is_none());
assert_eq!(session.len(), 0);
Source

pub fn len(&self) -> usize

returns the number of elements in the session hashmap

§Example
let mut session = Session::new();
assert_eq!(session.len(), 0);
session.insert("key", 0);
assert_eq!(session.len(), 1);
Source

pub fn regenerate(&mut self)

Generates a new id and cookie for this session

§Example
let mut session = Session::new();
let old_id = session.id().to_string();
session.regenerate();
assert!(session.id() != &old_id);
let new_id = session.id().to_string();
let cookie_value = session.into_cookie_value().unwrap();
assert_eq!(new_id, Session::id_from_cookie_value(&cookie_value)?);

sets the cookie value that this session will use to serialize itself. this should only be called by cookie stores. any other uses of this method will result in the cookie not getting correctly deserialized on subsequent requests.

§Example
let mut session = Session::new();
session.set_cookie_value("hello".to_owned());
let cookie_value = session.into_cookie_value().unwrap();
assert_eq!(cookie_value, "hello".to_owned());
Source

pub fn expiry(&self) -> Option<&DateTime<Utc>>

returns the expiry timestamp of this session, if there is one

§Example
let mut session = Session::new();
assert_eq!(None, session.expiry());
session.expire_in(std::time::Duration::from_secs(1));
assert!(session.expiry().is_some());
Source

pub fn set_expiry(&mut self, expiry: DateTime<Utc>)

assigns an expiry timestamp to this session

§Example
let mut session = Session::new();
assert_eq!(None, session.expiry());
session.set_expiry(chrono::Utc::now());
assert!(session.expiry().is_some());
Source

pub fn expire_in(&mut self, ttl: Duration)

assigns the expiry timestamp to a duration from the current time.

§Example
let mut session = Session::new();
assert_eq!(None, session.expiry());
session.expire_in(std::time::Duration::from_secs(1));
assert!(session.expiry().is_some());
Source

pub fn is_expired(&self) -> bool

predicate function to determine if this session is expired. returns false if there is no expiry set, or if it is in the past.

§Example
let mut session = Session::new();
assert_eq!(None, session.expiry());
assert!(!session.is_expired());
session.expire_in(Duration::from_secs(1));
assert!(!session.is_expired());
task::sleep(Duration::from_secs(2)).await;
assert!(session.is_expired());
Source

pub fn validate(self) -> Option<Self>

Ensures that this session is not expired. Returns None if it is expired

§Example
let session = Session::new();
let mut session = session.validate().unwrap();
session.expire_in(Duration::from_secs(1));
let session = session.validate().unwrap();
task::sleep(Duration::from_secs(2)).await;
assert_eq!(None, session.validate());
Source

pub fn data_changed(&self) -> bool

Checks if the data has been modified. This is based on the implementation of PartialEq for the inner data type.

§Example
let mut session = Session::new();
assert!(!session.data_changed(), "new session is not changed");
session.insert("key", 1);
assert!(session.data_changed());

session.reset_data_changed();
assert!(!session.data_changed());
session.remove("key");
assert!(session.data_changed());
Source

pub fn reset_data_changed(&self)

Resets data_changed dirty tracking. This is unnecessary for any session store that serializes the data to a string on storage.

§Example
let mut session = Session::new();
assert!(!session.data_changed(), "new session is not changed");
session.insert("key", 1);
assert!(session.data_changed());

session.reset_data_changed();
assert!(!session.data_changed());
session.remove("key");
assert!(session.data_changed());
Source

pub fn expires_in(&self) -> Option<Duration>

Ensures that this session is not expired. Returns None if it is expired

§Example
let mut session = Session::new();
session.expire_in(Duration::from_secs(123));
let expires_in = session.expires_in().unwrap();
assert!(123 - expires_in.as_secs() < 2);

Duration from now to the expiry time of this session

takes the cookie value and consume this session. this is generally only performed by the session store

§Example
let mut session = Session::new();
session.set_cookie_value("hello".to_owned());
let cookie_value = session.into_cookie_value().unwrap();
assert_eq!(cookie_value, "hello".to_owned());

Trait Implementations§

Source§

impl Clone for Session

Source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Session

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Session

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Session

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for Session

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Session

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,