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
//! Module for updating a single user's s3 data
//! record in the local postgres db
//! (note: this does not re-upload the s3 data again,
//! it just updates the local db record)
//!
//! ## Update an existing user data file record for a file stored in AWS S3
//!
//! Update the ``users_data`` tracking record for a file that exists in AWS S3
//!
//! - URL path: ``/user/data``
//! - Method: ``PUT``
//! - Handler: [`update_user_data`](crate::requests::user::update_user_data::update_user_data)
//! - Request: [`ApiReqUserUpdateData`](crate::requests::user::update_user_data::ApiReqUserUpdateData)
//! - Response: [`ApiResUserUpdateData`](crate::requests::user::update_user_data::ApiResUserUpdateData)
//!

use std::convert::Infallible;

use postgres_native_tls::MakeTlsConnector;

use bb8::Pool;
use bb8_postgres::PostgresConnectionManager;

use hyper::header::HeaderValue;
use hyper::Body;
use hyper::HeaderMap;
use hyper::Response;

use serde::Deserialize;
use serde::Serialize;

use kafka_threadpool::kafka_publisher::KafkaPublisher;

use crate::core::core_config::CoreConfig;
use crate::kafka::publish_msg::publish_msg;
use crate::requests::auth::validate_user_token::validate_user_token;
use crate::requests::models::user_data::ModelUserData;

/// ApiReqUserUpdateData
///
/// # Request Type For update_user_data
///
/// Handles updating a `users_data` record in the db
///
/// This type is the deserialized input for:
/// [`update_user_data`](crate::requests::user::update_user_data::update_user_data]
///
/// # Usage
///
/// This type is constructed from the deserialized
/// `bytes` (`&[u8]`) argument
/// on the
/// [`update_user_data`](crate::requests::user::update_user_data::update_user_data)
/// function.
///
/// # Arguments
///
/// * `user_id` - `i32` - user id
/// * `data_id` - `i32` - `users_data.id` record to update
/// * `filename` - `Option<String>` - change the
///   `users_data.filename` field
/// * `data_type` - `Option<String>` - change the
///   `users_data.data_type` field
/// * `comments` - `Option<String>` - change the
///   `users_data.comments` field
/// * `encoding` - `Option<String>` - change the
///   `users_data.encoding` field
/// * `sloc` - `Option<String>` - change the
///   `users_data.sloc` field
///
#[derive(Serialize, Deserialize, Clone)]
pub struct ApiReqUserUpdateData {
    pub user_id: i32,
    pub data_id: i32,
    pub filename: Option<String>,
    pub data_type: Option<String>,
    pub comments: Option<String>,
    pub encoding: Option<String>,
    pub sloc: Option<String>,
}

/// implementation for wrapping complex sql statement creation
impl ApiReqUserUpdateData {
    /// get_sql
    ///
    /// Build the update sql statement based off the
    /// object's values
    ///
    pub fn get_sql(&self) -> String {
        let mut update_value = ("UPDATE \
                users_data \
            SET ")
            .to_string();
        let mut num_params = 0;
        match &self.filename {
            Some(v) => {
                match num_params {
                    0 => {
                        update_value =
                            format!("{update_value} filename = '{v}'")
                    }
                    _ => {
                        update_value =
                            format!("{update_value}, filename = '{v}'")
                    }
                }
                num_params += 1;
                0
            }
            None => 1,
        };
        match &self.data_type {
            Some(v) => {
                match num_params {
                    0 => {
                        update_value =
                            format!("{update_value} data_type = '{v}'")
                    }
                    _ => {
                        update_value =
                            format!("{update_value}, data_type = '{v}'")
                    }
                }
                num_params += 1;
                0
            }
            None => 1,
        };
        match &self.comments {
            Some(v) => {
                match num_params {
                    0 => {
                        update_value =
                            format!("{update_value} comments = '{v}'")
                    }
                    _ => {
                        update_value =
                            format!("{update_value}, comments = '{v}'")
                    }
                }
                num_params += 1;
                0
            }
            None => 1,
        };
        match &self.encoding {
            Some(v) => {
                match num_params {
                    0 => {
                        update_value =
                            format!("{update_value} encoding = '{v}'")
                    }
                    _ => {
                        update_value =
                            format!("{update_value}, encoding = '{v}'")
                    }
                }
                num_params += 1;
                0
            }
            None => 1,
        };
        if false {
            println!(
                "ApiReqUserUpdateData \
                num_params={num_params}"
            );
        }
        // info!("ApiReqUserUpdateData query: {cur_query}");
        format!(
            "{} \
                WHERE \
                    users_data.id = {} \
                RETURNING \
                    users_data.id, \
                    users_data.user_id, \
                    users_data.filename, \
                    users_data.data_type, \
                    users_data.size_in_bytes, \
                    users_data.comments, \
                    users_data.encoding, \
                    users_data.sloc, \
                    users_data.created_at, \
                    users_data.updated_at",
            update_value, self.data_id
        )
    }
}

