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 FailedToDeserializeEvent => res!(INTERNAL_SERVER_ERROR, text),
77 FailedToReadSavedata => res!(INTERNAL_SERVER_ERROR, text),
78 FailedToSerializeEvent => res!(INTERNAL_SERVER_ERROR, text),
79 FailedToWriteSavedata => res!(INTERNAL_SERVER_ERROR, text),
80 FieldNotEmpty(..) => res!(BAD_REQUEST, text),
81 Forbidden => res!(FORBIDDEN, text),
82 IndexOutOfBounds(..) => res!(BAD_REQUEST, text),
83 InsufficientResources => res!(BAD_REQUEST, text),
84 InsufficientUnits => res!(BAD_REQUEST, text),
85 ManeuverIsDone(..) => res!(BAD_REQUEST, text),
86 ManeuverIsPending(..) => res!(BAD_REQUEST, text),
87 ManeuverIsReturning(..) => res!(BAD_REQUEST, text),
88 ManeuverNotFound(..) => res!(NOT_FOUND, text),
89 MineStatsNotFound(..) => res!(NOT_FOUND, text),
90 MineStatsNotFoundForLevel(..) => res!(NOT_FOUND, text),
91 NotWaitingPlayer(..) => res!(BAD_REQUEST, text),
92 OriginIsDestination(..) => res!(BAD_REQUEST, text),
93 PlayerAlreadySpawned(..) => res!(CONFLICT, text),
94 PlayerNotFound(..) => res!(NOT_FOUND, text),
95 PrecursorNotFound(..) => res!(NOT_FOUND, text),
96 ReportNotFound(..) => res!(NOT_FOUND, text),
97 ResourceReceiverIsSender(..) => res!(BAD_REQUEST, text),
98 RoundAlreadyStarted => res!(CONFLICT, text),
99 RoundHasPendingPlayers => res!(BAD_REQUEST, text),
100 RoundNotStarted => res!(BAD_REQUEST, text),
101 StorageStatsNotFound(..) => res!(NOT_FOUND, text),
102 StorageStatsNotFoundForLevel(..) => res!(NOT_FOUND, text),
103 TooManyResources(..) => res!(BAD_REQUEST, text),
104 UnexpectedUnit(..) => res!(BAD_REQUEST, text),
105 WallStatsNotFoundForLevel(..) => res!(NOT_FOUND, text),
106 WorldIsFull => res!(FORBIDDEN, text),
107 }
108}
109
110#[expect(clippy::match_same_arms)]
111fn from_database_err(err: DatabaseError) -> Response {
112 use DatabaseError::*;
113
114 match err {
115 Core(err) => from_core_err(err),
116 Deadpool(..) => res!(INTERNAL_SERVER_ERROR),
117 DeadpoolBuild(..) => res!(INTERNAL_SERVER_ERROR),
118 Diesel(err) => from_diesel_err(&err),
119 DieselConnection(..) => res!(INTERNAL_SERVER_ERROR),
120 GameNotFound(..) => res!(NOT_FOUND, err.to_string()),
121 InvalidPassword => res!(BAD_REQUEST, err.to_string()),
122 InvalidUsername(..) => res!(BAD_REQUEST, err.to_string()),
123 Io(..) => res!(INTERNAL_SERVER_ERROR),
124 Jiff(..) => res!(INTERNAL_SERVER_ERROR),
125 MigrationFailed(..) => res!(INTERNAL_SERVER_ERROR),
126 UserAlreadyExists(..) => res!(CONFLICT, err.to_string()),
127 UserNotFound(..) => res!(NOT_FOUND, err.to_string()),
128 Unknown(..) => res!(INTERNAL_SERVER_ERROR),
129 }
130}
131
132fn from_diesel_err(err: &DieselError) -> Response {
133 if let DieselError::NotFound = &err {
134 res!(NOT_FOUND)
135 } else {
136 res!(INTERNAL_SERVER_ERROR)
137 }
138}
139
140#[expect(clippy::match_same_arms)]
141fn from_server_err(err: Error) -> Response {
142 use Error::*;
143
144 match err {
145 Core(err) => from_core_err(err),
146 Database(err) => from_database_err(err),
147 IncorrectUserCredentials => res!(UNAUTHORIZED, err.to_string()),
148 IncorrectWorldCredentials(..) => res!(UNAUTHORIZED, err.to_string()),
149 Io(..) => res!(INTERNAL_SERVER_ERROR),
150 MaxCharactersExceeded { .. } => res!(BAD_REQUEST, err.to_string()),
151 MissingPassword => res!(BAD_REQUEST, err.to_string()),
152 Unknown(..) => res!(INTERNAL_SERVER_ERROR),
153 WorldLimitReached => res!(FORBIDDEN, err.to_string()),
154 WorldNotFound(..) => res!(NOT_FOUND, err.to_string()),
155 }
156}
157
158pub trait EitherExt<L, R> {
159 fn try_map_left<T, E, F>(self, f: F) -> Either<Response, R>
160 where
161 Self: Sized,
162 L: Try<Output = T, Residual = E>,
163 E: Into<Error>,
164 F: FnOnce(T) -> Response;
165}
166
167impl<L, R> EitherExt<L, R> for Either<L, R> {
168 fn try_map_left<T, E, F>(self, f: F) -> Either<Response, R>
169 where
170 Self: Sized,
171 L: Try<Output = T, Residual = E>,
172 E: Into<Error>,
173 F: FnOnce(T) -> Response,
174 {
175 match self {
176 Self::Left(left) => {
177 match left.branch() {
178 ControlFlow::Continue(value) => Either::Left(f(value)),
179 ControlFlow::Break(err) => Either::Left(from_err(err)),
180 }
181 }
182 Self::Right(right) => Either::Right(right),
183 }
184 }
185}
186
187#[doc(hidden)]
188#[macro_export]
189macro_rules! bail_if_city_is_not_owned_by {
190 ($world:expr, $player:expr, $coord:expr) => {
191 if !$world
192 .city($coord)?
193 .is_owned_by_player_and(|id| $player == id)
194 {
195 return $crate::res!(FORBIDDEN);
196 }
197 };
198}
199
200#[doc(hidden)]
201#[macro_export]
202macro_rules! bail_if_max_chars_exceeded {
203 ($value:expr, $max:expr) => {
204 let current = $value.chars().count();
205 if current > $max {
206 use $crate::error::Error;
207 let err = Error::MaxCharactersExceeded { max: $max, current };
208 return $crate::response::from_err(err);
209 }
210 };
211}
212
213#[doc(hidden)]
214#[macro_export]
215macro_rules! bail_if_player_is_not_pending {
216 ($world:expr, $player:expr) => {
217 if !$world.round().is_waiting_player($player) {
218 use nil_core::error::Error;
219 let err = Error::NotWaitingPlayer($player.clone());
220 return $crate::response::from_err(err);
221 }
222 };
223}
224
225#[doc(hidden)]
226#[macro_export]
227macro_rules! bail_if_player_ne {
228 ($current_player:expr, $player:expr) => {
229 if $current_player != $player {
230 return $crate::res!(FORBIDDEN);
231 }
232 };
233}