Struct tower_sessions::Session

source ยท
pub struct Session { /* private fields */ }
Expand description

A session which allows HTTP applications to associate key-value pairs with visitors.

Implementationsยง

sourceยง

impl Session

source

pub fn new(expiration_time: Option<OffsetDateTime>) -> Self

Create a new session with defaults.

If an expiration_time is not specified, the session will use an expiration strategy of โ€œSession,โ€ which means it will persist only until the userโ€™s session ends.

Examples
 use tower_sessions::Session;
 let session = Session::default();
source

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

Inserts a impl Serialize value into the session.

Examples
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42).expect("Serialization error.");
Errors

This method can fail when serde_json::to_value fails.

source

pub fn insert_value(&self, key: &str, value: Value) -> Option<Value>

Inserts a serde_json::Value into the session.

If the key was not present in the underlying map, None is returned and modified is set to true.

If the underlying map did have the key and its value is the same as the provided value, None is returned and modified is not set.

Examples
use tower_sessions::Session;
let session = Session::default();
let value = session.insert_value("foo", serde_json::json!(42));
assert!(value.is_none());

let value = session.insert_value("foo", serde_json::json!(42));
assert!(value.is_none());

let value = session.insert_value("foo", serde_json::json!("bar"));
assert_eq!(value, Some(serde_json::json!(42)));
source

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

Gets a value from the store.

Examples
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42).unwrap();
let value = session.get::<usize>("foo").unwrap();
assert_eq!(value, Some(42));
Errors

This method can fail when serde_json::from_value fails.

source

pub fn get_value(&self, key: &str) -> Option<Value>

Gets a serde_json::Value from the store.

Examples
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42).unwrap();
let value = session.get_value("foo").unwrap();
assert_eq!(value, serde_json::json!(42));
source

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

Removes a value from the store, retuning the value of the key if it was present in the underlying map.

Examples
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42).unwrap();
let value: Option<usize> = session.remove("foo").unwrap();
assert_eq!(value, Some(42));
let value: Option<usize> = session.get("foo").unwrap();
assert!(value.is_none());
Errors

This method can fail when serde_json::from_value fails.

source

pub fn remove_value(&self, key: &str) -> Option<Value>

Removes a serde_json::Value from the store.

Examples
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42).unwrap();
let value = session.remove_value("foo").unwrap();
assert_eq!(value, serde_json::json!(42));
let value: Option<usize> = session.get("foo").unwrap();
assert!(value.is_none());
source

pub fn replace_if_equal( &self, key: &str, old_value: impl Serialize, new_value: impl Serialize ) -> Result<bool, SessionError>

Replaces a value in the session with a new value if the current value matches the old value.

If the key was not present in the underlying map or the current value does not match, false is returned, indicating failure.

If the key was present and its value matches the old value, the new value is inserted, and true is returned, indicating success.

This method is essential for scenarios where data races need to be prevented. For instance, reading from and writing to a session is not transactional. To ensure that read values are not stale, itโ€™s crucial to use replace_if_equal when modifying the session.

Examples
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42).unwrap();

let success = session.replace_if_equal("foo", 42, 43).unwrap();
assert_eq!(success, true);

let success = session.replace_if_equal("foo", 42, 44).unwrap();
assert_eq!(success, false);
Errors

This method can fail when serde_json::to_value fails.

source

pub fn clear(&self)

Clears the session data.

Examples
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42).unwrap();
session.clear();
assert!(session.get_value("foo").is_none());
source

pub fn delete(&self)

Sets deleted on the session to SessionDeletion::Deleted.

Setting this flag indicates the session should be deleted from the underlying store.

This flag is consumed by a session management system to ensure session life cycle progression.

Examples
use tower_sessions::{session::SessionDeletion, Session};
let session = Session::default();
session.delete();
assert!(matches!(session.deleted(), Some(SessionDeletion::Deleted)));
source

pub fn cycle_id(&self)

Sets deleted on the session to SessionDeletion::Cycled(self.id)).

Setting this flag indicates the session ID should be cycled while retaining the sessionโ€™s data.

This flag is consumed by a session management system to ensure session life cycle progression.

Examples
use tower_sessions::{session::SessionDeletion, Session};
let session = Session::default();
session.insert("foo", 42);
session.cycle_id();
assert!(matches!(
    session.deleted(),
    Some(SessionDeletion::Cycled(ref cycled_id)) if cycled_id == session.id()
));
source

