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

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

            
12
use super::super::network_dldata::{
13
    Cursor, ListOptions, ListQueryCond, NetworkDlData, NetworkDlDataModel, QueryCond, SortKey,
14
    UpdateQueryCond, Updates, 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
15610
#[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
    pub resp: Option<DateTime>,
40
    pub status: i32,
41
    #[serde(rename = "unitId")]
42
    pub unit_id: String,
43
    #[serde(rename = "deviceId")]
44
    pub device_id: String,
45
    #[serde(rename = "networkCode")]
46
    pub network_code: String,
47
    #[serde(rename = "networkAddr")]
48
    pub network_addr: String,
49
    pub profile: String,
50
    pub data: String,
51
    #[serde(skip_serializing_if = "Option::is_none")]
52
    pub extension: Option<Document>,
53
}
54

            
55
const COL_NAME: &'static str = "networkDlData";
56

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

            
66
#[async_trait]
67
impl NetworkDlDataModel for Model {
68
12
    async fn init(&self) -> Result<(), Box<dyn StdError>> {
69
12
        let indexes = vec![
70
12
            doc! {"name": "dataId_1", "key": {"dataId": 1}, "unique": true},
71
12
            doc! {"name": "status_1", "key": {"status": 1}},
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": "resp_1", "key": {"resp": 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).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)
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<NetworkDlData>, 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
                Box::new(DbCursor::new(
108
86
                    build_find_options(opts, self.conn.collection::<Schema>(COL_NAME).find(filter))
109
172
                        .await?,
110
                ))
111
            }
112
13
            Some(cursor) => cursor,
113
        };
114

            
115
99
        let mut count: u64 = 0;
116
99
        let mut list = Vec::new();
117
1267
        while let Some(item) = cursor.try_next().await? {
118
1181
            list.push(item);
119
1181
            if let Some(cursor_max) = opts.cursor_max {
120
1089
                count += 1;
121
1089
                if count >= cursor_max {
122
13
                    return Ok((list, Some(cursor)));
123
1076
                }
124
92
            }
125
        }
126
86
        Ok((list, None))
127
198
    }
128

            
129
469
    async fn add(&self, data: &NetworkDlData) -> Result<(), Box<dyn StdError>> {
130
469
        let item = Schema {
131
469
            data_id: data.data_id.clone(),
132
469
            proc: data.proc.into(),
133
469
            publish: data.publish.into(),
134
469
            resp: match data.resp {
135
234
                None => None,
136
235
                Some(resp) => Some(resp.into()),
137
            },
138
469
            status: data.status,
139
469
            unit_id: data.unit_id.clone(),
140
469
            device_id: data.device_id.clone(),
141
469
            network_code: data.network_code.clone(),
142
469
            network_addr: data.network_addr.clone(),
143
469
            profile: data.profile.clone(),
144
469
            data: data.data.clone(),
145
469
            extension: match data.extension.as_ref() {
146
258
                None => None,
147
211
                Some(extension) => Some(bson::to_document(extension)?),
148
            },
149
        };
150
469
        self.conn
151
469
            .collection::<Schema>(COL_NAME)
152
469
            .insert_one(item)
153
939
            .await?;
154
468
        Ok(())
155
938
    }
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)
162
10
            .await?;
163
5
        Ok(())
164
10
    }
165

            
166
    async fn update(
167
        &self,
168
        cond: &UpdateQueryCond,
169
        updates: &Updates,
170
11
    ) -> Result<(), Box<dyn StdError>> {
171
11
        let filter = get_update_query_filter(cond, updates.status);
172
11
        if let Some(updates) = get_update_doc(updates) {
173
11
            self.conn
174
11
                .collection::<Schema>(COL_NAME)
175
11
                .update_one(filter, updates)
176
22
                .await?;
177
        }
178
11
        return Ok(());
179
22
    }
