1use crate::error::{CoreError, DatabaseError, Error};
5use axum::response::{IntoResponse, Response};
6use either::Either;
7use nil_server_database::error::DieselError;
8use std::ops::{ControlFlow, Try};
9
10pub type MaybeResponse<L> = Either<L, Response>;
11
12#[doc(hidden)]
13#[macro_export]
14macro_rules! res {
15 ($status:ident) => {{
16 use axum::body::Body;
17 use axum::http::StatusCode;
18 use axum::response::Response;
19
20 let status = StatusCode::$status;
21 let body = if (status.is_client_error() || status.is_server_error())
22 && let Some(reason) = status.canonical_reason()
23 {
24 Body::new(reason.to_string())
25 } else {
26 Body::empty()
27 };
28
29 Response::builder()
30 .status(status)
31 .body(body)
32 .unwrap()
33 }};
34 ($status:ident, $data:expr) => {{
35 use axum::http::StatusCode;
36 use axum::response::IntoResponse;
37
38 (StatusCode::$status, $data).into_response()
39 }};
40}
41
42impl From<Error> for Response {
43 fn from(err: Error) -> Self {
44 from_err(err)
45 }
46}
47
48impl IntoResponse for Error {
49 fn into_response(self) -> Response {
50 from_err(self)
51 }
52}
53
54pub(crate) fn from_err(err: impl Into<Error>) -> Response {
55 let err: Error = err.into();
56 tracing::error!(message = %err, error = ?err);
57 from_server_err(err)
58}
59
60#[expect(clippy::match_same_arms, clippy::needless_pass_by_value)]
61fn from_core_err(err: CoreError) -> Response {
62 use CoreError::*;
63
64 let text = err.to_string();
65 match err {
66 ArmyNotFound(..) => res!(NOT_FOUND, text),
67 ArmyNotIdle(..) => res!(BAD_REQUEST, text),
68 BotAlreadySpawned(..) => res!(CONFLICT, text),
69 BotNotFound(..) => res!(NOT_FOUND, text),
70 BuildingStatsNotFound(..) => res!(NOT_FOUND, text),
71 BuildingStatsNotFoundForLevel(..) => res!(NOT_FOUND, text),
72 CannotDecreaseBuildingLevel(..) => res!(BAD_REQUEST, text),
73 CannotIncreaseBuildingLevel(..) => res!(BAD_REQUEST, text),
74 CheatingNotAllowed => res!(BAD_REQUEST, text),
75 CityNotFound(..) => res!(NOT_FOUND, text),
76 FailedToReadSavedata => res!(INTERNAL_SERVER_ERROR, text),
77 FailedToWriteSavedata => res!(INTERNAL_SERVER_ERROR, text),
78 Forbidden => res!(FORBIDDEN, text),
79 IndexOutOfBounds(..) => res!(BAD_REQUEST, text),
80 InsufficientResources => res!(BAD_REQUEST, text),
81 InsufficientUnits => res!(BAD_REQUEST, text),
82 ManeuverIsDone(..) => res!(INTERNAL_SERVER_ERROR, text),
83 ManeuverIsPending(..) => res!(INTERNAL_SERVER_ERROR, text),
84 ManeuverIsReturning(..) => res!(INTERNAL_SERVER_ERROR, text),
85 ManeuverNotFound(..) => res!(NOT_FOUND, text),
86 MineStatsNotFound(..) => res!(NOT_FOUND, text),
87 MineStatsNotFoundForLevel(..) => res!(NOT_FOUND, text),
88 NoPlayer => res!(BAD_REQUEST, text),
89 NotWaitingPlayer(..) => res!(BAD_REQUEST, text),
90 OriginIsDestination(..) => res!(BAD_REQUEST, text),
91 PlayerAlreadySpawned(..) => res!(CONFLICT, text),
92 PlayerNotFound(..) => res!(NOT_FOUND, text),
93 PrecursorNotFound(..) => res!(NOT_FOUND, text),
94 ReportNotFound(..) => res!(NOT_FOUND, text),
95 RoundAlreadyStarted => res!(CONFLICT, text),
96 RoundHasPendingPlayers => res!(BAD_REQUEST, text),
97 RoundNotStarted => res!(BAD_REQUEST, text),
98 StorageStatsNotFound(..) => res!(NOT_FOUND, text),
99 StorageStatsNotFoundForLevel(..) => res!(NOT_FOUND, text),
100 UnexpectedUnit(..) => res!(INTERNAL_SERVER_ERROR, text),
101 WallStatsNotFoundForLevel(..) => res!(NOT_FOUND, text),
102 WorldIsFull => res!(INTERNAL_SERVER_ERROR, text),
103 }
104}
105
106#[expect(clippy::match_same_arms)]
107fn from_database_err(err: DatabaseError) -> Response {
108 use DatabaseError::*;
109
110 match err {
111 Core(err) => from_core_err(err),
112 Diesel(err) => from_diesel_err(&err),
113 DieselConnection(..) => res!(INTERNAL_SERVER_ERROR),
114 GameNotFound(..) => res!(NOT_FOUND, err.to_string()),
115 InvalidPassword => res!(BAD_REQUEST, err.to_string()),
116 InvalidUsername(..) => res!(BAD_REQUEST, err.to_string()),
117 Io(..) => res!(INTERNAL_SERVER_ERROR),
118 Jiff(..) => res!(INTERNAL_SERVER_ERROR),
119 UserAlreadyExists(..) => res!(CONFLICT, err.to_string()),
120 UserNotFound(..) => res!(NOT_FOUND, err.to_string()),
121 Unknown(..) => res!(INTERNAL_SERVER_ERROR),
122 }
123}
124
125fn from_diesel_err(err: &DieselError) -> Response {
126 if let DieselError::NotFound = &err {
127 res!(NOT_FOUND)
128 } else {
129 res!(INTERNAL_SERVER_ERROR)
130 }
131}
132
133#[expect(clippy::match_same_arms)]
134fn from_server_err(err: Error) -> Response {
135 use Error::*;
136
137 match err {
138 Core(err) => from_core_err(err),
139 Database(err) => from_database_err(err),
140 IncorrectUserCredentials => res!(UNAUTHORIZED, err.to_string()),
141 IncorrectWorldCredentials(..) => res!(UNAUTHORIZED, err.to_string()),
142 Io(..) => res!(INTERNAL_SERVER_ERROR),
143 MissingPassword => res!(BAD_REQUEST, err.to_string()),
144 Unknown(..) => res!(INTERNAL_SERVER_ERROR),
145 WorldLimitReached => res!(INTERNAL_SERVER_ERROR),
146 WorldNotFound(..) => res!(NOT_FOUND, err.to_string()),
147 }
148}
149
150pub trait EitherExt<L, R> {
151 fn try_map_left<T, E, F>(self, f: F) -> Either<Response, R>
152 where
153 Self: Sized,
154 L: Try<Output = T, Residual = E>,
155 E: Into<Error>,
156 F: FnOnce(T) -> Response;
157}
158
159impl<L, R> EitherExt<L, R> for Either<L, R> {
160 fn try_map_left<T, E, F>(self, f: F) -> Either<Response, R>
161 where
162 Self: Sized,
163 L: Try<Output = T, Residual = E>,
164 E: Into<Error>,
165 F: FnOnce(T) -> Response,
166 {
167 match self {
168 Self::Left(left) => {
169 match left.branch() {
170 ControlFlow::Continue(value) => Either::Left(f(value)),
171 ControlFlow::Break(err) => Either::Left(from_err(err)),
172 }
173 }
174 Self::Right(right) => Either::Right(right),
175 }
176 }
177}
178
179#[doc(hidden)]
180#[macro_export]
181macro_rules! bail_if_player_is_not_pending {
182 ($world:expr, $player:expr) => {
183 if !$world.round().is_waiting_player($player) {
184 use nil_core::error::Error;
185 let err = Error::NotWaitingPlayer($player.clone());
186 return $crate::response::from_err(err);
187 }
188 };
189}
190
191#[doc(hidden)]
192#[macro_export]
193macro_rules! bail_if_not_player {
194 ($current_player:expr, $player:expr) => {
195 if $current_player != $player {
196 return $crate::res!(FORBIDDEN);
197 }
198 };
199}
200
201#[doc(hidden)]
202#[macro_export]
203macro_rules! bail_if_city_is_not_owned_by {
204 ($world:expr, $player:expr, $coord:expr) => {
205 if !$world
206 .city($coord)?
207 .is_owned_by_player_and(|id| $player == id)
208 {
209 return $crate::res!(FORBIDDEN);
210 }
211 };
212}