pub fn flush(&self)

Sets deleted on the session to SessionDeletion::Deleted and clears the session data.

This helps ensure that session data cannot be accessed beyond this invocation.

Examples
use tower_sessions::{session::SessionDeletion, Session};
let session = Session::default();
session.insert("foo", 42).unwrap();
session.flush();
assert!(session.get_value("foo").is_none());
assert!(matches!(session.deleted(), Some(SessionDeletion::Deleted)));
source

pub fn id(&self) -> &SessionId

Get the session ID.

Examples
use tower_sessions::Session;
let session = Session::default();
session.id();
source

pub fn expiration_time(&self) -> Option<OffsetDateTime>

Get the session expiration time.

Examples
use time::{Duration, OffsetDateTime};
use tower_sessions::Session;
let expiration_time = OffsetDateTime::now_utc().saturating_add(Duration::hours(1));
let session = Session::new(Some(expiration_time));
assert!(session
    .expiration_time()
    .is_some_and(|et| et > OffsetDateTime::now_utc()));
source

pub fn set_expiration_time(&self, expiration_time: OffsetDateTime)

Set expiration_time give the given value.

This may be used within applications directly to alter the sessionโ€™s time to live.

Examples
use time::{Duration, OffsetDateTime};
use tower_sessions::Session;
let session = Session::default();
session.set_expiration_time(OffsetDateTime::now_utc());
session.insert("foo", 42);
assert!(!session.active());
assert!(session.modified());

session.set_expiration_time(OffsetDateTime::now_utc().saturating_add(Duration::hours(1)));
assert!(session.active());
assert!(session.modified());
source

pub fn set_expiration_time_from_max_age(&self, max_age: Duration)

Set expiration_time to current time in UTC plus the given max_age duration.

This may be used within applications directly to alter the sessionโ€™s time to live.

Examples
use time::Duration;
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42);
session.set_expiration_time_from_max_age(Duration::minutes(5));
assert!(session.active());
assert!(session.modified());

session.set_expiration_time_from_max_age(Duration::ZERO);
assert!(!session.active());
assert!(session.modified());
source

pub fn active(&self) -> bool

Returns true if the session is active and false otherwise.

Examples
use time::{Duration, OffsetDateTime};
use tower_sessions::Session;
let session = Session::default();
assert!(session.active());

let expiration_time = OffsetDateTime::now_utc().saturating_add(Duration::hours(1));
let session = Session::new(Some(expiration_time));
assert!(session.active());

let expiration_time = OffsetDateTime::now_utc().saturating_add(Duration::ZERO);
let session = Session::new(Some(expiration_time));
assert!(!session.active());
source

pub fn modified(&self) -> bool

Returns true if the session has been modified and false otherwise.

Examples
use tower_sessions::Session;
let session = Session::default();
assert!(!session.modified());
session.insert("foo", 42);
assert!(session.modified());
source

pub fn deleted(&self) -> Option<SessionDeletion>

Returns Some(SessionDeletion) if one has been set and None otherwise.

Examples
use tower_sessions::{session::SessionDeletion, Session};
let session = Session::default();
session.insert("foo", 42);
assert!(session.deleted().is_none());
session.delete();
assert!(matches!(session.deleted(), Some(SessionDeletion::Deleted)));
session.cycle_id();
assert!(matches!(
    session.deleted(),
    Some(SessionDeletion::Cycled(_))
))
source

pub fn is_empty(&self) -> bool

Returns true if the session is empty.

Examples
use tower_sessions::{Session, SessionRecord};
let session = Session::default();
assert!(session.is_empty());

session.insert("foo", 42);
assert!(!session.is_empty());

Trait Implementationsยง

sourceยง

impl Borrow<SessionId> for Session

sourceยง

fn borrow(&self) -> &SessionId

Immutably borrows from an owned value. Read more
sourceยง

impl Clone for Session

sourceยง

fn clone(&self) -> Session

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() -> Session

Returns the โ€œdefault valueโ€ for a type. Read more
sourceยง

impl From<&CookieConfig> for Session

sourceยง

fn from(cookie_config: &CookieConfig) -> Self

Converts to this type from the input type.
sourceยง

impl From<&Session> for SessionRecord

sourceยง

fn from(session: &Session) -> Self

Converts to this type from the input type.
sourceยง

impl From<SessionRecord> for Session

sourceยง

fn from(_: SessionRecord) -> Self

