tibba-model 0.2.0

model for tibba
Documentation
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// Copyright 2025 Tree xie.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::{
    Error, HttpDetectorModel, Model, ModelListParams, ResultValue, Schema, SchemaAllowCreate,
    SchemaAllowEdit, SchemaOption, SchemaOptionValue, SchemaType, SchemaView, SqlxSnafu,
    format_datetime,
};
use serde::{Deserialize, Serialize};
use snafu::ResultExt;
use sqlx::FromRow;
use sqlx::{Pool, Postgres, QueryBuilder};
use std::collections::HashMap;
use time::PrimitiveDateTime;

type Result<T> = std::result::Result<T, Error>;

#[derive(FromRow)]
struct HttpStatSchema {
    id: i64,
    target_id: i64,
    target_name: String,
    url: String,
    dns_lookup: i32,
    quic_connect: i32,
    tcp_connect: i32,
    tls_handshake: i32,
    server_processing: i32,
    content_transfer: i32,
    total: i32,
    addr: String,
    status_code: i32,
    tls: String,
    alpn: String,
    subject: String,
    issuer: String,
    cert_not_before: String,
    cert_not_after: String,
    cert_cipher: String,
    cert_domains: String,
    body_size: i32,
    error: String,
    result: i16,
    remark: String,
    region: String,
    created: PrimitiveDateTime,
    modified: PrimitiveDateTime,
}

#[derive(Default, Deserialize, Serialize, Debug, Clone)]
pub struct HttpStat {
    pub id: i64,
    pub target_id: i64,
    pub target_name: String,
    pub url: String,
    pub dns_lookup: i32,
    pub quic_connect: i32,
    pub tcp_connect: i32,
    pub tls_handshake: i32,
    pub server_processing: i32,
    pub content_transfer: i32,
    pub total: i32,
    pub addr: String,
    pub status_code: i32,
    pub tls: String,
    pub alpn: String,
    pub subject: String,
    pub issuer: String,
    pub cert_not_before: String,
    pub cert_not_after: String,
    pub cert_cipher: String,
    pub cert_domains: Vec<String>,
    pub body_size: i32,
    pub region: String,
    pub error: String,
    pub result: i16,
    pub remark: String,
    pub created: String,
    pub modified: String,
}

impl From<HttpStatSchema> for HttpStat {
    fn from(schema: HttpStatSchema) -> Self {
        Self {
            id: schema.id,
            target_id: schema.target_id,
            target_name: schema.target_name,
            url: schema.url,
            dns_lookup: schema.dns_lookup,
            quic_connect: schema.quic_connect,
            tcp_connect: schema.tcp_connect,
            tls_handshake: schema.tls_handshake,
            server_processing: schema.server_processing,
            content_transfer: schema.content_transfer,
            total: schema.total,
            addr: schema.addr,
            status_code: schema.status_code,
            tls: schema.tls,
            alpn: schema.alpn,
            subject: schema.subject,
            issuer: schema.issuer,
            cert_not_before: schema.cert_not_before,
            cert_not_after: schema.cert_not_after,
            cert_cipher: schema.cert_cipher,
            cert_domains: schema
                .cert_domains
                .split(',')
                .map(|s| s.to_string())
                .collect(),
            body_size: schema.body_size,
            region: schema.region,
            error: schema.error,
            result: schema.result,
            remark: schema.remark,
            created: format_datetime(schema.created),
            modified: format_datetime(schema.modified),
        }
    }
}

#[derive(Debug, Deserialize, Serialize, Default)]

pub struct HttpStatInsertParams {
    pub target_id: i64,
    pub target_name: String,
    pub url: String,
    pub dns_lookup: Option<i32>,
    pub quic_connect: Option<i32>,
    pub tcp_connect: Option<i32>,
    pub tls_handshake: Option<i32>,
    pub server_processing: Option<i32>,
    pub content_transfer: Option<i32>,
    pub total: Option<i32>,
    pub addr: String,
    pub status_code: Option<i16>,
    pub tls: Option<String>,
    pub alpn: Option<String>,
    pub subject: Option<String>,
    pub issuer: Option<String>,
    pub cert_not_before: Option<String>,
    pub cert_not_after: Option<String>,
    pub cert_cipher: Option<String>,
    pub cert_domains: Option<String>,
    pub body_size: Option<i32>,
    pub region: String,
    pub error: Option<String>,
    pub result: i16,
    pub remark: String,
}

pub struct HttpStatModel {}

