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

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

            
12
use sylvia_iot_corelib::strings;
13

            
14
use super::super::application::{
15
    Application, ApplicationModel, Cursor, ListOptions, ListQueryCond, QueryCond, SortKey,
16
    UpdateQueryCond, Updates,
17
};
18

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

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

            
33
/// MongoDB schema.
34
#[derive(Deserialize, Serialize)]
35
struct Schema {
36
    #[serde(rename = "applicationId")]
37
    application_id: String,
38
    code: String,
39
    #[serde(rename = "unitId")]
40
    unit_id: String,
41
    #[serde(rename = "unitCode")]
42
    unit_code: String,
43
    #[serde(rename = "createdAt")]
44
    created_at: DateTime,
45
    #[serde(rename = "modifiedAt")]
46
    modified_at: DateTime,
47
    #[serde(rename = "hostUri")]
48
    host_uri: String,
49
    name: String,
50
    info: Document,
51
}
52

            
53
const COL_NAME: &'static str = "application";
54

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

            
64
#[async_trait]
65
impl ApplicationModel for Model {
66
38
    async fn init(&self) -> Result<(), Box<dyn StdError>> {
67
        let indexes = vec![
68
            doc! {"name": "applicationId_1", "key": {"applicationId": 1}, "unique": true},
69
            doc! {"name": "unitId_1_code_1", "key": {"unitId": 1, "code": 1}, "unique": true},
70
            doc! {"name": "code_1", "key": {"code": 1}},
71
            doc! {"name": "unitId_1", "key": {"unitId": 1}},
72
            doc! {"name": "createdAt_1", "key": {"createdAt": 1}},
73
            doc! {"name": "modifiedAt_1", "key": {"modifiedAt": 1}},
74
            doc! {"name": "name_1", "key": {"name": 1}},
75
        ];
76
        let command = doc! {
77
            "createIndexes": COL_NAME,
78
            "indexes": indexes,
79
        };
80
        self.conn.run_command(command).await?;
81
        Ok(())
82
38
    }
83

            
84
60
    async fn count(&self, cond: &ListQueryCond) -> Result<u64, Box<dyn StdError>> {
85
        let filter = get_list_query_filter(cond);
86
        let count = self
87
            .conn
88
            .collection::<Schema>(COL_NAME)
89
            .count_documents(filter)
90
            .await?;
91
        Ok(count)
92
60
    }
93

            
94
    async fn list(
95
        &self,
96
        opts: &ListOptions,
97
        cursor: Option<Box<dyn Cursor>>,
98
192
    ) -> Result<(Vec<Application>, Option<Box<dyn Cursor>>), Box<dyn StdError>> {
99
        let mut cursor = match cursor {
100
            None => {
101
                let filter = get_list_query_filter(opts.cond);
102
                Box::new(DbCursor::new(
103
                    build_find_options(opts, self.conn.collection::<Schema>(COL_NAME).find(filter))
104
                        .await?,
105
                ))
106
            }
107
            Some(cursor) => cursor,
108
        };
109

            
110
        let mut count: u64 = 0;
111
        let mut list = Vec::new();
112
        while let Some(item) = cursor.try_next().await? {
113
            list.push(item);
114
192
            if let Some(cursor_max) = opts.cursor_max {
115
                count += 1;
116
                if count >= cursor_max {
117
                    return Ok((list, Some(cursor)));
118
                }
119
            }
120
        }
121
        Ok((list, None))
122
192
    }
123

            
124
432
    async fn get(&self, cond: &QueryCond) -> Result<Option<Application>, Box<dyn StdError>> {
125
        let filter = get_query_filter(cond);
126
        let mut cursor = self
127
            .conn
128
            .collection::<Schema>(COL_NAME)
129
            .find(filter)
130
            .await?;
131
        if let Some(item) = cursor.try_next().await? {
132
            return Ok(Some(Application {
133
                application_id: item.application_id,
134
                code: item.code,
135
                unit_id: item.unit_id,
136
                unit_code: item.unit_code,
137
                created_at: item.created_at.into(),
138
                modified_at: item.modified_at.into(),
139
                host_uri: item.host_uri,
140
                name: item.name,
141
                info: bson::deserialize_from_document(item.info)?,
142
            }));
143
        }
144
        Ok(None)
145
432
    }
146

            
147
1560
    async fn add(&self, application: &Application) -> Result<(), Box<dyn StdError>> {
148
        let item = Schema {
149
            application_id: application.application_id.clone(),
150
            code: application.code.clone(),
151
            unit_id: application.unit_id.clone(),
152
            unit_code: application.unit_code.clone(),
153
            created_at: application.created_at.into(),
154
            modified_at: application.modified_at.into(),
155
            host_uri: application.host_uri.clone(),
156
            name: application.name.clone(),
157
            info: bson::serialize_to_document(&application.info)?,
158
        };
159
        self.conn
160
            .collection::<Schema>(COL_NAME)
161
            .insert_one(item)
162
            .await?;
163
        Ok(())
164
1560
    }
165

            
166
34
    async fn del(&self, cond: &QueryCond) -> Result<(), Box<dyn StdError>> {
167
        let filter = get_query_filter(cond);
168
        self.conn
169
            .collection::<Schema>(COL_NAME)
170
            .delete_many(filter)
171
            .await?;
172
        Ok(())
173
34
    }
174

            
175
    async fn update(
176
        &self,
177
        cond: &UpdateQueryCond,
178
        updates: &Updates,
179
18
    ) -> Result<(), Box<dyn StdError>> {
180
        let filter = get_update_query_filter(cond);
181
        if let Some(updates) = get_update_doc(updates) {
182
            self.conn
183
                .collection::<Schema>(COL_NAME)
184
                .update_one(filter, updates)
185
                .await?;
186
        }
187
        return Ok(());
188
18
    }
189
}
190

            
191
impl DbCursor {
192
    /// To create the cursor instance with a collection cursor.
193
168
    pub fn new(cursor: MongoDbCursor<Schema>) -> Self {
194
168
        DbCursor { cursor, offset: 0 }
195
168
    }
196
}
197

            
198
#[async_trait]
199
impl Cursor for DbCursor {
200
2394
    async fn try_next(&mut self) -> Result<Option<Application>, Box<dyn StdError>> {
201
        if let Some(item) = self.cursor.try_next().await? {
202
            self.offset += 1;
203
            return Ok(Some(Application {
204
                application_id: item.application_id,
205
                code: item.code,
206
                unit_id: item.unit_id,
207
                unit_code: item.unit_code,
208
                created_at: item.created_at.into(),
209
                modified_at: item.modified_at.into(),
210
                host_uri: item.host_uri,
211
                name: item.name,
212
                info: bson::deserialize_from_document(item.info)?,
213
            }));
214
        }
215
        Ok(None)
216
2394
    }
217

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

            
223
/// Transforms query conditions to the MongoDB document.
224
466
fn get_query_filter(cond: &QueryCond) -> Document {
225
466
    let mut filter = Document::new();
226
466
    if let Some(value) = cond.unit_id {
227
46
        filter.insert("unitId", value);
228
420
    }
229
466
    if let Some(value) = cond.application_id {
230
432
        filter.insert("applicationId", value);
231
432
    }
232
466
    if let Some(value) = cond.code {
233
18
        filter.insert("code", value);
234
448
    }
235
466
    filter
236
466
}
237

            
238
/// Transforms query conditions to the MongoDB document.
239
228
fn get_list_query_filter(cond: &ListQueryCond) -> Document {
240
228
    let mut filter = Document::new();
241
228
    if let Some(value) = cond.unit_id {
242
100
        filter.insert("unitId", value);
243
128
    }
244
228
    if let Some(value) = cond.application_id {
245
12
        filter.insert("applicationId", value);
246
216
    }
247
228
    if let Some(value) = cond.code {
248
32
        filter.insert("code", value);
249
196
    }
250
228
    if let Some(value) = cond.code_contains {
251
38
        let escaped = strings::escape_regex_str(value);
252
38
        if let Ok(pattern) = CString::try_from(escaped.as_str()) {
253
38
            if let Ok(options) = CString::try_from("i") {
254
38
                filter.insert("code", Regex { pattern, options });
255
38
            }
256
        }
257
190
    }
258
228
    if let Some(value) = cond.name_contains {
259
16
        let escaped = strings::escape_regex_str(value);
260
16
        if let Ok(pattern) = CString::try_from(escaped.as_str()) {
261
16
            if let Ok(options) = CString::try_from("i") {
262
16
                filter.insert("name", Regex { pattern, options });
263
16
            }
264
        }
265
212
    }
266
228
    filter
267
228
}
268

            
269
/// Transforms model options to the options.
270
168
fn build_find_options<'a, T>(opts: &ListOptions, mut find: Find<'a, T>) -> Find<'a, T>
271
168
where
272
168
    T: Send + Sync,