180
}
181

            
182
impl DbCursor {
183
    /// To create the cursor instance with a collection cursor.
184
86
    pub fn new(cursor: MongoDbCursor<Schema>) -> Self {
185
86
        DbCursor { cursor, offset: 0 }
186
86
    }
187
}
188

            
189
#[async_trait]
190
impl Cursor for DbCursor {
191
1267
    async fn try_next(&mut self) -> Result<Option<NetworkDlData>, Box<dyn StdError>> {
192
1267
        if let Some(item) = self.cursor.try_next().await? {
193
1181
            self.offset += 1;
194
1181
            return Ok(Some(NetworkDlData {
195
1181
                data_id: item.data_id,
196
1181
                proc: item.proc.into(),
197
1181
                publish: item.publish.into(),
198
1181
                resp: match item.resp {
199
756
                    None => None,
200
425
                    Some(resp) => Some(resp.into()),
201
                },
202
1181
                status: item.status,
203
1181
                unit_id: item.unit_id,
204
1181
                device_id: item.device_id,
205
1181
                network_code: item.network_code,
206
1181
                network_addr: item.network_addr,
207
1181
                profile: item.profile,
208
1181
                data: item.data,
209
1181
                extension: match item.extension {
210
924
                    None => None,
211
257
                    Some(extension) => Some(bson::from_document(extension)?),
212
                },
213
            }));
214
86
        }
215
86
        Ok(None)
216
2534
    }
217

            
218
5
    fn offset(&self) -> u64 {
219
5
        self.offset
220
5
    }
221
}
222

            
223
/// Transforms query conditions to the MongoDB document.
224
5
fn get_query_filter(cond: &QueryCond) -> Document {
225
5
    let mut filter = Document::new();
226
5
    if let Some(value) = cond.unit_id {
227
3
        filter.insert("unitId", value);
228
3
    }
229
5
    if let Some(value) = cond.device_id {
230
1
        filter.insert("deviceId", value);
231
4
    }
232
5
    let mut time_doc = Document::new();
233
5
    if let Some(value) = cond.proc_gte {
234
1
        time_doc.insert("$gte", Bson::DateTime(value.into()));
235
4
    }
236
5
    if let Some(value) = cond.proc_lte {
237
1
        time_doc.insert("$lte", Bson::DateTime(value.into()));
238
4
    }
239
5
    if time_doc.len() > 0 {
240
1
        filter.insert("proc", time_doc);
241
4
    }
242
5
    filter
243
5
}
244

            
245
/// Transforms query conditions to the MongoDB document.
246
130
fn get_list_query_filter(cond: &ListQueryCond) -> Document {
247
130
    let mut filter = Document::new();
248
130
    if let Some(value) = cond.unit_id {
249
58
        filter.insert("unitId", value);
250
72
    }
251
130
    if let Some(value) = cond.device_id {
252
14
        filter.insert("deviceId", value);
253
116
    }
254
130
    if let Some(value) = cond.network_code {
255
8
        filter.insert("networkCode", value);
256
122
    }
257
130
    if let Some(value) = cond.network_addr {
258
6
        filter.insert("networkAddr", value);
259
124
    }
260
130
    if let Some(value) = cond.profile {
261
6
        filter.insert("profile", value);
262
124
    }
263
130
    let mut time_doc = Document::new();
264
130
    if let Some(value) = cond.proc_gte {
265
25
        time_doc.insert("$gte", Bson::DateTime(value.into()));
266
105
    }
267
130
    if let Some(value) = cond.proc_lte {
268
8
        time_doc.insert("$lte", Bson::DateTime(value.into()));
269
122
    }
270
130
    if time_doc.len() > 0 {
271
25
        filter.insert("proc", time_doc);
272
105
    }
273
130
    time_doc = Document::new();
274
130
    if let Some(value) = cond.pub_gte {
275
14
        time_doc.insert("$gte", Bson::DateTime(value.into()));
276
116
    }
277
130
    if let Some(value) = cond.pub_lte {
278
8
        time_doc.insert("$lte", Bson::DateTime(value.into()));
279
122
    }
280
130
    if time_doc.len() > 0 {
281
14
        filter.insert("pub", time_doc);
282
116
    }
283
130
    time_doc = Document::new();
284
130
    if let Some(value) = cond.resp_gte {
285
14
        time_doc.insert("$gte", Bson::DateTime(value.into()));
286
116
    }
287
130
    if let Some(value) = cond.resp_lte {
288
8
        time_doc.insert("$lte", Bson::DateTime(value.into()));
289
122
    }
290
130
    if time_doc.len() > 0 {
291
14
        filter.insert("resp", time_doc);
292
116
    }
293
130
    filter
294
130
}
295

            
296
/// Transforms model options to the options.
297
86
fn build_find_options<'a, T>(opts: &ListOptions, mut find: Find<'a, T>) -> Find<'a, T>
298
86
where
299
86
    T: Send + Sync,
300
86
{
301
86
    if let Some(offset) = opts.offset {
302
12
        find = find.skip(offset);
303
74
    }
304
86
    if let Some(limit) = opts.limit {
305
65
        if limit > 0 {
306
62
            find = find.limit(limit as i64);
307
62
        }
308
21
    }
309
86
    if let Some(sort_list) = opts.sort.as_ref() {
310
77
        if sort_list.len() > 0 {
311
77
            let mut sort_opts = Document::new();
312
93
            for cond in sort_list.iter() {
313
93
                let key = match cond.key {
314
69
                    SortKey::Proc => "proc",
315
4
                    SortKey::Pub => "pub",
316
4
                    SortKey::Resp => "resp",
317
8
                    SortKey::NetworkCode => "networkCode",
318
8
                    SortKey::NetworkAddr => "networkAddr",
319
                };
320
93
                if cond.asc {
321
43
                    sort_opts.insert(key.to_string(), 1);
322
50
                } else {
323
50
                    sort_opts.insert(key.to_string(), -1);
324
50
                }
325
            }
326
77
            find = find.sort(sort_opts);
327
        }
328
9
    }
329
86
    find
330
86
}
331

            
332
/// Transforms query conditions to the MongoDB document.
333
11
fn get_update_query_filter(cond: &UpdateQueryCond, status: i32) -> Document {
334
11
    let mut document = doc! {"dataId": cond.data_id};
335
11
    if status >= 0 {
336
7
        document.insert("status", doc! {"$ne": 0});
337
7
    } else {
338
4
        document.insert("status", doc! {"$lt": status});
339
4
    }
340
11
    document
341
11
}
342

            
343
/// Transforms the model object to the MongoDB document.
344
11
fn get_update_doc(updates: &Updates) -> Option<Document> {
345
11
    let document = doc! {
346
11
        "resp": DateTime::from_chrono(updates.resp),
347
11
        "status": updates.status,
348
11
    };
349
11
    Some(doc! {"$set": document})
350
11
}