Skip to main content

nil_server/
app.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4use crate::error::{Error, Result};
5use crate::response::{MaybeResponse, from_err};
6use crate::server::{remote, spawn_round_duration_task};
7use crate::{VERSION, res};
8use dashmap::DashMap;
9use either::Either;
10use jiff::Zoned;
11use nil_core::chat::Chat;
12use nil_core::continent::Continent;
13use nil_core::military::Military;
14use nil_core::npc::bot::BotManager;
15use nil_core::npc::precursor::PrecursorManager;
16use nil_core::player::PlayerManager;
17use nil_core::ranking::Ranking;
18use nil_core::round::Round;
19use nil_core::world::config::WorldId;
20use nil_core::world::{World, WorldOptions};
21use nil_crypto::password::Password;
22use nil_server_database::Database;
23use nil_server_database::model::game::{GameWithBlob, NewGame};
24use nil_server_database::sql_types::player_id::db_PlayerId;
25use nil_server_types::ServerKind;
26use nil_server_types::round::RoundDuration;
27use semver::{Prerelease, Version};
28use std::num::NonZeroU16;
29use std::sync::{Arc, Weak};
30use std::time::Duration;
31use tap::TryConv;
32use tokio::sync::RwLock;
33use tokio::task::{spawn, spawn_blocking};
34
35#[derive(Clone)]
36pub struct App {
37  server_kind: ServerKind,
38  database: Option<Database>,
39  worlds: Arc<DashMap<WorldId, Arc<RwLock<World>>>>,
40  world_limit: NonZeroU16,
41  world_limit_per_user: NonZeroU16,
42}
43
44#[bon::bon]
45impl App {
46  pub fn new_local(world: World) -> Self {
47    let id = world.config().id();
48    let app = Self {
49      server_kind: ServerKind::Local { id },
50      database: None,
51      worlds: Arc::new(DashMap::new()),
52      world_limit: NonZeroU16::MIN,
53      world_limit_per_user: NonZeroU16::MIN,
54    };
55
56    app
57      .worlds
58      .insert(id, Arc::new(RwLock::new(world)));
59
60    app
61  }
62
63  pub async fn new_remote(database_url: &str) -> Result<Self> {
64    let worlds = Arc::new(DashMap::new());
65    let database = Database::new(database_url)?;
66
67    let mut invalid_games = Vec::new();
68
69    for game_id in database.get_game_ids().await? {
70      if let Ok(game) = database.get_game_with_blob(game_id).await
71        && has_valid_version(&game)
72        && has_valid_age(&game)
73        && let Ok(world) = game.to_world()
74      {
75        let world_id = world.config().id();
76        let round_id = world.round().id();
77        let is_round_idle = world.round().is_idle();
78
79        let database = database.clone();
80        let world = Arc::new(RwLock::new(world));
81        let weak_world = Arc::downgrade(&world);
82
83        if let Some(round_duration) = game.round_duration
84          && !is_round_idle
85        {
86          spawn(spawn_round_duration_task(
87            round_id,
88            Weak::clone(&weak_world),
89            round_duration.into(),
90          ));
91        }
92
93        world.write().await.on_next_round(
94          remote::on_next_round()
95            .database(database)
96            .weak_world(weak_world)
97            .maybe_round_duration(game.round_duration)
98            .call(),
99        );
100
101        worlds.insert(world_id, world);
102      } else {
103        tracing::warn!(invalid_game = %game_id);
104        invalid_games.push(game_id);
105      }
106    }
107
108    database.delete_games(&invalid_games).await?;
109
110    Ok(Self {
111      server_kind: ServerKind::Remote,
112      database: Some(database),
113      worlds,
114      world_limit: nil_env::remote_world_limit(),
115      world_limit_per_user: nil_env::remote_world_limit_per_user(),
116    })
117  }
118
119  #[inline]
120  pub fn server_kind(&self) -> ServerKind {
121    self.server_kind
122  }
123
124  /// # Panics
125  ///
126  /// Panics if the server is not remote.
127  pub fn database(&self) -> Database {
128    if let ServerKind::Remote = self.server_kind
129      && let Some(database) = &self.database
130    {
131      database.clone()
132    } else {
133      panic!("Not a remote server")
134    }
135  }
136
137  pub fn world_ids(&self) -> Vec<WorldId> {
138    self
139      .worlds
140      .iter()
141      .map(|entry| *entry.key())
142      .collect()
143  }
144
145  #[inline]
146  pub fn world_limit(&self) -> u16 {
147    self.world_limit.get()
148  }
149
150  #[inline]
151  pub fn world_limit_per_user(&self) -> u16 {
152    self.world_limit_per_user.get()
153  }
154
155  /// Creates a new remote world with the given options.
156  ///
157  /// # Panics
158  ///
159  /// Panics if the server is not remote.
160  #[builder]
161  pub(crate) async fn create_remote(
162    &self,
163    #[builder(start_fn)] options: &WorldOptions,
164    #[builder(into)] player_id: db_PlayerId,
165    #[builder(into)] world_description: Option<String>,
166    #[builder(into)] world_password: Option<Password>,
167    #[builder(into)] round_duration: Option<RoundDuration>,
168    server_version: Version,
169  ) -> Result<WorldId> {
170    self
171      .check_remote_world_limit(player_id.clone())
172      .await?;
173
174    let database = self.database();
175    let user = database.get_user(player_id).await?;
176
177    let world = World::try_from(options)?;
178    let world_id = world.config().id();
179    let blob = world.to_bytes()?;
180
181    NewGame::builder(world_id, blob)
182      .created_by(user.id)
183      .maybe_description(world_description)
184      .maybe_password(world_password)
185      .maybe_round_duration(round_duration)
186      .server_version(server_version)
187      .build()
188      .await?
189      .create(&database)
190      .await?;
191
192    let database = database.clone();
193    let world = Arc::new(RwLock::new(world));
194
195    world.write().await.on_next_round(
196      remote::on_next_round()
197        .database(database)
198        .weak_world(Arc::downgrade(&world))
199        .maybe_round_duration(round_duration)
200        .call(),
201    );
202
203    self.worlds.insert(world_id, world);
204
205    Ok(world_id)
206  }
207
208  /// Checks if the player can create a new remote world.
209  async fn check_remote_world_limit(&self, player: db_PlayerId) -> Result<()> {
210    let database = self.database();
211
212    let limit = i64::from(self.world_limit.get());
213    if database.count_games().await? >= limit {
214      return Err(Error::WorldLimitReached);
215    }
216
217    let limit_per_user = i64::from(self.world_limit_per_user.get());
218    if database.count_games_by_user(player).await? >= limit_per_user {
219      return Err(Error::WorldLimitReached);
220    }
221
222    Ok(())
223  }
224
225  pub(crate) fn get(&self, id: WorldId) -> Result<Arc<RwLock<World>>> {
226    self
227      .worlds
228      .get(&id)
229      .map(|world| Arc::clone(&world))
230      .ok_or_else(|| Error::WorldNotFound(id))
231  }
232
233  pub(crate) fn remove(&self, id: WorldId) -> Option<Arc<RwLock<World>>> {
234    self.worlds.remove(&id).map(|it| it.1)
235  }
236
237  pub async fn world<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
238  where
239    F: FnOnce(&World) -> T,
240  {
241    match self.get(id) {
242      Ok(world) => Either::Left(f(&*world.read().await)),
243      Err(err) => Either::Right(from_err(err)),
244    }
245  }
246
247  pub async fn world_mut<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
248  where
249    F: FnOnce(&mut World) -> T,
250  {
251    match self.get(id) {
252      Ok(world) => Either::Left(f(&mut *world.write().await)),
253      Err(err) => Either::Right(from_err(err)),
254    }
255  }
256
257  pub async fn world_blocking<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
258  where
259    F: FnOnce(&World) -> T + Send + Sync + 'static,
260    T: Send + Sync + 'static,
261  {
262    match self.get(id) {
263      Ok(world) => {
264        match spawn_blocking(move || f(&world.blocking_read())).await {
265          Ok(value) => Either::Left(value),
266          Err(err) => {
267            tracing::error!(message = %err, error = ?err);
268            Either::Right(res!(INTERNAL_SERVER_ERROR))
269          }
270        }
271      }
272      Err(err) => Either::Right(from_err(err)),
273    }
274  }
275
276  pub async fn world_blocking_mut<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
277  where
278    F: FnOnce(&mut World) -> T + Send + Sync + 'static,
279    T: Send + Sync + 'static,
280  {
281    match self.get(id) {
282      Ok(world) => {
283        match spawn_blocking(move || f(&mut world.blocking_write())).await {
284          Ok(value) => Either::Left(value),
285          Err(err) => {
286            tracing::error!(message = %err, error = ?err);
287            Either::Right(res!(INTERNAL_SERVER_ERROR))
288          }
289        }
290      }
291      Err(err) => Either::Right(from_err(err)),
292    }
293  }
294
295  pub async fn bot_manager<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
296  where
297    F: FnOnce(&BotManager) -> T,
298  {
299    self
300      .world(id, |world| f(world.bot_manager()))
301      .await
302  }
303
304  pub async fn chat<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
305  where
306    F: FnOnce(&Chat) -> T,
307  {
308    self.world(id, |world| f(world.chat())).await
309  }
310
311  pub async fn continent<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
312  where
313    F: FnOnce(&Continent) -> T,
314  {
315    self
316      .world(id, |world| f(world.continent()))
317      .await
318  }
319
320  pub async fn military<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
321  where
322    F: FnOnce(&Military) -> T,
323  {
324    self
325      .world(id, |world| f(world.military()))
326      .await
327  }
328
329  pub async fn player_manager<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
330  where
331    F: FnOnce(&PlayerManager) -> T,
332  {
333    self
334      .world(id, |world| f(world.player_manager()))
335      .await
336  }
337
338  pub async fn precursor_manager<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
339  where
340    F: FnOnce(&PrecursorManager) -> T,
341  {
342    self
343      .world(id, |world| f(world.precursor_manager()))
344      .await
345  }
346
347  pub async fn ranking<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
348  where
349    F: FnOnce(&Ranking) -> T,
350  {
351    self
352      .world(id, |world| f(world.ranking()))
353      .await
354  }
355
356  pub async fn round<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
357  where
358    F: FnOnce(&Round) -> T,
359  {
360    self
361      .world(id, |world| f(world.round()))
362      .await
363  }
364}
365
366fn has_valid_version(game: &GameWithBlob) -> bool {
367  let Ok(version) = Version::parse(VERSION) else {
368    unreachable!("Current version should always be valid");
369  };
370
371  let minor = if version.major == 0 { version.minor } else { 0 };
372  let version_cmp = semver::Comparator {
373    op: semver::Op::Caret,
374    major: version.major,
375    minor: Some(minor),
376    patch: Some(0),
377    pre: Prerelease::EMPTY,
378  };
379
380  version_cmp.matches(&game.server_version)
381}
382
383fn has_valid_age(game: &GameWithBlob) -> bool {
384  let Ok(duration) = game
385    .updated_at
386    .duration_until(&Zoned::now())
387    .try_conv::<Duration>()
388  else {
389    return false;
390  };
391
392  duration <= Duration::from_days(30)
393}