diff --git a/database/bindings/EventType.ts b/database/bindings/EventType.ts index a43e90ee..0cb8b578 100644 --- a/database/bindings/EventType.ts +++ b/database/bindings/EventType.ts @@ -1,3 +1,3 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type EventType = "AppConnect" | "AppDisconnect" | "ClientConnectInit" | "ClientConnectResolve" | "ClientDisconnect" | "SignMessage" | "SignTransaction" | "SignAndSendTransaction" | "ChangeWallet" | "ChangeNetwork"; \ No newline at end of file +export type EventType = "AppConnect" | "AppDisconnect" | "ClientConnect" | "ClientDisconnect" | "SignMessage" | "SignTransaction" | "SignAndSendTransaction" | "ChangeWallet" | "ChangeNetwork"; \ No newline at end of file diff --git a/database/migrations/0012_events_tables.sql b/database/migrations/0012_events_tables.sql index be363263..9751e1ee 100644 --- a/database/migrations/0012_events_tables.sql +++ b/database/migrations/0012_events_tables.sql @@ -25,6 +25,7 @@ CREATE TABLE event_client_connect( CREATE TABLE event_client_disconnect( event_id BIGINT PRIMARY KEY REFERENCES events(event_id), + client_id TEXT NOT NULL, disconnected_session_id TEXT NOT NULL ); @@ -63,7 +64,7 @@ CREATE TABLE event_change_wallet( wallet_name TEXT NOT NULL, wallet_type TEXT NOT NULL, old_wallet_address TEXT NOT NULL, - new_wallet_address TEXT NOT NULL + new_wallet_address TEXT ); CREATE TABLE event_change_network( @@ -72,5 +73,5 @@ CREATE TABLE event_change_network( request_id TEXT NOT NULL, request_status request_status_enum NOT NULL, old_network TEXT NOT NULL, - new_network TEXT NOT NULL + new_network TEXT ); \ No newline at end of file diff --git a/database/src/tables/events/app_connect/table_struct.rs b/database/src/tables/events/app_connect/table_struct.rs index 346b7b8c..6cca1b7f 100644 --- a/database/src/tables/events/app_connect/table_struct.rs +++ b/database/src/tables/events/app_connect/table_struct.rs @@ -6,7 +6,7 @@ pub const EVENT_APP_CONNECT_KEYS: &str = #[derive(Clone, Debug, Eq, PartialEq)] pub struct AppConnectEvent { - pub event_id: String, + pub event_id: i64, pub app_id: String, pub session_id: String, pub device_metadata: String, diff --git a/database/src/tables/events/app_connect/update.rs b/database/src/tables/events/app_connect/update.rs index 036ffe94..330db8a3 100644 --- a/database/src/tables/events/app_connect/update.rs +++ b/database/src/tables/events/app_connect/update.rs @@ -8,6 +8,7 @@ impl Db { pub async fn create_new_event_app_connect( &self, tx: &mut Transaction<'_, Postgres>, + event_id: i64, session_id: &String, device_metadata: &String, lang: &String, @@ -15,10 +16,11 @@ impl Db { new_session: bool, ) -> Result<(), DbError> { let query_body = format!( - "INSERT INTO {EVENT_APP_CONNECT_TABLE_NAME} ({EVENT_APP_CONNECT_KEYS}) VALUES (DEFAULT, $1, $2, $3, $4, $5)" + "INSERT INTO {EVENT_APP_CONNECT_TABLE_NAME} ({EVENT_APP_CONNECT_KEYS}) VALUES ($1, $2, $3, $4, $5, $6)" ); let query_result = query(&query_body) + .bind(event_id) .bind(session_id) .bind(device_metadata) .bind(lang) diff --git a/database/src/tables/events/app_disconnect/update.rs b/database/src/tables/events/app_disconnect/update.rs index de33ccbd..e68ab2e6 100644 --- a/database/src/tables/events/app_disconnect/update.rs +++ b/database/src/tables/events/app_disconnect/update.rs @@ -9,13 +9,18 @@ impl Db { pub async fn create_new_event_app_disconnect( &self, tx: &mut Transaction<'_, Postgres>, + event_id: i64, session_id: &String, ) -> Result<(), DbError> { let query_body = format!( - "INSERT INTO {EVENT_APP_DISCONNECT_TABLE_NAME} ({EVENT_APP_DISCONNECT_KEYS}) VALUES (DEFAULT, $1)" + "INSERT INTO {EVENT_APP_DISCONNECT_TABLE_NAME} ({EVENT_APP_DISCONNECT_KEYS}) VALUES ($1, $2)" ); - let query_result = query(&query_body).bind(session_id).execute(&mut **tx).await; + let query_result = query(&query_body) + .bind(event_id) + .bind(session_id) + .execute(&mut **tx) + .await; match query_result { Ok(_) => Ok(()), diff --git a/database/src/tables/events/change_network/mod.rs b/database/src/tables/events/change_network/mod.rs new file mode 100644 index 00000000..6027081c --- /dev/null +++ b/database/src/tables/events/change_network/mod.rs @@ -0,0 +1,2 @@ +pub mod table_struct; +pub mod update; diff --git a/database/src/tables/events/change_network/table_struct.rs b/database/src/tables/events/change_network/table_struct.rs new file mode 100644 index 00000000..02cab388 --- /dev/null +++ b/database/src/tables/events/change_network/table_struct.rs @@ -0,0 +1,29 @@ +use crate::structs::request_status::RequestStatus; +use sqlx::{postgres::PgRow, FromRow, Row}; + +pub const EVENT_CHANGE_NETWORK_TABLE_NAME: &str = "event_change_network"; +pub const EVENT_CHANGE_NETWORK_KEYS: &str = + "event_id, session_id, request_id, request_status, old_network, new_network"; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ChangeNetworkEvent { + pub event_id: i64, + pub session_id: String, + pub request_id: String, + pub request_status: RequestStatus, + pub old_network: String, + pub new_network: Option, +} + +impl FromRow<'_, PgRow> for ChangeNetworkEvent { + fn from_row(row: &sqlx::postgres::PgRow) -> std::result::Result { + Ok(ChangeNetworkEvent { + event_id: row.get("event_id"), + session_id: row.get("session_id"), + request_id: row.get("request_id"), + request_status: row.get("request_status"), + old_network: row.get("old_network"), + new_network: row.get("new_network"), + }) + } +} diff --git a/database/src/tables/events/change_network/update.rs b/database/src/tables/events/change_network/update.rs new file mode 100644 index 00000000..4c2c7249 --- /dev/null +++ b/database/src/tables/events/change_network/update.rs @@ -0,0 +1,62 @@ +use crate::structs::request_status::RequestStatus; +use crate::{ + db::Db, + structs::db_error::DbError, + tables::events::change_network::table_struct::{ + EVENT_CHANGE_NETWORK_KEYS, EVENT_CHANGE_NETWORK_TABLE_NAME, + }, +}; +use sqlx::{query, Postgres, Transaction}; + +impl Db { + pub async fn create_new_event_change_network( + &self, + tx: &mut Transaction<'_, Postgres>, + event_id: i64, + session_id: &String, + request_id: &String, + old_network: &String, + ) -> Result<(), DbError> { + let query_body = format!( + "INSERT INTO {EVENT_CHANGE_NETWORK_TABLE_NAME} ({EVENT_CHANGE_NETWORK_KEYS}) VALUES ($1, $2, $3, $4, $5, NULL)" + ); + + let query_result = query(&query_body) + .bind(event_id) + .bind(session_id) + .bind(request_id) + .bind(RequestStatus::Pending) + .bind(old_network) + .execute(&mut **tx) + .await; + + match query_result { + Ok(_) => Ok(()), + Err(e) => Err(e).map_err(|e| e.into()), + } + } + + pub async fn update_event_change_network( + &self, + tx: &mut Transaction<'_, Postgres>, + request_id: &String, + request_status: RequestStatus, + new_network: Option, + ) -> Result<(), DbError> { + let query_body = format!( + "UPDATE {EVENT_CHANGE_NETWORK_TABLE_NAME} SET request_status = $1, new_network = $2 WHERE request_id = $3", + ); + + let query_result = query(&query_body) + .bind(request_status) + .bind(new_network) + .bind(request_id) + .execute(&mut **tx) + .await; + + match query_result { + Ok(_) => Ok(()), + Err(e) => Err(e).map_err(|e| e.into()), + } + } +} diff --git a/database/src/tables/events/change_wallet/mod.rs b/database/src/tables/events/change_wallet/mod.rs new file mode 100644 index 00000000..6027081c --- /dev/null +++ b/database/src/tables/events/change_wallet/mod.rs @@ -0,0 +1,2 @@ +pub mod table_struct; +pub mod update; diff --git a/database/src/tables/events/change_wallet/table_struct.rs b/database/src/tables/events/change_wallet/table_struct.rs new file mode 100644 index 00000000..cc712408 --- /dev/null +++ b/database/src/tables/events/change_wallet/table_struct.rs @@ -0,0 +1,35 @@ +use crate::structs::request_status::RequestStatus; +use sqlx::{postgres::PgRow, FromRow, Row}; + +pub const EVENT_CHANGE_WALLET_TABLE_NAME: &str = "event_change_wallet"; +pub const EVENT_CHANGE_WALLET_KEYS: &str = + "event_id, session_id, request_id, request_status, network, wallet_name, wallet_type, old_wallet_address, new_wallet_address"; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ChangeWalletEvent { + pub event_id: i64, + pub session_id: String, + pub request_id: String, + pub request_status: RequestStatus, + pub network: String, + pub wallet_name: String, + pub wallet_type: String, + pub old_wallet_address: String, + pub new_wallet_address: Option, +} + +impl FromRow<'_, PgRow> for ChangeWalletEvent { + fn from_row(row: &sqlx::postgres::PgRow) -> std::result::Result { + Ok(ChangeWalletEvent { + event_id: row.get("event_id"), + session_id: row.get("session_id"), + request_id: row.get("request_id"), + request_status: row.get("request_status"), + network: row.get("network"), + wallet_name: row.get("wallet_name"), + wallet_type: row.get("wallet_type"), + old_wallet_address: row.get("old_wallet_address"), + new_wallet_address: row.get("new_wallet_address"), + }) + } +} diff --git a/database/src/tables/events/change_wallet/update.rs b/database/src/tables/events/change_wallet/update.rs new file mode 100644 index 00000000..111e0e6a --- /dev/null +++ b/database/src/tables/events/change_wallet/update.rs @@ -0,0 +1,68 @@ +use crate::structs::request_status::RequestStatus; +use crate::{ + db::Db, + structs::db_error::DbError, + tables::events::change_wallet::table_struct::{ + EVENT_CHANGE_WALLET_KEYS, EVENT_CHANGE_WALLET_TABLE_NAME, + }, +}; +use sqlx::{query, Postgres, Transaction}; + +impl Db { + pub async fn create_new_event_change_wallet( + &self, + tx: &mut Transaction<'_, Postgres>, + event_id: &i64, + session_id: &String, + request_id: &String, + network_id: &String, + wallet_name: &String, + wallet_type: &String, + old_wallet_address: &String, + ) -> Result<(), DbError> { + let query_body = format!( + "INSERT INTO {EVENT_CHANGE_WALLET_TABLE_NAME} ({EVENT_CHANGE_WALLET_KEYS}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NULL)" + ); + + let query_result = query(&query_body) + .bind(event_id) + .bind(session_id) + .bind(request_id) + .bind(RequestStatus::Pending) + .bind(network_id) + .bind(wallet_name) + .bind(wallet_type) + .bind(old_wallet_address) + .execute(&mut **tx) + .await; + + match query_result { + Ok(_) => Ok(()), + Err(e) => Err(e).map_err(|e| e.into()), + } + } + + pub async fn update_event_change_wallet( + &self, + tx: &mut Transaction<'_, Postgres>, + request_id: &String, + request_status: RequestStatus, + new_wallet_address: Option, + ) -> Result<(), DbError> { + let query_body = format!( + "UPDATE {EVENT_CHANGE_WALLET_TABLE_NAME} SET request_status = $1, new_wallet_address = $2 WHERE request_id = $3", + ); + + let query_result = query(&query_body) + .bind(request_status) + .bind(new_wallet_address) + .bind(request_id) + .execute(&mut **tx) + .await; + + match query_result { + Ok(_) => Ok(()), + Err(e) => Err(e).map_err(|e| e.into()), + } + } +} diff --git a/database/src/tables/events/client_connect/mod.rs b/database/src/tables/events/client_connect/mod.rs new file mode 100644 index 00000000..6027081c --- /dev/null +++ b/database/src/tables/events/client_connect/mod.rs @@ -0,0 +1,2 @@ +pub mod table_struct; +pub mod update; diff --git a/database/src/tables/events/client_connect/table_struct.rs b/database/src/tables/events/client_connect/table_struct.rs new file mode 100644 index 00000000..0a7fe7da --- /dev/null +++ b/database/src/tables/events/client_connect/table_struct.rs @@ -0,0 +1,32 @@ +use sqlx::{postgres::PgRow, FromRow, Row}; + +pub const EVENT_CLIENT_CONNECT_TABLE_NAME: &str = "event_client_connect"; +pub const EVENT_CLIENT_CONNECT_KEYS: &str = + "event_id, client_id, session_id, addresses, wallet_name, wallet_type, session_type, success"; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClientConnectEvent { + pub event_id: String, + pub client_id: String, + pub session_id: String, + pub addresses: Vec, + pub wallet_name: String, + pub wallet_type: String, + pub session_type: String, + pub success: bool, +} + +impl FromRow<'_, PgRow> for ClientConnectEvent { + fn from_row(row: &sqlx::postgres::PgRow) -> std::result::Result { + Ok(ClientConnectEvent { + event_id: row.get("event_id"), + client_id: row.get("client_id"), + session_id: row.get("session_id"), + addresses: row.get("addresses"), + wallet_name: row.get("wallet_name"), + wallet_type: row.get("wallet_type"), + session_type: row.get("session_type"), + success: row.get("success"), + }) + } +} diff --git a/database/src/tables/events/client_connect/update.rs b/database/src/tables/events/client_connect/update.rs new file mode 100644 index 00000000..7d3b10dd --- /dev/null +++ b/database/src/tables/events/client_connect/update.rs @@ -0,0 +1,66 @@ +use crate::{ + db::Db, + structs::{db_error::DbError, session_type::SessionType}, + tables::events::client_connect::table_struct::{ + EVENT_CLIENT_CONNECT_KEYS, EVENT_CLIENT_CONNECT_TABLE_NAME, + }, +}; +use sqlx::{query, Postgres, Transaction}; + +impl Db { + pub async fn create_new_event_client_connect( + &self, + tx: &mut Transaction<'_, Postgres>, + event_id: i64, + client_id: &String, + session_id: &String, + wallet_name: &String, + wallet_type: &String, + session_type: &SessionType, + ) -> Result<(), DbError> { + let query_body = format!( + "INSERT INTO {EVENT_CLIENT_CONNECT_TABLE_NAME} ({EVENT_CLIENT_CONNECT_KEYS}) VALUES ($1, $2, $3, NULL, $4, $5, $6, false)" + ); + + let query_result = query(&query_body) + .bind(event_id) + .bind(client_id) + .bind(session_id) + .bind(wallet_name) + .bind(wallet_type) + .bind(session_type) + .execute(&mut **tx) + .await; + + match query_result { + Ok(_) => Ok(()), + Err(e) => Err(e).map_err(|e| e.into()), + } + } + + pub async fn update_event_client_connect( + &self, + tx: &mut Transaction<'_, Postgres>, + client_id: &String, + session_id: &String, + success: bool, + new_addresses: &Vec, + ) -> Result<(), DbError> { + let query_body = format!( + "UPDATE {EVENT_CLIENT_CONNECT_TABLE_NAME} SET success = $1, addresses = $2 WHERE client_id = $3 AND session_id = $4 AND success = false" + ); + + let query_result = query(&query_body) + .bind(success) + .bind(&new_addresses) + .bind(client_id) + .bind(session_id) + .execute(&mut **tx) + .await; + + match query_result { + Ok(_) => Ok(()), + Err(e) => Err(e).map_err(|e| e.into()), + } + } +} diff --git a/database/src/tables/events/client_disconnect/mod.rs b/database/src/tables/events/client_disconnect/mod.rs new file mode 100644 index 00000000..6027081c --- /dev/null +++ b/database/src/tables/events/client_disconnect/mod.rs @@ -0,0 +1,2 @@ +pub mod table_struct; +pub mod update; diff --git a/database/src/tables/events/client_disconnect/table_struct.rs b/database/src/tables/events/client_disconnect/table_struct.rs new file mode 100644 index 00000000..4c434d7b --- /dev/null +++ b/database/src/tables/events/client_disconnect/table_struct.rs @@ -0,0 +1,21 @@ +use sqlx::{postgres::PgRow, FromRow, Row}; + +pub const EVENT_CLIENT_DISCONNECT_TABLE_NAME: &str = "event_client_disconnect"; +pub const EVENT_CLIENT_DISCONNECT_KEYS: &str = "event_id, client_id, disconnected_session_id"; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClientDisconnectEvent { + pub event_id: i64, + pub client_id: String, + pub disconnected_session_id: String, +} + +impl FromRow<'_, PgRow> for ClientDisconnectEvent { + fn from_row(row: &sqlx::postgres::PgRow) -> std::result::Result { + Ok(ClientDisconnectEvent { + event_id: row.get("event_id"), + client_id: row.get("client_id"), + disconnected_session_id: row.get("disconnected_session_id"), + }) + } +} diff --git a/database/src/tables/events/client_disconnect/update.rs b/database/src/tables/events/client_disconnect/update.rs new file mode 100644 index 00000000..f574bc8d --- /dev/null +++ b/database/src/tables/events/client_disconnect/update.rs @@ -0,0 +1,34 @@ +use crate::{ + db::Db, + structs::db_error::DbError, + tables::events::client_disconnect::table_struct::{ + EVENT_CLIENT_DISCONNECT_KEYS, EVENT_CLIENT_DISCONNECT_TABLE_NAME, + }, +}; +use sqlx::{query, Postgres, Transaction}; + +impl Db { + pub async fn create_new_event_client_disconnect( + &self, + tx: &mut Transaction<'_, Postgres>, + event_id: i64, + client_id: &String, + session_id: &String, + ) -> Result<(), DbError> { + let query_body = format!( + "INSERT INTO {EVENT_CLIENT_DISCONNECT_TABLE_NAME} ({EVENT_CLIENT_DISCONNECT_KEYS}) VALUES ($1, $2, $3)" + ); + + let query_result = query(&query_body) + .bind(event_id) + .bind(client_id) + .bind(session_id) + .execute(&mut **tx) + .await; + + match query_result { + Ok(_) => Ok(()), + Err(e) => Err(e).map_err(|e| e.into()), + } + } +} diff --git a/database/src/tables/events/events_index/table_struct.rs b/database/src/tables/events/events_index/table_struct.rs index aafcec97..6e2aa896 100644 --- a/database/src/tables/events/events_index/table_struct.rs +++ b/database/src/tables/events/events_index/table_struct.rs @@ -8,7 +8,7 @@ pub const EVENTS_KEYS: &str = "event_id, app_id, event_type, creation_timestamp" #[derive(Clone, Debug, Eq, PartialEq)] pub struct Event { - pub event_id: String, + pub event_id: i64, pub app_id: String, pub event_type: EventType, pub creation_timestamp: DateTime, diff --git a/database/src/tables/events/events_index/update.rs b/database/src/tables/events/events_index/update.rs index 9ed47a7e..e4b86cde 100644 --- a/database/src/tables/events/events_index/update.rs +++ b/database/src/tables/events/events_index/update.rs @@ -3,8 +3,7 @@ use crate::{ structs::{db_error::DbError, event_type::EventType}, tables::events::events_index::table_struct::{EVENTS_KEYS, EVENTS_TABLE_NAME}, }; -use sqlx::Transaction; -use sqlx::{query, Postgres}; +use sqlx::{query, Postgres, Row, Transaction}; impl Db { pub async fn create_new_event_entry( @@ -12,19 +11,19 @@ impl Db { tx: &mut Transaction<'_, Postgres>, app_id: &String, event_type: &EventType, - ) -> Result<(), DbError> { + ) -> Result { let query_body = format!( - "INSERT INTO {EVENTS_TABLE_NAME} ({EVENTS_KEYS}) VALUES (DEFAULT, $1, $2, DEFAULT)" + "INSERT INTO {EVENTS_TABLE_NAME} ({EVENTS_KEYS}) VALUES (DEFAULT, $1, $2, DEFAULT) RETURNING event_id" ); let query_result = query(&query_body) .bind(app_id) .bind(event_type) - .execute(&mut **tx) + .fetch_one(&mut **tx) .await; match query_result { - Ok(_) => Ok(()), + Ok(row) => Ok(row.get("event_id")), Err(e) => Err(e).map_err(|e| e.into()), } } diff --git a/database/src/tables/events/mod.rs b/database/src/tables/events/mod.rs index dd01467d..d137e08e 100644 --- a/database/src/tables/events/mod.rs +++ b/database/src/tables/events/mod.rs @@ -1,3 +1,10 @@ pub mod app_connect; pub mod app_disconnect; +pub mod change_network; +pub mod change_wallet; +pub mod client_connect; +pub mod client_disconnect; pub mod events_index; +pub mod sign_and_send_transaction; +pub mod sign_message; +pub mod sign_transaction; diff --git a/database/src/tables/events/sign_and_send_transaction/mod.rs b/database/src/tables/events/sign_and_send_transaction/mod.rs new file mode 100644 index 00000000..6027081c --- /dev/null +++ b/database/src/tables/events/sign_and_send_transaction/mod.rs @@ -0,0 +1,2 @@ +pub mod table_struct; +pub mod update; diff --git a/database/src/tables/events/sign_and_send_transaction/table_struct.rs b/database/src/tables/events/sign_and_send_transaction/table_struct.rs new file mode 100644 index 00000000..369bfd1f --- /dev/null +++ b/database/src/tables/events/sign_and_send_transaction/table_struct.rs @@ -0,0 +1,29 @@ +use crate::structs::request_status::RequestStatus; +use sqlx::{postgres::PgRow, FromRow, Row}; + +pub const EVENT_SIGN_AND_SEND_TRANSACTION_TABLE_NAME: &str = "event_sign_and_send_transaction"; +pub const EVENT_SIGN_AND_SEND_TRANSACTION_KEYS: &str = + "event_id, session_id, request_id, request_status, network, tx_hash"; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SignAndSendTransactionEvent { + pub event_id: String, + pub session_id: String, + pub request_id: String, + pub request_status: RequestStatus, + pub network: String, + pub tx_hash: Option, +} + +impl FromRow<'_, PgRow> for SignAndSendTransactionEvent { + fn from_row(row: &sqlx::postgres::PgRow) -> std::result::Result { + Ok(SignAndSendTransactionEvent { + event_id: row.get("event_id"), + session_id: row.get("session_id"), + request_id: row.get("request_id"), + request_status: row.get("request_status"), + network: row.get("network"), + tx_hash: row.get("tx_hash"), + }) + } +} diff --git a/database/src/tables/events/sign_and_send_transaction/update.rs b/database/src/tables/events/sign_and_send_transaction/update.rs new file mode 100644 index 00000000..29f9a76e --- /dev/null +++ b/database/src/tables/events/sign_and_send_transaction/update.rs @@ -0,0 +1,62 @@ +use crate::structs::request_status::RequestStatus; +use crate::{ + db::Db, + structs::db_error::DbError, + tables::events::sign_and_send_transaction::table_struct::{ + EVENT_SIGN_AND_SEND_TRANSACTION_KEYS, EVENT_SIGN_AND_SEND_TRANSACTION_TABLE_NAME, + }, +}; +use sqlx::{query, Postgres, Transaction}; + +impl Db { + pub async fn create_new_event_sign_and_send_transaction( + &self, + tx: &mut Transaction<'_, Postgres>, + event_id: i64, + session_id: &String, + request_id: &String, + network_id: &String, + ) -> Result<(), DbError> { + let query_body = format!( + "INSERT INTO {EVENT_SIGN_AND_SEND_TRANSACTION_TABLE_NAME} ({EVENT_SIGN_AND_SEND_TRANSACTION_KEYS}) VALUES ($1, $2, $3, $4, $5, NULL)" + ); + + let query_result = query(&query_body) + .bind(event_id) + .bind(session_id) + .bind(request_id) + .bind(RequestStatus::Pending) + .bind(network_id) + .execute(&mut **tx) + .await; + + match query_result { + Ok(_) => Ok(()), + Err(e) => Err(e).map_err(|e| e.into()), + } + } + + pub async fn update_event_sign_and_send_transaction( + &self, + tx: &mut Transaction<'_, Postgres>, + request_id: &String, + request_status: RequestStatus, + tx_hash: Option, + ) -> Result<(), DbError> { + let query_body = format!( + "UPDATE {EVENT_SIGN_AND_SEND_TRANSACTION_TABLE_NAME} SET request_status = $1, tx_hash = $2 WHERE request_id = $3" + ); + + let query_result = query(&query_body) + .bind(request_status) + .bind(tx_hash) + .bind(request_id) + .execute(&mut **tx) + .await; + + match query_result { + Ok(_) => Ok(()), + Err(e) => Err(e).map_err(|e| e.into()), + } + } +} diff --git a/database/src/tables/events/sign_message/mod.rs b/database/src/tables/events/sign_message/mod.rs new file mode 100644 index 00000000..6027081c --- /dev/null +++ b/database/src/tables/events/sign_message/mod.rs @@ -0,0 +1,2 @@ +pub mod table_struct; +pub mod update; diff --git a/database/src/tables/events/sign_message/table_struct.rs b/database/src/tables/events/sign_message/table_struct.rs new file mode 100644 index 00000000..cfb35ef3 --- /dev/null +++ b/database/src/tables/events/sign_message/table_struct.rs @@ -0,0 +1,27 @@ +use crate::structs::request_status::RequestStatus; +use sqlx::{postgres::PgRow, FromRow, Row}; + +pub const EVENT_SIGN_MESSAGE_TABLE_NAME: &str = "event_sign_message"; +pub const EVENT_SIGN_MESSAGE_KEYS: &str = + "event_id, session_id, request_id, request_status, network"; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SignMessageEvent { + pub event_id: String, + pub session_id: String, + pub request_id: String, + pub request_status: RequestStatus, + pub network: String, +} + +impl FromRow<'_, PgRow> for SignMessageEvent { + fn from_row(row: &sqlx::postgres::PgRow) -> std::result::Result { + Ok(SignMessageEvent { + event_id: row.get("event_id"), + session_id: row.get("session_id"), + request_id: row.get("request_id"), + request_status: row.get("request_status"), + network: row.get("network"), + }) + } +} diff --git a/database/src/tables/events/sign_message/update.rs b/database/src/tables/events/sign_message/update.rs new file mode 100644 index 00000000..7307006c --- /dev/null +++ b/database/src/tables/events/sign_message/update.rs @@ -0,0 +1,60 @@ +use crate::structs::request_status::RequestStatus; +use crate::{ + db::Db, + structs::db_error::DbError, + tables::events::sign_message::table_struct::{ + EVENT_SIGN_MESSAGE_KEYS, EVENT_SIGN_MESSAGE_TABLE_NAME, + }, +}; +use sqlx::{query, Postgres, Transaction}; + +impl Db { + pub async fn create_new_event_sign_message( + &self, + tx: &mut Transaction<'_, Postgres>, + event_id: i64, + session_id: &String, + request_id: &String, + network_id: &String, + ) -> Result<(), DbError> { + let query_body = format!( + "INSERT INTO {EVENT_SIGN_MESSAGE_TABLE_NAME} ({EVENT_SIGN_MESSAGE_KEYS}) VALUES ($1, $2, $3, $4, $5)" + ); + + let query_result = query(&query_body) + .bind(event_id) + .bind(session_id) + .bind(request_id) + .bind(RequestStatus::Pending) + .bind(network_id) + .execute(&mut **tx) + .await; + + match query_result { + Ok(_) => Ok(()), + Err(e) => Err(e).map_err(|e| e.into()), + } + } + + pub async fn update_event_sign_message( + &self, + tx: &mut Transaction<'_, Postgres>, + request_id: &String, + request_status: RequestStatus, + ) -> Result<(), DbError> { + let query_body = format!( + "UPDATE {EVENT_SIGN_MESSAGE_TABLE_NAME} SET request_status = $1, WHERE request_id = $2" + ); + + let query_result = query(&query_body) + .bind(request_status) + .bind(request_id) + .execute(&mut **tx) + .await; + + match query_result { + Ok(_) => Ok(()), + Err(e) => Err(e).map_err(|e| e.into()), + } + } +} diff --git a/database/src/tables/events/sign_transaction/mod.rs b/database/src/tables/events/sign_transaction/mod.rs new file mode 100644 index 00000000..6027081c --- /dev/null +++ b/database/src/tables/events/sign_transaction/mod.rs @@ -0,0 +1,2 @@ +pub mod table_struct; +pub mod update; diff --git a/database/src/tables/events/sign_transaction/table_struct.rs b/database/src/tables/events/sign_transaction/table_struct.rs new file mode 100644 index 00000000..2f454dcc --- /dev/null +++ b/database/src/tables/events/sign_transaction/table_struct.rs @@ -0,0 +1,29 @@ +use crate::structs::request_status::RequestStatus; +use sqlx::{postgres::PgRow, FromRow, Row}; + +pub const EVENT_SIGN_TRANSACTION_TABLE_NAME: &str = "event_sign_transaction"; +pub const EVENT_SIGN_TRANSACTION_KEYS: &str = + "event_id, session_id, request_id, request_status, network, tx_hash"; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SignTransactionEvent { + pub event_id: String, + pub session_id: String, + pub request_id: String, + pub request_status: RequestStatus, + pub network: String, + pub tx_hash: Option, +} + +impl FromRow<'_, PgRow> for SignTransactionEvent { + fn from_row(row: &sqlx::postgres::PgRow) -> std::result::Result { + Ok(SignTransactionEvent { + event_id: row.get("event_id"), + session_id: row.get("session_id"), + request_id: row.get("request_id"), + request_status: row.get("request_status"), + network: row.get("network"), + tx_hash: row.get("tx_hash"), + }) + } +} diff --git a/database/src/tables/events/sign_transaction/update.rs b/database/src/tables/events/sign_transaction/update.rs new file mode 100644 index 00000000..0b3d6a11 --- /dev/null +++ b/database/src/tables/events/sign_transaction/update.rs @@ -0,0 +1,63 @@ +use crate::structs::request_status::RequestStatus; +use crate::{ + db::Db, + structs::db_error::DbError, + tables::events::sign_transaction::table_struct::{ + EVENT_SIGN_TRANSACTION_KEYS, EVENT_SIGN_TRANSACTION_TABLE_NAME, + }, +}; +use sqlx::{query, Postgres, Transaction}; + +impl Db { + pub async fn create_new_event_sign_transaction( + &self, + tx: &mut Transaction<'_, Postgres>, + event_id: i64, + session_id: &String, + request_id: &String, + network_id: &String, + ) -> Result<(), DbError> { + let query_body = format!( + "INSERT INTO {EVENT_SIGN_TRANSACTION_TABLE_NAME} ({EVENT_SIGN_TRANSACTION_KEYS}) VALUES ($1, $2, $3, $4, $5)" + ); + + let query_result = query(&query_body) + .bind(event_id) + .bind(session_id) + .bind(request_id) + .bind(RequestStatus::Pending) + .bind(network_id) + .bind(None::) + .execute(&mut **tx) + .await; + + match query_result { + Ok(_) => Ok(()), + Err(e) => Err(e).map_err(|e| e.into()), + } + } + + pub async fn update_event_sign_transaction( + &self, + tx: &mut Transaction<'_, Postgres>, + request_id: &String, + request_status: RequestStatus, + tx_hash: Option, + ) -> Result<(), DbError> { + let query_body = format!( + "UPDATE {EVENT_SIGN_TRANSACTION_TABLE_NAME} SET request_status = $1, tx_hash = $2 WHERE request_id = $3" + ); + + let query_result = query(&query_body) + .bind(request_status) + .bind(tx_hash) + .bind(request_id) + .execute(&mut **tx) + .await; + + match query_result { + Ok(_) => Ok(()), + Err(e) => Err(e).map_err(|e| e.into()), + } + } +} diff --git a/server/bindings/ChangeNetworkEvent.ts b/server/bindings/ChangeNetworkEvent.ts index 2f6b7099..825b32ed 100644 --- a/server/bindings/ChangeNetworkEvent.ts +++ b/server/bindings/ChangeNetworkEvent.ts @@ -1,3 +1,3 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export interface ChangeNetworkEvent { sessionId: string, requestId: string, network: string, } \ No newline at end of file +export interface ChangeNetworkEvent { sessionId: string, requestId: string, oldNetwork: string, newNetwork: string, } \ No newline at end of file diff --git a/server/bindings/ChangeNetworkResolveEvent.ts b/server/bindings/ChangeNetworkResolveEvent.ts new file mode 100644 index 00000000..71d3d9d9 --- /dev/null +++ b/server/bindings/ChangeNetworkResolveEvent.ts @@ -0,0 +1,4 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { RequestFail } from "./RequestFail"; + +export interface ChangeNetworkResolveEvent { sessionId: string, requestId: string, failureReason?: RequestFail, } \ No newline at end of file diff --git a/server/bindings/ChangeWalletEvent.ts b/server/bindings/ChangeWalletEvent.ts index b9a9dc59..5901df65 100644 --- a/server/bindings/ChangeWalletEvent.ts +++ b/server/bindings/ChangeWalletEvent.ts @@ -1,3 +1,3 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export interface ChangeWalletEvent { sessionId: string, requestId: string, network: string, walletName: string, walletType: string, } \ No newline at end of file +export interface ChangeWalletEvent { sessionId: string, requestId: string, network: string, walletName: string, walletType: string, oldWalletAddress: string, } \ No newline at end of file diff --git a/server/bindings/ChangeWalletResolveEvent.ts b/server/bindings/ChangeWalletResolveEvent.ts new file mode 100644 index 00000000..2f809fb8 --- /dev/null +++ b/server/bindings/ChangeWalletResolveEvent.ts @@ -0,0 +1,4 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { RequestFail } from "./RequestFail"; + +export interface ChangeWalletResolveEvent { sessionId: string, requestId: string, newWalletAddress?: string, failureReason?: RequestFail, } \ No newline at end of file diff --git a/server/bindings/ClientConnectInitEvent.ts b/server/bindings/ClientConnectInitEvent.ts index abb1e536..d1ed7726 100644 --- a/server/bindings/ClientConnectInitEvent.ts +++ b/server/bindings/ClientConnectInitEvent.ts @@ -1,4 +1,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { SessionType } from "./SessionType"; -export interface ClientConnectInitEvent { clientId: string, sessionType: SessionType, sessionId: string, } \ No newline at end of file +export interface ClientConnectInitEvent { clientId: string, sessionId: string, walletName: string, walletType: string, sessionType: SessionType, } \ No newline at end of file diff --git a/server/bindings/ClientConnectResolveEvent.ts b/server/bindings/ClientConnectResolveEvent.ts index a126cadf..e8260452 100644 --- a/server/bindings/ClientConnectResolveEvent.ts +++ b/server/bindings/ClientConnectResolveEvent.ts @@ -1,4 +1,3 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { SessionType } from "./SessionType"; -export interface ClientConnectResolveEvent { clientId: string, sessionId: string, publicKeys: Array, walletName: string, walletType: string, sessionType: SessionType, success: boolean, } \ No newline at end of file +export interface ClientConnectResolveEvent { clientId: string, sessionId: string, addresses: Array, success: boolean, } \ No newline at end of file diff --git a/server/src/http/cloud/events/events_handler.rs b/server/src/http/cloud/events/events_handler.rs index 5a95137a..4c04314f 100644 --- a/server/src/http/cloud/events/events_handler.rs +++ b/server/src/http/cloud/events/events_handler.rs @@ -3,7 +3,7 @@ use super::{ processors::{ process_event_app_connect::process_event_app_connect, process_event_app_disconnect::process_event_app_disconnect, - process_event_client_connect_init::process_event_client_connect_init, + process_event_client_connect::process_event_client_connect_init, process_event_client_connect_resolve::process_event_client_connect_resolve, process_event_client_disconnect::process_event_client_disconnect, }, @@ -37,7 +37,7 @@ pub async fn process_event( EventData::AppDisconnect(event) => { process_event_app_disconnect(event, &event_payload.app_id, ip, db_connection).await; } - EventData::ClientConnectInit(event) => { + EventData::ClientConnect(event) => { process_event_client_connect_init( event, &event_payload.app_id, diff --git a/server/src/http/cloud/events/processors/mod.rs b/server/src/http/cloud/events/processors/mod.rs index 7d8de239..66ea5480 100644 --- a/server/src/http/cloud/events/processors/mod.rs +++ b/server/src/http/cloud/events/processors/mod.rs @@ -1,5 +1,5 @@ pub mod process_event_app_connect; pub mod process_event_app_disconnect; -pub mod process_event_client_connect_init; +pub mod process_event_client_connect; pub mod process_event_client_connect_resolve; pub mod process_event_client_disconnect; diff --git a/server/src/http/cloud/events/processors/process_event_app_connect.rs b/server/src/http/cloud/events/processors/process_event_app_connect.rs index 0a690f6c..f74abfc9 100644 --- a/server/src/http/cloud/events/processors/process_event_app_connect.rs +++ b/server/src/http/cloud/events/processors/process_event_app_connect.rs @@ -5,6 +5,7 @@ use crate::{ }; use database::{ db::Db, + structs::event_type::EventType, tables::{ sessions::table_struct::DbNcSession, utils::{get_current_datetime, get_date_time}, @@ -21,6 +22,9 @@ pub async fn process_event_app_connect( geo_loc_requester: &Arc, sessions: &Sessions, ) { + // Save event to Db + save_event_app_connect(db, app_id, event).await; + if event.new_session { // New session, get the data from sessions and create a new session in the database let session_data = { @@ -98,17 +102,88 @@ pub async fn process_event_app_connect( // Commit the transaction if let Err(err) = tx.commit().await { error!( - "Failed to commit transaction for new app connection event, app_id: [{}], ip: [{}], event: [{:?}], err: [{}]", + "Failed to commit transaction for new app connection, app_id: [{}], ip: [{}], event: [{:?}], err: [{}]", app_id, ip, event, err ); } } Err(err) => { error!( - "Failed to create new connection event, app_id: [{}], ip: [{}], event: [{:?}], err: [{}]", + "Failed to create new connection, app_id: [{}], ip: [{}], event: [{:?}], err: [{}]", app_id, ip, event, err ); } } } } + +async fn save_event_app_connect(db: &Arc, app_id: &String, event: &AppConnectEvent) { + // Establish a new transaction + match db.connection_pool.begin().await { + Ok(mut tx) => { + // Create a new event index in the database + match db + .create_new_event_entry(&mut tx, &app_id, &EventType::AppConnect) + .await + { + Ok(event_id) => { + // Now create a new event app connect corresponding to the event + match db + .create_new_event_app_connect( + &mut tx, + event_id, + &event.session_id, + &event + .device_metadata + .to_string() + .unwrap_or("Failed to serialize device metadata".to_string()), + &event.language, + &event.timezone, + event.new_session, + ) + .await + { + Ok(_) => { + // Commit the transaction + if let Err(err) = tx.commit().await { + error!( + "Failed to commit transaction for new app connection event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + + return; + } + Err(err) => { + error!( + "Failed to create new app connection event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } + } + Err(err) => { + error!( + "Failed to create new event index, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } + + // If we have not returned yet, then we have failed to save the event + // Rollback the transaction + if let Err(err) = tx.rollback().await { + error!( + "Failed to rollback transaction for new app connection event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } + Err(err) => { + error!( + "Failed to create new transaction to save app connection event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } +} diff --git a/server/src/http/cloud/events/processors/process_event_app_disconnect.rs b/server/src/http/cloud/events/processors/process_event_app_disconnect.rs index 1a9d81de..824326e9 100644 --- a/server/src/http/cloud/events/processors/process_event_app_disconnect.rs +++ b/server/src/http/cloud/events/processors/process_event_app_disconnect.rs @@ -1,5 +1,5 @@ use crate::structs::cloud::cloud_events::event_types::app_disconnect_event::AppDisconnectEvent; -use database::db::Db; +use database::{db::Db, structs::event_type::EventType}; use log::error; use std::{net::SocketAddr, sync::Arc}; @@ -9,6 +9,9 @@ pub async fn process_event_app_disconnect( ip: SocketAddr, db: &Arc, ) { + // Save event to Db + save_event_app_disconnect(db, app_id, event).await; + // Close app connection in the database if let Err(err) = db.close_app_connection(&event.session_id, &app_id).await { error!( @@ -17,3 +20,63 @@ pub async fn process_event_app_disconnect( ); } } + +async fn save_event_app_disconnect(db: &Arc, app_id: &String, event: &AppDisconnectEvent) { + // Establish a new transaction + match db.connection_pool.begin().await { + Ok(mut tx) => { + // Create a new event index in the database + match db + .create_new_event_entry(&mut tx, &app_id, &EventType::AppDisconnect) + .await + { + Ok(event_id) => { + // Now create a new event app disconnect corresponding to the event + match db + .create_new_event_app_disconnect(&mut tx, event_id, &event.session_id) + .await + { + Ok(_) => { + // Commit the transaction + if let Err(err) = tx.commit().await { + error!( + "Failed to commit transaction for new app disconnect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + + return; + } + Err(err) => { + error!( + "Failed to create new app disconnect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } + } + Err(err) => { + error!( + "Failed to create new event index, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } + + // If we have not returned yet, then we have failed to save the event + // Rollback the transaction + if let Err(err) = tx.rollback().await { + error!( + "Failed to rollback transaction for new app disconnect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } + Err(err) => { + error!( + "Failed to create new transaction to save app disconnect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } +} diff --git a/server/src/http/cloud/events/processors/process_event_client_connect.rs b/server/src/http/cloud/events/processors/process_event_client_connect.rs new file mode 100644 index 00000000..08e4804d --- /dev/null +++ b/server/src/http/cloud/events/processors/process_event_client_connect.rs @@ -0,0 +1,121 @@ +use crate::{ + ip_geolocation::GeolocationRequester, + structs::cloud::cloud_events::event_types::client_connect_event::ClientConnectEvent, + utils::get_geolocation_data, +}; +use database::{db::Db, structs::event_type::EventType}; +use log::error; +use std::{net::SocketAddr, sync::Arc}; + +pub async fn process_event_client_connect_init( + event: &ClientConnectEvent, + app_id: &String, + ip: SocketAddr, + db: &Arc, + geo_loc_requester: &Arc, +) { + // Save event to Db + save_event_client_connect(db, app_id, event).await; + + // Save connection attempt by client + let mut tx = db.connection_pool.begin().await.unwrap(); + + // Get the geolocation data + let geo_location_data = get_geolocation_data(&db, &geo_loc_requester, &ip).await; + + match db + .create_new_connection_event_by_client( + &mut tx, + &app_id, + &event.session_id, + &event.session_type, + &ip.to_string(), + geo_location_data, + ) + .await + { + Ok(_) => { + // Commit the transaction + if let Err(err) = tx.commit().await { + error!( + "Failed to commit transaction for new app connection event, app_id: [{}], ip: [{}], event: [{:?}], err: [{}]", + app_id, ip, event, err + ); + } + } + Err(err) => { + error!( + "Failed to create new connection event, app_id: [{}], ip: [{}], event: [{:?}], err: [{}]", + app_id, ip, event, err + ); + } + } +} + +async fn save_event_client_connect(db: &Arc, app_id: &String, event: &ClientConnectEvent) { + // Establish a new transaction + match db.connection_pool.begin().await { + Ok(mut tx) => { + // Create a new event index in the database + match db + .create_new_event_entry(&mut tx, &app_id, &EventType::ClientConnect) + .await + { + Ok(event_id) => { + // Now create a new event client connect corresponding to the event + match db + .create_new_event_client_connect( + &mut tx, + event_id, + &event.client_id, + &event.session_id, + &event.wallet_name, + &event.wallet_type, + &event.session_type, + ) + .await + { + Ok(_) => { + // Commit the transaction + if let Err(err) = tx.commit().await { + error!( + "Failed to commit transaction for new client connect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + + return; + } + Err(err) => { + error!( + "Failed to create new client connect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } + } + Err(err) => { + error!( + "Failed to create new event index, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } + + // If we have not returned yet, then we have failed to save the event + // Rollback the transaction + if let Err(err) = tx.rollback().await { + error!( + "Failed to rollback transaction for new client connect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } + Err(err) => { + error!( + "Failed to create new transaction to save client connect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } +} diff --git a/server/src/http/cloud/events/processors/process_event_client_connect_init.rs b/server/src/http/cloud/events/processors/process_event_client_connect_init.rs deleted file mode 100644 index c756d2ac..00000000 --- a/server/src/http/cloud/events/processors/process_event_client_connect_init.rs +++ /dev/null @@ -1,50 +0,0 @@ -use crate::{ - ip_geolocation::GeolocationRequester, - structs::cloud::cloud_events::event_types::client_connect_init_event::ClientConnectInitEvent, - utils::get_geolocation_data, -}; -use database::db::Db; -use log::error; -use std::{net::SocketAddr, sync::Arc}; - -pub async fn process_event_client_connect_init( - event: &ClientConnectInitEvent, - app_id: &String, - ip: SocketAddr, - db: &Arc, - geo_loc_requester: &Arc, -) { - // Save connection attempt by client - let mut tx = db.connection_pool.begin().await.unwrap(); - - // Get the geolocation data - let geo_location_data = get_geolocation_data(&db, &geo_loc_requester, &ip).await; - - match db - .create_new_connection_event_by_client( - &mut tx, - &app_id, - &event.session_id, - &event.session_type, - &ip.to_string(), - geo_location_data, - ) - .await - { - Ok(_) => { - // Commit the transaction - if let Err(err) = tx.commit().await { - error!( - "Failed to commit transaction for new app connection event, app_id: [{}], ip: [{}], event: [{:?}], err: [{}]", - app_id, ip, event, err - ); - } - } - Err(err) => { - error!( - "Failed to create new connection event, app_id: [{}], ip: [{}], event: [{:?}], err: [{}]", - app_id, ip, event, err - ); - } - } -} diff --git a/server/src/http/cloud/events/processors/process_event_client_connect_resolve.rs b/server/src/http/cloud/events/processors/process_event_client_connect_resolve.rs index faa557da..2dd05e53 100644 --- a/server/src/http/cloud/events/processors/process_event_client_connect_resolve.rs +++ b/server/src/http/cloud/events/processors/process_event_client_connect_resolve.rs @@ -9,24 +9,82 @@ pub async fn process_event_client_connect_resolve( ip: SocketAddr, db: &Arc, ) { - // // Check if connection attempt by client was successful, if not then there is nothing to do - // if event.success { - // if let Err(err) = db - // .connect_user_to_the_session( - // &event.client_id, - // &event.wallet_name, - // &event.wallet_type, - // &get_current_datetime(), - // &event.public_keys, - // &app_id.clone(), - // &event.session_id, - // ) - // .await - // { - // error!( - // "Failed to process user successful connect, app_id: [{}], ip: [{}], event: [{:?}], err: [{}]", - // app_id, ip, event, err - // ); - // } - // } + // Save event to Db + save_event_client_connect_resolve(db, app_id, event).await; + + // Check if connection attempt by client was successful, if not then there is nothing to do + if event.success { + if let Err(err) = db + .connect_user_to_the_session( + &event.client_id, + &event.wallet_name, + &event.wallet_type, + &get_current_datetime(), + &event.addresses, + &app_id.clone(), + &event.session_id, + ) + .await + { + error!( + "Failed to process user successful connect, app_id: [{}], ip: [{}], event: [{:?}], err: [{}]", + app_id, ip, event, err + ); + } + } +} + +async fn save_event_client_connect_resolve( + db: &Arc, + app_id: &String, + event: &ClientConnectResolveEvent, +) { + // Establish a new transaction + match db.connection_pool.begin().await { + Ok(mut tx) => { + // Update the connection status for the user + match db + .update_event_client_connect( + &mut tx, + &event.client_id, + &event.session_id, + event.success, + &event.addresses, + ) + .await + { + Ok(_) => { + // Commit the transaction + if let Err(err) = tx.commit().await { + error!( + "Failed to commit transaction for update client connect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } + Err(err) => { + error!( + "Failed to update client connect status, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + + // Rollback the transaction + if let Err(err) = tx.rollback().await { + error!( + "Failed to rollback transaction for update client connect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + + return; + } + } + } + } + Err(err) => { + error!( + "Failed to create new transaction to save client disconnect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } } diff --git a/server/src/http/cloud/events/processors/process_event_client_disconnect.rs b/server/src/http/cloud/events/processors/process_event_client_disconnect.rs index 5d971d83..7d8838dc 100644 --- a/server/src/http/cloud/events/processors/process_event_client_disconnect.rs +++ b/server/src/http/cloud/events/processors/process_event_client_disconnect.rs @@ -1,5 +1,5 @@ use crate::structs::cloud::cloud_events::event_types::client_disconnect_event::ClientDisconnectEvent; -use database::db::Db; +use database::{db::Db, structs::event_type::EventType}; use log::error; use std::{net::SocketAddr, sync::Arc}; @@ -9,6 +9,9 @@ pub async fn process_event_client_disconnect( ip: SocketAddr, db: &Arc, ) { + // Save event to Db + save_event_client_disconnect(db, app_id, event).await; + // Update connection status for user let mut tx = db.connection_pool.begin().await.unwrap(); @@ -33,3 +36,72 @@ pub async fn process_event_client_disconnect( } } } + +async fn save_event_client_disconnect( + db: &Arc, + app_id: &String, + event: &ClientDisconnectEvent, +) { + // Establish a new transaction + match db.connection_pool.begin().await { + Ok(mut tx) => { + // Create a new event index in the database + match db + .create_new_event_entry(&mut tx, &app_id, &EventType::ClientDisconnect) + .await + { + Ok(event_id) => { + // Now create a new event client disconnect corresponding to the event + match db + .create_new_event_client_disconnect( + &mut tx, + event_id, + &event.client_id, + &event.disconnected_session_id, + ) + .await + { + Ok(_) => { + // Commit the transaction + if let Err(err) = tx.commit().await { + error!( + "Failed to commit transaction for new client disconnect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + + return; + } + Err(err) => { + error!( + "Failed to create new client disconnect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } + } + Err(err) => { + error!( + "Failed to create new event index, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } + + // If we have not returned yet, then we have failed to save the event + // Rollback the transaction + if let Err(err) = tx.rollback().await { + error!( + "Failed to rollback transaction for new client disconnect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } + Err(err) => { + error!( + "Failed to create new transaction to save client disconnect event, app_id: [{}], event: [{:?}], err: [{}]", + app_id, event, err + ); + } + } +} diff --git a/server/src/structs/cloud/cloud_events/event_types/client_connect_init_event.rs b/server/src/structs/cloud/cloud_events/event_types/client_connect_event.rs similarity index 91% rename from server/src/structs/cloud/cloud_events/event_types/client_connect_init_event.rs rename to server/src/structs/cloud/cloud_events/event_types/client_connect_event.rs index 3bc100d7..55a57b72 100644 --- a/server/src/structs/cloud/cloud_events/event_types/client_connect_init_event.rs +++ b/server/src/structs/cloud/cloud_events/event_types/client_connect_event.rs @@ -5,7 +5,7 @@ use ts_rs::TS; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] #[ts(export)] #[serde(rename_all = "camelCase")] -pub struct ClientConnectInitEvent { +pub struct ClientConnectEvent { pub client_id: String, pub session_id: String, pub wallet_name: String, diff --git a/server/src/structs/cloud/cloud_events/event_types/client_connect_resolve_event.rs b/server/src/structs/cloud/cloud_events/event_types/client_connect_resolve_event.rs index b567b764..6cfe83a3 100644 --- a/server/src/structs/cloud/cloud_events/event_types/client_connect_resolve_event.rs +++ b/server/src/structs/cloud/cloud_events/event_types/client_connect_resolve_event.rs @@ -8,5 +8,7 @@ pub struct ClientConnectResolveEvent { pub client_id: String, pub session_id: String, pub addresses: Vec, + pub wallet_name: String, + pub wallet_type: String, pub success: bool, } diff --git a/server/src/structs/cloud/cloud_events/event_types/client_disconnect_event.rs b/server/src/structs/cloud/cloud_events/event_types/client_disconnect_event.rs index e69d14ba..1ba2b7b3 100644 --- a/server/src/structs/cloud/cloud_events/event_types/client_disconnect_event.rs +++ b/server/src/structs/cloud/cloud_events/event_types/client_disconnect_event.rs @@ -5,5 +5,6 @@ use ts_rs::TS; #[ts(export)] #[serde(rename_all = "camelCase")] pub struct ClientDisconnectEvent { + pub client_id: String, pub disconnected_session_id: String, } diff --git a/server/src/structs/cloud/cloud_events/event_types/mod.rs b/server/src/structs/cloud/cloud_events/event_types/mod.rs index 472a7a8d..efb7f919 100644 --- a/server/src/structs/cloud/cloud_events/event_types/mod.rs +++ b/server/src/structs/cloud/cloud_events/event_types/mod.rs @@ -4,7 +4,7 @@ pub mod change_network_event; pub mod change_network_resolve_event; pub mod change_wallet_event; pub mod change_wallet_resolve_event; -pub mod client_connect_init_event; +pub mod client_connect_event; pub mod client_connect_resolve_event; pub mod client_disconnect_event; pub mod sign_and_send_transaction_event; diff --git a/server/src/structs/cloud/cloud_events/events.rs b/server/src/structs/cloud/cloud_events/events.rs index 2e26e8e1..03316ec3 100644 --- a/server/src/structs/cloud/cloud_events/events.rs +++ b/server/src/structs/cloud/cloud_events/events.rs @@ -1,7 +1,7 @@ use super::event_types::{ app_connect_event::AppConnectEvent, app_disconnect_event::AppDisconnectEvent, change_network_event::ChangeNetworkEvent, change_wallet_event::ChangeWalletEvent, - client_connect_init_event::ClientConnectInitEvent, + client_connect_event::ClientConnectEvent, client_connect_resolve_event::ClientConnectResolveEvent, client_disconnect_event::ClientDisconnectEvent, sign_and_send_transaction_event::SignAndSendTransactionEvent, @@ -19,7 +19,7 @@ use ts_rs::TS; pub enum EventData { AppConnect(AppConnectEvent), AppDisconnect(AppDisconnectEvent), - ClientConnectInit(ClientConnectInitEvent), + ClientConnect(ClientConnectEvent), ClientConnectResolve(ClientConnectResolveEvent), ClientDisconnect(ClientDisconnectEvent), SignMessage(SignMessageEvent), diff --git a/server/src/structs/cloud/device_metadata.rs b/server/src/structs/cloud/device_metadata.rs index 0e2765a5..a1b447da 100644 --- a/server/src/structs/cloud/device_metadata.rs +++ b/server/src/structs/cloud/device_metadata.rs @@ -27,3 +27,13 @@ pub struct WebMetadata { pub os: String, pub os_version: String, } + +impl DeviceMetadata { + pub fn to_string(&self) -> Result { + serde_json::to_string(self) + } + + pub fn from_string(s: &str) -> Result { + serde_json::from_str(s) + } +} diff --git a/server/src/structs/common.rs b/server/src/structs/common.rs index c8d47eac..0612eaa8 100644 --- a/server/src/structs/common.rs +++ b/server/src/structs/common.rs @@ -38,7 +38,7 @@ pub enum SessionStatus { Idle, // Both disconnected, but session is still alive for a while in case client reconnects } -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] +#[derive(Debug, Display, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] #[ts(export)] pub enum Device { Apple,