Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better error handling #16

Merged
merged 15 commits into from
Jan 9, 2025
Merged
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: 4 additions & 0 deletions docs/docs/discord.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ discord:

It is recommended that you set `bot_token` and `client_secret` with their environment variables `RHOMBUS__DISCORD__BOT_TOKEN` and `RHOMBUS__DISCORD__CLIENT_SECRET` respectively.

## Top 10 Role

The top 10 role is a Discord role that is given to the players in the top 10 teams in each division. For example, this role can be used to give access to channel where the top 10 teams can post high quality memes.

## Generative AI

This feature exists not because it is useful, but because it is funny. For example, if an author does not feel like creating a response to a ticket, or if the person creating the ticket clearly used AI, then the author can use AI to generate a response.
Expand Down
8 changes: 6 additions & 2 deletions rhombus/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,13 @@ tokio-rustls = { version = "0.26.0", default-features = false, optional = true,
"tls12",
] }
tokio-util = "0.7.12"
tower = "0.5.1"
tower = { version = "0.5.1", features = ["timeout"] }
tower_governor = "0.4.2"
tower-http = { version = "0.6.1", features = ["compression-full", "fs"] }
tower-http = { version = "0.6.1", features = [
"compression-full",
"fs",
"catch-panic",
] }
tower-livereload = "0.9.4"
tracing = "0.1.40"
unic-langid = { version = "0.9.5", features = ["unic-langid-macros"] }
Expand Down
13 changes: 8 additions & 5 deletions rhombus/migrations/libsql/0001_setup.up.sql
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,13 @@ CREATE TABLE IF NOT EXISTS rhombus_user (
FOREIGN KEY (owner_team_id) REFERENCES rhombus_team(id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS team_id_idx ON rhombus_user(team_id);
CREATE INDEX IF NOT EXISTS team_id_idx ON rhombus_user(team_id, discord_id);

CREATE TABLE IF NOT EXISTS rhombus_user_historical_names (
user_id INTEGER NOT NULL,
name TEXT NOT NULL,
at INTEGER NOT NULL DEFAULT(strftime('%s', 'now')),
PRIMARY KEY (user_id, name, at),
PRIMARY KEY (user_id, at DESC, name),
FOREIGN KEY (user_id) REFERENCES rhombus_user(id)
);

Expand Down Expand Up @@ -155,7 +155,7 @@ CREATE TABLE IF NOT EXISTS rhombus_team_historical_names (
team_id INTEGER NOT NULL,
name TEXT NOT NULL,
at INTEGER NOT NULL DEFAULT(strftime('%s', 'now')),
PRIMARY KEY (team_id, name, at),
PRIMARY KEY (team_id, at DESC, name),
FOREIGN KEY (team_id) REFERENCES rhombus_team(id)
);

Expand All @@ -173,11 +173,14 @@ CREATE TABLE IF NOT EXISTS rhombus_ticket (
FOREIGN KEY (challenge_id) REFERENCES rhombus_challenge(id)
);

CREATE INDEX IF NOT EXISTS challenge_idx ON rhombus_ticket (challenge_id, user_id, closed_at);
CREATE INDEX IF NOT EXISTS user_idx ON rhombus_ticket (user_id, opened_at DESC);

CREATE TABLE IF NOT EXISTS rhombus_ticket_email_message_id_reference (
message_id TEXT NOT NULL,
message_id TEXT NOT NULL UNIQUE,
ticket_number INTEGER NOT NULL,
user_sent INTEGER NOT NULL DEFAULT(FALSE), -- 0 or 1
PRIMARY KEY (message_id),
PRIMARY KEY (ticket_number, message_id, user_sent),
FOREIGN KEY (ticket_number) REFERENCES rhombus_ticket(ticket_number)
);

Expand Down
45 changes: 33 additions & 12 deletions rhombus/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,18 @@ use std::{
};

use axum::{
http::{Extensions, HeaderMap, StatusCode},
error_handling::HandleErrorLayer,
http::{Extensions, HeaderMap, StatusCode, Uri},
middleware,
response::{Html, IntoResponse},
response::Html,
routing::{delete, get, post},
Extension,
BoxError, Extension,
};
use reqwest::Method;
use tokio::sync::{Mutex, RwLock};
use tower::ServiceBuilder;
use tower_governor::{governor::GovernorConfigBuilder, GovernorLayer};
use tower_http::compression::CompressionLayer;
use tower_http::{catch_panic::CatchPanicLayer, compression::CompressionLayer};
use tracing::info;

use crate::{
Expand All @@ -32,7 +35,7 @@ use crate::{
route_signin, route_signin_credentials, route_signin_ctftime,
route_signin_ctftime_callback, route_signin_discord, route_signin_discord_callback,
route_signin_email, route_signin_email_callback, route_signin_email_confirm_callback,
route_signout,
route_signout, MaybeUser,
},
command_palette::route_command_palette_items,
database::{
Expand All @@ -45,6 +48,7 @@ use crate::{
MaxDivisionPlayers, OpenDivisionEligibilityProvider,
},
email::{mailgun::MailgunProvider, outbound_mailer::OutboundMailer},
errors::{error_handler_middleware, handle_panic, route_not_found, timeout_inner},
health::{healthcheck_catch_up, healthcheck_runner},
ip::{
default_ip_extractor, ip_insert_blank_middleware, ip_insert_middleware,
Expand All @@ -70,7 +74,7 @@ use crate::{
ChallengePoints, DynamicPoints, StaticPoints, TEAM_BURSTED_POINTS,
},
home::route_home,
meta::{page_meta_middleware, route_robots_txt, GlobalPageMeta},
meta::{page_meta_middleware, route_robots_txt, GlobalPageMeta, PageMeta},
public::{route_public_team, route_public_user},
scoreboard::{
route_scoreboard, route_scoreboard_division, route_scoreboard_division_ctftime,
Expand Down Expand Up @@ -549,7 +553,7 @@ impl Builder {
}
};

open_graph_cache_evictor(20);
open_graph_cache_evictor(60 * 10);

let mut localizer = locales::Localizations::new();

Expand Down Expand Up @@ -942,7 +946,7 @@ impl Builder {
});

let rhombus_router = axum::Router::new()
.fallback(handler_404)
.fallback(route_not_found)
.route("/admin", get(|| async { (StatusCode::OK, Html("Admin")) }))
.route("/reload", get(route_reload))
.route_layer(middleware::from_fn(enforce_admin_middleware))
Expand Down Expand Up @@ -1032,6 +1036,23 @@ impl Builder {

track_flusher(cached_db);

let router = {
let router_state_clone = router_state.clone();
router.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(
|user: Extension<MaybeUser>,
page: Extension<PageMeta>,
method: Method,
uri: Uri,
err: BoxError| async move {
timeout_inner(router_state_clone, user, page, method, uri, err)
},
))
.timeout(Duration::from_secs(30)),
)
};

let router = router
.layer(middleware::from_fn(page_meta_middleware))
.layer(middleware::from_fn_with_state(
Expand Down Expand Up @@ -1086,6 +1107,10 @@ impl Builder {
router
};

let router = router.layer(CatchPanicLayer::custom(handle_panic)).layer(
axum::middleware::from_fn_with_state(router_state, error_handler_middleware),
);

let router = router.layer(CompressionLayer::new());

(self_rc, router)
Expand Down Expand Up @@ -1113,10 +1138,6 @@ fn not_htmx_predicate<T>(req: &axum::http::Request<T>) -> bool {
!req.headers().contains_key("hx-request")
}

async fn handler_404() -> impl IntoResponse {
(StatusCode::NOT_FOUND, Html("404"))
}

pub fn hash(s: impl AsRef<str>) -> i64 {
let s = s.as_ref();
let mut hasher =
Expand Down
7 changes: 5 additions & 2 deletions rhombus/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,14 @@ pub enum RhombusError {
#[error("Required configuration: {0}")]
MissingConfiguration(String),

#[error("Database error not found")]
DatabaseReturnedNoRows,

#[error("Database error")]
UnknownDatabase(),
UnknownDatabase,

#[error("Unknown")]
Unknown(),
Unknown,

#[error("Configuration: {0}")]
Configuration(#[from] ConfigError),
Expand Down
Loading
Loading