273
{
274
168
    if let Some(offset) = opts.offset {
275
20
        find = find.skip(offset);
276
148
    }
277
168
    if let Some(limit) = opts.limit {
278
80
        if limit > 0 {
279
78
            find = find.limit(limit as i64);
280
78
        }
281
88
    }
282
168
    if let Some(sort_list) = opts.sort.as_ref() {
283
110
        if sort_list.len() > 0 {
284
108
            let mut sort_opts = Document::new();
285
112
            for cond in sort_list.iter() {
286
112
                let key = match cond.key {
287
12
                    SortKey::CreatedAt => "createdAt",
288
8
                    SortKey::ModifiedAt => "modifiedAt",
289
80
                    SortKey::Code => "code",
290
12
                    SortKey::Name => "name",
291
                };
292
112
                if cond.asc {
293
94
                    sort_opts.insert(key.to_string(), 1);
294
94
                } else {
295
18
                    sort_opts.insert(key.to_string(), -1);
296
18
                }
297
            }
298
108
            find = find.sort(sort_opts);
299
2
        }
300
58
    }
301
168
    find
302
168
}
303

            
304
/// Transforms query conditions to the MongoDB document.
305
18
fn get_update_query_filter(cond: &UpdateQueryCond) -> Document {
306
18
    doc! {"applicationId": cond.application_id}
307
18
}
308

            
309
/// Transforms the model object to the MongoDB document.
310
18
fn get_update_doc(updates: &Updates) -> Option<Document> {
311
18
    let mut count = 0;
312
18
    let mut document = Document::new();
313
18
    if let Some(value) = updates.modified_at.as_ref() {
314
16
        document.insert(
315
16
            "modifiedAt",
316
16
            DateTime::from_millis(value.timestamp_millis()),
317
16
        );
318
16
        count += 1;
319
16
    }
320
18
    if let Some(value) = updates.host_uri {
321
8
        document.insert("hostUri", value);
322
8
        count += 1;
323
10
    }
324
18
    if let Some(value) = updates.name {
325
12
        document.insert("name", value);
326
12
        count += 1;
327
12
    }
328
18
    if let Some(value) = updates.info {
329
12
        document.insert(
330
            "info",
331
12
            match bson::serialize_to_document(value) {
332
                Err(_) => return None,
333
12
                Ok(doc) => doc,
334
            },
335
        );
336
12
        count += 1;
337
6
    }
338
18
    if count == 0 {
339
2
        return None;
340
16
    }
341
16
    Some(doc! {"$set": document})
342
18
}