Skip to main content

nil_server/
response.rs

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