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    Diesel(err) => from_diesel_err(&err),
115    DieselConnection(..) => res!(INTERNAL_SERVER_ERROR),
116    GameNotFound(..) => res!(NOT_FOUND, err.to_string()),
117    InvalidPassword => res!(BAD_REQUEST, err.to_string()),
118    InvalidUsername(..) => res!(BAD_REQUEST, err.to_string()),
119    Io(..) => res!(INTERNAL_SERVER_ERROR),
120    Jiff(..) => res!(INTERNAL_SERVER_ERROR),
121    MigrationFailed(..) => res!(INTERNAL_SERVER_ERROR),
122    UserAlreadyExists(..) => res!(CONFLICT, err.to_string()),
123    UserNotFound(..) => res!(NOT_FOUND, err.to_string()),
124    Unknown(..) => res!(INTERNAL_SERVER_ERROR),
125  }
126}
127
128fn from_diesel_err(err: &DieselError) -> Response {
129  if let DieselError::NotFound = &err {
130    res!(NOT_FOUND)
131  } else {
132    res!(INTERNAL_SERVER_ERROR)
133  }
134}
135
136#[expect(clippy::match_same_arms)]
137fn from_server_err(err: Error) -> Response {
138  use Error::*;
139
140  match err {
141    Core(err) => from_core_err(err),
142    Database(err) => from_database_err(err),
143    IncorrectUserCredentials => res!(UNAUTHORIZED, err.to_string()),
144    IncorrectWorldCredentials(..) => res!(UNAUTHORIZED, err.to_string()),
145    Io(..) => res!(INTERNAL_SERVER_ERROR),
146    MissingPassword => res!(BAD_REQUEST, err.to_string()),
147    Unknown(..) => res!(INTERNAL_SERVER_ERROR),
148    WorldLimitReached => res!(FORBIDDEN, err.to_string()),
149    WorldNotFound(..) => res!(NOT_FOUND, err.to_string()),
150  }
151}
152
153pub trait EitherExt<L, R> {
154  fn try_map_left<T, E, F>(self, f: F) -> Either<Response, R>
155  where
156    Self: Sized,
157    L: Try<Output = T, Residual = E>,
158    E: Into<Error>,
159    F: FnOnce(T) -> Response;
160}
161
162impl<L, R> EitherExt<L, R> for Either<L, R> {
163  fn try_map_left<T, E, F>(self, f: F) -> Either<Response, R>
164  where
165    Self: Sized,
166    L: Try<Output = T, Residual = E>,
167    E: Into<Error>,
168    F: FnOnce(T) -> Response,
169  {
170    match self {
171      Self::Left(left) => {
172        match left.branch() {
173          ControlFlow::Continue(value) => Either::Left(f(value)),
174          ControlFlow::Break(err) => Either::Left(from_err(err)),
175        }
176      }
177      Self::Right(right) => Either::Right(right),
178    }
179  }
180}
181
182#[doc(hidden)]
183#[macro_export]
184macro_rules! bail_if_player_is_not_pending {
185  ($world:expr, $player:expr) => {
186    if !$world.round().is_waiting_player($player) {
187      use nil_core::error::Error;
188      let err = Error::NotWaitingPlayer($player.clone());
189      return $crate::response::from_err(err);
190    }
191  };
192}
193
194#[doc(hidden)]
195#[macro_export]
196macro_rules! bail_if_not_player {
197  ($current_player:expr, $player:expr) => {
198    if $current_player != $player {
199      return $crate::res!(FORBIDDEN);
200    }
201  };
202}
203
204#[doc(hidden)]
205#[macro_export]
206macro_rules! bail_if_city_is_not_owned_by {
207  ($world:expr, $player:expr, $coord:expr) => {
208    if !$world
209      .city($coord)?
210      .is_owned_by_player_and(|id| $player == id)
211    {
212      return $crate::res!(FORBIDDEN);
213    }
214  };
215}