Add network actor and auth gui flow
Browse files at this commit12db4fbc2b5fc8387d2532201f1a20b141ed9a0dParent: eda18f3- feat
- add network actor and auth gui flow
9 changed files +681 -25
- configs/client_config.toml +3 -0
- crates/client/src/gui.rs +61 -2
- crates/client/src/gui/chat.rs +2 -6
- crates/client/src/gui/login.rs +26 -14
- crates/client/src/gui/register.rs +96 -0
- crates/client/src/lib.rs +30 -0
- crates/client/src/main.rs +6 -3
- crates/client/src/network.rs +228 -0
- crates/client/src/request.rs +229 -0
configs/client_config.tomladded+3 -0
| @@ -0,0 +1,3 @@ | |||
| 1 | +[client_config] | ||
| 2 | +server_address = "127.0.0.1:2026" | ||
| 3 | +server_name = "localhost" | ||
crates/client/src/gui.rsmodified+61 -2
| @@ -1,31 +1,76 @@ | |||
| 1 | +use common::user::User; | ||
| 1 | use gpui::{IntoElement, ParentElement, Render, Styled, div, rgb}; | 2 | use gpui::{IntoElement, ParentElement, Render, Styled, div, rgb}; |
| 2 | use gpui_component::Root; | 3 | use gpui_component::Root; |
| 4 | +use tokio::sync::mpsc; | ||
| 3 | 5 | ||
| 4 | -use crate::gui::{chat::Chat, login::Login}; | 6 | +use crate::{ |
| 7 | + gui::{chat::Chat, login::Login, register::Register}, | ||
| 8 | + network::{NetworkEvent, NetworkHandle}, | ||
| 9 | +}; | ||
| 5 | mod chat; | 10 | mod chat; |
| 6 | mod login; | 11 | mod login; |
| 12 | +mod register; | ||
| 7 | 13 | ||
| 8 | #[derive(Debug, PartialEq, Eq)] | 14 | #[derive(Debug, PartialEq, Eq)] |
| 9 | enum Route { | 15 | enum Route { |
| 16 | + Register, | ||
| 10 | Login, | 17 | Login, |
| 11 | Chat, | 18 | Chat, |
| 12 | } | 19 | } |
| 13 | 20 | ||
| 14 | pub struct Yumush { | 21 | pub struct Yumush { |
| 22 | + user: Option<User>, | ||
| 15 | current_route: Route, | 23 | current_route: Route, |
| 24 | + register: Register, | ||
| 16 | login: Login, | 25 | login: Login, |
| 17 | chat: Chat, | 26 | chat: Chat, |
| 27 | + network: NetworkHandle, | ||
| 28 | + connected: bool, | ||
| 18 | } | 29 | } |
| 19 | 30 | ||
| 20 | impl Yumush { | 31 | impl Yumush { |
| 21 | - pub fn new(window: &mut gpui::Window, cx: &mut gpui::Context<Self>) -> Self { | 32 | + pub fn new( |
| 33 | + network: NetworkHandle, | ||
| 34 | + mut network_event_receiver: mpsc::Receiver<NetworkEvent>, | ||
| 35 | + window: &mut gpui::Window, | ||
| 36 | + cx: &mut gpui::Context<Self>, | ||
| 37 | + ) -> Self { | ||
| 38 | + cx.spawn(async move |this, cx| { | ||
| 39 | + while let Some(event) = network_event_receiver.recv().await { | ||
| 40 | + let updated = this.update(cx, |yumush, cx| { | ||
| 41 | + yumush.handle_network_event(event, cx); | ||
| 42 | + }); | ||
| 43 | + | ||
| 44 | + if updated.is_err() { | ||
| 45 | + break; | ||
| 46 | + } | ||
| 47 | + } | ||
| 48 | + }) | ||
| 49 | + .detach(); | ||
| 50 | + | ||
| 22 | Self { | 51 | Self { |
| 52 | + user: None, | ||
| 23 | current_route: Route::Login, | 53 | current_route: Route::Login, |
| 54 | + register: Register::new(window, cx), | ||
| 24 | login: Login::new(window, cx), | 55 | login: Login::new(window, cx), |
| 25 | chat: Chat::new(window, cx), | 56 | chat: Chat::new(window, cx), |
| 57 | + network, | ||
| 58 | + connected: false, | ||
| 26 | } | 59 | } |
| 27 | } | 60 | } |
| 28 | 61 | ||
| 62 | + fn set_user(&mut self, user: User) { | ||
| 63 | + self.user = Some(user); | ||
| 64 | + } | ||
| 65 | + | ||
| 66 | + fn reset_user(&mut self) { | ||
| 67 | + self.user = None; | ||
| 68 | + } | ||
| 69 | + | ||
| 70 | + fn get_username(&self) -> Option<&str> { | ||
| 71 | + self.user.as_ref().map(|user| user.get_username()) | ||
| 72 | + } | ||
| 73 | + | ||
| 29 | fn change_page( | 74 | fn change_page( |
| 30 | &mut self, | 75 | &mut self, |
| 31 | new_route: Route, | 76 | new_route: Route, |
| @@ -35,10 +80,23 @@ impl Yumush { | |||
| 35 | self.current_route = new_route; | 80 | self.current_route = new_route; |
| 36 | 81 | ||
| 37 | match self.current_route { | 82 | match self.current_route { |
| 83 | + Route::Register => self.register.focus(window, cx), | ||
| 38 | Route::Login => self.login.focus(window, cx), | 84 | Route::Login => self.login.focus(window, cx), |
| 39 | Route::Chat => self.chat.focus(window, cx), | 85 | Route::Chat => self.chat.focus(window, cx), |
| 40 | } | 86 | } |
| 41 | } | 87 | } |
| 88 | + | ||
| 89 | + fn handle_network_event(&mut self, event: NetworkEvent, cx: &mut gpui::Context<Self>) { | ||
| 90 | + match event { | ||
| 91 | + NetworkEvent::Connected => self.connected = true, | ||
| 92 | + NetworkEvent::ConnectionFailed(_) | NetworkEvent::Disconnected(_) => { | ||
| 93 | + self.connected = false; | ||
| 94 | + self.reset_user(); | ||
| 95 | + } | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + cx.notify(); | ||
| 99 | + } | ||
| 42 | } | 100 | } |
| 43 | 101 | ||
| 44 | impl Render for Yumush { | 102 | impl Render for Yumush { |
| @@ -60,6 +118,7 @@ impl Render for Yumush { | |||
| 60 | .bg(rgb(0x1e1e1e)) | 118 | .bg(rgb(0x1e1e1e)) |
| 61 | .text_color(rgb(0xffffff)) | 119 | .text_color(rgb(0xffffff)) |
| 62 | .child(match self.current_route { | 120 | .child(match self.current_route { |
| 121 | + Route::Register => self.register_page(cx).into_any_element(), | ||
| 63 | Route::Login => self.login_page(cx).into_any_element(), | 122 | Route::Login => self.login_page(cx).into_any_element(), |
| 64 | Route::Chat => self.chat_page().into_any_element(), | 123 | Route::Chat => self.chat_page().into_any_element(), |
| 65 | }), | 124 | }), |
crates/client/src/gui/chat.rsmodified+2 -6
| @@ -3,11 +3,7 @@ use gpui::{ | |||
| 3 | AppContext, Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, | 3 | AppContext, Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, |
| 4 | StatefulInteractiveElement, Styled, Window, div, rgb, | 4 | StatefulInteractiveElement, Styled, Window, div, rgb, |
| 5 | }; | 5 | }; |
| 6 | -use gpui_component::{ | 6 | +use gpui_component::input::{Input, InputEvent, InputState}; |
| 7 | - WindowExt, | ||
| 8 | - input::{Input, InputEvent, InputState}, | ||
| 9 | - notification::Notification, | ||
| 10 | -}; | ||
| 11 | 7 | ||
| 12 | use crate::gui::Yumush; | 8 | use crate::gui::Yumush; |
| 13 | 9 | ||
| @@ -35,7 +31,7 @@ impl Chat { | |||
| 35 | let message = Message::new( | 31 | let message = Message::new( |
| 36 | "1", | 32 | "1", |
| 37 | this.chat.community.get_community_id(), | 33 | this.chat.community.get_community_id(), |
| 38 | - this.login.get_user().unwrap().get_username(), | 34 | + this.get_username().unwrap(), |
| 39 | &input.read(cx).text().to_string(), | 35 | &input.read(cx).text().to_string(), |
| 40 | ); | 36 | ); |
| 41 | 37 | ||
crates/client/src/gui/login.rsmodified+26 -14
| @@ -1,4 +1,3 @@ | |||
| 1 | -use common::user::User; | ||
| 2 | use gpui::{AppContext, Context, Entity, IntoElement, ParentElement, Styled, Window, div}; | 1 | use gpui::{AppContext, Context, Entity, IntoElement, ParentElement, Styled, Window, div}; |
| 3 | use gpui_component::{ | 2 | use gpui_component::{ |
| 4 | WindowExt, | 3 | WindowExt, |
| @@ -11,7 +10,6 @@ use crate::gui::{Route, Yumush}; | |||
| 11 | 10 | ||
| 12 | pub struct Login { | 11 | pub struct Login { |
| 13 | username_input: Entity<InputState>, | 12 | username_input: Entity<InputState>, |
| 14 | - user: Option<User>, | ||
| 15 | } | 13 | } |
| 16 | 14 | ||
| 17 | impl Login { | 15 | impl Login { |
| @@ -31,14 +29,7 @@ impl Login { | |||
| 31 | }) | 29 | }) |
| 32 | .detach(); | 30 | .detach(); |
| 33 | 31 | ||
| 34 | - Self { | 32 | + Self { username_input } |
| 35 | - username_input, | ||
| 36 | - user: None, | ||
| 37 | - } | ||
| 38 | - } | ||
| 39 | - | ||
| 40 | - pub fn get_user(&self) -> Option<User> { | ||
| 41 | - self.user.clone() | ||
| 42 | } | 33 | } |
| 43 | 34 | ||
| 44 | pub fn focus(&self, window: &mut Window, cx: &mut Context<'_, Yumush>) { | 35 | pub fn focus(&self, window: &mut Window, cx: &mut Context<'_, Yumush>) { |
| @@ -54,12 +45,23 @@ fn login_action( | |||
| 54 | window: &mut Window, | 45 | window: &mut Window, |
| 55 | cx: &mut Context<'_, Yumush>, | 46 | cx: &mut Context<'_, Yumush>, |
| 56 | ) { | 47 | ) { |
| 57 | - let id = "A".to_string(); | ||
| 58 | let username = input.read(cx).text().to_string(); | 48 | let username = input.read(cx).text().to_string(); |
| 49 | + let network = this.network.clone(); | ||
| 50 | + | ||
| 51 | + cx.spawn_in(window, async move |this, cx| { | ||
| 52 | + let result = network.authenticate(&username).await; | ||
| 59 | 53 | ||
| 60 | - let user = User::new(&id, &username); | 54 | + let _ = this.update_in(cx, |yumush, window, cx| match result { |
| 61 | - this.login.user = Some(user); | 55 | + Ok(user) => { |
| 62 | - this.change_page(Route::Chat, window, cx); | 56 | + yumush.set_user(user); |
| 57 | + yumush.change_page(Route::Chat, window, cx); | ||
| 58 | + } | ||
| 59 | + Err(error_value) => { | ||
| 60 | + window.push_notification(Notification::error(error_value.to_string()), cx); | ||
| 61 | + } | ||
| 62 | + }); | ||
| 63 | + }) | ||
| 64 | + .detach(); | ||
| 63 | } | 65 | } |
| 64 | 66 | ||
| 65 | impl Yumush { | 67 | impl Yumush { |
| @@ -74,11 +76,21 @@ impl Yumush { | |||
| 74 | }) | 76 | }) |
| 75 | .label("Login"); | 77 | .label("Login"); |
| 76 | 78 | ||
| 79 | + let entity = cx.entity(); | ||
| 80 | + let register_page_switch_button = Button::new("register_page_switch_button") | ||
| 81 | + .on_click(move |_, window, cx| { | ||
| 82 | + entity.update(cx, |this, cx| { | ||
| 83 | + this.change_page(Route::Register, window, cx); | ||
| 84 | + }) | ||
| 85 | + }) | ||
| 86 | + .label("Go to Register Page"); | ||
| 87 | + | ||
| 77 | div() | 88 | div() |
| 78 | .w_1_5() | 89 | .w_1_5() |
| 79 | .child("Username") | 90 | .child("Username") |
| 80 | .child(Input::new(&self.login.username_input)) | 91 | .child(Input::new(&self.login.username_input)) |
| 81 | .child(login_button) | 92 | .child(login_button) |
| 93 | + .child(register_page_switch_button) | ||
| 82 | .into_element() | 94 | .into_element() |
| 83 | } | 95 | } |
| 84 | } | 96 | } |
crates/client/src/gui/register.rsadded+96 -0
| @@ -0,0 +1,96 @@ | |||
| 1 | +use gpui::{AppContext, Context, Entity, IntoElement, ParentElement, Styled, Window, div}; | ||
| 2 | +use gpui_component::{ | ||
| 3 | + WindowExt, | ||
| 4 | + button::Button, | ||
| 5 | + input::{Input, InputEvent, InputState}, | ||
| 6 | + notification::Notification, | ||
| 7 | +}; | ||
| 8 | + | ||
| 9 | +use crate::gui::{Route, Yumush}; | ||
| 10 | + | ||
| 11 | +pub struct Register { | ||
| 12 | + username_input: Entity<InputState>, | ||
| 13 | +} | ||
| 14 | + | ||
| 15 | +impl Register { | ||
| 16 | + pub fn new(window: &mut Window, cx: &mut Context<Yumush>) -> Self { | ||
| 17 | + let username_input = cx.new(|cx| { | ||
| 18 | + let mut input_state = InputState::new(window, cx); | ||
| 19 | + input_state.set_placeholder("Username...", window, cx); | ||
| 20 | + input_state.focus(window, cx); | ||
| 21 | + | ||
| 22 | + input_state | ||
| 23 | + }); | ||
| 24 | + | ||
| 25 | + cx.subscribe_in(&username_input, window, |this, input, event, window, cx| { | ||
| 26 | + if matches!(event, InputEvent::PressEnter { .. }) { | ||
| 27 | + register_action(this, input, window, cx); | ||
| 28 | + } | ||
| 29 | + }) | ||
| 30 | + .detach(); | ||
| 31 | + | ||
| 32 | + Self { username_input } | ||
| 33 | + } | ||
| 34 | + | ||
| 35 | + pub fn focus(&self, window: &mut Window, cx: &mut Context<'_, Yumush>) { | ||
| 36 | + self.username_input.update(cx, |input, cx| { | ||
| 37 | + input.focus(window, cx); | ||
| 38 | + }); | ||
| 39 | + } | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +fn register_action( | ||
| 43 | + this: &mut Yumush, | ||
| 44 | + input: &Entity<InputState>, | ||
| 45 | + window: &mut Window, | ||
| 46 | + cx: &mut Context<'_, Yumush>, | ||
| 47 | +) { | ||
| 48 | + let username = input.read(cx).text().to_string(); | ||
| 49 | + let network = this.network.clone(); | ||
| 50 | + | ||
| 51 | + cx.spawn_in(window, async move |this, cx| { | ||
| 52 | + let result = network.create_user(&username).await; | ||
| 53 | + | ||
| 54 | + let _ = this.update_in(cx, |yumush, window, cx| match result { | ||
| 55 | + Ok(user) => { | ||
| 56 | + yumush.set_user(user); | ||
| 57 | + yumush.change_page(Route::Chat, window, cx); | ||
| 58 | + } | ||
| 59 | + Err(error_value) => { | ||
| 60 | + window.push_notification(Notification::error(error_value.to_string()), cx); | ||
| 61 | + } | ||
| 62 | + }); | ||
| 63 | + }) | ||
| 64 | + .detach(); | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +impl Yumush { | ||
| 68 | + pub fn register_page(&mut self, cx: &mut Context<Self>) -> impl IntoElement { | ||
| 69 | + let entity = cx.entity(); | ||
| 70 | + let username_input = self.register.username_input.clone(); | ||
| 71 | + let register_button = Button::new("register_button") | ||
| 72 | + .on_click(move |_, window, cx| { | ||
| 73 | + entity.update(cx, |this, cx| { | ||
| 74 | + register_action(this, &username_input, window, cx); | ||
| 75 | + }) | ||
| 76 | + }) | ||
| 77 | + .label("Register"); | ||
| 78 | + | ||
| 79 | + let entity = cx.entity(); | ||
| 80 | + let login_page_switch_button = Button::new("login_page_switch_button") | ||
| 81 | + .on_click(move |_, window, cx| { | ||
| 82 | + entity.update(cx, |this, cx| { | ||
| 83 | + this.change_page(Route::Login, window, cx); | ||
| 84 | + }) | ||
| 85 | + }) | ||
| 86 | + .label("Go to Login Page"); | ||
| 87 | + | ||
| 88 | + div() | ||
| 89 | + .w_1_5() | ||
| 90 | + .child("Username") | ||
| 91 | + .child(Input::new(&self.register.username_input)) | ||
| 92 | + .child(register_button) | ||
| 93 | + .child(login_page_switch_button) | ||
| 94 | + .into_element() | ||
| 95 | + } | ||
| 96 | +} | ||
crates/client/src/lib.rsmodified+30 -0
| @@ -1 +1,31 @@ | |||
| 1 | +use common::utils::TOML; | ||
| 2 | + | ||
| 1 | pub mod gui; | 3 | pub mod gui; |
| 4 | +pub mod network; | ||
| 5 | +mod request; | ||
| 6 | + | ||
| 7 | +pub const NAME: &str = "Yumush"; | ||
| 8 | + | ||
| 9 | +const CLIENT_CONFIG_FILE_CONTENT: &str = include_str!(concat!( | ||
| 10 | + env!("CARGO_MANIFEST_DIR"), | ||
| 11 | + "/../../configs/client_config.toml" | ||
| 12 | +)); | ||
| 13 | + | ||
| 14 | +pub struct ClientConfig { | ||
| 15 | + server_address: String, | ||
| 16 | + server_name: String, | ||
| 17 | +} | ||
| 18 | + | ||
| 19 | +impl Default for ClientConfig { | ||
| 20 | + fn default() -> Self { | ||
| 21 | + let toml = TOML::naive_toml_parser_from_content(CLIENT_CONFIG_FILE_CONTENT).unwrap(); | ||
| 22 | + | ||
| 23 | + let server_address = toml.fields.get("server_address").unwrap().to_owned(); | ||
| 24 | + let server_name = toml.fields.get("server_name").unwrap().to_owned(); | ||
| 25 | + | ||
| 26 | + Self { | ||
| 27 | + server_address, | ||
| 28 | + server_name, | ||
| 29 | + } | ||
| 30 | + } | ||
| 31 | +} | ||
crates/client/src/main.rsmodified+6 -3
| @@ -1,4 +1,4 @@ | |||
| 1 | -use client::gui::Yumush; | 1 | +use client::{ClientConfig, NAME, gui::Yumush, network}; |
| 2 | use gpui::{ | 2 | use gpui::{ |
| 3 | App, AppContext, Application, Bounds, TitlebarOptions, WindowBounds, WindowOptions, px, size, | 3 | App, AppContext, Application, Bounds, TitlebarOptions, WindowBounds, WindowOptions, px, size, |
| 4 | }; | 4 | }; |
| @@ -7,13 +7,15 @@ use gpui_component::Root; | |||
| 7 | fn main() { | 7 | fn main() { |
| 8 | println!("Hello, world!"); | 8 | println!("Hello, world!"); |
| 9 | 9 | ||
| 10 | + let (network_handle, network_event_receiver) = network::start(ClientConfig::default()); | ||
| 11 | + | ||
| 10 | Application::new().run(|cx: &mut App| { | 12 | Application::new().run(|cx: &mut App| { |
| 11 | gpui_component::init(cx); | 13 | gpui_component::init(cx); |
| 12 | 14 | ||
| 13 | let window_bounds = Bounds::centered(None, size(px(800.0), px(600.0)), cx); | 15 | let window_bounds = Bounds::centered(None, size(px(800.0), px(600.0)), cx); |
| 14 | 16 | ||
| 15 | let titlebar = TitlebarOptions { | 17 | let titlebar = TitlebarOptions { |
| 16 | - title: Some("Nefes".into()), | 18 | + title: Some(NAME.into()), |
| 17 | ..Default::default() | 19 | ..Default::default() |
| 18 | }; | 20 | }; |
| 19 | 21 | ||
| @@ -24,7 +26,8 @@ fn main() { | |||
| 24 | ..Default::default() | 26 | ..Default::default() |
| 25 | }, | 27 | }, |
| 26 | |window, cx| { | 28 | |window, cx| { |
| 27 | - let view = cx.new(|cx| Yumush::new(window, cx)); | 29 | + let view = |
| 30 | + cx.new(|cx| Yumush::new(network_handle, network_event_receiver, window, cx)); | ||
| 28 | cx.new(|cx| Root::new(view, window, cx)) | 31 | cx.new(|cx| Root::new(view, window, cx)) |
| 29 | }, | 32 | }, |
| 30 | ) | 33 | ) |
crates/client/src/network.rsadded+228 -0
| @@ -0,0 +1,228 @@ | |||
| 1 | +use std::sync::Arc; | ||
| 2 | + | ||
| 3 | +use common::error::Error; | ||
| 4 | +use quinn::{ | ||
| 5 | + Endpoint, | ||
| 6 | + crypto::rustls::QuicClientConfig, | ||
| 7 | + rustls::{ | ||
| 8 | + self, | ||
| 9 | + client::danger::{ServerCertVerified, ServerCertVerifier}, | ||
| 10 | + }, | ||
| 11 | +}; | ||
| 12 | + | ||
| 13 | +use crate::{ClientConfig, request::ClientRequest}; | ||
| 14 | + | ||
| 15 | +pub async fn connect(server_address: &str, server_name: &str) -> Result<ClientRequest, Error> { | ||
| 16 | + let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)?; | ||
| 17 | + endpoint.set_default_client_config(config()); | ||
| 18 | + | ||
| 19 | + let connection = endpoint | ||
| 20 | + .connect(server_address.parse().unwrap(), server_name)? | ||
| 21 | + .await?; | ||
| 22 | + | ||
| 23 | + Ok(ClientRequest::new(connection)) | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +fn config() -> quinn::ClientConfig { | ||
| 27 | + let crypto_provider = Arc::new(rustls::crypto::ring::default_provider()); | ||
| 28 | + let tls_config = rustls::ClientConfig::builder_with_provider(crypto_provider.clone()) | ||
| 29 | + .with_protocol_versions(&[&rustls::version::TLS13]) | ||
| 30 | + .unwrap() | ||
| 31 | + .dangerous() | ||
| 32 | + .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate(crypto_provider))) | ||
| 33 | + .with_no_client_auth(); | ||
| 34 | + | ||
| 35 | + quinn::ClientConfig::new(Arc::new(QuicClientConfig::try_from(tls_config).unwrap())) | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +use std::time::Duration; | ||
| 39 | + | ||
| 40 | +use common::{community::Community, error::network, message::Message, user::User}; | ||
| 41 | +use tokio::sync::{mpsc, oneshot}; | ||
| 42 | + | ||
| 43 | +const CHANNEL_SIZE: usize = 32; | ||
| 44 | +const RECONNECT_DELAY: Duration = Duration::from_secs(3); | ||
| 45 | + | ||
| 46 | +macro_rules! network_commands { | ||
| 47 | + ($($variant:ident => $method:ident($($arg:ident), *) -> $ret:ty),* $(,)?) => { | ||
| 48 | + #[derive(Debug)] | ||
| 49 | + pub enum NetworkCommand { | ||
| 50 | + $($variant{ | ||
| 51 | + $($arg: String, )* | ||
| 52 | + reply: oneshot::Sender<Result<$ret, Error>>, | ||
| 53 | + },)* | ||
| 54 | + } | ||
| 55 | + | ||
| 56 | + impl NetworkHandle { | ||
| 57 | + $(pub async fn $method(&self, $($arg: &str),*) -> Result<$ret, Error> { | ||
| 58 | + let (reply, response) = oneshot::channel(); | ||
| 59 | + let command = NetworkCommand::$variant { | ||
| 60 | + $($arg: $arg.to_string(),)* | ||
| 61 | + reply, | ||
| 62 | + }; | ||
| 63 | + | ||
| 64 | + self.command_sender.send(command).await.map_err(|_| network::Error::ChannelClosed)?; | ||
| 65 | + | ||
| 66 | + response.await.map_err(|_| network::Error::ChannelClosed)? | ||
| 67 | + })* | ||
| 68 | + } | ||
| 69 | + | ||
| 70 | + async fn dispatch(client_request: ClientRequest, command: NetworkCommand) { | ||
| 71 | + match command { | ||
| 72 | + $(NetworkCommand::$variant { $($arg,)* reply} => { | ||
| 73 | + let _ = reply.send(client_request.$method($(&$arg),*).await); | ||
| 74 | + })* | ||
| 75 | + } | ||
| 76 | + } | ||
| 77 | + }; | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +network_commands! { | ||
| 81 | + Authenticate => authenticate(authentication_token) -> User, | ||
| 82 | + Deauthenticate => deauthenticate(authentication_token) -> User, | ||
| 83 | + CreateUser => create_user(username) -> User, | ||
| 84 | + ReadUser => read_user(user_id) -> User, | ||
| 85 | + UpdateUser => update_user(user_id, username) -> User, | ||
| 86 | + DeleteUser => delete_user(user_id) -> User, | ||
| 87 | + CreateCommunity => create_community(community_name) -> Community, | ||
| 88 | + ReadCommunity => read_community(community_id) -> Community, | ||
| 89 | + UpdateCommunity => update_community(community_id, community_name) -> Community, | ||
| 90 | + DeleteCommunity => delete_community(community_id) -> Community, | ||
| 91 | + CreateMessage => create_message(user_id, community_id, message_body) -> Message, | ||
| 92 | + ReadMessage => read_message(message_id) -> Message, | ||
| 93 | + UpdateMessage => update_message(message_id, message_body) -> Message, | ||
| 94 | + DeleteMessage => delete_message(message_id) -> Message, | ||
| 95 | + JoinCommunity => join_community(user_id, community_id) -> (), | ||
| 96 | + LeaveCommunity => leave_community(user_id, community_id) -> () | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +#[derive(Debug)] | ||
| 100 | +pub enum NetworkEvent { | ||
| 101 | + Connected, | ||
| 102 | + ConnectionFailed(Error), | ||
| 103 | + Disconnected(Error), | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +#[derive(Debug, Clone)] | ||
| 107 | +pub struct NetworkHandle { | ||
| 108 | + command_sender: mpsc::Sender<NetworkCommand>, | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +impl NetworkHandle { | ||
| 112 | + fn new(command_sender: mpsc::Sender<NetworkCommand>) -> Self { | ||
| 113 | + Self { command_sender } | ||
| 114 | + } | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<NetworkEvent>) { | ||
| 118 | + let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE); | ||
| 119 | + let (event_sender, event_receiver) = mpsc::channel(CHANNEL_SIZE); | ||
| 120 | + | ||
| 121 | + std::thread::Builder::new() | ||
| 122 | + .name("network".to_string()) | ||
| 123 | + .spawn(move || { | ||
| 124 | + tokio::runtime::Builder::new_current_thread() | ||
| 125 | + .enable_all() | ||
| 126 | + .build() | ||
| 127 | + .expect("network runtime") | ||
| 128 | + .block_on(actor(client_config, command_receiver, event_sender)); | ||
| 129 | + }) | ||
| 130 | + .expect("network thread"); | ||
| 131 | + | ||
| 132 | + (NetworkHandle::new(command_sender), event_receiver) | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +async fn actor( | ||
| 136 | + client_config: ClientConfig, | ||
| 137 | + mut command_receiver: mpsc::Receiver<NetworkCommand>, | ||
| 138 | + event_sender: mpsc::Sender<NetworkEvent>, | ||
| 139 | +) { | ||
| 140 | + 'session: loop { | ||
| 141 | + let client_request = loop { | ||
| 142 | + match connect(&client_config.server_address, &client_config.server_name).await { | ||
| 143 | + Ok(client_request) => break client_request, | ||
| 144 | + Err(error_value) => { | ||
| 145 | + if event_sender | ||
| 146 | + .send(NetworkEvent::ConnectionFailed(error_value)) | ||
| 147 | + .await | ||
| 148 | + .is_err() | ||
| 149 | + { | ||
| 150 | + return; | ||
| 151 | + } | ||
| 152 | + | ||
| 153 | + tokio::time::sleep(RECONNECT_DELAY).await; | ||
| 154 | + } | ||
| 155 | + }; | ||
| 156 | + }; | ||
| 157 | + | ||
| 158 | + if event_sender.send(NetworkEvent::Connected).await.is_err() { | ||
| 159 | + return; | ||
| 160 | + } | ||
| 161 | + | ||
| 162 | + loop { | ||
| 163 | + tokio::select! { | ||
| 164 | + command = command_receiver.recv() => match command { | ||
| 165 | + Some(command) => { | ||
| 166 | + tokio::spawn(dispatch(client_request.clone(), command)); | ||
| 167 | + } | ||
| 168 | + None => break 'session, | ||
| 169 | + }, | ||
| 170 | + error_value = client_request.closed() => { | ||
| 171 | + if event_sender.send(NetworkEvent::Disconnected(error_value.into())).await.is_err() { | ||
| 172 | + return ; | ||
| 173 | + } | ||
| 174 | + | ||
| 175 | + break; | ||
| 176 | + } | ||
| 177 | + } | ||
| 178 | + } | ||
| 179 | + } | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +#[derive(Debug)] | ||
| 183 | +struct AcceptAnyCertificate(Arc<rustls::crypto::CryptoProvider>); | ||
| 184 | + | ||
| 185 | +impl ServerCertVerifier for AcceptAnyCertificate { | ||
| 186 | + fn verify_server_cert( | ||
| 187 | + &self, | ||
| 188 | + _end_entity: &rustls::pki_types::CertificateDer<'_>, | ||
| 189 | + _intermediates: &[rustls::pki_types::CertificateDer<'_>], | ||
| 190 | + _server_name: &rustls::pki_types::ServerName<'_>, | ||
| 191 | + _ocsp_response: &[u8], | ||
| 192 | + _now: rustls::pki_types::UnixTime, | ||
| 193 | + ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> { | ||
| 194 | + Ok(ServerCertVerified::assertion()) | ||
| 195 | + } | ||
| 196 | + | ||
| 197 | + fn verify_tls12_signature( | ||
| 198 | + &self, | ||
| 199 | + message: &[u8], | ||
| 200 | + cert: &rustls::pki_types::CertificateDer<'_>, | ||
| 201 | + dss: &rustls::DigitallySignedStruct, | ||
| 202 | + ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> { | ||
| 203 | + rustls::crypto::verify_tls12_signature( | ||
| 204 | + message, | ||
| 205 | + cert, | ||
| 206 | + dss, | ||
| 207 | + &self.0.signature_verification_algorithms, | ||
| 208 | + ) | ||
| 209 | + } | ||
| 210 | + | ||
| 211 | + fn verify_tls13_signature( | ||
| 212 | + &self, | ||
| 213 | + message: &[u8], | ||
| 214 | + cert: &rustls::pki_types::CertificateDer<'_>, | ||
| 215 | + dss: &rustls::DigitallySignedStruct, | ||
| 216 | + ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> { | ||
| 217 | + rustls::crypto::verify_tls13_signature( | ||
| 218 | + message, | ||
| 219 | + cert, | ||
| 220 | + dss, | ||
| 221 | + &self.0.signature_verification_algorithms, | ||
| 222 | + ) | ||
| 223 | + } | ||
| 224 | + | ||
| 225 | + fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> { | ||
| 226 | + self.0.signature_verification_algorithms.supported_schemes() | ||
| 227 | + } | ||
| 228 | +} | ||
crates/client/src/request.rsadded+229 -0
| @@ -0,0 +1,229 @@ | |||
| 1 | +use common::{ | ||
| 2 | + community::Community, | ||
| 3 | + error::Error, | ||
| 4 | + message::Message, | ||
| 5 | + network::Network, | ||
| 6 | + request::{ | ||
| 7 | + Authentication, Deauthentication, Request, | ||
| 8 | + community::{CreateCommunity, DeleteCommunity, ReadCommunity, UpdateCommunity}, | ||
| 9 | + message::{CreateMessage, DeleteMessage, ReadMessage, UpdateMessage}, | ||
| 10 | + user::{CreateUser, DeleteUser, ReadUser, UpdateUser}, | ||
| 11 | + user_community::{JoinCommunity, LeaveCommunity}, | ||
| 12 | + }, | ||
| 13 | + response::Response, | ||
| 14 | + user::User, | ||
| 15 | +}; | ||
| 16 | + | ||
| 17 | +macro_rules! send_request_receive_response_then_classify { | ||
| 18 | + ($request:expr, $variant:path, $connection:expr) => {{ | ||
| 19 | + let (send_stream, receive_stream) = $connection.open_bi().await?; | ||
| 20 | + let response = | ||
| 21 | + Network::send_request_and_receive_response(&$request, send_stream, receive_stream) | ||
| 22 | + .await?; | ||
| 23 | + match response { | ||
| 24 | + $variant(inner) => Ok(inner), | ||
| 25 | + Response::Error(error) => Err(error), | ||
| 26 | + _ => Err(Error::Server), | ||
| 27 | + } | ||
| 28 | + }}; | ||
| 29 | + | ||
| 30 | + (@unit $request:expr, $variant:path, $connection:expr) => {{ | ||
| 31 | + let (send_stream, receive_stream) = $connection.open_bi().await?; | ||
| 32 | + let response = | ||
| 33 | + Network::send_request_and_receive_response(&$request, send_stream, receive_stream) | ||
| 34 | + .await?; | ||
| 35 | + match response { | ||
| 36 | + $variant => Ok(()), | ||
| 37 | + Response::Error(error_value) => Err(error_value), | ||
| 38 | + _ => Err(Error::Server), | ||
| 39 | + } | ||
| 40 | + }}; | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +#[derive(Debug, Clone)] | ||
| 44 | +pub struct ClientRequest { | ||
| 45 | + connection: quinn::Connection, | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +impl ClientRequest { | ||
| 49 | + pub fn new(connection: quinn::Connection) -> Self { | ||
| 50 | + Self { connection } | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + pub async fn closed(&self) -> Error { | ||
| 54 | + self.connection.closed().await.into() | ||
| 55 | + } | ||
| 56 | + | ||
| 57 | + pub async fn authenticate(&self, authentication_token: &str) -> Result<User, Error> { | ||
| 58 | + let authentication = Authentication::new(authentication_token); | ||
| 59 | + let request = Request::Authentication(authentication); | ||
| 60 | + | ||
| 61 | + send_request_receive_response_then_classify!( | ||
| 62 | + request, | ||
| 63 | + Response::Authentication, | ||
| 64 | + self.connection | ||
| 65 | + ) | ||
| 66 | + } | ||
| 67 | + | ||
| 68 | + pub async fn deauthenticate(&self, authentication_token: &str) -> Result<User, Error> { | ||
| 69 | + let deauthentication = Deauthentication::new(authentication_token); | ||
| 70 | + let request = Request::Deauthentication(deauthentication); | ||
| 71 | + | ||
| 72 | + send_request_receive_response_then_classify!( | ||
| 73 | + request, | ||
| 74 | + Response::Deauthentication, | ||
| 75 | + self.connection | ||
| 76 | + ) | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + pub async fn create_user(&self, username: &str) -> Result<User, Error> { | ||
| 80 | + let create_user = CreateUser::new(username)?; | ||
| 81 | + let request = Request::CreateUser(create_user); | ||
| 82 | + | ||
| 83 | + send_request_receive_response_then_classify!(request, Response::CreateUser, self.connection) | ||
| 84 | + } | ||
| 85 | + | ||
| 86 | + pub async fn read_user(&self, user_id: &str) -> Result<User, Error> { | ||
| 87 | + let read_user = ReadUser::new(user_id); | ||
| 88 | + let request = Request::ReadUser(read_user); | ||
| 89 | + | ||
| 90 | + send_request_receive_response_then_classify!(request, Response::ReadUser, self.connection) | ||
| 91 | + } | ||
| 92 | + | ||
| 93 | + pub async fn update_user(&self, user_id: &str, username: &str) -> Result<User, Error> { | ||
| 94 | + let update_user = UpdateUser::new(user_id, username)?; | ||
| 95 | + let request = Request::UpdateUser(update_user); | ||
| 96 | + | ||
| 97 | + send_request_receive_response_then_classify!(request, Response::UpdateUser, self.connection) | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + pub async fn delete_user(&self, user_id: &str) -> Result<User, Error> { | ||
| 101 | + let delete_user = DeleteUser::new(user_id); | ||
| 102 | + let request = Request::DeleteUser(delete_user); | ||
| 103 | + | ||
| 104 | + send_request_receive_response_then_classify!(request, Response::DeleteUser, self.connection) | ||
| 105 | + } | ||
| 106 | + | ||
| 107 | + pub async fn create_community(&self, community_name: &str) -> Result<Community, Error> { | ||
| 108 | + let create_community = CreateCommunity::new(community_name)?; | ||
| 109 | + let request = Request::CreateCommunity(create_community); | ||
| 110 | + | ||
| 111 | + send_request_receive_response_then_classify!( | ||
| 112 | + request, | ||
| 113 | + Response::CreateCommunity, | ||
| 114 | + self.connection | ||
| 115 | + ) | ||
| 116 | + } | ||
| 117 | + | ||
| 118 | + pub async fn read_community(&self, community_id: &str) -> Result<Community, Error> { | ||
| 119 | + let read_community = ReadCommunity::new(community_id); | ||
| 120 | + let request = Request::ReadCommunity(read_community); | ||
| 121 | + | ||
| 122 | + send_request_receive_response_then_classify!( | ||
| 123 | + request, | ||
| 124 | + Response::ReadCommunity, | ||
| 125 | + self.connection | ||
| 126 | + ) | ||
| 127 | + } | ||
| 128 | + | ||
| 129 | + pub async fn update_community( | ||
| 130 | + &self, | ||
| 131 | + community_id: &str, | ||
| 132 | + community_name: &str, | ||
| 133 | + ) -> Result<Community, Error> { | ||
| 134 | + let update_community = UpdateCommunity::new(community_id, community_name)?; | ||
| 135 | + let request = Request::UpdateCommunity(update_community); | ||
| 136 | + | ||
| 137 | + send_request_receive_response_then_classify!( | ||
| 138 | + request, | ||
| 139 | + Response::UpdateCommunity, | ||
| 140 | + self.connection | ||
| 141 | + ) | ||
| 142 | + } | ||
| 143 | + | ||
| 144 | + pub async fn delete_community(&self, community_id: &str) -> Result<Community, Error> { | ||
| 145 | + let delete_community = DeleteCommunity::new(community_id); | ||
| 146 | + let request = Request::DeleteCommunity(delete_community); | ||
| 147 | + | ||
| 148 | + send_request_receive_response_then_classify!( | ||
| 149 | + request, | ||
| 150 | + Response::DeleteCommunity, | ||
| 151 | + self.connection | ||
| 152 | + ) | ||
| 153 | + } | ||
| 154 | + | ||
| 155 | + pub async fn create_message( | ||
| 156 | + &self, | ||
| 157 | + user_id: &str, | ||
| 158 | + community_id: &str, | ||
| 159 | + message_body: &str, | ||
| 160 | + ) -> Result<Message, Error> { | ||
| 161 | + let create_message = CreateMessage::new(user_id, community_id, message_body)?; | ||
| 162 | + let request = Request::CreateMessage(create_message); | ||
| 163 | + | ||
| 164 | + send_request_receive_response_then_classify!( | ||
| 165 | + request, | ||
| 166 | + Response::CreateMessage, | ||
| 167 | + self.connection | ||
| 168 | + ) | ||
| 169 | + } | ||
| 170 | + | ||
| 171 | + pub async fn read_message(&self, message_id: &str) -> Result<Message, Error> { | ||
| 172 | + let read_message = ReadMessage::new(message_id); | ||
| 173 | + let request = Request::ReadMessage(read_message); | ||
| 174 | + | ||
| 175 | + send_request_receive_response_then_classify!( | ||
| 176 | + request, | ||
| 177 | + Response::ReadMessage, | ||
| 178 | + self.connection | ||
| 179 | + ) | ||
| 180 | + } | ||
| 181 | + | ||
| 182 | + pub async fn update_message( | ||
| 183 | + &self, | ||
| 184 | + message_id: &str, | ||
| 185 | + message_body: &str, | ||
| 186 | + ) -> Result<Message, Error> { | ||
| 187 | + let update_message = UpdateMessage::new(message_id, message_body)?; | ||
| 188 | + let request = Request::UpdateMessage(update_message); | ||
| 189 | + | ||
| 190 | + send_request_receive_response_then_classify!( | ||
| 191 | + request, | ||
| 192 | + Response::UpdateMessage, | ||
| 193 | + self.connection | ||
| 194 | + ) | ||
| 195 | + } | ||
| 196 | + | ||
| 197 | + pub async fn delete_message(&self, message_id: &str) -> Result<Message, Error> { | ||
| 198 | + let delete_message = DeleteMessage::new(message_id); | ||
| 199 | + let request = Request::DeleteMessage(delete_message); | ||
| 200 | + | ||
| 201 | + send_request_receive_response_then_classify!( | ||
| 202 | + request, | ||
| 203 | + Response::DeleteMessage, | ||
| 204 | + self.connection | ||
| 205 | + ) | ||
| 206 | + } | ||
| 207 | + | ||
| 208 | + pub async fn join_community(&self, user_id: &str, community_id: &str) -> Result<(), Error> { | ||
| 209 | + let join_community = JoinCommunity::new(user_id, community_id); | ||
| 210 | + let request = Request::JoinCommunity(join_community); | ||
| 211 | + | ||
| 212 | + send_request_receive_response_then_classify!( | ||
| 213 | + @unit request, | ||
| 214 | + Response::JoinCommunity, | ||
| 215 | + self.connection | ||
| 216 | + ) | ||
| 217 | + } | ||
| 218 | + | ||
| 219 | + pub async fn leave_community(&self, user_id: &str, community_id: &str) -> Result<(), Error> { | ||
| 220 | + let leave_community = LeaveCommunity::new(user_id, community_id); | ||
| 221 | + let request = Request::LeaveCommunity(leave_community); | ||
| 222 | + | ||
| 223 | + send_request_receive_response_then_classify!( | ||
| 224 | + @unit request, | ||
| 225 | + Response::LeaveCommunity, | ||
| 226 | + self.connection | ||
| 227 | + ) | ||
| 228 | + } | ||
| 229 | +} | ||