Storage

Struct Storage 

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

Takes the underlying backend and provides common methods for it

It can be stored in actix_web’s Data and be used from handlers without specifying the backend itself and provides all the common methods from underlying store and expiry. The backend this struct holds should implement ExpiryStore either directly, or by depending on the default polyfill. Look StorageBuilder for more details.

§Example

use actix_storage::Storage;
use actix_web::*;

async fn index(storage: Storage) -> Result<String, Error>{
    storage.set_bytes("key", "value").await;
    let val = storage.get_bytes("key").await?.unwrap_or_default();
    Ok(std::str::from_utf8(&val)
        .map_err(|err| error::ErrorInternalServerError("Storage error"))?.to_string())
}

It is also possible to set and get values directly using serde by enabling with-serde feature flag.

Implementations§

Source§

impl Storage

Source

pub fn build() -> StorageBuilder

Returns the storage builder struct

Source

pub fn scope(&self, scope: impl AsRef<[u8]>) -> Storage

Return a new Storage struct for the specified scope.

Scopes may or may not be implemented as key prefixes but should provide some guarantees to not mutate other scopes.

§Example
let cache = storage.scope("cache");
cache.set("age", &60_u8).await;
Source

pub async fn set<V>(&self, key: impl AsRef<[u8]>, value: &V) -> Result<()>
where V: Serialize,

Stores a generic serializable value on storage using serde

Calling set operations twice on the same key, overwrites it’s value and clear the expiry on that key(if it exist).

§Example
storage.set("age", &60_u8).await;
§Errors

Beside the normal errors caused by the storage itself, it will result in error if serialization fails.

Note: it required the value to be Sized as some of the serde extensions currently has the same requirement, this restriction may be lifted in future.

requires "with-serde" feature and one of the format features to work ex. "serde-json"

Source

pub async fn set_expiring<V>( &self, key: impl AsRef<[u8]>, value: &V, expires_in: Duration, ) -> Result<()>
where V: Serialize,

Stores a generic serializable value on storage using serde and sets expiry on the key It should be prefered over explicity setting a value and putting an expiry on it as providers may provide a more optimized way to do both operations at once.

Calling set operations twice on the same key, overwrites it’s value and clear the expiry on that key(if it exist).

§Example
storage.set_expiring("age", &60_u8, Duration::from_secs(10)).await;
§Errors

Beside the normal errors caused by the storage itself, it will result in error if expiry provider is not set or serialization fails.

Note: it required the value to be Sized as some of the serde extensions currently has the same requirement, this restriction may be lifted in future.

requires "with-serde" feature and one of the format features to work ex. "serde-json"

Source

pub async fn set_bytes( &self, key: impl AsRef<[u8]>, value: impl AsRef<[u8]>, ) -> Result<()>

Stores a sequence of bytes on storage

Calling set operations twice on the same key, overwrites it’s value and clear the expiry on that key(if it exist).

§Example
storage.set_bytes("age", vec![10]).await;
storage.set_bytes("name", "Violet".as_bytes()).await;
Source

pub async fn set_expiring_bytes( &self, key: impl AsRef<[u8]>, value: impl AsRef<[u8]>, expires_in: Duration, ) -> Result<()>

Stores a sequence of bytes on storage and sets expiry on the key It should be prefered over calling set and expire as providers may define a more optimized way to do both operations at once.

Calling set operations twice on the same key, overwrites it’s value and clear the expiry on that key(if it exist).

§Example
storage.set_expiring_bytes("name", "Violet".as_bytes(), Duration::from_secs(10)).await;
§Errors

Beside the normal errors caused by the storage itself, it will result in error if expiry provider is not set.

Source

pub async fn get<K, V>(&self, key: K) -> Result<Option<V>>
where K: AsRef<[u8]>, V: DeserializeOwned,

Gets a generic deserializable value from backend using serde

§Example
let val: Option<String> = storage.get("key").await?;
§Errors

Beside the normal errors caused by the storage itself, it will result in error if deserialization fails.

requires "with-serde" feature and one of the format features to work ex. "serde-json"

Source

