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

            
3
use async_trait::async_trait;
4
use chrono::{TimeZone, Utc};
5
use futures::TryStreamExt;
6
use sql_builder::{quote, SqlBuilder};
7
use sqlx::SqlitePool;
8

            
9
use super::super::coremgr_opdata::{
10
    CoremgrOpData, CoremgrOpDataModel, Cursor, ListOptions, ListQueryCond, QueryCond, SortKey,
11
};
12

            
13
/// Model instance.
14
pub struct Model {
15
    /// The associated database connection.
16
    conn: Arc<SqlitePool>,
17
}
18

            
19
/// Cursor instance.
20
///
21
/// The SQLite implementation uses the original list options and the progress offset.
22
pub struct DbCursor {
23
    offset: u64,
24
}
25

            
26
/// SQLite schema.
27
#[derive(sqlx::FromRow)]
28
struct Schema {
29
    pub data_id: String,
30
    /// i64 as time tick from Epoch in milliseconds.
31
    pub req_time: i64,
32
    /// i64 as time tick from Epoch in milliseconds.
33
    pub res_time: i64,
34
    pub latency_ms: i64,
35
    pub status: i32,
36
    pub source_ip: String,
37
    pub method: String,
38
    pub path: String,
39
    /// use empty string as NULL.
40
    pub body: String,
41
    pub user_id: String,
42
    pub client_id: String,
43
    /// use empty string as NULL.
44
    pub err_code: String,
45
    /// use empty string as NULL.
46
    pub err_message: String,
47
}
48

            
49
/// Use "COUNT(*)" instead of "COUNT(fields...)" to simplify the implementation.
50
#[derive(sqlx::FromRow)]
51
struct CountSchema {
52
    #[sqlx(rename = "COUNT(*)")]
53
    count: i64,
54
}
55

            
56
const TABLE_NAME: &'static str = "coremgr_opdata";
57
const FIELDS: &'static [&'static str] = &[
58
    "data_id",
59
    "req_time",
60
    "res_time",
61
    "latency_ms",
62
    "status",
63
    "source_ip",
64
    "method",
65
    "path",
66
    "body",
67
    "user_id",
68
    "client_id",
69
    "err_code",
70
    "err_message",
71
];
72
const TABLE_INIT_SQL: &'static str = "\
73
    CREATE TABLE IF NOT EXISTS coremgr_opdata (\
74
    data_id TEXT NOT NULL UNIQUE,\
75
    req_time INTEGER NOT NULL,\
76
    res_time INTEGER NOT NULL,\
77
    latency_ms INTEGER NOT NULL,\
78
    status INTEGER NOT NULL,\
79
    source_ip TEXT NOT NULL,\
80
    method TEXT NOT NULL,\
81
    path TEXT NOT NULL,\
82
    body TEXT NOT NULL,\
83
    user_id TEXT NOT NULL,\
84
    client_id TEXT NOT NULL,\
85
    err_code TEXT NOT NULL,\
86
    err_message TEXT NOT NULL)";