impl HttpStatModel {
    pub async fn add_stat(
        &self,
        pool: &Pool<Postgres>,
        params: HttpStatInsertParams,
    ) -> Result<u64> {
        let row: (i64,) = sqlx::query_as(
            r#"INSERT INTO http_stats (target_id, target_name, url, dns_lookup, quic_connect, tcp_connect, tls_handshake, server_processing, content_transfer, total, addr, status_code, tls, alpn, subject, issuer, cert_not_before, cert_not_after, cert_cipher, cert_domains, body_size, region, error, result, remark) VALUES ($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) RETURNING id"#,
        )
        .bind(params.target_id)
        .bind(params.target_name)
        .bind(params.url)
        .bind(params.dns_lookup.unwrap_or(-1))
        .bind(params.quic_connect.unwrap_or(-1))
        .bind(params.tcp_connect.unwrap_or(-1))
        .bind(params.tls_handshake.unwrap_or(-1))
        .bind(params.server_processing.unwrap_or(-1))
        .bind(params.content_transfer.unwrap_or(-1))
        .bind(params.total.unwrap_or(-1))
        .bind(params.addr)
        .bind(params.status_code.unwrap_or(0))
        .bind(params.tls.unwrap_or_default())
        .bind(params.alpn.unwrap_or_default())
        .bind(params.subject.unwrap_or_default())
        .bind(params.issuer.unwrap_or_default())
        .bind(params.cert_not_before.unwrap_or_default())
        .bind(params.cert_not_after.unwrap_or_default())
        .bind(params.cert_cipher.unwrap_or_default())
        .bind(params.cert_domains.unwrap_or_default())
        .bind(params.body_size.unwrap_or(-1))
        .bind(params.region)
        .bind(params.error.unwrap_or_default())
        .bind(params.result)
        .bind(params.remark)
        .fetch_one(pool)
        .await
        .context(SqlxSnafu)?;

        Ok(row.0 as u64)
    }
    pub async fn list_by_created(
        &self,
        pool: &Pool<Postgres>,
        created_range: (&str, &str),
    ) -> Result<Vec<HttpStat>> {
        let detectors = sqlx::query_as::<_, HttpStatSchema>(
            r#"SELECT * FROM http_stats WHERE created >= $1 AND created <= $2"#,
        )
        .bind(created_range.0)
        .bind(created_range.1)
        .fetch_all(pool)
        .await
        .context(SqlxSnafu)?;
        Ok(detectors.into_iter().map(|schema| schema.into()).collect())
    }
}

impl Model for HttpStatModel {
    type Output = HttpStat;
    fn new() -> Self {
        Self {}
    }
    fn keyword(&self) -> String {
        "target_name".to_string()
    }
    async fn schema_view(&self, pool: &Pool<Postgres>) -> SchemaView {
        let mut detector_options = vec![];
        let detector_model = HttpDetectorModel {};
        if let Ok(detectors) = detector_model.list_enabled(pool).await {
            for detector in detectors {
                detector_options.push(SchemaOption {
                    label: detector.name,
                    value: SchemaOptionValue::String(detector.id.to_string()),
                });
            }
            detector_options.sort_by_key(|option| option.label.clone());
        }
        SchemaView {
            schemas: vec![
                Schema {
                    name: "target_id".to_string(),
                    category: SchemaType::String,
                    hidden: true,
                    filterable: !detector_options.is_empty(),
                    options: Some(detector_options),
                    ..Default::default()
                },
                Schema {
                    name: "target_name".to_string(),
                    label: Some("name".to_string()),
                    category: SchemaType::String,
                    fixed: true,
                    ..Default::default()
                },
                Schema {
                    name: "url".to_string(),
                    category: SchemaType::String,
                    max_width: Some(200),
                    ..Default::default()
                },
                Schema {
                    name: "result".to_string(),
                    category: SchemaType::Result,
                    filterable: true,
                    options: Some(vec![
                        SchemaOption {
                            label: "Success".to_string(),
                            value: SchemaOptionValue::String(
                                (ResultValue::Success as u8).to_string(),
                            ),
                        },
                        SchemaOption {
                            label: "Failed".to_string(),
                            value: SchemaOptionValue::String(
                                (ResultValue::Failed as u8).to_string(),
                            ),
                        },
                    ]),
                    ..Default::default()
                },
                Schema {
                    name: "total".to_string(),
                    category: SchemaType::Number,
                    hidden_values: vec!["-1".to_string()],
                    filterable: true,
                    options: Some(vec![
                        SchemaOption {
                            label: ">= 1s".to_string(),
                            value: SchemaOptionValue::String("1000".to_string()),
                        },
                        SchemaOption {
                            label: ">= 2s".to_string(),
                            value: SchemaOptionValue::String("2000".to_string()),
                        },
                        SchemaOption {
                            label: ">= 3s".to_string(),
                            value: SchemaOptionValue::String("3000".to_string()),
                        },
                    ]),
                    ..Default::default()
                },
                Schema {
                    name: "dns_lookup".to_string(),
                    category: SchemaType::Number,
                    hidden_values: vec!["-1".to_string()],
                    ..Default::default()
                },
                Schema {
                    name: "quic_connect".to_string(),
                    category: SchemaType::Number,
                    hidden_values: vec!["-1".to_string()],
                    ..Default::default()
                },
                Schema {
                    name: "tcp_connect".to_string(),
                    category: SchemaType::Number,
                    hidden_values: vec!["-1".to_string()],
                    ..Default::default()
                },
                Schema {
                    name: "tls_handshake".to_string(),
                    category: SchemaType::Number,
                    hidden_values: vec!["-1".to_string()],
                    ..Default::default()
                },
                Schema {
                    name: "server_processing".to_string(),
                    category: SchemaType::Number,
                    hidden_values: vec!["-1".to_string()],
                    ..Default::default()
                },
                Schema {
                    name: "content_transfer".to_string(),
                    category: SchemaType::Number,
                    hidden_values: vec!["-1".to_string()],
                    ..Default::default()
                },
                Schema {
                    name: "timing".to_string(),
                    category: SchemaType::PopoverCard,
                    combinations: Some(vec![
                        "dns_lookup".to_string(),
                        "quic_connect".to_string(),
                        "tcp_connect".to_string(),
                        "tls_handshake".to_string(),
                        "server_processing".to_string(),
                        "content_transfer".to_string(),
                        "total".to_string(),
                    ]),
                    ..Default::default()
                },
                Schema {
                    name: "addr".to_string(),
                    category: SchemaType::String,
                    ..Default::default()
                },
                Schema {
                    name: "status_code".to_string(),
                    category: SchemaType::Number,
                    hidden_values: vec!["0".to_string()],
                    ..Default::default()
                },
                Schema {
                    name: "tls".to_string(),
                    category: SchemaType::String,
                    ..Default::default()
                },
                Schema {
                    name: "alpn".to_string(),
                    category: SchemaType::String,
                    ..Default::default()
                },
                Schema {
                    name: "subject".to_string(),
                    category: SchemaType::String,
                    ..Default::default()
                },
                Schema {
                    name: "issuer".to_string(),
                    category: SchemaType::String,
                    ..Default::default()
                },
                Schema {
                    name: "cert_not_before".to_string(),
                    category: SchemaType::Date,
                    ..Default::default()
                },
                Schema {
                    name: "cert_not_after".to_string(),
                    category: SchemaType::Date,
                    ..Default::default()
                },
                Schema {
                    name: "cert_cipher".to_string(),
                    category: SchemaType::String,
                    ..Default::default()
                },
                Schema {
                    name: "cert_domains".to_string(),
                    category: SchemaType::Strings,
                    ..Default::default()
                },
                Schema {
                    name: "body_size".to_string(),
                    category: SchemaType::ByteSize,
                    ..Default::default()
                },
                Schema {
                    name: "error".to_string(),
                    category: SchemaType::String,
                    ..Default::default()
                },
                Schema {
                    name: "region".to_string(),
                    category: SchemaType::String,
                    ..Default::default()
                },
                Schema::new_readonly_remark(),
                Schema::new_created(),
                Schema::new_filterable_modified(),
            ],
            allow_edit: SchemaAllowEdit {
                disabled: true,
                ..Default::default()
            },
            allow_create: SchemaAllowCreate {
                disabled: true,
                ..Default::default()
            },
        }
    }

