Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ actix-web = "4.11.0"
actix-web-prom = "0.10.0"
actix-ws = "0.3.0"
aes-gcm = "0.10.3"
anyhow = "1.0.100"
arc-swap = "1.7.1"
argon2 = { version = "0.5.3", features = ["std"] }
ariadne = { path = "packages/ariadne" }
Expand Down
2 changes: 1 addition & 1 deletion apps/app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ license = "GPL-3.0-only"

[dependencies]
aes-gcm = { workspace = true }
anyhow = { workspace = true }
async_zip = { workspace = true, features = ["deflate", "tokio-fs"] }
base64 = { workspace = true }
chrono = { workspace = true }
Expand Down Expand Up @@ -39,7 +40,6 @@ tauri-plugin-single-instance = { workspace = true }
tauri-plugin-updater = { workspace = true }
tauri-plugin-window-state = { workspace = true }
theseus = { workspace = true, features = ["tauri"] }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["time"] }
tokio-util = { workspace = true, features = ["rt"] }
tracing = { workspace = true }
Expand Down
138 changes: 38 additions & 100 deletions apps/app/src/api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer};
use thiserror::Error;
use theseus::ErrorKind;

pub mod auth;
pub mod import;
Expand Down Expand Up @@ -33,110 +33,48 @@ pub mod worlds;

mod oauth_utils;

pub type Result<T> = std::result::Result<T, TheseusSerializableError>;
pub type Result<T> = std::result::Result<T, CommandError>;

// // Main returnable Theseus GUI error
// // Needs to be Serializable to be returned to the JavaScript side
// #[derive(Error, Debug, Serialize)]
// pub enum TheseusGuiError {
// #[error(transparent)]
// Serializable(),
// }
#[derive(Debug)]
pub struct CommandError(anyhow::Error);