87

            
88
impl Model {
89
    /// To create the model instance with a database connection.
90
12
    pub async fn new(conn: Arc<SqlitePool>) -> Result<Self, Box<dyn StdError>> {
91
12
        let model = Model { conn };
92
23
        model.init().await?;
93
12
        Ok(model)
94
12
    }
95
}
96

            
97
#[async_trait]
98
impl CoremgrOpDataModel for Model {
99
20
    async fn init(&self) -> Result<(), Box<dyn StdError>> {
100
20
        let _ = sqlx::query(TABLE_INIT_SQL)
101
20
            .execute(self.conn.as_ref())
102
39
            .await?;
103
20
        Ok(())
104
40
    }
105

            
106
18
    async fn count(&self, cond: &ListQueryCond) -> Result<u64, Box<dyn StdError>> {
107
18
        let sql = build_list_where(SqlBuilder::select_from(TABLE_NAME).count("*"), &cond).sql()?;
108

            
109
18
        let result: Result<CountSchema, sqlx::Error> = sqlx::query_as(sql.as_str())
110
18
            .fetch_one(self.conn.as_ref())
111
36
            .await;
112

            
113
18
        let row = match result {
114
            Err(e) => return Err(Box::new(e)),
115
18
            Ok(row) => row,
116
18
        };
117
18
        Ok(row.count as u64)
118
36
    }
119

            
120
    async fn list(
121
        &self,
122
        opts: &ListOptions,
123
        cursor: Option<Box<dyn Cursor>>,
124
69
    ) -> Result<(Vec<CoremgrOpData>, Option<Box<dyn Cursor>>), Box<dyn StdError>> {
125
69
        let mut cursor = match cursor {
126
56
            None => Box::new(DbCursor::new()),
127
13
            Some(cursor) => cursor,
128
        };
129

            
130
69
        let mut opts = ListOptions { ..*opts };
131
69
        if let Some(offset) = opts.offset {
132
19
            opts.offset = Some(offset + cursor.offset());
133
50
        } else {
134
50
            opts.offset = Some(cursor.offset());
135
50
        }
136
69
        let opts_limit = opts.limit;
137
69
        if let Some(limit) = opts_limit {
138
50
            if limit > 0 {
139
44
                if cursor.offset() >= limit {
140
3
                    return Ok((vec![], None));
141
41
                }
142
41
                opts.limit = Some(limit - cursor.offset());
143
6
            }
144
19
        }
145
66
        let mut builder = SqlBuilder::select_from(TABLE_NAME);
146
66
        build_limit_offset(&mut builder, &opts);
147
66
        build_sort(&mut builder, &opts);
148
66
        let sql = build_list_where(&mut builder, opts.cond).sql()?;
149

            
150
66
        let mut rows = sqlx::query_as::<_, Schema>(sql.as_str()).fetch(self.conn.as_ref());
151
66

            
152
66
        let mut count: u64 = 0;
153
66
        let mut list = vec![];
154
1121
        while let Some(row) = rows.try_next().await? {
155
1077
            let _ = cursor.as_mut().try_next().await?;
156
1077
            list.push(CoremgrOpData {
157
1077
                data_id: row.data_id,
158
1077
                req_time: Utc.timestamp_nanos(row.req_time * 1000000),
159
1077
                res_time: Utc.timestamp_nanos(row.res_time * 1000000),
160
1077
                latency_ms: row.latency_ms,
161
1077
                status: row.status,
162
1077
                source_ip: row.source_ip,
163
1077
                method: row.method,
164
1077
                path: row.path,
165
1077
                body: match row.body.len() {
166
825
                    0 => None,
167
252
                    _ => Some(serde_json::from_str(row.body.as_str())?),
168
                },
169
1077
                user_id: row.user_id,
170
1077
                client_id: row.client_id,
171
1077
                err_code: match row.err_code.len() {
172
826
                    0 => None,
173
251
                    _ => Some(row.err_code),
174
                },
175
1077
                err_message: match row.err_message.len() {
176
826
                    0 => None,
177
251
                    _ => Some(row.err_message),
178
                },
179
            });
180
1077
            if let Some(limit) = opts_limit {
181
1021
                if limit > 0 && cursor.offset() >= limit {
182
12
                    if let Some(cursor_max) = opts.cursor_max {
183
11
                        if (count + 1) >= cursor_max {
184
3
                            return Ok((list, Some(cursor)));
185
8
                        }
186
1
                    }
187
9
                    return Ok((list, None));
188
1009
                }
189
56
            }
190
1065
            if let Some(cursor_max) = opts.cursor_max {
191
1000
                count += 1;
192
1000
                if count >= cursor_max {
193
10
                    return Ok((list, Some(cursor)));
194
990
                }
195
65
            }
196
        }
197
44
        Ok((list, None))
198
138
    }
199

            
200
463
    async fn add(&self, data: &CoremgrOpData) -> Result<(), Box<dyn StdError>> {
201
463
        let body = match data.body.as_ref() {
202
250
            None => quote(""),
203
213
            Some(body) => match serde_json::to_string(body) {
204
                Err(_) => quote("{}"),
205
213
                Ok(value) => quote(value.as_str()),
206
            },
207
        };
208
463
        let err_code = match data.err_code.as_deref() {
209
250
            None => quote(""),
210
213
            Some(value) => quote(value),
211
        };
212
463
        let err_message = match data.err_message.as_deref() {
213
250
            None => quote(""),
214
213
            Some(value) => quote(value),
215
        };
216
463
        let values = vec![
217
463
            quote(data.data_id.as_str()),
218
463
            data.req_time.timestamp_millis().to_string(),
219
463
            data.res_time.timestamp_millis().to_string(),
220
463
            data.latency_ms.to_string(),
221
463
            data.status.to_string(),
222
463
            quote(data.source_ip.as_str()),
223
463
            quote(data.method.as_str()),
224
463
            quote(data.path.as_str()),
225
463
            body,
226
463
            quote(data.user_id.as_str()),
227
463
            quote(data.client_id.as_str()),
228
463
            err_code,
229
463
            err_message,
230
463
        ];
231
463
        let sql = SqlBuilder::insert_into(TABLE_NAME)
232
463
            .fields(FIELDS)
233
463
            .values(&values)
234
463
            .sql()?;
235
463
        let _ = sqlx::query(sql.as_str())
236
463
            .execute(self.conn.as_ref())
237
926
            .await?;
238
462
        Ok(())
239
926
    }
240

            
241
41
    async fn del(&self, cond: &QueryCond) -> Result<(), Box<dyn StdError>> {
242
41
        let sql = build_where(&mut SqlBuilder::delete_from(TABLE_NAME), cond).sql()?;
243
41
        let _ = sqlx::query(sql.as_str())
244
41
            .execute(self.conn.as_ref())
245
81
            .await?;
246
41
        Ok(())
247
82
    }
248
}
249

            
250
impl DbCursor {
251
    /// To create the cursor instance.
252
56
    pub fn new() -> Self {
253
56
        DbCursor { offset: 0 }
254
56
    }
255
}
256

            
257
#[async_trait]
258
impl Cursor for DbCursor {
259
1077
    async fn try_next(&mut self) -> Result<Option<CoremgrOpData>, Box<dyn StdError>> {
260
1077
        self.offset += 1;
261
1077
        Ok(None)
262
2154
    }
263

            
264
776
    fn offset(&self) -> u64 {
265
776
        self.offset
266
776
    }
267
}
268

            
269
/// Transforms query conditions to the SQL builder.
270
41
fn build_where<'a>(builder: &'a mut SqlBuilder, cond: &QueryCond<'a>) -> &'a mut SqlBuilder {
271
41
    if let Some(value) = cond.user_id {
272
3
        builder.and_where_eq("user_id", quote(value));
273
38
    }
274
41
    if let Some(value) = cond.client_id {
275
1
        builder.and_where_eq("client_id", quote(value));
276
40
    }
277
41
    if let Some(value) = cond.req_gte {
278
1
        builder.and_where_ge("req_time", value.timestamp_millis());
279
40
    }
280
41
    if let Some(value) = cond.req_lte {
281
1
        builder.and_where_le("req_time", value.timestamp_millis());
282
40
    }
283
41
    builder
284
41
}
285

            
286
/// Transforms query conditions to the SQL builder.
287
84
fn build_list_where<'a>(
288
84
    builder: &'a mut SqlBuilder,