    fn push_filter_conditions<'args>(
        &self,
        qb: &mut QueryBuilder<'args, Postgres>,
        filters: &HashMap<String, String>,
    ) -> Result<()> {
        if let Some(result) = filters.get("result").and_then(|s| s.parse::<i16>().ok()) {
            qb.push(" AND result = ");
            qb.push_bind(result);
        }
        if let Some(target_id) = filters.get("target_id").and_then(|s| s.parse::<i64>().ok()) {
            qb.push(" AND target_id = ");
            qb.push_bind(target_id);
        }
        if let Some(total) = filters.get("total").and_then(|s| s.parse::<i32>().ok()) {
            qb.push(" AND total >= ");
            qb.push_bind(total);
        }
        Ok(())
    }

    async fn list(
        &self,
        pool: &Pool<Postgres>,
        params: &ModelListParams,
    ) -> Result<Vec<Self::Output>> {
        let mut qb = QueryBuilder::new("SELECT * FROM http_stats");
        self.push_conditions(&mut qb, params)?;
        params.push_pagination(&mut qb);
        let stats = qb
            .build_query_as::<HttpStatSchema>()
            .fetch_all(pool)
            .await
            .context(SqlxSnafu)?;
        Ok(stats.into_iter().map(|s| s.into()).collect())
    }
    async fn count(&self, pool: &Pool<Postgres>, params: &ModelListParams) -> Result<i64> {
        let mut qb = QueryBuilder::new("SELECT COUNT(*) FROM http_stats");
        self.push_conditions(&mut qb, params)?;
        let count = qb
            .build_query_scalar::<i64>()
            .fetch_one(pool)
            .await
            .context(SqlxSnafu)?;
        Ok(count)
    }
    async fn get_by_id(&self, pool: &Pool<Postgres>, id: u64) -> Result<Option<Self::Output>> {
        let stat = sqlx::query_as::<_, HttpStatSchema>(r#"SELECT * FROM http_stats WHERE id = $1"#)
            .bind(id as i64)
            .fetch_optional(pool)
            .await
            .context(SqlxSnafu)?;
        Ok(stat.map(|schema| schema.into()))
    }
}