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
//! This module contains the actual implementation for the `User` gRPC service.

use crate::repository;
use log::{error, info};
use minerva_broker as broker;
use minerva_data as lib_data;
use minerva_data::db::DBPool;
use minerva_rpc as lib_rpc;
use minerva_rpc::user::user_server::User;
use minerva_rpc::{messages, metadata};
use std::collections::HashMap;
use tonic::{Request, Response, Status};

/// Represents a gRPC service for user.
#[derive(Clone)]
pub struct UserService {
    /// Holds database connection pools for all tenants.
    pub pools: HashMap<String, (DBPool, broker::LapinPool)>,
}

#[tonic::async_trait]
impl User for UserService {
    async fn index(
        &self,
        req: Request<messages::PageIndex>,
    ) -> Result<Response<messages::UserList>, Status> {
        let tenant = metadata::get_value(req.metadata(), "tenant").ok_or_else(|| {
            error!("Tenant not found on request metadata!");
            Status::failed_precondition("Missing tenant on request metadata")
        })?;

        let requestor = metadata::get_value(req.metadata(), "requestor").ok_or_else(|| {
            error!("Requestor not found on request metadata!");
            Status::failed_precondition("Missing requestor on request metadata")
        })?;

        info!(
            "{}",
            lib_data::log::format(
                lib_rpc::get_address(&req),
                &requestor,
                &tenant,
                "get user index"
            )
        );

        let page = req.into_inner().index.unwrap_or(0);

        let result = {
            let (dbpool, _rmqpool) = self.pools.get(&tenant).expect("Unable to find tenant");

            let connection = dbpool.get().await.map_err(|e| {
                error!("Database access error: {}", e);
                Status::internal("There was an error while accessing the database")
            })?;

            repository::get_list(page, &connection).map_err(|e| {
                error!("Could not recover user list: {}", e);
                Status::internal("There was an error while recovering the user list")
            })?
        };

        Ok(Response::new(minerva_data::user::vec_to_message(result)))
    }

    async fn show(
        &self,
        req: Request<messages::EntityIndex>,
    ) -> Result<Response<messages::User>, Status> {
        let tenant = metadata::get_value(req.metadata(), "tenant").ok_or_else(|| {
            error!("Tenant not found on request metadata!");
            Status::failed_precondition("Missing tenant on request metadata")
        })?;

        let requestor = metadata::get_value(req.metadata(), "requestor").ok_or_else(|| {
            error!("Requestor not found on request metadata!");
            Status::failed_precondition("Missing requestor on request metadata")
        })?;

        info!(
            "{}",
            lib_data::log::format(lib_rpc::get_address(&req), &requestor, &tenant, "show user")
        );

        let result = {
            let (dbpool, _rmqpool) = self.pools.get(&tenant).expect("Unable to find tenant");

            let connection = dbpool.get().await.map_err(|e| {
                error!("Database access error: {}", e);
                Status::internal("There was an error while accessing the database")
            })?;

            repository::get_user(req.get_ref().index, &connection).map_err(|e| {
                error!("Cannot recover user: {}", e);
                Status::internal("There was an error while trying to recover user data")
            })?
        };

        if let Some(user) = result {
            Ok(Response::new(user.into()))
        } else {
            Err(Status::not_found("User not found"))
        }
    }

    async fn store(
        &self,
        req: Request<messages::User>,
    ) -> Result<Response<messages::User>, Status> {
        let tenant = metadata::get_value(req.metadata(), "tenant").ok_or_else(|| {
            error!("Tenant not found on request metadata!");
            Status::failed_precondition("Missing tenant on request metadata")
        })?;

        let requestor = metadata::get_value(req.metadata(), "requestor").ok_or_else(|| {
            error!("Requestor not found on request metadata!");
            Status::failed_precondition("Missing requestor on request metadata")
        })?;

        info!(
            "{}",
            lib_data::log::format(
                lib_rpc::get_address(&req),
                &requestor,
                &tenant,
                "store user"
            )
        );

        let result = {
            let data = req.into_inner().into();

            let (dbpool, _rmqserver) = self.pools.get(&tenant).expect("Unable to find tenant");

            let connection = dbpool.get().await.map_err(|e| {
                error!("Database access error: {}", e);
                Status::internal("There was an error while accessing the database")
            })?;

            repository::add_user(data, requestor, &connection)
        };

        result.map(|u| Response::new(u.into())).map_err(|e| {
            error!("Unable to register user (possibly already exists): {}", e);

            // Assume that the user already exists, at this point.
            // Possibly a conflict on unique keys.
            Status::already_exists("This username or e-mail already exists")
        })
    }

    async fn update(
        &self,
        req: Request<messages::User>,
    ) -> Result<Response<messages::User>, Status> {
        let tenant = metadata::get_value(req.metadata(), "tenant").ok_or_else(|| {
            error!("Tenant not found on request metadata!");
            Status::failed_precondition("Missing tenant on request metadata")
        })?;

        let requestor = metadata::get_value(req.metadata(), "requestor").ok_or_else(|| {
            error!("Requestor not found on request metadata!");
            Status::failed_precondition("Missing requestor on request metadata")
        })?;

        info!(
            "{}",
            lib_data::log::format(
                lib_rpc::get_address(&req),
                &requestor,
                &tenant,
                "update user"
            )
        );

        let result = {
            let data = req.into_inner().into();

            let (dbpool, _rmqpool) = self.pools.get(&tenant).expect("Unable to find tenant");

            let connection = dbpool.get().await.map_err(|e| {
                error!("Database access error: {}", e);
                Status::internal("There was an error while accessing the database")
            })?;

            repository::update_user(data, requestor, &connection)
        };

        result.map(|u| Response::new(u.into())).map_err(|e| {
            error!("Unable to register user: {}", e);
            Status::failed_precondition("There was an error while trying to create the new user")
        })
    }

    async fn delete(&self, req: Request<messages::EntityIndex>) -> Result<Response<()>, Status> {
        let tenant = metadata::get_value(req.metadata(), "tenant").ok_or_else(|| {
            error!("Tenant not found on request metadata!");
            Status::failed_precondition("Missing tenant on request metadata")
        })?;

        let requestor = metadata::get_value(req.metadata(), "requestor").ok_or_else(|| {
            error!("Requestor not found on request metadata!");
            Status::failed_precondition("Missing requestor on request metadata")
        })?;

        info!(
            "{}",
            lib_data::log::format(
                lib_rpc::get_address(&req),
                &requestor,
                &tenant,
                "delete user"
            )
        );

        let result = {
            let (dbpool, rmqpool) = self.pools.get(&tenant).expect("Unable to find tenant");

            let rabbitmq = rmqpool.get().await.map_err(|e| {
                error!("Could not connect to RabbitMQ: {}", e);
                Status::internal("There was an error while trying to connect to the message broker")
            })?;

            repository::delete_user(req.get_ref().index, requestor, dbpool, &rabbitmq).await
        };

        result.map(|_| Response::new(()))
    }
}