sqs_lambda/
cache.rs

1use std::collections::hash_map::DefaultHasher;
2use std::hash::{Hash, Hasher};
3
4use async_trait::async_trait;
5
6pub trait Cacheable {
7    fn identity(&self) -> Vec<u8>;
8}
9
10impl<H> Cacheable for H
11where
12    H: Hash,
13{
14    fn identity(&self) -> Vec<u8> {
15        let mut hasher = DefaultHasher::new();
16        self.hash(&mut hasher);
17        let hash = hasher.finish();
18        hash.to_le_bytes().to_vec()
19    }
20}
21
22#[derive(Clone)]
23pub enum CacheResponse {
24    Hit,
25    Miss,
26}
27
28#[async_trait]
29pub trait Cache: Clone {
30    async fn get<CA: Cacheable + Send + Sync + 'static>(
31        &mut self,
32        cacheable: CA,
33    ) -> Result<CacheResponse, crate::error::Error>;
34    async fn store(&mut self, identity: Vec<u8>) -> Result<(), crate::error::Error>;
35}
36
37#[async_trait]
38pub trait ReadableCache {
39    async fn get<CA: Cacheable + Send + Sync + 'static>(
40        &mut self,
41        cacheable: CA,
42    ) -> Result<CacheResponse, crate::error::Error>;
43}
44
45#[async_trait]
46impl<C> ReadableCache for C
47where
48    C: Cache + Send + Sync + 'static,
49{
50    async fn get<CA>(&mut self, cacheable: CA) -> Result<CacheResponse, crate::error::Error>
51    where
52        CA: Cacheable + Send + Sync + 'static,
53    {
54        Cache::get(self, cacheable).await
55    }
56}
57
58#[derive(Clone)]
59pub struct NopCache {}
60
61#[async_trait]
62impl Cache for NopCache {
63    async fn get<CA: Cacheable + Send + Sync + 'static>(
64        &mut self,
65        _cacheable: CA,
66    ) -> Result<CacheResponse, crate::error::Error> {
67        Ok(CacheResponse::Miss)
68    }
69    async fn store(&mut self, _identity: Vec<u8>) -> Result<(), crate::error::Error> {
70        Ok(())
71    }
72}