sylvia_iot_broker/models/memory/
device.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
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::{
        DelCacheQueryCond, DeviceCache, DeviceCacheItem, GetCacheQueryCond, QueryCond, QueryOneCond,
    },
    Model,
};

pub struct Cache {
    model: Arc<dyn Model>,
    uldata: Arc<RwLock<LruCache<String, Option<DeviceCacheItem>>>>,
}

pub struct Options {
    pub uldata_size: usize,
}

const DEF_SIZE: usize = 10_000;

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

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

    async fn get(
        &self,
        cond: &GetCacheQueryCond,
    ) -> Result<Option<DeviceCacheItem>, Box<dyn StdError>> {
        // Try to hit cache first, or returns a model query condition.
        let model_cond = match cond {
            GetCacheQueryCond::CodeAddr(cond) => {
                let key = match cond.unit_code {
                    None => format!(".{}.{}", cond.network_code, cond.network_addr),
                    Some(unit) => format!("{}.{}.{}", unit, cond.network_code, cond.network_addr),
                };
                {
                    let mut lock = self.uldata.write().await;
                    if let Some(value) = lock.get(&key) {
                        return Ok(value.clone());
                    }
                }
                QueryCond {
                    device: Some(QueryOneCond {
                        unit_code: cond.unit_code,
                        network_code: cond.network_code,
                        network_addr: cond.network_addr,
                    }),
                    ..Default::default()
                }
            }
        };

        let item = match self.model.device().get(&model_cond).await? {
            None => None,
            Some(device) => Some(DeviceCacheItem {
                device_id: device.device_id,
                profile: device.profile,
            }),
        };
        let _ = self.set(cond, item.as_ref()).await;
        Ok(item)
    }

    async fn set(
        &self,
        cond: &GetCacheQueryCond,
        value: Option<&DeviceCacheItem>,
    ) -> Result<(), Box<dyn StdError>> {
        match cond {
            GetCacheQueryCond::CodeAddr(cond) => {
                let key = match cond.unit_code {
                    None => format!(".{}.{}", cond.network_code, cond.network_addr),
                    Some(unit) => format!("{}.{}.{}", unit, cond.network_code, cond.network_addr),
                };
                {
                    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(&self, cond: &DelCacheQueryCond) -> Result<(), Box<dyn StdError>> {
        let key = match cond.network_code {
            None => {
                // Disallow deleting all devices of public networks.
                if cond.unit_code.len() == 0 {
                    return Ok(());
                }

                // 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.uldata.write().await;
                        lock.pop(&key);
                    }
                    return Ok(());
                }
            },
        };
        {
            let mut lock = self.uldata.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,
        }
    }
}