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

            
3
use axum::{response::IntoResponse, Router};
4
use reqwest;
5
use serde::{Deserialize, Serialize};
6

            
7
use general_mq::Queue;
8
use sylvia_iot_corelib::{
9
    constants::DbEngine,
10
    http::{Json, Query},
11
};
12

            
13
use crate::{
14
    libs::{
15
        config::{self, Config},
16
        mq::{self, Connection},
17
    },
18
    models::{self, ConnOptions, Model, MongoDbOptions, SqliteOptions},
19
};
20

            
21
pub mod middleware;
22
mod v1;
23

            
24
/// The resources used by this service.
25
#[derive(Clone)]
26
pub struct State {
27
    /// The scope root path for the service.
28
    ///
29
    /// For example `/data`, the APIs are
30
    /// - `http://host:port/data/api/v1/application-uldata/xxx`
31
    /// - `http://host:port/data/api/v1/network-uldata/xxx`
32
    pub scope_path: &'static str,
33
    /// The database model.
34
    pub model: Arc<dyn Model>,
35
    /// The sylvia-iot-auth base API path with host.
36
    ///
37
    /// For example, `http://localhost:1080/auth`.
38
    pub auth_base: String,
39
    /// The sylvia-iot-broker base API path with host.
40
    ///
41
    /// For example, `http://localhost:2080/broker`.
42
    pub broker_base: String,
43
    /// The client for internal HTTP requests.
44
    pub client: reqwest::Client,
45
    /// Queue connections. Key is uri.
46
    pub mq_conns: HashMap<String, Connection>,
47
    /// Data channel receivers. Key is data channel name such as `broker.data`, `coremgr.data`, ...
48
    pub data_receivers: HashMap<String, Queue>,
49
}
50

            
51
/// The sylvia-iot module specific error codes in addition to standard [`ErrResp`].
52
pub struct ErrReq;
53

            
54
/// Query parameters for `GET /version`
55
7
#[derive(Deserialize)]
56
pub struct GetVersionQuery {
57
    q: Option<String>,
58
}
59

            
60
#[derive(Serialize)]
61
struct GetVersionRes<'a> {
62
    data: GetVersionResData<'a>,
63
}
64

            
65
#[derive(Serialize)]
66
struct GetVersionResData<'a> {
67
    name: &'a str,
68
    version: &'a str,
69
}
70

            
71
const SERV_NAME: &'static str = env!("CARGO_PKG_NAME");
72
const SERV_VER: &'static str = env!("CARGO_PKG_VERSION");
73

            
74
impl ErrReq {
75
    pub const UNIT_NOT_EXIST: (u16, &'static str) = (400, "err_data_unit_not_exist");
76
    pub const USER_NOT_EXIST: (u16, &'static str) = (400, "err_data_user_not_exist");
77
}
78

            
79
/// To create resources for the service.
80
8
pub async fn new_state(
81
8
    scope_path: &'static str,
82
8
    conf: &Config,
83
8
) -> Result<State, Box<dyn StdError>> {
84
8
    let conf = config::apply_default(conf);
85
8
    let db_opts = match conf.db.as_ref().unwrap().engine.as_ref().unwrap().as_str() {
86
8
        DbEngine::MONGODB => {
87
3
            let conf = conf.db.as_ref().unwrap().mongodb.as_ref().unwrap();
88
3
            ConnOptions::MongoDB(MongoDbOptions {
89
3
                url: conf.url.as_ref().unwrap().to_string(),
90
3
                db: conf.database.as_ref().unwrap().to_string(),
91
3
                pool_size: conf.pool_size,
92
3
            })
93
        }
94
        _ => {
95
5
            let conf = conf.db.as_ref().unwrap().sqlite.as_ref().unwrap();
96
5
            ConnOptions::Sqlite(SqliteOptions {
97
5
                path: conf.path.as_ref().unwrap().to_string(),
98
5
            })
99
        }
100
    };
101
199
    let model = models::new(&db_opts).await?;
102
8
    let auth_base = conf.auth.as_ref().unwrap().clone();
103
8
    let broker_base = conf.broker.as_ref().unwrap().clone();
104
8
    let mut mq_conns = HashMap::new();
105
8
    let ch_conf = conf.mq_channels.as_ref().unwrap();
106
8
    let data_receivers = new_data_receivers(&model, &mut mq_conns, ch_conf)?;
107
8
    let state = State {
108
8
        scope_path,
109
8
        model,
110
8
        auth_base,
111
8
        broker_base,
112
8
        client: reqwest::Client::new(),
113
8
        mq_conns,
114
8
        data_receivers,
115
8
    };
116
8
    Ok(state)
117
8
}
118

            
119
/// To register service URIs in the specified root path.
120
1263
pub fn new_service(state: &State) -> Router {
121
1263
    Router::new().nest(
122
1263
        &state.scope_path,
123
1263
        Router::new()
124
1263
            .merge(v1::application_uldata::new_service(
125
1263
                "/api/v1/application-uldata",
126
1263
                state,
127
1263
            ))
128
1263
            .merge(v1::application_dldata::new_service(
129
1263
                "/api/v1/application-dldata",
130
1263
                state,
131
1263
            ))
132
1263
            .merge(v1::network_uldata::new_service(
133
1263
                "/api/v1/network-uldata",
134
1263
                state,
135
1263
            ))
136
1263
            .merge(v1::network_dldata::new_service(
137
1263
                "/api/v1/network-dldata",
138
1263
                state,
139
1263
            ))
140
1263
            .merge(v1::coremgr_opdata::new_service(
141
1263
                "/api/v1/coremgr-opdata",
142
1263
                state,
143
1263
            )),
144
1263
    )
145
1263
}
146

            
147
8
pub fn new_data_receivers(
148
8
    model: &Arc<dyn Model>,
149
8
    mq_conns: &mut HashMap<String, Connection>,
150
8
    ch_conf: &config::MqChannels,
151
8
) -> Result<HashMap<String, Queue>, Box<dyn StdError>> {
152
8
    let mut data_receivers = HashMap::<String, Queue>::new();
153
8

            
154
8
    let conf = ch_conf.broker.as_ref().unwrap();
155
8
    let q = mq::broker::new(model.clone(), mq_conns, &conf)?;
156
8
    data_receivers.insert("broker.data".to_string(), q);
157
8

            
158
8
    let conf = ch_conf.coremgr.as_ref().unwrap();
159
8
    let q = mq::coremgr::new(model.clone(), mq_conns, &conf)?;
160
8
    data_receivers.insert("coremgr.data".to_string(), q);
161
8

            
162
8
    Ok(data_receivers)
163
8
}
164

            
165
4
pub async fn get_version(Query(query): Query<GetVersionQuery>) -> impl IntoResponse {
166
4
    if let Some(q) = query.q.as_ref() {
167
3
        match q.as_str() {
168
3
            "name" => return SERV_NAME.into_response(),
169
2
            "version" => return SERV_VER.into_response(),
170
1
            _ => (),
171
        }
172
1
    }
173

            
174
2
    Json(GetVersionRes {
175
2
        data: GetVersionResData {
176
2
            name: SERV_NAME,
177
2
            version: SERV_VER,
178
2
        },
179
2
    })
180
2
    .into_response()
181
4
}