From 15b5e42a536d84f5d5dfc229bc1a7ac785201dea Mon Sep 17 00:00:00 2001 From: sargon64 Date: Fri, 15 Sep 2023 21:43:39 -0700 Subject: [PATCH 1/4] fix: remove global write state --- TournamentAssistantProtos | 1 + src/main.rs | 17 ++++------------- src/packets.rs | 25 +++++++++++++++++-------- 3 files changed, 22 insertions(+), 21 deletions(-) create mode 160000 TournamentAssistantProtos diff --git a/TournamentAssistantProtos b/TournamentAssistantProtos new file mode 160000 index 0000000..5d0eba2 --- /dev/null +++ b/TournamentAssistantProtos @@ -0,0 +1 @@ +Subproject commit 5d0eba234584c903e43894500b2f82842929edb9 diff --git a/src/main.rs b/src/main.rs index 162c621..c1e501d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -45,9 +45,6 @@ lazy_static::lazy_static! { pub static ref TA_STATE : RwLock = { RwLock::new(packets::TAState::new()) }; - pub static ref TA_CON: RwLock> = { - RwLock::new(None) - }; pub static ref TA_UPDATE_SINK: Sink = { Sink::new() @@ -73,14 +70,7 @@ async fn main() -> anyhow::Result<()> { .unwrap() .block_on(async { log::info!("Connecting to Server..."); - *TA_CON.write().await = Some( - connection::TAConnection::connect( - std::env::var("TA_WS_URI").unwrap(), - "TA-Relay-TX", - ) - .await - .unwrap(), - ); + let mut ta_con = connection::TAConnection::connect( std::env::var("TA_WS_URI").unwrap(), "TA-Relay-RX", @@ -96,8 +86,9 @@ async fn main() -> anyhow::Result<()> { continue; } }; - tokio::spawn(async { - packets::route_packet(&mut *TA_STATE.write().await, msg) + + tokio::spawn(async move { + packets::route_packet(&mut *TA_STATE.write().await,msg) .await .unwrap(); diff --git a/src/packets.rs b/src/packets.rs index f2284c8..4fb72c5 100644 --- a/src/packets.rs +++ b/src/packets.rs @@ -6,8 +6,8 @@ use crate::{ proto::{ models, packet::{self, event}, - }, - TA_CON, + }, connection::TAConnection, + // TA_CON, }; #[derive(Debug, Default, Clone)] @@ -105,15 +105,22 @@ impl TAState { //add the overlay to the match's associated users. r#match .associated_users - .extend(self.server_users.iter().map(|u| u.guid.clone())); + .extend(self.server_users.iter().filter(|f| !f.name.contains("TX")).map(|u| u.guid.clone())); self.matches.push(r#match.clone()); - TA_CON - .write() - .await - .as_mut() - .unwrap() + let mut con = TAConnection::connect( + std::env::var("TA_WS_URI").unwrap(), + "TA-Relay-TX", + ) + .await + .unwrap(); + + con + // .write() + // .await + // .as_mut() + // .unwrap() .send(packet::Packet { id: Uuid::new_v4().to_string(), from: "".to_string(), @@ -130,6 +137,8 @@ impl TAState { )), }) .await?; + + con.close().await; } None => { log::warn!("Received MatchCreatedEvent with no match"); From 55becbbe9bb63e62682dcf11495d8e9dbe5c2d1e Mon Sep 17 00:00:00 2001 From: sargon64 Date: Fri, 15 Sep 2023 21:59:25 -0700 Subject: [PATCH 2/4] fix: add better error msg --- src/connection.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/connection.rs b/src/connection.rs index 30c5cb9..e540206 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -20,7 +20,13 @@ impl TAConnection { pub async fn connect, U: Into>(uri: T, name: U) -> anyhow::Result { let uri = uri.into(); let name = name.into(); - let (ws_stream, _) = tokio_tungstenite::connect_async(uri).await?; + let (ws_stream, _) = match tokio_tungstenite::connect_async(uri).await { + Ok(c) => c, + Err(_) => { + log::error!("Failed to connect to server. Are you sure you're connecting to the overlay websocket?"); + return Err(anyhow::anyhow!("Failed to connect to server. Are you sure you're connecting to the overlay websocket?")); + }, + }; let (mut ws_tx, ws_rx) = ws_stream.split(); let ws_user = models::User { guid: uuid::Uuid::new_v4().to_string(), From e9296f271d843183f8d69c92c5853f08fd7ada8e Mon Sep 17 00:00:00 2001 From: sargon64 Date: Sun, 17 Sep 2023 00:38:02 -0700 Subject: [PATCH 3/4] feat: add historic data logging --- .idea/.gitignore | 8 + .idea/dataSources.xml | 12 + .idea/modules.xml | 8 + .idea/sqldialects.xml | 7 + .idea/ta-relay-rs.iml | 11 + .idea/vcs.xml | 7 + Cargo.lock | 725 ++++++++++++++++++++++++++++++++++++++++-- Cargo.toml | 9 +- build.rs | 11 +- src/connection.rs | 62 ++-- src/gql.rs | 20 +- src/main.rs | 37 ++- src/packets.rs | 115 ++++--- src/structs.rs | 20 +- 14 files changed, 938 insertions(+), 114 deletions(-) create mode 100644 .idea/.gitignore create mode 100644 .idea/dataSources.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/sqldialects.xml create mode 100644 .idea/ta-relay-rs.iml create mode 100644 .idea/vcs.xml diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml new file mode 100644 index 0000000..73c8f28 --- /dev/null +++ b/.idea/dataSources.xml @@ -0,0 +1,12 @@ + + + + + postgresql + true + org.postgresql.Driver + jdbc:postgresql://localhost:5432/postgres + $ProjectFileDir$ + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..174bfec --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/sqldialects.xml b/.idea/sqldialects.xml new file mode 100644 index 0000000..e4f7c09 --- /dev/null +++ b/.idea/sqldialects.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/ta-relay-rs.iml b/.idea/ta-relay-rs.iml new file mode 100644 index 0000000..cf84ae4 --- /dev/null +++ b/.idea/ta-relay-rs.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..8e51d3e --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 869caf8..0bfe9f6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,18 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" +[[package]] +name = "ahash" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f" +dependencies = [ + "cfg-if", + "getrandom 0.2.10", + "once_cell", + "version_check", +] + [[package]] name = "aho-corasick" version = "1.0.4" @@ -26,6 +38,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "allocator-api2" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" + [[package]] name = "android-tzdata" version = "0.1.1" @@ -86,6 +104,21 @@ dependencies = [ "syn 2.0.28", ] +[[package]] +name = "async_once" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ce4f10ea3abcd6617873bae9f91d1c5332b4a778bd9ce34d0cd517474c1de82" + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + [[package]] name = "autocfg" version = "1.1.0" @@ -119,6 +152,12 @@ version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d" +[[package]] +name = "base64ct" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" + [[package]] name = "bitflags" version = "1.3.2" @@ -130,6 +169,9 @@ name = "bitflags" version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635" +dependencies = [ + "serde", +] [[package]] name = "block-buffer" @@ -154,7 +196,7 @@ dependencies = [ "rand 0.7.3", "serde", "serde_json", - "uuid", + "uuid 0.8.2", ] [[package]] @@ -265,6 +307,12 @@ dependencies = [ "unreachable", ] +[[package]] +name = "const-oid" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28c122c3980598d243d63d9a704629a2d748d101f278052ff068be5a4423ab6f" + [[package]] name = "core-foundation" version = "0.9.3" @@ -290,6 +338,21 @@ dependencies = [ "libc", ] +[[package]] +name = "crc" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86ec7a15cbe22e59248fc7eadb1907dab5ba09372595da4d73dd805ed4417dfe" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cace84e55f07e7301bae1c519df89cdad8cc3cd868413d3fdbdeca9ff3db484" + [[package]] name = "crossbeam-channel" version = "0.5.8" @@ -300,6 +363,16 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "crossbeam-queue" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1cfb3ea8a53f37c40dea2c7bedcbd88bdfae54f5e2175d6ecaff1c988353add" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.16" @@ -325,6 +398,17 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2e66c9d817f1720209181c316d28635c050fa304f9c79e47a520882661b7308" +[[package]] +name = "der" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fffa369a668c8af7dbf8b5e56c9f744fbd399949ed171606040001947de40b1c" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + [[package]] name = "derive_utils" version = "0.11.2" @@ -343,7 +427,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", + "const-oid", "crypto-common", + "subtle", ] [[package]] @@ -352,11 +438,20 @@ version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f" +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + [[package]] name = "either" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" +dependencies = [ + "serde", +] [[package]] name = "encoding_rs" @@ -416,18 +511,53 @@ dependencies = [ "version_check", ] +[[package]] +name = "etcetera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +dependencies = [ + "cfg-if", + "home", + "windows-sys", +] + +[[package]] +name = "event-listener" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" + [[package]] name = "fastrand" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6999dc1837253364c2ebb0704ba97994bd874e8f195d665c50b7548f6ea92764" +[[package]] +name = "finl_unicode" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fcfdc7a0362c9f4444381a9e697c79d435fe65b52a37466fc2c1184cee9edc6" + [[package]] name = "fixedbitset" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" +[[package]] +name = "flume" +version = "0.10.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1657b4441c3403d9f7b3409e47575237dac27b1b5726df654a6ecbf92f0f7577" +dependencies = [ + "futures-core", + "futures-sink", + "pin-project", + "spin 0.9.8", +] + [[package]] name = "fnv" version = "1.0.7" @@ -496,6 +626,17 @@ dependencies = [ "futures-util", ] +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + [[package]] name = "futures-io" version = "0.3.28" @@ -627,6 +768,19 @@ name = "hashbrown" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" +dependencies = [ + "ahash", + "allocator-api2", +] + +[[package]] +name = "hashlink" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7" +dependencies = [ + "hashbrown 0.14.0", +] [[package]] name = "headers" @@ -658,6 +812,9 @@ name = "heck" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" +dependencies = [ + "unicode-segmentation", +] [[package]] name = "hermit-abi" @@ -671,6 +828,33 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hkdf" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791a029f6b9fc27657f6f188ec6e5e43f6911f6f878e0dc5501396e09809d437" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "home" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5444c27eef6923071f7ebcc33e3444508466a76f7a2b93da00ed6e19f30c1ddb" +dependencies = [ + "windows-sys", +] + [[package]] name = "http" version = "0.2.9" @@ -802,9 +986,9 @@ dependencies = [ [[package]] name = "itertools" -version = "0.10.5" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" dependencies = [ "either", ] @@ -843,7 +1027,7 @@ dependencies = [ "smartstring", "static_assertions", "url", - "uuid", + "uuid 0.8.2", ] [[package]] @@ -902,6 +1086,9 @@ name = "lazy_static" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +dependencies = [ + "spin 0.5.2", +] [[package]] name = "libc" @@ -909,6 +1096,23 @@ version = "0.2.147" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3" +[[package]] +name = "libm" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7012b1bbb0719e1097c47611d3898568c546d597c2e74d66f6087edd5233ff4" + +[[package]] +name = "libsqlite3-sys" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afc22eff61b133b115c6e8c74e818c628d6d5e7a502afea6f64dee076dd94326" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + [[package]] name = "linked-hash-map" version = "0.5.6" @@ -937,6 +1141,15 @@ version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" +[[package]] +name = "md-5" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6365506850d44bff6e2fbcb5176cf63650e48bd45ef2fe2665ae1570e0f4b9ca" +dependencies = [ + "digest", +] + [[package]] name = "memchr" version = "2.5.0" @@ -959,6 +1172,12 @@ dependencies = [ "unicase", ] +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.7.1" @@ -1003,6 +1222,54 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a" +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc84195820f291c7697304f3cbdadd1cb7199c0efc917ff5eafd71225c136151" +dependencies = [ + "byteorder", + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.5", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-integer" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +dependencies = [ + "autocfg", + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d03e6c028c5dc5cac6e2dec0efda81fc887605bb3d884578bb6d6bf7514e252" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.16" @@ -1010,6 +1277,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -1059,13 +1327,31 @@ version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93f00c865fe7cabf650081affecd3871070f26767e7b2070a3ffae14c654b447" dependencies = [ + "backtrace", "cfg-if", "libc", - "redox_syscall", + "petgraph", + "redox_syscall 0.3.5", "smallvec", + "thread-id", "windows-targets", ] +[[package]] +name = "paste" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.0" @@ -1114,6 +1400,33 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" + [[package]] name = "ppv-lite86" version = "0.2.17" @@ -1122,12 +1435,12 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "prettyplease" -version = "0.1.25" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c8646e95016a7a6c4adea95bafa8a16baab64b583356217f2c85db4a39d9a86" +checksum = "6c64d9ba0963cdcea2e1b2230fbae2bab30eb25a174be395c41e764bfb65dd62" dependencies = [ "proc-macro2", - "syn 1.0.109", + "syn 2.0.28", ] [[package]] @@ -1165,9 +1478,9 @@ dependencies = [ [[package]] name = "prost" -version = "0.11.9" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b82eaa1d779e9a4bc1c3217db8ffbeabaae1dca241bf70183242128d48681cd" +checksum = "f4fdd22f3b9c31b53c060df4a0613a1c7f062d4115a2b984dd15b1858f7e340d" dependencies = [ "bytes", "prost-derive", @@ -1175,44 +1488,44 @@ dependencies = [ [[package]] name = "prost-build" -version = "0.11.9" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "119533552c9a7ffacc21e099c24a0ac8bb19c2a2a3f363de84cd9b844feab270" +checksum = "8bdf592881d821b83d471f8af290226c8d51402259e9bb5be7f9f8bdebbb11ac" dependencies = [ "bytes", "heck", "itertools", - "lazy_static", "log", "multimap", + "once_cell", "petgraph", "prettyplease", "prost", "prost-types", "regex", - "syn 1.0.109", + "syn 2.0.28", "tempfile", "which", ] [[package]] name = "prost-derive" -version = "0.11.9" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5d2d8d10f3c6ded6da8b05b5fb3b8a5082514344d56c9f871412d29b4e075b4" +checksum = "265baba7fabd416cf5078179f7d2cbeca4ce7a9041111900675ea7c4cb8a4c32" dependencies = [ "anyhow", "itertools", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.28", ] [[package]] name = "prost-types" -version = "0.11.9" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "213622a1460818959ac1181aaeb2dc9c7f63df720db7d788b3e24eacd1983e13" +checksum = "e081b29f63d83a4bc75cfc9f3fe424f9156cf92d8a4f0c9407cce9a1b67327cf" dependencies = [ "prost", ] @@ -1308,6 +1621,15 @@ dependencies = [ "rand_core 0.5.1", ] +[[package]] +name = "redox_syscall" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +dependencies = [ + "bitflags 1.3.2", +] + [[package]] name = "redox_syscall" version = "0.3.5" @@ -1361,6 +1683,28 @@ dependencies = [ "winapi", ] +[[package]] +name = "rsa" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ab43bb47d23c1a631b4b680199a45255dce26fa9ab2fa902581f624ff13e6a8" +dependencies = [ + "byteorder", + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-iter", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rustc-demangle" version = "0.1.23" @@ -1568,6 +1912,17 @@ dependencies = [ "digest", ] +[[package]] +name = "sha2" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479fb9d862239e610720565ca91403019f2f00410f1864c5aa7479b950a76ed8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "signal-hook-registry" version = "1.4.1" @@ -1577,6 +1932,16 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e1788eed21689f9cf370582dfc467ef36ed9c707f073528ddafa8d83e3b8500" +dependencies = [ + "digest", + "rand_core 0.6.4", +] + [[package]] name = "skeptic" version = "0.13.7" @@ -1649,6 +2014,236 @@ name = "spin" version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spki" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1e996ef02c474957d681f1b05213dfb0abab947b446a62d37770b23500184a" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "sqlformat" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b7b278788e7be4d0d29c0f39497a0eef3fba6bbc8e70d8bf7fde46edeaa9e85" +dependencies = [ + "itertools", + "nom", + "unicode_categories", +] + +[[package]] +name = "sqlx" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e58421b6bc416714d5115a2ca953718f6c621a51b68e4f4922aea5a4391a721" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd4cef4251aabbae751a3710927945901ee1d97ee96d757f6880ebb9a79bfd53" +dependencies = [ + "ahash", + "atoi", + "byteorder", + "bytes", + "chrono", + "crc", + "crossbeam-queue", + "dotenvy", + "either", + "event-listener", + "futures-channel", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashlink", + "hex", + "indexmap 2.0.0", + "log", + "memchr", + "once_cell", + "paste", + "percent-encoding", + "rustls 0.21.6", + "rustls-pemfile", + "serde", + "serde_json", + "sha2", + "smallvec", + "sqlformat", + "thiserror", + "tokio", + "tokio-stream", + "tracing", + "url", + "uuid 1.4.1", + "webpki-roots", +] + +[[package]] +name = "sqlx-macros" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "208e3165167afd7f3881b16c1ef3f2af69fa75980897aac8874a0696516d12c2" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 1.0.109", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a4a8336d278c62231d87f24e8a7a74898156e34c1c18942857be2acb29c7dfc" +dependencies = [ + "dotenvy", + "either", + "heck", + "hex", + "once_cell", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2", + "sqlx-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn 1.0.109", + "tempfile", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ca69bf415b93b60b80dc8fda3cb4ef52b2336614d8da2de5456cc942a110482" +dependencies = [ + "atoi", + "base64 0.21.2", + "bitflags 2.4.0", + "byteorder", + "bytes", + "chrono", + "crc", + "digest", + "dotenvy", + "either", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "generic-array", + "hex", + "hkdf", + "hmac", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "percent-encoding", + "rand 0.8.5", + "rsa", + "serde", + "sha1", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "uuid 1.4.1", + "whoami", +] + +[[package]] +name = "sqlx-postgres" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0db2df1b8731c3651e204629dd55e52adbae0462fa1bdcbed56a2302c18181e" +dependencies = [ + "atoi", + "base64 0.21.2", + "bitflags 2.4.0", + "byteorder", + "chrono", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "hex", + "hkdf", + "hmac", + "home", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "rand 0.8.5", + "serde", + "serde_json", + "sha1", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "uuid 1.4.1", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4c21bf34c7cae5b283efb3ac1bcc7670df7561124dc2f8bdc0b59be40f79a2" +dependencies = [ + "atoi", + "chrono", + "flume", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "sqlx-core", + "tracing", + "url", + "uuid 1.4.1", +] [[package]] name = "static_assertions" @@ -1656,6 +2251,23 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "stringprep" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb41d74e231a107a1b4ee36bd1214b11285b77768d2e3824aedafa988fd36ee6" +dependencies = [ + "finl_unicode", + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "subtle" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" + [[package]] name = "syn" version = "1.0.109" @@ -1684,6 +2296,7 @@ version = "0.1.0" dependencies = [ "anyhow", "async-stream", + "async_once", "carboxyl", "chrono", "crossbeam-channel", @@ -1697,15 +2310,17 @@ dependencies = [ "juniper_warp", "lazy_static", "log", + "parking_lot", "prost", "prost-build", "prost-types", "serde", "serde_json", + "sqlx", "text-to-ascii-art", "tokio", "tokio-tungstenite 0.20.0", - "uuid", + "uuid 0.8.2", "warp", ] @@ -1717,7 +2332,7 @@ checksum = "dc02fddf48964c42031a0b3fe0428320ecf3a73c401040fc0096f97794310651" dependencies = [ "cfg-if", "fastrand", - "redox_syscall", + "redox_syscall 0.3.5", "rustix", "windows-sys", ] @@ -1757,6 +2372,17 @@ dependencies = [ "syn 2.0.28", ] +[[package]] +name = "thread-id" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79474f573561cdc4871a0de34a51c92f7f5a56039113fbb5b9c9f96bdb756669" +dependencies = [ + "libc", + "redox_syscall 0.2.16", + "winapi", +] + [[package]] name = "time" version = "0.1.45" @@ -1901,9 +2527,21 @@ dependencies = [ "cfg-if", "log", "pin-project-lite", + "tracing-attributes", "tracing-core", ] +[[package]] +name = "tracing-attributes" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f4f31f56159e98206da9efd823404b79b6ef3143b4a7ab76e67b1751b25a4ab" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.28", +] + [[package]] name = "tracing-core" version = "0.1.31" @@ -1994,6 +2632,18 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-segmentation" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" + +[[package]] +name = "unicode_categories" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" + [[package]] name = "unreachable" version = "1.0.0" @@ -2036,6 +2686,18 @@ dependencies = [ "serde", ] +[[package]] +name = "uuid" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79daa5ed5740825c40b389c5e50312b9c86df53fccd33f281df655642b43869d" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.4" @@ -2191,6 +2853,15 @@ dependencies = [ "untrusted", ] +[[package]] +name = "webpki-roots" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b291546d5d9d1eab74f069c77749f2cb8504a12caa20f0f2de93ddbf6f411888" +dependencies = [ + "rustls-webpki", +] + [[package]] name = "which" version = "4.4.0" @@ -2202,6 +2873,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "whoami" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22fc3756b8a9133049b26c7f61ab35416c130e8c09b660f5b3958b446f52cc50" + [[package]] name = "winapi" version = "0.3.9" @@ -2307,3 +2984,9 @@ name = "windows_x86_64_msvc" version = "0.48.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d419259aba16b663966e29e6d7c6ecfa0bb8425818bb96f6f1f3c3eb71a6e7b9" + +[[package]] +name = "zeroize" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a0956f1ba7c7909bfb66c2e9e4124ab6f6482560f6628b5aaeba39207c9aad9" diff --git a/Cargo.toml b/Cargo.toml index 0a3df3a..859707c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ authors = ["sargon64 ", "skkeye <[email protected]>"] # actix-web-actors = "4.2.0" anyhow = "1.0.74" async-stream = "0.3.5" +async_once = "0.2.6" carboxyl = "0.2.2" chrono = "0.4.26" crossbeam-channel = "0.5.8" @@ -26,10 +27,11 @@ juniper_subscriptions = "0.16.0" juniper_warp = { version = "0.7.0", features = ["subscriptions"] } lazy_static = "1.4.0" log = "0.4.20" -prost = "0.11.9" -prost-types = "0.11.9" +prost = "0.12.1" +prost-types = "0.12.1" serde = { version = "1.0.183", features = ["derive"] } serde_json = "1.0.105" +sqlx = { version = "0.7.1", features = ["uuid", "macros", "chrono", "runtime-tokio-rustls", "postgres"] } text-to-ascii-art = "0.1.9" tokio = { version = "1.31.0", features = ["full"] } tokio-tungstenite = { version = "0.20.0", features = [ @@ -37,6 +39,7 @@ tokio-tungstenite = { version = "0.20.0", features = [ ] } uuid = { version = "0.8", features = ["serde", "v4"] } warp = { version = "0.3.5", features = ["tokio-rustls"] } +parking_lot = {version = "0.12.1", features = ["deadlock_detection"]} [build-dependencies] -prost-build = "0.11.9" +prost-build = "0.12.1" diff --git a/build.rs b/build.rs index d0b9b34..b9b59ed 100644 --- a/build.rs +++ b/build.rs @@ -1,7 +1,14 @@ use std::io::Result; fn main() -> Result<()> { - prost_build::compile_protos(&["TournamentAssistantProtos/discord.proto", "TournamentAssistantProtos/models.proto", "TournamentAssistantProtos/packets.proto"], &["TournamentAssistantProtos/"])?; + prost_build::compile_protos( + &[ + "TournamentAssistantProtos/discord.proto", + "TournamentAssistantProtos/models.proto", + "TournamentAssistantProtos/packets.proto", + ], + &["TournamentAssistantProtos/"], + )?; Ok(()) -} \ No newline at end of file +} diff --git a/src/connection.rs b/src/connection.rs index e540206..1123909 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -1,13 +1,14 @@ -use std::sync::Arc; +use futures_util::{ + stream::{SplitSink, SplitStream}, + SinkExt, Stream, StreamExt, +}; -use futures_util::{stream::{SplitStream, SplitSink}, StreamExt, SinkExt, AsyncRead, Stream}; -use log::info; use prost::Message as _; use tokio::net::TcpStream; -use tokio_tungstenite::{WebSocketStream, MaybeTlsStream, tungstenite::Message}; +use tokio_tungstenite::{tungstenite::Message, MaybeTlsStream, WebSocketStream}; use uuid::Uuid; -use crate::{proto::{models, packet}, packets::TAState}; +use crate::proto::{models, packet}; #[derive(Debug)] pub struct TAConnection { @@ -17,7 +18,10 @@ pub struct TAConnection { } impl TAConnection { - pub async fn connect, U: Into>(uri: T, name: U) -> anyhow::Result { + pub async fn connect, U: Into>( + uri: T, + name: U, + ) -> anyhow::Result { let uri = uri.into(); let name = name.into(); let (ws_stream, _) = match tokio_tungstenite::connect_async(uri).await { @@ -25,66 +29,70 @@ impl TAConnection { Err(_) => { log::error!("Failed to connect to server. Are you sure you're connecting to the overlay websocket?"); return Err(anyhow::anyhow!("Failed to connect to server. Are you sure you're connecting to the overlay websocket?")); - }, + } }; let (mut ws_tx, ws_rx) = ws_stream.split(); - let ws_user = models::User { - guid: uuid::Uuid::new_v4().to_string(), + let ws_user = models::User { + guid: Uuid::new_v4().to_string(), client_type: models::user::ClientTypes::WebsocketConnection.into(), - name, + name, ..Default::default() }; let connect = packet::Packet { - id: uuid::Uuid::new_v4().to_string(), + id: Uuid::new_v4().to_string(), from: "".to_string(), packet: Some(packet::packet::Packet::Request(packet::Request { r#type: Some(packet::request::Type::Connect(packet::request::Connect { user: Some(ws_user.clone()), password: "".to_string(), - client_version: 74 - })) - })) + client_version: 74, + })), + })), }; - ws_tx.send(Message::Binary(connect.encode_to_vec())).await.unwrap(); + ws_tx + .send(Message::Binary(connect.encode_to_vec())) + .await + .unwrap(); Ok(TAConnection { ws_rx, ws_tx, ws_user, }) - } + } pub async fn send(&mut self, packet: packet::Packet) -> anyhow::Result<()> { - self.ws_tx.send(Message::Binary(packet.encode_to_vec())).await?; + self.ws_tx + .send(Message::Binary(packet.encode_to_vec())) + .await?; Ok(()) } pub async fn close(self) { drop(self); - } + } } impl Stream for TAConnection { type Item = anyhow::Result; - fn poll_next(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll> { + fn poll_next( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { let p = self.ws_rx.poll_next_unpin(cx); match p { std::task::Poll::Ready(Some(Ok(msg))) => { let packet = packet::Packet::decode(msg.into_data().as_slice())?; std::task::Poll::Ready(Some(Ok(packet))) - }, + } std::task::Poll::Ready(Some(Err(e))) => { std::task::Poll::Ready(Some(Err(anyhow::anyhow!(e)))) - }, - std::task::Poll::Ready(None) => { - std::task::Poll::Ready(None) - }, - std::task::Poll::Pending => { - std::task::Poll::Pending } + std::task::Poll::Ready(None) => std::task::Poll::Ready(None), + std::task::Poll::Pending => std::task::Poll::Pending, } } -} \ No newline at end of file +} diff --git a/src/gql.rs b/src/gql.rs index d19acf8..01d063b 100644 --- a/src/gql.rs +++ b/src/gql.rs @@ -1,17 +1,16 @@ use std::pin::Pin; use futures_util::Stream; -use juniper::{GraphQLObject, RootNode, EmptyMutation, EmptySubscription, FieldError}; -use uuid::Uuid; +use juniper::{EmptyMutation, FieldError, RootNode}; -use crate::{TA_STATE, structs::GQLTAState, TA_UPDATE_SINK, TAUpdates}; +use crate::{structs::GQLTAState, TAUpdates, TA_STATE, TA_UPDATE_SINK}; pub struct Query; #[juniper::graphql_object(context = Context)] impl Query { - async fn state() -> GQLTAState { - (*TA_STATE.read().await).into_gql().await + async fn state() -> GQLTAState { + (*TA_STATE.read().await).as_gql().await } } @@ -21,20 +20,21 @@ type GQLTAStateStream = Pin #[juniper::graphql_subscription(context = Context)] impl Subscription { - async fn state() -> GQLTAStateStream { + async fn state() -> GQLTAStateStream { let mut stream = TA_UPDATE_SINK.stream().events(); // magic macro :) - async_stream::stream! { + async_stream::stream! { while let Some(update) = stream.next() { match update { TAUpdates::NewState => { - yield Ok((*TA_STATE.read().await).into_gql().await); + yield Ok((*TA_STATE.read().await).as_gql().await); }, _ => {} } } - }.boxed() + } + .boxed() } } @@ -46,4 +46,4 @@ pub type Schema = RootNode<'static, Query, EmptyMutation, Subscription> pub fn create_schema() -> Schema { Schema::new(Query {}, EmptyMutation::new(), Subscription {}) -} \ No newline at end of file +} diff --git a/src/main.rs b/src/main.rs index c1e501d..c2825d1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,12 +1,17 @@ -use std::{convert::Infallible, sync::Arc, time::Duration}; +use async_once::AsyncOnce; +use std::{str::FromStr, sync::Arc, time::Duration}; +// use parking_lot::RwLock; // use actix_cors::Cors; // use actix_web::{get, middleware::Logger, App, HttpServer, Responder, HttpResponse, Error, web::{self, Data}, http::header, HttpRequest}; use carboxyl::Sink; use futures_util::{FutureExt, StreamExt}; -use gql::Schema; + use juniper_graphql_ws::ConnectionConfig; use juniper_warp::subscriptions::serve_graphql_ws; +use log::LevelFilter; +use sqlx::migrate::Migrator; +use sqlx::ConnectOptions; use text_to_ascii_art::convert; use tokio::sync::RwLock; use warp::Filter; @@ -46,11 +51,23 @@ lazy_static::lazy_static! { RwLock::new(packets::TAState::new()) }; + pub static ref TA_CON: RwLock> = RwLock::new(None); + pub static ref TA_UPDATE_SINK: Sink = { Sink::new() }; + + pub static ref DB_POOL: AsyncOnce> = AsyncOnce::new(async { + sqlx::postgres::PgPoolOptions::new() + .max_connections(5) + .connect_with(sqlx::postgres::PgConnectOptions::from_str(&std::env::var("DATABASE_URL").unwrap()).unwrap().log_statements(LevelFilter::Trace).log_slow_statements(LevelFilter::Info, Duration::from_secs(1))) + .await + .unwrap() + }); } +static MIGRATION: Migrator = sqlx::migrate!(); + #[tokio::main(flavor = "current_thread")] async fn main() -> anyhow::Result<()> { dotenv::dotenv().ok(); @@ -63,6 +80,11 @@ async fn main() -> anyhow::Result<()> { &env!("CARGO_PKG_AUTHORS").replace(":", " & ") ); + MIGRATION + .run(&*DB_POOL.get().await) + .await + .expect("Failed to run migrations"); + std::thread::spawn(|| { tokio::runtime::Builder::new_multi_thread() .enable_all() @@ -70,7 +92,14 @@ async fn main() -> anyhow::Result<()> { .unwrap() .block_on(async { log::info!("Connecting to Server..."); - + *TA_CON.write().await = Some( + connection::TAConnection::connect( + std::env::var("TA_WS_URI").unwrap(), + "TA-Relay-TX", + ) + .await + .unwrap(), + ); let mut ta_con = connection::TAConnection::connect( std::env::var("TA_WS_URI").unwrap(), "TA-Relay-RX", @@ -88,7 +117,7 @@ async fn main() -> anyhow::Result<()> { }; tokio::spawn(async move { - packets::route_packet(&mut *TA_STATE.write().await,msg) + packets::route_packet(&mut *TA_STATE.write().await, msg) .await .unwrap(); diff --git a/src/packets.rs b/src/packets.rs index 4fb72c5..6b10d80 100644 --- a/src/packets.rs +++ b/src/packets.rs @@ -2,13 +2,10 @@ use std::collections::HashMap; use uuid::Uuid; -use crate::{ - proto::{ - models, - packet::{self, event}, - }, connection::TAConnection, - // TA_CON, -}; +use crate::{proto::{ + models, + packet::{self, event}, +}, TA_CON}; #[derive(Debug, Default, Clone)] pub struct TAState { @@ -17,7 +14,7 @@ pub struct TAState { pub players: Vec, pub matches: Vec, pub servers: Vec, - pub rts: HashMap, // perhaps + pub rts: HashMap, // perhaps } impl TAState { @@ -39,9 +36,25 @@ impl TAState { self.coordinators.push(user); } models::user::ClientTypes::Player => { - log::info!("Player added: {}", user.name); - self.players.push(user) + log::info!("Player added: {}", &user.name); + match sqlx::query!( + "SELECT * FROM users WHERE steam_id = $1", + &user.user_id + ) + .fetch_optional(&*crate::DB_POOL.get().await) + .await + .unwrap() + { + Some(_) => {} + None => { + sqlx::query!("INSERT INTO users (steam_id, name) VALUES ($1, $2)", &user.user_id, &user.name) + .execute(&*crate::DB_POOL.get().await) + .await.unwrap(); + } + } + self.players.push(user); } + _ => {} } } @@ -103,24 +116,20 @@ impl TAState { Some(mut r#match) => { log::info!("Match created: {}", r#match.guid); //add the overlay to the match's associated users. - r#match - .associated_users - .extend(self.server_users.iter().filter(|f| !f.name.contains("TX")).map(|u| u.guid.clone())); + r#match.associated_users.extend( + self.server_users + .iter() + .map(|u| u.guid.clone()), + ); + log::warn!("users: {:#?}", r#match.associated_users); self.matches.push(r#match.clone()); - let mut con = TAConnection::connect( - std::env::var("TA_WS_URI").unwrap(), - "TA-Relay-TX", - ) - .await - .unwrap(); - - con - // .write() - // .await - // .as_mut() - // .unwrap() + TA_CON + .write() + .await + .as_mut() + .unwrap() .send(packet::Packet { id: Uuid::new_v4().to_string(), from: "".to_string(), @@ -137,8 +146,6 @@ impl TAState { )), }) .await?; - - con.close().await; } None => { log::warn!("Received MatchCreatedEvent with no match"); @@ -263,18 +270,49 @@ impl TAState { match push.data { Some(data) => match data { packet::push::Data::RealtimeScore(s) => { - log::info!("Received RealtimeScore of {} for {}", &s.score, &s.user_guid); + log::info!( + "Received RealtimeScore of {} for {}", + &s.score, + &s.user_guid + ); let user = self.players.iter().find(|u| u.guid == s.user_guid).unwrap(); - let _ = tokio::fs::create_dir_all(format!("./data/{}", &user.name)).await; - let _ = tokio::fs::write( - format!( - "./data/{}/{}.dat", - user.name, - chrono::Utc::now().timestamp_millis() - ), - format!("{:#?}", &s), + // + let id = match sqlx::query!( + "SELECT id FROM users WHERE steam_id = $1", + user.user_id ) - .await; + .fetch_optional(&*crate::DB_POOL.get().await) + .await + .unwrap() + { + None => { + sqlx::query!( + "INSERT INTO users (steam_id, name) VALUES ($1, $2)", + user.user_id, + user.name + ) + .execute(&*crate::DB_POOL.get().await) + .await + .unwrap(); + sqlx::query!("SELECT id FROM users WHERE steam_id = $1", user.user_id) + .fetch_one(&*crate::DB_POOL.get().await) + .await + .unwrap() + .id + } + Some(r) => r.id, + }; + let right_hand = s.right_hand.clone().unwrap_or_default(); + let left_hand = s.left_hand.clone().unwrap_or_default(); + + sqlx::query!("INSERT INTO real_time_score\ + (owner, score, score_with_modifiers, max_score, max_score_with_modifiers,\ + combo, player_health, accuracy, song_position, notes_missed, bad_cuts,\ + bomb_hits, wall_hits, max_combo, left_hand_hits, left_hand_misses,\ + left_hand_bad_cut, right_hand_hits, right_hand_misses, right_hand_bad_cut)\ + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)", id, s.score, s.score_with_modifiers, s.max_score, s.max_score_with_modifiers, s.combo, s.player_health as f64, s.accuracy as f64, s.song_position as f64, s.notes_missed, s.bad_cuts, s.bomb_hits, s.wall_hits, s.max_combo, left_hand.hit, left_hand.miss, left_hand.bad_cut, right_hand.hit, right_hand.miss, right_hand.bad_cut) + .execute(&*crate::DB_POOL.get().await) + .await.unwrap(); self.rts.insert(s.user_guid.clone(), s); } @@ -297,7 +335,8 @@ impl TAState { } pub async fn route_packet(state: &mut TAState, packet: packet::Packet) -> anyhow::Result<()> { - log::debug!("Received packet: {:?}", packet.packet); + log::debug!("Received packet: {:#?}", packet.packet); + log::debug!("s_user {:#?}", state.server_users); match packet.packet { Some(packet::packet::Packet::Event(p)) => { state.process_event(p).await?; diff --git a/src/structs.rs b/src/structs.rs index 97114ca..21e93d9 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -6,6 +6,7 @@ use crate::packets::TAState; pub struct User { id: Uuid, name: String, + steam_id: String, } #[derive(juniper::GraphQLObject)] @@ -60,7 +61,7 @@ pub struct GQLTAState { } impl TAState { - pub async fn into_gql(&self) -> GQLTAState { + pub async fn as_gql(&self) -> GQLTAState { GQLTAState { players: self .players @@ -68,6 +69,7 @@ impl TAState { .map(|p| User { id: Uuid::parse_str(&p.guid).unwrap(), name: p.name.clone(), + steam_id: p.user_id.clone(), }) .collect(), coordinators: self @@ -76,6 +78,7 @@ impl TAState { .map(|p| User { id: Uuid::parse_str(&p.guid).unwrap(), name: p.name.clone(), + steam_id: p.user_id.clone(), }) .collect(), matches: self @@ -87,13 +90,11 @@ impl TAState { .associated_users .iter() .filter_map(|u| { - self.players - .iter() - .find(|p| p.guid == *u) - .map(|p| User { - id: Uuid::parse_str(&p.guid).unwrap(), - name: p.name.clone(), - }) + self.players.iter().find(|p| p.guid == *u).map(|p| User { + id: Uuid::parse_str(&p.guid).unwrap(), + name: p.name.clone(), + steam_id: p.user_id.clone(), + }) }) .collect(), coordinators: m @@ -106,12 +107,13 @@ impl TAState { .map(|c| User { id: Uuid::parse_str(&c.guid).unwrap(), name: c.name.clone(), + steam_id: c.user_id.clone(), }) }) .collect(), current_map: { let level = m.selected_level.as_ref(); - if let Some(level) = level { + if let Some(level) = level { Some(Map { id: level.level_id.clone(), name: level.name.clone(), From 0f0fe217df07c95953535680a1cef3e3e0f4d3d2 Mon Sep 17 00:00:00 2001 From: sargon64 Date: Sun, 17 Sep 2023 00:52:03 -0700 Subject: [PATCH 4/4] fix: add migration --- migrations/20230917041936_init.sql | 32 ++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 migrations/20230917041936_init.sql diff --git a/migrations/20230917041936_init.sql b/migrations/20230917041936_init.sql new file mode 100644 index 0000000..a7de22c --- /dev/null +++ b/migrations/20230917041936_init.sql @@ -0,0 +1,32 @@ +-- Add migration script here +create table users ( + id uuid primary key not null default gen_random_uuid(), + steam_id text not null, + name text not null +); + +create table real_time_score( + owner uuid not null references users(id), + time timestamptz not null default now(), + score int not null, + score_with_modifiers int not null, + max_score int not null, + max_score_with_modifiers int not null, + combo int not null, + player_health float not null, + accuracy float not null, + song_position float not null, + notes_missed int not null, + bad_cuts int not null, + bomb_hits int not null, + wall_hits int not null, + max_combo int not null, + left_hand_hits int not null, + left_hand_misses int not null, + left_hand_bad_cut int not null, + right_hand_hits int not null, + right_hand_misses int not null, + right_hand_bad_cut int not null +); + +select create_hypertable('real_time_score', 'time');