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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/*-
 * cdns-rs - a simple sync/async DNS query library
 * Copyright (C) 2020  Aleksandr Morozov
 * 
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

/// This file contains configuration caches.

use std::path::Path;
use std::sync::Arc;
use std::time::SystemTime;

use tokio::fs;

use tokio::sync::Mutex;


use crate::cfg_host_parser::HostConfig;
use crate::cfg_resolv_parser::ResolveConfig;
use crate::{async_write_error, internal_error, internal_error_map, error::*};

use super::cfg_parsers::*;

lazy_static!{
    pub static ref CACHE: CachesController = CachesController::new();
}


pub trait CacheOperations
{
    fn is_reload_allowed(&self) -> bool;
}

#[derive(Clone, Debug)]
struct CacheTime<'cache>
{
    path: &'cache Path,
    last_modif: SystemTime,
}

impl<'cache> CacheTime<'cache>
{
    async 
    fn new(path: &'cache Path) -> CDnsResult<CacheTime<'cache>>
    {
        return Ok(CacheTime { path: path, last_modif: Self::get_last_modified(path).await? });
    }

    fn fake(path: &'cache Path) -> Self
    {
        return Self { path: path, last_modif: SystemTime::now() };
    }

    async 
    fn get_last_modified(path: &'cache Path) -> CDnsResult<SystemTime>
    {
        let metadata = fs::metadata(path).await.map_err(|e| 
            internal_error_map!(CDnsErrorType::InternalError, "fs::metadata::modified() not supported on this platform: '{}'", e)
        )?;

        let last_modif = 
            metadata.modified().map_err(|e| 
                internal_error_map!(CDnsErrorType::InternalError, "fs::metadata::modified() not supported on this platform: '{}'", e)
            )?;

        return Ok(last_modif);
    }

    async 
    fn check_modified(&mut self) -> CDnsResult<bool>
    {
        // in case if get_last_modified() will return Err, return what was cached prevously
        let last_modif = 
            match Self::get_last_modified(self.path).await
            {
                Ok(t) => t,
                Err(e) => internal_error!(CDnsErrorType::InternalError, "{}", e),
            };

        return Ok(self.last_modif != last_modif);
    }
}

#[derive(Clone, Debug)]
pub struct CacheInstance<T: Default + ConfigParser<T> + CacheOperations>//, P: ConfigParser<T>>
{
    last_modif: CacheTime<'static>,
    cache: Arc<T>,
   // f: PhantomData<P>,
}

impl<T: Default + ConfigParser<T> + CacheOperations> Default for CacheInstance<T>
{
    fn default() -> Self 
    {
        return 
            Self 
            {
                last_modif: CacheTime::fake(T::get_file_path()), 
                cache: Arc::new(T::default()),
              //  f: PhantomData,
            };
    }
}

impl<T: Default + ConfigParser<T> + CacheOperations> CacheInstance<T>
{
    async  
    fn new() -> CDnsResult<Self>
    {
        return Ok(
            Self 
            {
                last_modif: CacheTime::new(T::get_file_path()).await?, 
                cache: Arc::new(T::parse_config().await?),
                //f: PhantomData,
            }
        );
    }

    async 
    fn read_config() -> CDnsResult<Arc<T>>
    {
        return Ok(Arc::new(T::parse_config().await?));
    }

    async 
    fn check_modified(&mut self) -> CDnsResult<()>
    {
        // in case if get_last_modified() will return Err, save what was cached prevously
        if self.cache.is_reload_allowed() == false
        {
            // just return OK
            return Ok(());
        }

        if self.last_modif.check_modified().await? == true
        {
            // reload
            self.cache = Self::read_config().await?;
        }
        
        return Ok(());
    }

    fn clone_cache(&self) -> Arc<T>
    {
        return self.cache.clone();
    }
}

pub struct CachesController
{
    resolv_cache: Mutex<CacheInstance<ResolveConfig>>,
    host_cache: Mutex<CacheInstance<HostConfig>>
}

unsafe impl Sync for CachesController{}
unsafe impl Send for CachesController{}

impl CachesController
{
    /// Just creates insrance, but does not read anything from disk. 
    fn new() -> Self
    {
        /*let resolve_cache_res = CacheInstance::<ResolveConfig>::new().await;

        let host_cache_res = CacheInstance::<HostConfig>::new().await;

        let resolve_cache = 
            match resolve_cache_res
            {
                Ok(r) => r,
                Err(e) =>
                {
                    write_error!("{}", e);

                    CacheInstance::default()
                }
            };
        
        let host_cache = 
            match host_cache_res
            {
                Ok(r) => r,
                Err(e) =>
                {
                    write_error!("{}", e);

                    CacheInstance::default()
                }
            };
    */

        return 
            CachesController
            { 
                resolv_cache: Mutex::new(CacheInstance::default()),//resolve_cache),
                host_cache: Mutex::new(CacheInstance::default()),//host_cache),
            };
    }

    pub async 
    fn is_resolve_cached(&self) -> bool
    {
        return !self.resolv_cache.lock().await.cache.is_default();
    }

    pub async 
    fn is_host_cached(&self) -> bool
    {
        return !self.host_cache.lock().await.cache.is_default();
    }

    async 
    fn try_cache_resolve(&self) -> CDnsResult<Arc<ResolveConfig>>
    {
        let mut mutx_resolv = self.resolv_cache.lock().await;
        mutx_resolv.check_modified().await?;

        return Ok(mutx_resolv.clone_cache());
    }

    pub async 
    fn clone_resolve_list(&self) -> CDnsResult<Arc<ResolveConfig>>
    {
        // clone from cache and/or reload cache
        match self.try_cache_resolve().await
        {
            Ok(r) => return Ok(r),
            Err(e) => 
            {
                async_write_error!("{}", e);

                // try to read directly, this ignores all reload restrictions
                return CacheInstance::<ResolveConfig>::read_config().await;
            }
        }
    }

    async 
    fn try_cache_host(&self) -> CDnsResult<Arc<HostConfig>>
    {
        let mut mutx_host = self.host_cache.lock().await;
        mutx_host.check_modified().await?;

        return Ok(mutx_host.clone_cache());
    }

    pub async 
    fn clone_host_list(&self) -> CDnsResult<Arc<HostConfig>>
    {
        match self.try_cache_host().await
        {
            Ok(r) => return Ok(r),
            Err(e) =>
            {
                async_write_error!("{}", e);

                // try to read directly, this ignores all reload restrictions
                return CacheInstance::<HostConfig>::read_config().await;
            }
        }
    }
}


#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_init()
{
    let res = CACHE.clone_resolve_list().await;
    assert_eq!(res.is_ok(), true, "{}", res.err().unwrap());

    let res = res.unwrap();

    println!("{:?}", res);

    let res = CACHE.clone_host_list().await;
    assert_eq!(res.is_ok(), true, "{}", res.err().unwrap());

    let res = res.unwrap();

    println!("{:?}", res);
}