sylvia_iot_broker/models/memory/
device_route.rs

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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
use std::{error::Error as StdError, num::NonZeroUsize, sync::Arc};

use async_trait::async_trait;
use lru::LruCache;
use tokio::sync::RwLock;

use super::super::{
    device::{QueryCond as DeviceQueryCond, QueryOneCond as DeviceQueryOneCond},
    device_route::{
        DelCachePubQueryCond, DelCacheQueryCond, DeviceRouteCache, DeviceRouteCacheDlData,
        DeviceRouteCacheUlData, GetCachePubQueryCond, GetCacheQueryCond, ListOptions,
        ListQueryCond,
    },
    Model,
};

pub struct Cache {
    model: Arc<dyn Model>,
    uldata: Arc<RwLock<LruCache<String, Option<DeviceRouteCacheUlData>>>>,
    dldata: Arc<RwLock<LruCache<String, Option<DeviceRouteCacheDlData>>>>,
    dldata_pub: Arc<RwLock<LruCache<String, Option<DeviceRouteCacheDlData>>>>,
}

pub struct Options {
    pub uldata_size: usize,
    pub dldata_size: usize,
    pub dldata_pub_size: usize,
}

const DEF_SIZE: usize = 10_000;

impl Cache {
    pub fn new(opts: &Options, model: Arc<dyn Model>) -> Self {
        let (uldata, dldata, dldata_pub) = unsafe {
            (
                NonZeroUsize::new_unchecked(opts.uldata_size),
                NonZeroUsize::new_unchecked(opts.dldata_size),
                NonZeroUsize::new_unchecked(opts.dldata_pub_size),
            )
        };
        Cache {
            model,
            uldata: Arc::new(RwLock::new(LruCache::new(uldata))),
            dldata: Arc::new(RwLock::new(LruCache::new(dldata))),
            dldata_pub: Arc::new(RwLock::new(LruCache::new(dldata_pub))),
        }
    }
}

#[async_trait]
impl DeviceRouteCache for Cache {
    async fn clear(&self) -> Result<(), Box<dyn StdError>> {
        // To collect all locks before clearing cache.
        let mut lock1 = self.uldata.write().await;
        let mut lock2 = self.dldata.write().await;
        let mut lock3 = self.dldata_pub.write().await;
        lock1.clear();
        lock2.clear();
        lock3.clear();
        Ok(())
    }

    async fn get_uldata(
        &self,
        device_id: &str,
    ) -> Result<Option<DeviceRouteCacheUlData>, Box<dyn StdError>> {
        {
            let mut lock = self.uldata.write().await;
            if let Some(value) = lock.get(device_id) {
                return Ok(value.clone());
            }
        }

        let opts = ListOptions {
            cond: &ListQueryCond {
                device_id: Some(device_id),
                ..Default::default()
            },
            offset: None,
            limit: None,
            sort: None,
            cursor_max: None,
        };
        let (mut routes, _) = self.model.device_route().list(&opts, None).await?;
        let data: Option<DeviceRouteCacheUlData> = match routes.len() {
            0 => None,
            _ => {
                let mut routes_data = vec![];
                for r in routes.iter() {
                    routes_data.push(format!("{}.{}", r.unit_code, r.application_code))
                }
                let _ = routes.pop().unwrap();
                Some(DeviceRouteCacheUlData {
                    app_mgr_keys: routes_data,
                })
            }
        };
        let _ = self.set_uldata(device_id, data.as_ref()).await;
        Ok(data)
    }

    async fn set_uldata(
        &self,
        device_id: &str,
        value: Option<&DeviceRouteCacheUlData>,
    ) -> Result<(), Box<dyn StdError>> {
        let key = device_id.to_string();
        let mut lock = self.uldata.write().await;
        let _ = match value {
            None => lock.push(key, None),
            Some(value) => lock.push(key, Some(value.clone())),
        };
        Ok(())
    }

    async fn del_uldata(&self, device_id: &str) -> Result<(), Box<dyn StdError>> {
        let mut lock = self.uldata.write().await;
        lock.pop(device_id);
        Ok(())
    }

    async fn get_dldata(
        &self,
        cond: &GetCacheQueryCond,
    ) -> Result<Option<DeviceRouteCacheDlData>, Box<dyn StdError>> {
        let key = format!(
            "{}.{}.{}",
            cond.unit_code, cond.network_code, cond.network_addr
        );

        {
            let mut lock = self.dldata.write().await;
            if let Some(value) = lock.get(&key) {
                match value {
                    None => return Ok(None),
                    Some(value) => return Ok(Some(value.clone())),
                }
            }
        }

        let dev_cond = DeviceQueryCond {
            device: Some(DeviceQueryOneCond {
                unit_code: Some(cond.unit_code),
                network_code: cond.network_code,
                network_addr: cond.network_addr,
            }),
            ..Default::default()
        };
        let device = self.model.device().get(&dev_cond).await?;
        let data = match device {
            None => None,
            Some(device) => match device.unit_code.as_ref() {
                // This should not occur!
                None => None,
                Some(unit_code) => Some(DeviceRouteCacheDlData {
                    net_mgr_key: format!("{}.{}", unit_code, cond.network_code),
                    network_id: device.network_id,
                    network_addr: device.network_addr,
                    device_id: device.device_id,
                    profile: device.profile,
                }),
            },
        };
        let _ = self.set_dldata(cond, data.as_ref()).await;
        Ok(data)
    }