/// ApiResUserUpdateData
///
/// # Response type for update_user_data
///
/// Return user's db record
///
/// # Usage
///
/// This type is the serialized output for the function:
/// [`update_user_data`](crate::requests::user::update_user_data::update_user_data]
/// and contained within the
/// hyper [`Body`](hyper::Body)
/// of the
/// hyper [`Response`](hyper::Response)
/// sent back to the client.
///
/// # Arguments
///
/// * `data` - [`ModelUserData`](crate::requests::models::user_data::ModelUserData) -
///   the newly-updated record from the `users_data` db table
/// * `msg` - `String` - help message
///
#[derive(Serialize, Deserialize, Clone)]
pub struct ApiResUserUpdateData {
    pub data: ModelUserData,
    pub msg: String,
}

/// update_user_data
///
/// Handles updating a user data record (in the `users_data` table)
/// based off values in the POST-ed hyper
/// [`Request`](hyper::Request)'s [`Body`](hyper::Body)
///
/// ## Overview Notes
///
/// This function only updates 1 `users_data` record at a time.
///
/// # Arguments
///
/// * `tracking_label` - `&str` - caller logging label
/// * `config` - [`CoreConfig`](crate::core::core_config::CoreConfig)
/// * `db_pool` - [`Pool`](bb8::Pool) - postgres client
///   db threadpool with required tls encryption
/// * `kafka_pool` -
///   [`KafkaPublisher`](kafka_threadpool::kafka_publisher::KafkaPublisher)
///   for asynchronously publishing messages to the connected kafka cluster
/// * `headers` - [`HeaderMap`](hyper::HeaderMap) -
///   hashmap containing headers in key-value pairs
///   [`Request`](hyper::Request)'s [`Body`](hyper::Body)
/// * `bytes` - `&[u8]` - received bytes from the hyper
///   [`Request`](hyper::Request)'s [`Body`](hyper::Body)
///
/// # Returns
///
/// ## update_user_data on Success Returns
///
/// The newly-updated `users_data` record from the db
/// ([`ModelUserData`](crate::requests::models::user_data::ModelUserData))
///
/// hyper [`Response`](hyper::Response)
/// containing a json-serialized
/// [`ApiResUserUpdateData`](crate::requests::user::update_user_data::ApiResUserUpdateData)
/// dictionary within the
/// [`Body`](hyper::Body) and a
/// `200` HTTP status code
///
/// Ok([`Response`](hyper::Response))
///
/// # Errors
///
/// ## update_user_data on Failure Returns
///
/// All errors return as a
/// hyper [`Response`](hyper::Response)
/// containing a json-serialized
/// [`ApiResUserUpdateData`](crate::requests::user::update_user_data::ApiResUserUpdateData)
/// dictionary with a
/// `non-200` HTTP status code
///
/// Err([`Response`](hyper::Response))
///
pub async fn update_user_data(
    tracking_label: &str,
    config: &CoreConfig,
    db_pool: &Pool<PostgresConnectionManager<MakeTlsConnector>>,
    kafka_pool: &KafkaPublisher,
    headers: &HeaderMap<HeaderValue>,
    bytes: &[u8],
) -> std::result::Result<Response<Body>, Infallible> {
    let user_object: ApiReqUserUpdateData = match serde_json::from_slice(bytes)
    {
        Ok(uo) => uo,
        Err(_) => {
            let response = Response::builder()
                .status(400)
                .body(Body::from(
                    serde_json::to_string(&ApiResUserUpdateData {
                        data: ModelUserData::default(),
                        msg: ("User update data failed - please ensure \
                            user_id and id are set \
                            with optional arguments \
                            filename, size_in_bytes, \
                            comments, data_type, encoding \
                            were set correctly in the request")
                            .to_string(),
                    })
                    .unwrap(),
                ))
                .unwrap();
            return Ok(response);
        }
    };
    let user_id = user_object.user_id;
    let conn = db_pool.get().await.unwrap();
    let _token = match validate_user_token(
        tracking_label,
        config,
        &conn,
        headers,
        user_object.user_id,
    )
    .await
    {
        Ok(_token) => _token,
        Err(_) => {
            let response = Response::builder()
                .status(400)
                .body(Body::from(
                    serde_json::to_string(&ApiResUserUpdateData {
                        data: ModelUserData::default(),
                        msg: ("User update data failed due to invalid token")
                            .to_string(),
                    })
                    .unwrap(),
                ))
                .unwrap();
            return Ok(response);
        }
    };

    let cur_query = user_object.get_sql();
    let stmt = conn.prepare(&cur_query).await.unwrap();
    let query_result = match conn.query(&stmt, &[]).await {
        Ok(query_result) => query_result,
        Err(e) => {
            let err_msg = format!("{e}");
            let response = Response::builder()
                .status(500)
                .body(Body::from(
                    serde_json::to_string(&ApiResUserUpdateData {
                        data: ModelUserData::default(),
                        msg: format!(
                            "User update data failed for user_id={user_id} \
                                with err='{err_msg}'"
                        ),
                    })
                    .unwrap(),
                ))
                .unwrap();
            return Ok(response);
        }
    };
    let mut row_list: Vec<ModelUserData> = Vec::with_capacity(1);
    for row in query_result.iter() {
        let found_data_id: i32 = row.try_get("id").unwrap();
        let found_user_id: i32 = row.try_get("user_id").unwrap();
        let found_filename: String = row.try_get("filename").unwrap();
        let found_data_type: String = row.try_get("data_type").unwrap();
        let found_size_in_bytes: i64 = row.try_get("size_in_bytes").unwrap();
        let found_comments: String = row.try_get("comments").unwrap();
        let found_encoding: String = row.try_get("encoding").unwrap();
        let found_sloc: String = row.try_get("sloc").unwrap();
        let created_at_utc: chrono::DateTime<chrono::Utc> =
            row.try_get("created_at").unwrap();
        let updated_at_str: String = match row.try_get("updated_at") {
            Ok(v) => {
                let updated_at_utc: chrono::DateTime<chrono::Utc> = v;
                format!("{}", updated_at_utc.format("%Y-%m-%dT%H:%M:%SZ"))
            }
            Err(_) => "".to_string(),
        };
        row_list.push(ModelUserData {
            user_id: found_user_id,
            data_id: found_data_id,
            filename: found_filename,
            data_type: found_data_type,
            size_in_bytes: found_size_in_bytes,
            comments: found_comments,
            encoding: found_encoding,
            sloc: found_sloc,
            created_at: format!(
                "{}",
                created_at_utc.format("%Y-%m-%dT%H:%M:%SZ")
            ),
            updated_at: updated_at_str,
            msg: "success".to_string(),
        });
    }
    if row_list.is_empty() {
        let response = Response::builder()
            .status(200)
            .body(Body::from(
                serde_json::to_string(&ApiResUserUpdateData {
                    data: ModelUserData::default(),
                    msg: "no update data found".to_string(),
                })
                .unwrap(),
            ))
            .unwrap();
        Ok(response)
    } else {
        // if enabled, publish to kafka
        if config.kafka_publish_events {
            publish_msg(
                kafka_pool,
                // topic
                "user.events",
                // partition key
                &format!("user-{}", user_id),
                // optional headers stored in: Option<HashMap<String, String>>
                None,
                // payload in the message
                &format!("USER_UPDATE_DATA user={user_id}"),
            )
            .await;
        }

        let response = Response::builder()
            .status(200)
            .body(Body::from(
                serde_json::to_string(&ApiResUserUpdateData {
                    data: row_list.remove(0),
                    msg: "success".to_string(),
                })
                .unwrap(),
            ))
            .unwrap();
        Ok(response)
    }
}