pub async fn get_expiring<K, V>( &self, key: K, ) -> Result<Option<(V, Option<Duration>)>>
where K: AsRef<[u8]>, V: DeserializeOwned,

Gets a generic deserializable value from backend using serde together with its expiry It should be prefered over calling get and expiry as providers may define a more optimized way to do the both operations at once.

§Example
let val: Option<(String, _)> = storage.get_expiring("key").await?;
§Errors

Beside the normal errors caused by the storage itself, it will result in error if expiry provider is not set or deserialization fails.

requires "with-serde" and one of the format features to work ex. "serde-json"

Source

pub async fn get_bytes(&self, key: impl AsRef<[u8]>) -> Result<Option<Vec<u8>>>

Gets a sequence of bytes from backend, resulting in an owned vector

§Example
let val = storage.get_bytes("key").await?;
Source

pub async fn get_expiring_bytes( &self, key: impl AsRef<[u8]>, ) -> Result<Option<(Vec<u8>, Option<Duration>)>>

Same as get_bytes but it also gets expiry.

§Example
let val = storage.get_expiring_bytes("key").await?;
Source

pub async fn get_bytes_ref( &self, key: impl AsRef<[u8]>, ) -> Result<Option<Arc<[u8]>>>

Gets a sequence of bytes from backend, resulting in an arc

§Example
let val = storage.get_bytes_ref("key").await?;
Source

pub async fn get_expiring_bytes_ref( &self, key: impl AsRef<[u8]>, ) -> Result<Option<(Arc<[u8]>, Option<Duration>)>>

Same as get_bytes_ref but it also gets expiry.

§Example
let val = storage.get_expiring_bytes_ref("key").await?;
Source

pub async fn delete(&self, key: impl AsRef<[u8]>) -> Result<()>

Deletes/Removes a key value pair from storage.

§Example
storage.delete("key").await?;
Source

pub async fn contains_key(&self, key: impl AsRef<[u8]>) -> Result<bool>

Checks if storage contains a key.

§Example
let exist = storage.contains_key("key").await?;
Source

pub async fn expire( &self, key: impl AsRef<[u8]>, expire_in: Duration, ) -> Result<()>

Sets expiry on a key, it won’t result in error if the key doesn’t exist.

Calling set methods twice or calling persist will result in expiry being erased from the key, calling expire itself twice will overwrite the expiry for key.

§Example
storage.expire("key", Duration::from_secs(10)).await?;
Source

pub async fn expiry(&self, key: impl AsRef<[u8]>) -> Result<Option<Duration>>

Gets expiry for the provided key, it will give none if there is no expiry set.

The result of this method is not guaranteed to be exact and may be inaccurate depending on sotrage implementation.

§Example
let exp = storage.expiry("key").await?;
if let Some(exp) = exp{
    println!("Key will expire in {} seconds", exp.as_secs());
} else {
    println!("Long live the key");
}
Source

pub async fn extend( &self, key: impl AsRef<[u8]>, expire_in: Duration, ) -> Result<()>

Extends expiry for a key, it won’t result in error if the key doesn’t exist.

If the provided key doesn’t have an expiry set, it will set the expiry on that key.

§Example
storage.expire("key", Duration::from_secs(5)).await?;
storage.extend("key", Duration::from_secs(5)).await?; // ket will expire in ~10 seconds
Source

pub async fn persist(&self, key: impl AsRef<[u8]>) -> Result<()>

Clears expiry from the provided key, making it persistant.

Calling expire will overwrite persist.

§Example
storage.persist("key").await?;

Trait Implementations§

Source§

impl Clone for Storage

Source§

fn clone(&self) -> Storage

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 FromRequest for Storage

It is pretty much copied as-is from actix-web Data

Source§

type Error = Error

The associated error which can be returned.
Source§

type Future = Ready<Result<Storage, Error>>

Future that resolves to a Self. Read more
Source§

fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future

Create a Self from request parts asynchronously.
Source§

fn extract(req: &HttpRequest) -> Self::Future

Create a Self from request head asynchronously. 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, 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> 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> 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> 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
Source§

impl<T> ErasedDestructor for T
where T: 'static,