From 4ba005a6253dde332bdaa62654fe5d062bec6037 Mon Sep 17 00:00:00 2001 From: Sebastian <19Sebastian95@gmx.de> Date: Sun, 14 May 2023 13:52:00 +0200 Subject: [PATCH] GH-29: Replace error handling result with type alias --- .github/workflows/pr.yml | 4 --- src-tauri/src/connection/mod.rs | 26 +++++++------------ .../src/connection/threads/main_thread.rs | 4 +-- src-tauri/src/connection/threads/mod.rs | 6 +++-- src-tauri/src/connection/traits.rs | 6 ++--- src-tauri/src/errors/mod.rs | 4 +++ src-tauri/src/manager/channel.rs | 7 +++-- src-tauri/src/manager/text_message.rs | 9 +++---- src-tauri/src/manager/user.rs | 16 +++--------- src-tauri/src/manager/voice.rs | 15 ++++------- src-tauri/src/protocol/message_router.rs | 15 +++++------ src-tauri/src/protocol/message_transmitter.rs | 4 +-- src-tauri/src/protocol/stream_reader.rs | 9 ++++--- src-tauri/src/utils/audio/decoder.rs | 11 ++++---- src-tauri/src/utils/audio/player.rs | 7 ++--- src-tauri/src/utils/audio/recorder.rs | 7 ++--- src-tauri/src/utils/certificate_store.rs | 8 +++--- src-tauri/src/utils/file.rs | 6 ++--- src-tauri/src/utils/varint.rs | 6 ++--- 19 files changed, 75 insertions(+), 95 deletions(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 8606a34..195c5ae 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -160,7 +160,3 @@ jobs: - name: Build the app uses: tauri-apps/tauri-action@v0 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - releaseId: ${{ needs.create-release.outputs.release_id }} diff --git a/src-tauri/src/connection/mod.rs b/src-tauri/src/connection/mod.rs index 7aa5cdd..ab8570a 100644 --- a/src-tauri/src/connection/mod.rs +++ b/src-tauri/src/connection/mod.rs @@ -1,6 +1,7 @@ pub mod threads; pub mod traits; use crate::connection::traits::Shutdown; +use crate::errors::AnyError; use crate::mumble; use crate::protocol::init_connection; use crate::protocol::stream_reader::StreamReader; @@ -11,7 +12,6 @@ use async_trait::async_trait; use base64::engine::general_purpose; use base64::Engine; use std::collections::HashMap; -use std::error::Error; use std::sync::atomic::AtomicBool; use std::sync::Arc; use tauri::PackageInfo; @@ -92,7 +92,7 @@ impl Connection { async fn setup_connection( &mut self, - ) -> Result>, Box> { + ) -> AnyError>> { let server_uri = format!( "{}:{}", self.server_data.server_host, self.server_data.server_port @@ -110,7 +110,7 @@ impl Connection { )) } - pub async fn connect(&mut self) -> Result<(), Box> { + pub async fn connect(&mut self) -> AnyError<()> { { self.running .store(true, std::sync::atomic::Ordering::Relaxed); @@ -127,11 +127,7 @@ impl Connection { Ok(()) } - pub fn send_message( - &self, - channel_id: Option, - message: &str, - ) -> Result<(), Box> { + pub fn send_message(&self, channel_id: Option, message: &str) -> AnyError<()> { self.tx_message_channel.send(TextMessage { message: message.to_string(), channel_id, @@ -145,7 +141,7 @@ impl Connection { } //TODO: Move to output Thread - pub fn like_message(&self, message_id: &str) -> Result<(), Box> { + pub fn like_message(&self, message_id: &str) -> AnyError<()> { let like_message = mumble::proto::PluginDataTransmission { sender_session: None, receiver_sessions: Vec::new(), @@ -157,11 +153,7 @@ impl Connection { Ok(()) } - pub async fn set_user_image( - &self, - image_path: &str, - image_type: &str, - ) -> Result<(), Box> { + pub async fn set_user_image(&self, image_path: &str, image_type: &str) -> AnyError<()> { let image = get_file_as_byte_vec(image_path).await?; match image_type { @@ -189,7 +181,7 @@ impl Connection { Ok(()) } - pub fn join_channel(&self, channel_id: u32) -> Result<(), Box> { + pub fn join_channel(&self, channel_id: u32) -> AnyError<()> { let join_channel = mumble::proto::UserState { session: None, actor: None, @@ -220,14 +212,14 @@ impl Connection { Ok(()) } - pub fn update_user_info(&self) -> Result<(), Box> { + pub fn update_user_info(&self) -> AnyError<()> { todo!() } } #[async_trait] impl Shutdown for Connection { - async fn shutdown(&mut self) -> Result<(), Box> { + async fn shutdown(&mut self) -> AnyError<()> { info!("Sending Shutdown Request"); self.running .store(false, std::sync::atomic::Ordering::Relaxed); diff --git a/src-tauri/src/connection/threads/main_thread.rs b/src-tauri/src/connection/threads/main_thread.rs index 6c82538..cc1bd35 100644 --- a/src-tauri/src/connection/threads/main_thread.rs +++ b/src-tauri/src/connection/threads/main_thread.rs @@ -2,10 +2,10 @@ use async_trait::async_trait; use crate::connection::{Connection, BUFFER_SIZE}; use crate::errors::application_error::ApplicationError; +use crate::errors::AnyError; use super::{ConnectionThread, MainThread, DEADMAN_INTERVAL}; use std::cmp; -use std::error::Error; use std::sync::atomic::Ordering; use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader}; use tokio::net::TcpStream; @@ -19,7 +19,7 @@ impl MainThread for Connection { async fn init_main_thread( &mut self, stream: Option>, - ) -> Result<(), Box> { + ) -> AnyError<()> { if self.threads.get(&ConnectionThread::Main).is_some() { return Err(Box::new(ApplicationError::new( "MainThread already running", diff --git a/src-tauri/src/connection/threads/mod.rs b/src-tauri/src/connection/threads/mod.rs index 2ea13f7..8efdd4c 100644 --- a/src-tauri/src/connection/threads/mod.rs +++ b/src-tauri/src/connection/threads/mod.rs @@ -4,9 +4,11 @@ mod input_thread; mod main_thread; mod output_thread; mod ping_thread; -use std::{error::Error, time::Duration}; +use std::time::Duration; use tokio::net::TcpStream; +use crate::errors::AnyError; + pub const DEADMAN_INTERVAL: Duration = Duration::from_millis(500); #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] @@ -45,5 +47,5 @@ pub trait MainThread { async fn init_main_thread( &mut self, stream: Option>, - ) -> Result<(), Box>; + ) -> AnyError<()>; } diff --git a/src-tauri/src/connection/traits.rs b/src-tauri/src/connection/traits.rs index f49c9e9..099827e 100644 --- a/src-tauri/src/connection/traits.rs +++ b/src-tauri/src/connection/traits.rs @@ -1,10 +1,10 @@ -use std::error::Error; - use async_trait::async_trait; +use crate::errors::AnyError; + #[async_trait] pub trait Shutdown { - async fn shutdown(&mut self) -> Result<(), Box>; + async fn shutdown(&mut self) -> AnyError<()>; } #[async_trait] diff --git a/src-tauri/src/errors/mod.rs b/src-tauri/src/errors/mod.rs index e90e115..76a9e56 100644 --- a/src-tauri/src/errors/mod.rs +++ b/src-tauri/src/errors/mod.rs @@ -1,2 +1,6 @@ +use std::error::Error; + pub mod application_error; pub mod voice_error; + +pub type AnyError = Result>; diff --git a/src-tauri/src/manager/channel.rs b/src-tauri/src/manager/channel.rs index f88d9f7..6a83e05 100644 --- a/src-tauri/src/manager/channel.rs +++ b/src-tauri/src/manager/channel.rs @@ -1,6 +1,5 @@ use std::{ collections::{hash_map::Entry, HashMap}, - error::Error, mem, }; @@ -8,7 +7,7 @@ use serde::Serialize; use tracing::{debug, error, info}; use crate::{ - mumble, protocol::serialize::message_container::FrontendMessage, + errors::AnyError, mumble, protocol::serialize::message_container::FrontendMessage, utils::messages::message_builder, }; @@ -103,7 +102,7 @@ impl Manager { &self, channel_info: &Data, description_hash: &Vec, - ) -> Result<(), Box> { + ) -> AnyError<()> { let channel_id = channel_info.channel_id; let cached_channel_description_hash = &self .channels @@ -152,7 +151,7 @@ impl Manager { pub fn update_channel( &mut self, channel_info: &mut mumble::proto::ChannelState, - ) -> Result<(), Box> { + ) -> AnyError<()> { let has_description = channel_info.description.is_some() && !channel_info .description diff --git a/src-tauri/src/manager/text_message.rs b/src-tauri/src/manager/text_message.rs index ae8e430..521bb51 100644 --- a/src-tauri/src/manager/text_message.rs +++ b/src-tauri/src/manager/text_message.rs @@ -1,13 +1,10 @@ -use std::{ - error::Error, - time::{SystemTime, UNIX_EPOCH}, -}; +use std::time::{SystemTime, UNIX_EPOCH}; use serde::Serialize; use tokio::sync::broadcast::Sender; use tracing::error; -use crate::{mumble, protocol::serialize::message_container::FrontendMessage}; +use crate::{errors::AnyError, mumble, protocol::serialize::message_container::FrontendMessage}; use super::user::User; @@ -71,7 +68,7 @@ impl Manager { &mut self, text_message: mumble::proto::TextMessage, user: &User, - ) -> Result<(), Box> { + ) -> AnyError<()> { let message = TextMessage { sender: SenderInfo { user_id: user.id, diff --git a/src-tauri/src/manager/user.rs b/src-tauri/src/manager/user.rs index d1259f0..e5d154e 100644 --- a/src-tauri/src/manager/user.rs +++ b/src-tauri/src/manager/user.rs @@ -1,7 +1,6 @@ use base64::{engine::general_purpose, Engine as _}; use std::{ collections::{hash_map::Entry, HashMap}, - error::Error, mem, }; @@ -9,7 +8,7 @@ use serde::Serialize; use tracing::{debug, error, info, trace}; use crate::{ - mumble, protocol::serialize::message_container::FrontendMessage, + errors::AnyError, mumble, protocol::serialize::message_container::FrontendMessage, utils::messages::message_builder, }; @@ -138,7 +137,7 @@ impl Manager { } } - fn fill_user_images(&self, user_id: u32, texture_hash: &Vec) -> Result<(), Box> { + fn fill_user_images(&self, user_id: u32, texture_hash: &Vec) -> AnyError<()> { let user = self.users.get(&user_id); if user.is_none() { return Err(format!("User {user_id} not found").into()); @@ -172,11 +171,7 @@ impl Manager { Ok(()) } - fn fill_user_comment( - &self, - user_id: u32, - comment_hash: &Vec, - ) -> Result<(), Box> { + fn fill_user_comment(&self, user_id: u32, comment_hash: &Vec) -> AnyError<()> { let cached_user_comment_hash = &self .users .get(&user_id) @@ -207,10 +202,7 @@ impl Manager { Ok(()) } - pub fn update_user( - &mut self, - user_info: &mut mumble::proto::UserState, - ) -> Result<(), Box> { + pub fn update_user(&mut self, user_info: &mut mumble::proto::UserState) -> AnyError<()> { let has_texture = user_info.texture.is_some() && !user_info .texture diff --git a/src-tauri/src/manager/voice.rs b/src-tauri/src/manager/voice.rs index ecec8ee..f66e5bf 100644 --- a/src-tauri/src/manager/voice.rs +++ b/src-tauri/src/manager/voice.rs @@ -1,13 +1,11 @@ +use crate::errors::AnyError; use crate::protocol::serialize::message_container::FrontendMessage; use crate::utils::audio; use crate::utils::audio::player::Player; use crate::{connection::traits::Shutdown, errors::voice_error::VoiceError}; use async_trait::async_trait; use serde::Serialize; -use std::{ - collections::{hash_map::Entry, HashMap}, - error::Error, -}; +use std::collections::{hash_map::Entry, HashMap}; use tokio::sync::broadcast::Sender; use tracing::error; @@ -29,10 +27,7 @@ pub struct Manager { } impl Manager { - pub fn new( - send_to: Sender, - server_channel: Sender>, - ) -> Result> { + pub fn new(send_to: Sender, server_channel: Sender>) -> AnyError { let mut player = Player::new(); if let Err(error) = player.start() { error!("Failed to start audio player: {}", error); @@ -65,7 +60,7 @@ impl Manager { } } - pub fn notify_audio(&mut self, audio_data: &[u8]) -> Result<(), Box> { + pub fn notify_audio(&mut self, audio_data: &[u8]) -> AnyError<()> { let audio_data = self.decoder.decode_audio(audio_data)?; self.send_taking_information(audio_data.user_id, audio_data.talking); if let Err(error) = self @@ -104,7 +99,7 @@ impl Manager { #[async_trait] impl Shutdown for Manager { - async fn shutdown(&mut self) -> Result<(), Box> { + async fn shutdown(&mut self) -> AnyError<()> { self.audio_player.stop(); Ok(()) diff --git a/src-tauri/src/protocol/message_router.rs b/src-tauri/src/protocol/message_router.rs index 4dc0f19..21c3874 100644 --- a/src-tauri/src/protocol/message_router.rs +++ b/src-tauri/src/protocol/message_router.rs @@ -7,7 +7,7 @@ use tracing::{error, trace}; use crate::{ connection::{traits::Shutdown, MessageChannels}, - errors::application_error::ApplicationError, + errors::{application_error::ApplicationError, AnyError}, manager::{ channel::{self}, connection_state, text_message, @@ -27,10 +27,7 @@ pub struct MessageRouter { } impl MessageRouter { - pub fn new( - sender: MessageChannels, - server_channel: Sender>, - ) -> Result> { + pub fn new(sender: MessageChannels, server_channel: Sender>) -> AnyError { Ok(Self { user_manager: user::Manager::new( sender.message_channel.clone(), @@ -49,7 +46,7 @@ impl MessageRouter { }) } - fn handle_downcast(message_info: MessageInfo) -> Result> { + fn handle_downcast(message_info: MessageInfo) -> AnyError { match message_info.message_data.downcast::() { Ok(a) => Ok(*a), Err(e) => Err(Box::new(ApplicationError::new( @@ -58,7 +55,7 @@ impl MessageRouter { } } - fn handle_text_message(&mut self, message: MessageInfo) -> Result<(), Box> { + fn handle_text_message(&mut self, message: MessageInfo) -> AnyError<()> { let text_message = Self::handle_downcast::(message)?; match text_message.actor { Some(actor) => { @@ -75,7 +72,7 @@ impl MessageRouter { Ok(()) } - pub fn recv_message(&mut self, message: MessageInfo) -> Result<(), Box> { + pub fn recv_message(&mut self, message: MessageInfo) -> AnyError<()> { if message.message_type != crate::utils::messages::MessageTypes::UdpTunnel { trace!("Received message: {:<100?}", message); } @@ -142,7 +139,7 @@ impl MessageRouter { Ok(()) } - pub async fn shutdown(&mut self) -> Result<(), Box> { + pub async fn shutdown(&mut self) -> AnyError<()> { self.voice_manager.shutdown().await?; Ok(()) diff --git a/src-tauri/src/protocol/message_transmitter.rs b/src-tauri/src/protocol/message_transmitter.rs index da934df..0c8b006 100644 --- a/src-tauri/src/protocol/message_transmitter.rs +++ b/src-tauri/src/protocol/message_transmitter.rs @@ -1,8 +1,8 @@ -use std::error::Error; use std::sync::{Arc, RwLock}; use crate::connection::threads::DEADMAN_INTERVAL; use crate::connection::traits::{HandleMessage, Shutdown}; +use crate::errors::AnyError; use async_trait::async_trait; use tauri::Manager; use tokio::task::JoinHandle; @@ -58,7 +58,7 @@ impl MessageTransmitter { #[async_trait] impl Shutdown for MessageTransmitter { - async fn shutdown(&mut self) -> Result<(), Box> { + async fn shutdown(&mut self) -> AnyError<()> { trace!("Sending Shutdown Request"); if let Ok(mut running) = self.running.write() { *running = false; diff --git a/src-tauri/src/protocol/stream_reader.rs b/src-tauri/src/protocol/stream_reader.rs index df2c381..257fa9d 100644 --- a/src-tauri/src/protocol/stream_reader.rs +++ b/src-tauri/src/protocol/stream_reader.rs @@ -1,8 +1,11 @@ use byteorder::{BigEndian, ReadBytesExt}; -use std::{error::Error, io::Cursor}; +use std::io::Cursor; use tracing::error; -use crate::utils::messages::{get_message, MessageInfo, MessageTypes}; +use crate::{ + errors::AnyError, + utils::messages::{get_message, MessageInfo, MessageTypes}, +}; use super::message_router::MessageRouter; @@ -68,7 +71,7 @@ impl StreamReader { &self.stream_buffer[start..(n + start)] } - pub async fn shutdown(&mut self) -> Result<(), Box> { + pub async fn shutdown(&mut self) -> AnyError<()> { self.stream_buffer.clear(); self.message_handler.shutdown().await?; diff --git a/src-tauri/src/utils/audio/decoder.rs b/src-tauri/src/utils/audio/decoder.rs index cba26c9..b9e957e 100644 --- a/src-tauri/src/utils/audio/decoder.rs +++ b/src-tauri/src/utils/audio/decoder.rs @@ -1,6 +1,7 @@ -use std::error::Error; - -use crate::utils::varint::{self}; +use crate::{ + errors::AnyError, + utils::varint::{self}, +}; pub struct DecodedMessage { pub user_id: u32, @@ -15,7 +16,7 @@ pub struct Decoder { } impl Decoder { - pub fn new(sample_rate: u32, channels: opus::Channels) -> Result> { + pub fn new(sample_rate: u32, channels: opus::Channels) -> AnyError { let decoder = opus::Decoder::new(sample_rate, channels)?; Ok(Self { decoder, @@ -28,7 +29,7 @@ impl Decoder { #[allow(clippy::cast_possible_truncation)] // We are aware of the possible truncation, but we are not using the full range of u32 #[allow(clippy::cast_sign_loss)] - pub fn decode_audio(&mut self, audio_data: &[u8]) -> Result> { + pub fn decode_audio(&mut self, audio_data: &[u8]) -> AnyError { let audio_header = audio_data[0]; let audio_type = (audio_header & 0xE0) >> 5; diff --git a/src-tauri/src/utils/audio/player.rs b/src-tauri/src/utils/audio/player.rs index 8ac03a1..d86cd47 100644 --- a/src-tauri/src/utils/audio/player.rs +++ b/src-tauri/src/utils/audio/player.rs @@ -1,5 +1,4 @@ use std::{ - error::Error, sync::{ atomic::{AtomicBool, Ordering}, mpsc::{self, Receiver, Sender}, @@ -11,6 +10,8 @@ use std::{ use tracing::{error, trace}; +use crate::errors::AnyError; + pub struct Player { audio_thread: Option>, queue_rx: Option>>, @@ -30,7 +31,7 @@ impl Player { } } - pub fn start(&mut self) -> Result<(), Box> { + pub fn start(&mut self) -> AnyError<()> { if self.playing.swap(true, Ordering::Relaxed) || self.audio_thread.is_some() { error!("Audio thread already started"); return Err("Audio thread already started".into()); @@ -82,7 +83,7 @@ impl Player { Ok(()) } - pub fn add_to_queue(&mut self, data: Vec, _user_id: u32) -> Result<(), Box> { + pub fn add_to_queue(&mut self, data: Vec, _user_id: u32) -> AnyError<()> { if self.playing.load(Ordering::Relaxed) { //todo add user id to audio data self.queue_tx.send(data)?; diff --git a/src-tauri/src/utils/audio/recorder.rs b/src-tauri/src/utils/audio/recorder.rs index 46a3ed8..3952054 100644 --- a/src-tauri/src/utils/audio/recorder.rs +++ b/src-tauri/src/utils/audio/recorder.rs @@ -1,5 +1,4 @@ use std::{ - error::Error, sync::{ atomic::{AtomicBool, Ordering}, mpsc::{self, Receiver, Sender}, @@ -10,6 +9,8 @@ use std::{ use tracing::{error, trace}; +use crate::errors::AnyError; + pub struct Recorder { audio_thread: Option>, _queue_rx: Receiver>, @@ -29,7 +30,7 @@ impl Recorder { } } - pub fn start(&mut self) -> Result<(), Box> { + pub fn start(&mut self) -> AnyError<()> { if self.playing.swap(true, Ordering::Relaxed) || self.audio_thread.is_some() { error!("Audio thread already started"); return Err("Audio thread already started".into()); @@ -46,7 +47,7 @@ impl Recorder { Ok(()) } - /*pub fn read_queue(&mut self) -> Result, Box> { + /*pub fn read_queue(&mut self) -> AnyError> { if self.playing.load(Ordering::Relaxed) { //todo add user id to audio data return Ok(self.queue_rx.recv_timeout(Duration::from_millis(2000))?); diff --git a/src-tauri/src/utils/certificate_store.rs b/src-tauri/src/utils/certificate_store.rs index d48a4f9..b071f06 100644 --- a/src-tauri/src/utils/certificate_store.rs +++ b/src-tauri/src/utils/certificate_store.rs @@ -1,5 +1,3 @@ -use std::error::Error; - use openssl::{ asn1::Asn1Time, hash::MessageDigest, @@ -12,12 +10,14 @@ use openssl::{ }; use tokio_native_tls::native_tls::{self, Identity}; +use crate::errors::AnyError; + struct CertificateStore { certificate: Vec, private_key: Vec, } -fn create_tls_certificate() -> Result> { +fn create_tls_certificate() -> AnyError { //TODO: Currently we always generate a new certificate. We should store the certificate and private key in a file and only generate a new one if the file does not exist. //TODO: We should also check if the certificate is still valid and generate a new one if it is not. //TODO: We currently always use fancy-mumble.com as the certificate's common name. We should use a client specified common name instead. @@ -60,7 +60,7 @@ fn create_tls_certificate() -> Result> { }) } -pub fn get_client_certificate() -> Result> { +pub fn get_client_certificate() -> AnyError { let cert_store = create_tls_certificate()?; let identity = diff --git a/src-tauri/src/utils/file.rs b/src-tauri/src/utils/file.rs index 9fd73bc..ce39e49 100644 --- a/src-tauri/src/utils/file.rs +++ b/src-tauri/src/utils/file.rs @@ -1,11 +1,11 @@ -use std::error::Error; - use tokio::fs::{self, File}; use tokio::io::AsyncReadExt; +use crate::errors::AnyError; + // we check that the file is not too large #[allow(clippy::cast_possible_truncation)] -pub async fn get_file_as_byte_vec(filename: &str) -> Result, Box> { +pub async fn get_file_as_byte_vec(filename: &str) -> AnyError> { let mut f = File::open(&filename).await?; let metadata = fs::metadata(&filename).await?; let mut buffer = vec![0; metadata.len() as usize]; diff --git a/src-tauri/src/utils/varint.rs b/src-tauri/src/utils/varint.rs index 93c9949..e005c30 100644 --- a/src-tauri/src/utils/varint.rs +++ b/src-tauri/src/utils/varint.rs @@ -1,6 +1,6 @@ use std::error::Error; -use crate::errors::voice_error::VoiceError; +use crate::errors::{voice_error::VoiceError, AnyError}; fn create_voice_eoi(on: &str) -> Box { Box::new(VoiceError::new(format!("Unexpected end of input for {on}"))) @@ -28,7 +28,7 @@ impl From<&[u8]> for Builder { } impl Builder { - pub fn build(self) -> Result> { + pub fn build(self) -> AnyError { Ok(Varint { _bytes: self.bytes.ok_or_else(|| VoiceError::new("No bytes"))?, parsed_value: self @@ -53,7 +53,7 @@ impl Varint { (self.parsed_value, self.parsed_bytes) } - fn parse(bytes: &[u8]) -> Result<(i128, u32), Box> { + fn parse(bytes: &[u8]) -> AnyError<(i128, u32)> { if bytes.is_empty() { return Err(Box::new(VoiceError::new("Unexpected end of input"))); }