Session

Struct Session 

Source
pub struct Session<S: SessionStore> { /* private fields */ }
Expand description

A parsed on-demand session store.

Implementations§

Source§

impl<S> Session<S>
where S: SessionStore,

Source

pub fn new(inner: Arc<Inner<S>>) -> Self

Creates a new Session instance.

Source

pub async fn get<T>(&self, field: &str) -> Result<Option<T>, Error>
where T: Send + Sync + DeserializeOwned,

Retrieves the value of a field from the session store.

§Example
use ruts::{Session};
use fred::clients::Client;
use serde::Deserialize;
use ruts::store::memory::MemoryStore;

#[derive(Clone, Deserialize)]
struct User {
    id: i64,
    name: String,
}

async fn some_handler_could_be_axum(session: Session<MemoryStore>) {
    session.get::<User>("user").await.unwrap();
}
Source

pub async fn get_all(&self) -> Result<Option<SessionMap>, Error>

This method performs one bulk query to the store and returns a wrapper that allows for lazy, on-demand deserialization of each field.

Source

pub async fn insert<T>( &self, field: &str, value: &T, field_ttl_secs: Option<i64>, ) -> Result<bool, Error>
where T: Send + Sync + Serialize + 'static,

Inserts a value into the session store under the given field.

The behavior of field_ttl_secs determines how this field affects session persistence:

  • -1: Marks this field as persistent. The session key itself will also be persisted, making the associated cookie persistent. This does not alter the TTL of other fields in the session.
  • 0: Removes this field from the store. The session behaves as if remove was called on this field.
  • > 0: Sets a TTL (in seconds) for this field. The session TTL is updated according to:
    • If the session key is already persistent, its TTL remains unchanged.
    • If the field TTL is less than the current session TTL, the session TTL remains unchanged.
    • If the field TTL is greater than the current session TTL, the session TTL is updated to match the field TTL.

Returns true if the field-value pair was successfully inserted or updated, and false if the operation resulted in deletion (e.g., TTL = 0 for a non-existent session).

§Example
use ruts::{Session};
use fred::clients::Client;
use serde::Serialize;
use ruts::store::memory::MemoryStore;

#[derive(Serialize)]
struct User {
    id: i64,
    name: String,
}

async fn example_handler(session: Session<MemoryStore>) {
    let user = User { id: 34895634, name: "John Doe".to_string() };
    // Insert the field with a TTL of 5 seconds
    session.insert("app", &user, Some(5)).await.unwrap();
}
Source

pub async fn update<T>( &self, field: &str, value: &T, field_ttl_secs: Option<i64>, ) -> Result<bool, Error>
where T: Send + Sync + Serialize + 'static,

Updates a value in the session store.

If the key doesn’t exist, it will be inserted.

  • -1: Marks this field as persistent. The session key itself will also be persisted, making the associated cookie persistent. This does not alter the TTL of other fields in the session.
  • 0: Removes this field from the store. The session behaves as if remove was called on this field.
  • > 0: Sets a TTL (in seconds) for this field. The session TTL is updated according to:
    • If the session key is already persistent, its TTL remains unchanged.
    • If the field TTL is less than the current session TTL, the session TTL remains unchanged.
    • If the field TTL is greater than the current session TTL, the session TTL is updated to match the field TTL.

Returns true if the field-value pair was successfully inserted or updated, and false if the operation resulted in deletion (e.g., TTL = 0 for a non-existent session).

§Example
use ruts::{Session};
use fred::clients::Client;
use serde::Serialize;
use ruts::store::memory::MemoryStore;

#[derive(Serialize)]
struct User {
    id: i64,
    name: String,
}

async fn some_handler_could_be_axum(session: Session<MemoryStore>) {
    let user = User {id: 21342365, name: String::from("Jane Doe")};

    let updated = session.update("app", &user, Some(5)).await.unwrap();
}
Source

pub async fn remove(&self, field: &str) -> Result<bool, Error>

Removes a field along with its value from the session store.

Returns true if the field was successfully removed.

§Example
use ruts::{Session};
use fred::clients::Client;
use ruts::store::memory::MemoryStore;

async fn some_handler_could_be_axum(session: Session<MemoryStore>) {
    let removed = session.remove("user").await.unwrap();
}
Source

pub async fn delete(&self) -> Result<bool, Error>

Deletes the entire session from the store.

Returns true if the session was successfully deleted.

§Example
use ruts::{Session};
use fred::clients::Client;
use ruts::store::memory::MemoryStore;

async fn some_handler_could_be_axum(session: Session<MemoryStore>) {
    let deleted = session.delete().await.unwrap();
}
Source

pub async fn expire(&self, ttl_secs: i64) -> Result<bool, Error>

Updates the cookie’s max-age and session expiry time in the store.

  • A value of -1 persists the session.
  • A value of 0 immediately expires the session and deletes it.

Returns true if the expiry was successfully updated.

§Example
use ruts::{Session};
use fred::clients::Client;
use ruts::store::memory::MemoryStore;

async fn some_handler_could_be_axum(session: Session<MemoryStore>) {
    session.expire(30).await.unwrap();
}
Source

pub fn set_expiration(&self, seconds: i64)

Updates the cookie max-age.

Any subsequent call to insert, update or regenerate within this request cycle will use this value.

Source

pub async fn regenerate(&self) -> Result<Option<Id>, Error>

Regenerates the session with a new ID.

Returns the new session ID if successful.

§Example
use ruts::{Session};
use fred::clients::Client;
use ruts::store::memory::MemoryStore;

async fn some_handler_could_be_axum(session: Session<MemoryStore>) {
    let id = session.regenerate().await.unwrap();
}

Note: This does not renew the session expiry.

Source

pub fn prepare_regenerate(&self) -> Id

Prepares a new session ID to be used in the next store operation. The new ID will be used to rename the current session (if it exists) when the next insert or update operation is performed.

§Example
use ruts::Session;
use fred::clients::Client;
use ruts::store::memory::MemoryStore;

async fn some_handler_could_be_axum(session: Session<MemoryStore>) {
    let new_id = session.prepare_regenerate();
    // The next update/insert operation will use this new ID
    session.update("field", &"value", None).await.unwrap();
}
Source

pub fn id(&self) -> Option<Id>

Returns the session ID, if it exists.

Trait Implementations§

Source§

impl<S: Clone + SessionStore> Clone for Session<S>

Source§

fn clone(&self) -> Session<S>

Returns a duplicate 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<S: Debug + SessionStore> Debug for Session<S>

Source§

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

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

impl<S, T> FromRequestParts<S> for Session<T>
where S: Sync + Send, T: SessionStore,

axum extractor for Session.

Source§

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§

async fn from_request_parts( parts: &mut Parts, _state: &S, ) -> Result<Self, Self::Rejection>

Perform the extraction.

Auto Trait Implementations§

§

impl<S> Freeze for Session<S>

§

impl<S> !RefUnwindSafe for Session<S>

§

impl<S> Send for Session<S>

§

impl<S> Sync for Session<S>

§

impl<S> Unpin for Session<S>

§

impl<S> !UnwindSafe for Session<S>

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, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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 T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<S, T> FromRequest<S, ViaParts> for T
where S: Send + Sync, T: FromRequestParts<S>,

Source§

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( req: Request<Body>, state: &S, ) -> impl Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>>

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