289
84
    cond: &ListQueryCond<'a>,
290
84
) -> &'a mut SqlBuilder {
291
84
    if let Some(value) = cond.user_id {
292
24
        builder.and_where_eq("user_id", quote(value));
293
60
    }
294
84
    if let Some(value) = cond.client_id {
295
4
        builder.and_where_eq("client_id", quote(value));
296
80
    }
297
84
    if let Some(value) = cond.req_gte {
298
19
        builder.and_where_ge("req_time", value.timestamp_millis());
299
65
    }
300
84
    if let Some(value) = cond.req_lte {
301
2
        builder.and_where_le("req_time", value.timestamp_millis());
302
82
    }
303
84
    if let Some(value) = cond.res_gte {
304
2
        builder.and_where_ge("res_time", value.timestamp_millis());
305
82
    }
306
84
    if let Some(value) = cond.res_lte {
307
2
        builder.and_where_le("res_time", value.timestamp_millis());
308
82
    }
309
84
    builder
310
84
}
311

            
312
/// Transforms model options to the SQL builder.
313
66
fn build_limit_offset<'a>(builder: &'a mut SqlBuilder, opts: &ListOptions) -> &'a mut SqlBuilder {
314
66
    if let Some(value) = opts.limit {
315
47
        if value > 0 {
316
41
            builder.limit(value);
317
41
        }
318
19
    }
319
66
    if let Some(value) = opts.offset {
320
66
        match opts.limit {
321
19
            None => builder.limit(-1).offset(value),
322
6
            Some(0) => builder.limit(-1).offset(value),
323
41
            _ => builder.offset(value),
324
        };
325
    }
326
66
    builder
327
66
}
328

            
329
/// Transforms model options to the SQL builder.
330
66
fn build_sort<'a>(builder: &'a mut SqlBuilder, opts: &ListOptions) -> &'a mut SqlBuilder {
331
66
    if let Some(sort_cond) = opts.sort.as_ref() {
332
56
        for cond in sort_cond.iter() {
333
56
            let key = match cond.key {
334
48
                SortKey::ReqTime => "req_time",
335
4
                SortKey::ResTime => "res_time",
336
4
                SortKey::Latency => "latency_ms",
337
            };
338
56
            builder.order_by(key, !cond.asc);
339
        }
340
10
    }
341
66
    builder
342
66
}