refactor error handling to catch more things

This commit is contained in:
iliana etaoin 2023-04-06 20:31:41 -07:00
parent 310886f2ca
commit 2506aa1be3
4 changed files with 124 additions and 74 deletions

7
Cargo.lock generated
View File

@ -23,12 +23,6 @@ dependencies = [
"alloc-no-stdlib", "alloc-no-stdlib",
] ]
[[package]]
name = "anyhow"
version = "1.0.70"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7de8ce5e0f9f8d88245311066a578d72b7af3e7088f32783804676302df237e4"
[[package]] [[package]]
name = "askama" name = "askama"
version = "0.12.0" version = "0.12.0"
@ -284,7 +278,6 @@ checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91"
name = "emojos-dot-in" name = "emojos-dot-in"
version = "2.0.0" version = "2.0.0"
dependencies = [ dependencies = [
"anyhow",
"askama", "askama",
"reqwest", "reqwest",
"rocket", "rocket",

View File

@ -10,7 +10,6 @@ publish = false
include = ["/build.rs", "/src", "/static", "/templates", "/LICENSE", ".gitignore"] include = ["/build.rs", "/src", "/static", "/templates", "/LICENSE", ".gitignore"]
[dependencies] [dependencies]
anyhow = "1"
askama = { version = "0.12", default-features = false } askama = { version = "0.12", default-features = false }
reqwest = { version = "0.11", features = ["gzip", "brotli", "deflate", "json"] } reqwest = { version = "0.11", features = ["gzip", "brotli", "deflate", "json"] }
rocket = { version = "0.5.0-rc.3", default-features = false } rocket = { version = "0.5.0-rc.3", default-features = false }

View File

@ -7,7 +7,7 @@ mod trivial;
use askama::Template; use askama::Template;
use reqwest::{Client, StatusCode, Url}; use reqwest::{Client, StatusCode, Url};
use rocket::http::{ContentType, Header, Status}; use rocket::http::{Header, Status};
use rocket::response::{self, Debug, Responder}; use rocket::response::{self, Debug, Responder};
use rocket::{get, routes, Request, Response, State}; use rocket::{get, routes, Request, Response, State};
use serde::Deserialize; use serde::Deserialize;
@ -39,7 +39,6 @@ fn rocket() -> _ {
) )
} }
#[derive(Debug)]
struct Html<T: Template>(T); struct Html<T: Template>(T);
impl<T: Template> Responder<'_, 'static> for Html<T> { impl<T: Template> Responder<'_, 'static> for Html<T> {
@ -52,74 +51,134 @@ impl<T: Template> Responder<'_, 'static> for Html<T> {
} }
} }
#[derive(Deserialize)]
struct Emojo {
shortcode: String,
url: String,
static_url: String,
visible_in_picker: Option<bool>,
}
#[derive(Template)]
#[template(path = "emojo.html")]
struct Output {
instance: String,
show_animated: bool,
emojo: Vec<Emojo>,
}
#[get("/<instance>?<show_all>&<show_animated>")] #[get("/<instance>?<show_all>&<show_animated>")]
async fn instance( async fn instance(
client: &State<Client>, client: &State<Client>,
instance: &str, instance: String,
show_all: Option<bool>, show_all: Option<bool>,
show_animated: Option<bool>, show_animated: Option<bool>,
) -> Result<(ContentType, String), Debug<anyhow::Error>> { ) -> Result<Html<Output>, InstanceError> {
#[derive(Deserialize)]
struct Emojo {
shortcode: String,
url: String,
static_url: String,
visible_in_picker: Option<bool>,
}
#[derive(Template)]
#[template(path = "emojo.html")]
struct Output<'a> {
instance: &'a str,
show_animated: bool,
emojo: Vec<Emojo>,
}
#[derive(Template)]
#[template(path = "oh_no.html")]
struct OhNo<'a> {
instance: &'a str,
status: StatusCode,
why: &'a str,
}
let show_all = show_all.unwrap_or_default(); let show_all = show_all.unwrap_or_default();
let show_animated = show_animated.unwrap_or_default(); let show_animated = show_animated.unwrap_or_default();
let output = async { let mut url = Url::from_str("https://host.invalid/api/v1/custom_emojis").unwrap();
let mut url = Url::from_str("https://host.invalid/api/v1/custom_emojis").unwrap(); if url.set_host(Some(&instance)).is_err() {
url.set_host(Some(instance))?; return Err(InstanceError::from_kind(Kind::NotFound, instance));
}
let response = client.get(url).send().await?;
if response.status().is_client_error() || response.status().is_server_error() { let mut emojo = match client
return Ok(OhNo { .get(url)
instance, .send()
status: response.status(), .await
why: match response.status() { .and_then(reqwest::Response::error_for_status)
StatusCode::FORBIDDEN => "This instance's emoji list is private.", {
StatusCode::NOT_FOUND => { Ok(response) => match response.json::<Vec<Emojo>>().await {
"This instance doesn't support the Mastodon custom emoji API." Ok(emojo) => emojo,
} Err(err) => return Err(InstanceError::new(err, instance)),
_ => "That's all we know.", },
}, Err(err) => return Err(InstanceError::new(err, instance)),
} };
.render()?); if !show_all {
} emojo.retain(|x| x.visible_in_picker.unwrap_or(true));
}
let mut emojo: Vec<Emojo> = response.json().await?;
if !show_all { Ok(Html(Output {
emojo.retain(|x| x.visible_in_picker.unwrap_or(true)); instance,
} show_animated,
emojo,
anyhow::Ok( }))
Output { }
instance,
show_animated, #[derive(Template)]
emojo, #[template(path = "oh_no.html")]
} struct ErrorDisplay {
.render()?, status: Status,
) instance: String,
kind: Kind,
}
#[derive(Responder)]
enum InstanceError {
Display((Status, Html<ErrorDisplay>)),
Debug(Debug<reqwest::Error>),
}
impl InstanceError {
fn new(err: reqwest::Error, instance: String) -> InstanceError {
let kind = match err.status() {
Some(StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) => Kind::Private,
Some(StatusCode::NOT_FOUND | StatusCode::METHOD_NOT_ALLOWED | StatusCode::GONE) => {
Kind::NotFound
}
Some(_) => return InstanceError::Debug(Debug(err)),
None => {
if err.is_connect() {
Kind::NotFound
} else if err.is_decode() || err.is_redirect() {
Kind::Malformed
} else if err.is_timeout() {
Kind::TimedOut
} else {
return InstanceError::Debug(Debug(err));
}
}
};
InstanceError::from_kind(kind, instance)
}
fn from_kind(kind: Kind, instance: String) -> InstanceError {
InstanceError::from(ErrorDisplay {
status: match kind {
Kind::Malformed => Status::BadGateway,
Kind::NotFound => Status::NotFound,
Kind::Private => Status::Forbidden,
Kind::TimedOut => Status::GatewayTimeout,
},
instance,
kind,
})
}
}
impl From<ErrorDisplay> for InstanceError {
fn from(display: ErrorDisplay) -> InstanceError {
InstanceError::Display((display.status, Html(display)))
}
}
#[derive(Clone, Copy)]
enum Kind {
Malformed,
NotFound,
Private,
TimedOut,
}
impl Kind {
fn message(self) -> &'static str {
match self {
Kind::Malformed => "Response from the instance was malformed",
Kind::NotFound => {
"Not a fediverse instance, or does not support the Mastodon custom emoji API"
}
Kind::Private => "Instance emoji list is private",
Kind::TimedOut => "Timed out waiting for response",
}
} }
.await?;
Ok((ContentType::HTML, output))
} }

View File

@ -1,8 +1,7 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block title %}Custom emoji list for {{ instance }}{% endblock title %} {% block title %}Error{% endblock title %}
{% block body %} {% block body %}
<p> <p>
<b>{{ instance }}</b>'s custom emoji API (/api/v1/custom_emojis) returned {{ status }}. <b>Error</b>: {{ instance }}: {{ kind.message() }}. :(
{{ why }} :(
</p> </p>
{% endblock body %} {% endblock body %}