1
use std::{error::Error as StdError, sync::Arc};
2

            
3
use async_trait::async_trait;
4
use futures::TryStreamExt;
5
use mongodb::{
6
    bson::{self, doc, Bson, DateTime, Document},
7
    options::FindOptions,
8
    Cursor as MongoDbCursor, Database,
9
};
10
use serde::{Deserialize, Serialize};
11

            
12
use super::super::application_uldata::{
13
    ApplicationUlData, ApplicationUlDataModel, Cursor, ListOptions, ListQueryCond, QueryCond,
14
    SortKey, EXPIRES,
15
};
16

            
17
/// Model instance.
18
pub struct Model {
19
    /// The associated database connection.
20
    conn: Arc<Database>,
21
}
22

            
23
/// Cursor instance.
24
struct DbCursor {
25
    /// The associated collection cursor.
26
    cursor: MongoDbCursor<Schema>,
27
    /// (Useless) only for Cursor trait implementation.
28
    offset: u64,
29
}
30

            
31
/// MongoDB schema.
32
28642
#[derive(Deserialize, Serialize)]
33
struct Schema {
34
    #[serde(rename = "dataId")]
35
    pub data_id: String,
36
    pub proc: DateTime,
37
    #[serde(rename = "pub")]
38
    pub publish: DateTime,
39
    #[serde(rename = "unitCode")]
40
    pub unit_code: Option<String>,
41
    #[serde(rename = "networkCode")]
42
    pub network_code: String,
43
    #[serde(rename = "networkAddr")]
44
    pub network_addr: String,
45
    #[serde(rename = "unitId")]
46
    pub unit_id: String,
47
    #[serde(rename = "deviceId")]
48
    pub device_id: String,
49
    pub time: DateTime,
50
    pub profile: String,
51
    pub data: String,
52
    #[serde(skip_serializing_if = "Option::is_none")]
53
    pub extension: Option<Document>,
54
}
55

            
56
const COL_NAME: &'static str = "applicationUlData";
57

            
58
impl Model {
59
    /// To create the model instance with a database connection.
60
7
    pub async fn new(conn: Arc<Database>) -> Result<Self, Box<dyn StdError>> {
61
7
        let model = Model { conn };
62
14
        model.init().await?;
63
7
        Ok(model)
64
7
    }
65
}
66

            
67
#[async_trait]
68
impl ApplicationUlDataModel for Model {
69
12
    async fn init(&self) -> Result<(), Box<dyn StdError>> {
70
12
        let indexes = vec![
71
12
            doc! {"name": "dataId_1", "key": {"dataId": 1}, "unique": true},
72
12
            doc! {"name": "unitId_1", "key": {"unitId": 1}},
73
12
            doc! {"name": "deviceId_1", "key": {"deviceId": 1}},
74
12
            doc! {"name": "networkCode_1", "key": {"networkCode": 1}},
75
12
            doc! {"name": "networkAddr_1", "key": {"networkAddr": 1}},
76
12
            doc! {"name": "profile_1", "key": {"profile": 1}},
77
12
            doc! {"name": "proc_1", "key": {"proc": 1}, "expireAfterSeconds": EXPIRES},
78
12
            doc! {"name": "pub_1", "key": {"pub": 1}},
79
12
            doc! {"name": "time_1", "key": {"time": 1}},
80
12
        ];
81
12
        let command = doc! {
82
12
            "createIndexes": COL_NAME,
83
12
            "indexes": indexes,
84
12
        };
85
24
        self.conn.run_command(command, None).await?;
86
12
        Ok(())
87
24
    }
88

            
89
44
    async fn count(&self, cond: &ListQueryCond) -> Result<u64, Box<dyn StdError>> {
90
44
        let filter = get_list_query_filter(cond);
91
44
        let count = self
92
44
            .conn
93
44
            .collection::<Schema>(COL_NAME)
94
44
            .count_documents(filter, None)
95
88
            .await?;
96
44
        Ok(count)
97
88
    }
98

            
99
    async fn list(
100
        &self,
101
        opts: &ListOptions,
102
        cursor: Option<Box<dyn Cursor>>,
103
99
    ) -> Result<(Vec<ApplicationUlData>, Option<Box<dyn Cursor>>), Box<dyn StdError>> {
104
99
        let mut cursor = match cursor {
105
            None => {
106
86
                let filter = get_list_query_filter(opts.cond);
107
86
                let options = get_find_options(opts);
108
86
                Box::new(DbCursor::new(
109
86
                    self.conn
110
86
                        .collection::<Schema>(COL_NAME)
111
86
                        .find(filter, options)
112
172
                        .await?,
113
                ))
114
            }
115
13
            Some(cursor) => cursor,
116
        };
117

            
118
99
        let mut count: u64 = 0;
119
99
        let mut list = Vec::new();
120
1258
        while let Some(item) = cursor.try_next().await? {
121
1172
            list.push(item);
122
1172
            if let Some(cursor_max) = opts.cursor_max {
123
1080
                count += 1;
124
1080
                if count >= cursor_max {
125
13
                    return Ok((list, Some(cursor)));
126
1067
                }
127
92
            }
128
        }
129
86
        Ok((list, None))
130
198
    }
131

            
132
459
    async fn add(&self, data: &ApplicationUlData) -> Result<(), Box<dyn StdError>> {
133
459
        let item = Schema {
134
459
            data_id: data.data_id.clone(),
135
459
            proc: data.proc.into(),
136
459
            publish: data.publish.into(),
137
459
            unit_code: data.unit_code.clone(),
138
459
            network_code: data.network_code.clone(),
139
459
            network_addr: data.network_addr.clone(),
140
459
            unit_id: data.unit_id.clone(),
141
459
            device_id: data.device_id.clone(),
142
459
            time: data.time.into(),
143
459
            profile: data.profile.clone(),
144
459
            data: data.data.clone(),
145
459
            extension: match data.extension.as_ref() {
146
248
                None => None,
147
211
                Some(extension) => Some(bson::to_document(extension)?),
148
            },
149
        };
150
459
        self.conn
151
459
            .collection::<Schema>(COL_NAME)
152
459
            .insert_one(item, None)
153
918
            .await?;
154
458
        Ok(())
155
918
    }
156

            
157
5
    async fn del(&self, cond: &QueryCond) -> Result<(), Box<dyn StdError>> {
158
5
        let filter = get_query_filter(cond);
159
5
        self.conn
160
5
            .collection::<Schema>(COL_NAME)
161
5
            .delete_many(filter, None)
162
10
            .await?;
163
5
        Ok(())
164
10
    }
165
}
166

            
167
impl DbCursor {
168
    /// To create the cursor instance with a collection cursor.
169
86
    pub fn new(cursor: MongoDbCursor<Schema>) -> Self {
170
86
        DbCursor { cursor, offset: 0 }
171
86
    }
172
}
173

            
174
#[async_trait]
175
impl Cursor for DbCursor {
176
1258
    async fn try_next(&mut self) -> Result<Option<ApplicationUlData>, Box<dyn StdError>> {
177
1258
        if let Some(item) = self.cursor.try_next().await? {
178
1172
            self.offset += 1;
179
1172
            return Ok(Some(ApplicationUlData {
180
1172
                data_id: item.data_id,
181
1172
                proc: item.proc.into(),
182
1172
                publish: item.publish.into(),
183
1172
                unit_code: item.unit_code,
184
1172
                network_code: item.network_code,
185
1172
                network_addr: item.network_addr,
186
1172
                unit_id: item.unit_id,
187
1172
                device_id: item.device_id,
188
1172
                time: item.time.into(),
189
1172
                profile: item.profile,
190
1172
                data: item.data,
191
1172
                extension: match item.extension {
192
915
                    None => None,
193
257
                    Some(extension) => Some(bson::from_document(extension)?),
194
                },
195
            }));
196
86
        }
197
86
        Ok(None)
198
2516
    }
199

            
200
5
    fn offset(&self) -> u64 {
201
5
        self.offset
202
5
    }
203
}
204

            
205
/// Transforms query conditions to the MongoDB document.
206
5
fn get_query_filter(cond: &QueryCond) -> Document {
207
5
    let mut filter = Document::new();
208
5
    if let Some(value) = cond.unit_id {
209
3
        filter.insert("unitId", value);
210
3
    }
211
5
    if let Some(value) = cond.device_id {
212
1
        filter.insert("deviceId", value);
213
4
    }
214
5
    let mut time_doc = Document::new();
215
5
    if let Some(value) = cond.proc_gte {
216
1
        time_doc.insert("$gte", Bson::DateTime(value.into()));
217
4
    }
218
5
    if let Some(value) = cond.proc_lte {
219
1
        time_doc.insert("$lte", Bson::DateTime(value.into()));
220
4
    }
221
5
    if time_doc.len() > 0 {
222
1
        filter.insert("proc", time_doc);
223
4
    }
224
5
    filter
225
5
}
226

            
227
/// Transforms query conditions to the MongoDB document.
228
130
fn get_list_query_filter(cond: &ListQueryCond) -> Document {
229
130
    let mut filter = Document::new();
230
130
    if let Some(value) = cond.unit_id {
231
58
        filter.insert("unitId", value);
232
72
    }
233
130
    if let Some(value) = cond.device_id {
234
14
        filter.insert("deviceId", value);
235
116
    }
236
130
    if let Some(value) = cond.network_code {
237
8
        filter.insert("networkCode", value);
238
122
    }
239
130
    if let Some(value) = cond.network_addr {
240
6
        filter.insert("networkAddr", value);
241
124
    }
242
130
    if let Some(value) = cond.profile {
243
6
        filter.insert("profile", value);
244
124
    }
245
130
    let mut time_doc = Document::new();
246
130
    if let Some(value) = cond.proc_gte {
247
25
        time_doc.insert("$gte", Bson::DateTime(value.into()));
248
105
    }
249
130
    if let Some(value) = cond.proc_lte {
250
8
        time_doc.insert("$lte", Bson::DateTime(value.into()));
251
122
    }
252
130
    if time_doc.len() > 0 {
253
25
        filter.insert("proc", time_doc);
254
105
    }
255
130
    time_doc = Document::new();
256
130
    if let Some(value) = cond.pub_gte {
257
14
        time_doc.insert("$gte", Bson::DateTime(value.into()));
258
116
    }
259
130
    if let Some(value) = cond.pub_lte {
260
8
        time_doc.insert("$lte", Bson::DateTime(value.into()));
261
122
    }
262
130
    if time_doc.len() > 0 {
263
14
        filter.insert("pub", time_doc);
264
116
    }
265
130
    time_doc = Document::new();
266
130
    if let Some(value) = cond.time_gte {
267
14
        time_doc.insert("$gte", Bson::DateTime(value.into()));
268
116
    }
269
130
    if let Some(value) = cond.time_lte {
270
8
        time_doc.insert("$lte", Bson::DateTime(value.into()));
271
122
    }
272
130
    if time_doc.len() > 0 {
273
14
        filter.insert("time", time_doc);
274
116
    }
275
130
    filter
276
130
}
277

            
278
/// Transforms model options to the options.
279
86
fn get_find_options(opts: &ListOptions) -> FindOptions {
280
86
    let mut options = FindOptions::builder().build();
281
86
    if let Some(offset) = opts.offset {
282
12
        options.skip = Some(offset);
283
74
    }
284
86
    if let Some(limit) = opts.limit {
285
65
        if limit > 0 {
286
62
            options.limit = Some(limit as i64);
287
62
        }
288
21
    }
289
86
    if let Some(sort_list) = opts.sort.as_ref() {
290
77
        if sort_list.len() > 0 {
291
77
            let mut sort_opts = Document::new();
292
93
            for cond in sort_list.iter() {
293
93
                let key = match cond.key {
294
69
                    SortKey::Proc => "proc",
295
4
                    SortKey::Pub => "pub",
296
4
                    SortKey::Time => "time",
297
8
                    SortKey::NetworkCode => "networkCode",
298
8
                    SortKey::NetworkAddr => "networkAddr",
299
                };
300
93
                if cond.asc {
301
43
                    sort_opts.insert(key.to_string(), 1);
302
50
                } else {
303
50
                    sort_opts.insert(key.to_string(), -1);
304
50
                }
305
            }
306
77
            options.sort = Some(sort_opts);
307
        }
308
9
    }
309
86
    options
310
86
}