    async fn set_dldata(
        &self,
        cond: &GetCacheQueryCond,
        value: Option<&DeviceRouteCacheDlData>,
    ) -> Result<(), Box<dyn StdError>> {
        let key = format!(
            "{}.{}.{}",
            cond.unit_code, cond.network_code, cond.network_addr
        );
        let mut lock = self.dldata.write().await;
        let _ = match value {
            None => lock.push(key, None),
            Some(value) => lock.push(key, Some(value.clone())),
        };
        Ok(())
    }

    async fn del_dldata(&self, cond: &DelCacheQueryCond) -> Result<(), Box<dyn StdError>> {
        let key = match cond.network_code {
            None => {
                // Remove all routes of the unit.
                cond.unit_code.to_string()
            }
            Some(code) => match cond.network_addr {
                None => {
                    // Remove all routes of the network.
                    format!("{}.{}", cond.unit_code, code)
                }
                Some(addr) => {
                    let key = format!("{}.{}.{}", cond.unit_code, code, addr);
                    let mut lock = self.dldata.write().await;
                    let _ = lock.pop(&key);
                    return Ok(());
                }
            },
        };
        {
            let mut lock = self.dldata.write().await;
            loop {
                let mut rm_key = None;
                for (k, _) in lock.iter() {
                    if k.starts_with(key.as_str()) {
                        rm_key = Some(k.clone());
                        break;
                    }
                }
                match rm_key {
                    None => break,
                    Some(key) => {
                        let _ = lock.pop(&key);
                    }
                }
            }
        }
        Ok(())
    }

    async fn get_dldata_pub(
        &self,
        cond: &GetCachePubQueryCond,
    ) -> Result<Option<DeviceRouteCacheDlData>, Box<dyn StdError>> {
        let key = format!("{}.{}", cond.unit_id, cond.device_id);

        {
            let mut lock = self.dldata_pub.write().await;
            if let Some(value) = lock.get(&key) {
                match value {
                    None => return Ok(None),
                    Some(value) => return Ok(Some(value.clone())),
                }
            }
        }

        let dev_cond = DeviceQueryCond {
            unit_id: Some(cond.unit_id),
            device_id: Some(cond.device_id),
            ..Default::default()
        };
        let device = self.model.device().get(&dev_cond).await?;
        let data = match device {
            None => None,
            Some(device) => match device.unit_code.as_ref() {
                None => Some(DeviceRouteCacheDlData {
                    net_mgr_key: format!(".{}", device.network_code),
                    network_id: device.network_id,
                    network_addr: device.network_addr,
                    device_id: device.device_id,
                    profile: device.profile,
                }),
                Some(unit_code) => Some(DeviceRouteCacheDlData {
                    net_mgr_key: format!("{}.{}", unit_code, device.network_code),
                    network_id: device.network_id,
                    network_addr: device.network_addr,
                    device_id: device.device_id,
                    profile: device.profile,
                }),
            },
        };
        let _ = self.set_dldata_pub(cond, data.as_ref()).await;
        Ok(data)
    }

    async fn set_dldata_pub(
        &self,
        cond: &GetCachePubQueryCond,
        value: Option<&DeviceRouteCacheDlData>,
    ) -> Result<(), Box<dyn StdError>> {
        let key = format!("{}.{}", cond.unit_id, cond.device_id);
        let mut lock = self.dldata_pub.write().await;
        let _ = match value {
            None => lock.push(key, None),
            Some(value) => lock.push(key, Some(value.clone())),
        };
        Ok(())
    }

    async fn del_dldata_pub(&self, cond: &DelCachePubQueryCond) -> Result<(), Box<dyn StdError>> {
        let key = match cond.device_id {
            None => {
                // Remove all routes of the unit.
                cond.unit_id.to_string()
            }
            Some(id) => {
                let key = format!("{}.{}", cond.unit_id, id);
                {
                    let mut lock = self.dldata_pub.write().await;
                    lock.pop(&key);
                }
                return Ok(());
            }
        };
        {
            let mut lock = self.dldata_pub.write().await;
            loop {
                let mut rm_key = None;
                for (k, _) in lock.iter() {
                    if k.starts_with(key.as_str()) {
                        rm_key = Some(k.clone());
                        break;
                    }
                }
                match rm_key {
                    None => break,
                    Some(key) => {
                        let _ = lock.pop(&key);
                    }
                }
            }
        }
        Ok(())
    }
}

impl Default for Options {
    fn default() -> Self {
        Options {
            uldata_size: DEF_SIZE,
            dldata_size: DEF_SIZE,
            dldata_pub_size: DEF_SIZE,
        }
    }
}