Converts to this type from the input type.
sourceยง

impl<S> FromRequestParts<S> for Sessionwhere S: Sync + Send,

Available on crate feature axum-core only.
ยง

type Rejection = (StatusCode, &'static str)

If the extractor fails itโ€™ll use this โ€œrejectionโ€ type. A rejection is a kind of error that can be converted into a response.
sourceยง

fn from_request_parts<'life0, 'life1, 'async_trait>( parts: &'life0 mut Parts, _state: &'life1 S ) -> Pin<Box<dyn Future<Output = Result<Self, Self::Rejection>> + Send + 'async_trait>>where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Perform the extraction.
sourceยง

impl Hash for Session

sourceยง

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 ยท sourceยง

fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
sourceยง

impl PartialEq for Session

sourceยง

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

This method tests for self and other values to be equal, and is used by ==.
1.0.0 ยท sourceยง

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
sourceยง

impl Eq for Session

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

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

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

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

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

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

sourceยง

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

Mutably borrows from an owned value. Read more
ยง

impl<T> Conv for T

ยง

fn conv<T>(self) -> Twhere Self: Into<T>,

Converts self into T using Into<T>. Read more
ยง

impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

ยง

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
ยง

impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

ยง

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
sourceยง

impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

sourceยง

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
ยง

impl<T> FmtForward for T

ยง

fn fmt_binary(self) -> FmtBinary<Self>where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
ยง

fn fmt_display(self) -> FmtDisplay<Self>where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
ยง

fn fmt_lower_exp(self) -> FmtLowerExp<Self>where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
ยง

fn fmt_lower_hex(self) -> FmtLowerHex<Self>where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
ยง

fn fmt_octal(self) -> FmtOctal<Self>where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
ยง

fn fmt_pointer(self) -> FmtPointer<Self>where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
ยง

fn fmt_upper_exp(self) -> FmtUpperExp<Self>where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
ยง

fn fmt_upper_hex(self) -> FmtUpperHex<Self>where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
ยง

fn fmt_list(self) -> FmtList<Self>where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

sourceยง

impl<T> FromRef<T> for Twhere T: Clone,

sourceยง

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
sourceยง

impl<S, B, T> FromRequest<S, B, ViaParts> for Twhere B: Send + 'static, S: Send + Sync, T: FromRequestParts<S>,

ยง

type Rejection = <T as FromRequestParts<S>>::Rejection

If the extractor fails itโ€™ll use this โ€œrejectionโ€ type. A rejection is a kind of error that can be converted into a response.
sourceยง

fn from_request<'life0, 'async_trait>( req: Request<B>, state: &'life0 S ) -> Pin<Box<dyn Future<Output = Result<T, <T as FromRequest<S, B, ViaParts>>::Rejection>> + Send + 'async_trait>>where 'life0: 'async_trait, T: 'async_trait,

Perform the extraction.
sourceยง

impl<T> Instrument for T

sourceยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
sourceยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for Twhere 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.

ยง

impl<T> Pipe for Twhere T: ?Sized,

ยง

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
ยง

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
ยง

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
ยง

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> Rwhere Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
ยง

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R ) -> Rwhere Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
ยง

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> Rwhere Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
ยง

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> Rwhere Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
ยง

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> Rwhere Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
ยง

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R ) -> Rwhere Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
ยง

impl<T> Pointable for T

ยง

const ALIGN: usize = _

The alignment of pointer.
ยง

type Init = T

The type for initializers.
ยง

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
ยง

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
ยง

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
ยง

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
sourceยง

impl<T> Same for T

ยง

type Output = T

Should always be Self
ยง

impl<T> Tap for T

ยง

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
ยง

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
ยง

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Selfwhere Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
ยง

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
ยง

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Selfwhere Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
ยง

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
ยง

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Selfwhere Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
ยง

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
ยง

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
ยง

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
ยง

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Selfwhere Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
ยง

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
ยง

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Selfwhere Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
ยง

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
ยง

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Selfwhere Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
ยง

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
sourceยง

impl<T> ToOwned for Twhere T: Clone,

ยง

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
ยง

impl<T> TryConv for T

ยง

fn try_conv<T>(self) -> Result<T, Self::Error>where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
sourceยง

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

ยง

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 Twhere U: TryFrom<T>,

ยง

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.
ยง

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

ยง

fn vzip(self) -> V

sourceยง

impl<T> WithSubscriber for T

sourceยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
sourceยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more