1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
use std::{collections::HashMap, future::Future, hash::Hash, time::Duration};

use chrono::prelude::*;

use thiserror::Error;

#[derive(Error, Debug)]
pub enum Error {
    #[error("PostgresPool {0}")]
    PostgresPool(#[from] deadpool_postgres::PoolError),

    #[error("Postgres {0}")]
    Postgres(#[from] deadpool_postgres::tokio_postgres::Error),
}

pub struct HolderMap<K, V> {
    map: HashMap<K, V>,
    expire_interval: Duration,
    expire_at: DateTime<Utc>,
    pg_pool: deadpool_postgres::Pool,
}

impl<K, V> HolderMap<K, V>
where
    K: PartialEq + Eq + Hash + Clone,
    V: Clone,
{
    pub fn new(
        pg_pool: deadpool_postgres::Pool,
        expire_interval: Duration,
        now: Option<DateTime<Utc>>,
    ) -> Self {
        Self {
            map: HashMap::new(),
            expire_interval,
            expire_at: now.unwrap_or(Utc::now()),
            pg_pool,
        }
    }

    pub async fn get<FutOne, FutAll>(
        &mut self,
        key: &K,
        now: Option<DateTime<Utc>>,
        f: impl FnOnce(deadpool_postgres::Client, K) -> FutOne,
        g: impl FnOnce(deadpool_postgres::Client) -> FutAll,
    ) -> Result<Option<V>, Error>
    where
        FutOne: Future<Output = Result<Option<V>, Error>>,
        FutAll: Future<Output = Result<HashMap<K, V>, Error>>,
    {
        if get_now(now) >= self.expire_at {
            let pg_client = self.pg_pool.get().await?;
            self.map = g(pg_client).await?;
            self.expire_at = expire_at(now, self.expire_interval);
        }
        if let Some(value) = self.map.get(key) {
            return Ok(Some(value.clone()));
        }
        let pg_client = self.pg_pool.get().await?;
        let Some(value) = f(pg_client, key.clone()).await? else {
            return Ok(None);
        };
        self.map.insert(key.clone(), value.clone());
        Ok(Some(value))
    }
}

pub struct HolderMapEachExpire<K, V> {
    map: HashMap<K, (V, DateTime<Utc>)>,
    expire_interval: Duration,
    pg_pool: deadpool_postgres::Pool,
}

impl<K, V> HolderMapEachExpire<K, V>
where
    K: PartialEq + Eq + Hash + Clone,
    V: Clone,
{
    pub fn new(pg_pool: deadpool_postgres::Pool, expire_interval: Duration) -> Self {
        Self {
            map: HashMap::new(),
            expire_interval,
            pg_pool,
        }
    }

    pub async fn get<FutOne>(
        &mut self,
        key: &K,
        now: Option<DateTime<Utc>>,
        f: impl FnOnce(deadpool_postgres::Client, K) -> FutOne,
    ) -> Result<Option<V>, Error>
    where
        FutOne: Future<Output = Result<Option<V>, Error>>,
    {
        match self.map.get(key) {
            Some((value, expire_at)) if get_now(now) < *expire_at => {
                return Ok(Some(value.clone()));
            }
            _ => {}
        }
        let pg_client = self.pg_pool.get().await?;
        let Some(value) = f(pg_client, key.clone()).await? else {
            return Ok(None);
        };
        self.map.insert(
            key.clone(),
            (value.clone(), expire_at(now, self.expire_interval)),
        );
        Ok(Some(value))
    }
}

fn get_now(now: Option<DateTime<Utc>>) -> DateTime<Utc> {
    now.unwrap_or(Utc::now())
}

fn expire_at(now: Option<DateTime<Utc>>, interval: Duration) -> DateTime<Utc> {
    get_now(now) + interval
}