hitbox_actix/
actor.rs

1//! Cache actor and Builder.
2use crate::builder::CacheBuilder;
3use actix::dev::ToEnvelope;
4use actix::prelude::*;
5use hitbox::dev::{Delete, Get, Lock, Set};
6#[cfg(feature = "metrics")]
7use hitbox::metrics::{
8    CACHE_HIT_COUNTER, CACHE_MISS_COUNTER, CACHE_STALE_COUNTER, CACHE_UPSTREAM_HANDLING_HISTOGRAM,
9};
10use hitbox::settings::CacheSettings;
11use hitbox::CacheError;
12use hitbox_backend::Backend;
13use hitbox_redis::RedisBackend;
14use tracing::{debug, info};
15
16/// Actix actor implements cache logic.
17///
18/// This actor implement only `Handler<QueryCache>`.
19/// Where [QueryCache](crate::QueryCache) - Actix message with two fields:
20/// * Generic actix message for sending to upstream actor.
21/// * Address of upstream actor
22///
23/// # Example
24/// ```rust
25/// use actix::prelude::*;
26/// use hitbox_actix::{Cache, RedisBackend, CacheError};
27///
28/// #[actix_rt::main]
29/// async fn main() -> Result<(), CacheError> {
30///     let cache = Cache::new().await?.start();
31///     Ok(())
32/// }
33/// ```
34pub struct CacheActor<B>
35where
36    B: Backend,
37{
38    pub(crate) settings: CacheSettings,
39    pub(crate) backend: Addr<B>,
40}
41
42impl<B> CacheActor<B>
43where
44    B: Actor + Backend,
45    <B as Actor>::Context:
46        ToEnvelope<B, Get> + ToEnvelope<B, Set> + ToEnvelope<B, Lock> + ToEnvelope<B, Delete>,
47{
48    /// Initialize new Cache actor with default [`hitbox_redis::RedisBackend`].
49    #[allow(clippy::new_ret_no_self)]
50    pub async fn new() -> Result<CacheActor<RedisBackend>, CacheError> {
51        let backend = RedisBackend::new()
52            .await
53            .map_err(|err| CacheError::BackendError(err.into()))?
54            .start();
55        Ok(CacheBuilder::default().finish(backend))
56    }
57
58    /// Creates new [CacheBuilder] instance for Cache actor configuration.
59    pub fn builder() -> CacheBuilder<B> {
60        CacheBuilder::default()
61    }
62}
63
64impl<B> Actor for CacheActor<B>
65where
66    B: Backend,
67{
68    type Context = Context<Self>;
69
70    fn started(&mut self, _: &mut Self::Context) {
71        info!("Cache actor started");
72        debug!("Cache enabled: {:?}", self.settings);
73    }
74}