// Serializable error intermediary, so TheseusGuiError can be Serializable (eg: so that we can return theseus::Errors in Tauri directly)
#[derive(Error, Debug)]
pub enum TheseusSerializableError {
#[error("{0}")]
Theseus(#[from] theseus::Error),

#[error("IO error: {0}")]
IO(#[from] std::io::Error),

#[error("Tauri error: {0}")]
Tauri(#[from] tauri::Error),

#[cfg(feature = "updater")]
#[error("Updater error: {0}")]
Updater(#[from] tauri_plugin_updater::Error),

#[cfg(feature = "updater")]
#[error("HTTP error: {0}")]
Http(#[from] tauri_plugin_http::reqwest::Error),
impl<E: Into<anyhow::Error>> From<E> for CommandError {
fn from(error: E) -> Self {
Self(error.into())
}
}

// Generic implementation of From<T> for ErrorTypeA
// impl<T> From<T> for TheseusGuiError
// where
// TheseusSerializableError: From<T>,
// {
// fn from(error: T) -> Self {
// TheseusGuiError::Serializable(TheseusSerializableError::from(error))
// }
// }
impl Serialize for CommandError {
fn serialize<S>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
tracing::warn!("{:?}", self.0);

// This is a very simple macro that implements a very basic Serializable for each variant of TheseusSerializableError,
// where the field is the string. (This allows easy extension to errors without many match arms)
macro_rules! impl_serialize {
($($variant:ident),* $(,)?) => {
impl Serialize for TheseusSerializableError {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
TheseusSerializableError::Theseus(theseus_error) => {
let unavailable_reason = match theseus_error.raw.as_ref() {
theseus::ErrorKind::SharedInstanceUnavailable(reason) => Some(reason),
_ => None,
};
let code = match theseus_error.raw.as_ref() {
theseus::ErrorKind::SharedInstanceUnavailable(_) => {
Some("shared_instance_unavailable")
}
theseus::ErrorKind::SharedInstancesApiError(_) => {
Some("shared_instances_api_error")
}
_ => None,
};
let mut state = serializer.serialize_struct(
"Theseus",
2 + usize::from(code.is_some()) + usize::from(unavailable_reason.is_some()),
)?;
state.serialize_field("field_name", "Theseus")?;
state.serialize_field("message", &theseus_error.to_string())?;
if let Some(code) = code {
state.serialize_field("code", code)?;
}
if let Some(reason) = unavailable_reason {
state.serialize_field("reason", reason)?;
}
state.end()
}
$(
TheseusSerializableError::$variant(message) => {
let mut state = serializer.serialize_struct(stringify!($variant), 2)?;
state.serialize_field("field_name", stringify!($variant))?;
state.serialize_field("message", &message.to_string())?;
state.end()
},
)*
}
let (code, reason) = match self.0.downcast_ref::<ErrorKind>() {
Some(ErrorKind::SharedInstanceUnavailable(reason)) => {
(Some("shared_instance_unavailable"), Some(reason))
}
}
};
}

// Use the macro to implement Serialize for TheseusSerializableError
#[cfg(not(feature = "updater"))]
impl_serialize! {
IO,
Tauri,
}
Some(ErrorKind::SharedInstancesApiError(_)) => {
(Some("shared_instances_api_error"), None)
}
_ => (None, None),
};

#[cfg(feature = "updater")]
impl_serialize! {
IO,
Tauri,
Updater,
Http,
let mut state = serializer.serialize_struct(
"CommandError",
1 + usize::from(code.is_some()) + usize::from(reason.is_some()),
)?;
state.serialize_field("message", &self.0.to_string())?;
if let Some(code) = code {
state.serialize_field("code", code)?;
}
if let Some(reason) = reason {
state.serialize_field("reason", reason)?;
}
state.end()
}
}
17 changes: 7 additions & 10 deletions apps/app/src/api/mr_auth.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::api::Result;
use crate::api::TheseusSerializableError;
use crate::api::oauth_utils;
use crate::api::oauth_utils::auth_code_reply::AuthReplySession;
use crate::api::oauth_utils::auth_seal::AuthSeal;
Expand Down Expand Up @@ -46,18 +45,16 @@ pub async fn modrinth_login<R: Runtime>(
app.opener()
.open_url(auth_request_uri, None::<&str>)
.map_err(|e| {
TheseusSerializableError::Theseus(
theseus::ErrorKind::OtherError(format!(
"Failed to open auth request URI: {e}"
))
.into(),
)
theseus::ErrorKind::OtherError(format!(
"Failed to open auth request URI: {e}"
))
.as_error()
})?;

let Some(auth_code) = reply.wait().await? else {
return Err(TheseusSerializableError::Theseus(
theseus::ErrorKind::OtherError("Login canceled".into()).into(),
));
return Err(theseus::ErrorKind::OtherError("Login canceled".into())
.as_error()
.into());
};
let session_token = seal.open(&auth_code)?;
let credentials = mr_auth::authenticate_finish_flow(&session_token).await?;
Expand Down
17 changes: 3 additions & 14 deletions apps/app/src/api/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ use theseus::{
prelude::{CommandPayload, DirectoryInfo, app_db_backup_dir},
};

use crate::api::Result;
use crate::api::oauth_utils::auth_code_reply::{
normalize_deep_link_command, parse_auth_deeplink, submit_deeplink,
};
use crate::api::{Result, TheseusSerializableError};
use dashmap::DashMap;
use std::path::{Path, PathBuf};
use theseus::prelude::canonicalize;
Expand Down Expand Up @@ -281,20 +281,9 @@ pub(crate) fn tauri_convert_file_src(path: &Path) -> Result<Url> {
#[cfg(not(any(windows, target_os = "android")))]
const BASE: &str = "asset://localhost/";

macro_rules! theseus_try {
($test:expr) => {
match $test {
Ok(val) => val,
Err(e) => {
return Err(TheseusSerializableError::Theseus(e.into()))
}
}
};
}

let path = theseus_try!(canonicalize(path));
let path = canonicalize(path)?;
let path = path.to_string_lossy();
let encoded = urlencoding::encode(&path);

Ok(theseus_try!(Url::parse(&format!("{BASE}{encoded}"))))
Ok(Url::parse(&format!("{BASE}{encoded}"))?)
}
2 changes: 1 addition & 1 deletion packages/app-lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ name = "export_app_events"
required-features = ["export-ts"]

[dependencies]
anyhow = { workspace = true }
ariadne = { workspace = true }
async-minecraft-ping = { workspace = true, features = ["srv"] }
async-recursion = { workspace = true }
Expand Down Expand Up @@ -39,7 +40,6 @@ dunce = { workspace = true }
either = { workspace = true }
encoding_rs = { workspace = true }
enumset = { workspace = true }
eyre = { workspace = true }
flate2 = { workspace = true }
fs4 = { workspace = true, features = ["tokio"] }
futures = { workspace = true, features = ["alloc", "async-await"] }
Expand Down
20 changes: 12 additions & 8 deletions packages/app-lib/src/api/instance/synced_packs/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,12 +309,16 @@ pub(in crate::api::instance) async fn seed_from_instance(
{
Ok(candidate) => candidate,
Err(error)
if matches!(
error.raw.as_ref(),
crate::ErrorKind::JSONError(_)
| crate::ErrorKind::InputError(_)
| crate::ErrorKind::StdIOError(_)
) =>
if error.is::<serde_json::Error>()
|| error.is::<std::io::Error>()
|| matches!(
error.downcast_ref::<crate::ErrorKind>(),
Some(
crate::ErrorKind::JSONError(_)
| crate::ErrorKind::InputError(_)
| crate::ErrorKind::StdIOError(_)
)
) =>
{
tracing::warn!(
"Skipping pack {} from instance {instance_id} while initializing pack sync: {error}",
Expand Down Expand Up @@ -400,8 +404,8 @@ async fn sync_pack_inner(
match sync_pack_once(instance_id, project_path, automatic).await {
Err(error)
if matches!(
error.raw.as_ref(),
crate::ErrorKind::PackSyncChanged
error.downcast_ref::<crate::ErrorKind>(),
Some(crate::ErrorKind::PackSyncChanged)
) =>
{
tokio::task::yield_now().await;
Expand Down
12 changes: 7 additions & 5 deletions packages/app-lib/src/api/instance/synced_packs/reconciliation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -836,9 +836,11 @@ async fn apply_instance_inner(
Ok(prepared) => prepared,
Err(error)
if matches!(
error.raw.as_ref(),
crate::ErrorKind::PackSyncChanged
| crate::ErrorKind::Ratelimited { .. }
error.downcast_ref::<crate::ErrorKind>(),
Some(
crate::ErrorKind::PackSyncChanged
| crate::ErrorKind::Ratelimited { .. }
)
) =>
{
return Err(error);
Expand Down Expand Up @@ -1068,8 +1070,8 @@ pub(crate) async fn reconcile_after_content_change(instance_id: &str) {
match capture_after_change(instance_id).await {
Err(error)
if matches!(
error.raw.as_ref(),
crate::ErrorKind::PackSyncChanged
error.downcast_ref::<crate::ErrorKind>(),
Some(crate::ErrorKind::PackSyncChanged)
) =>
{
tokio::task::yield_now().await;
Expand Down
Loading
Loading