nil-server 0.5.1

Multiplayer strategy game
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// Copyright (C) Call of Nil contributors
// SPDX-License-Identifier: AGPL-3.0-only

use crate::error::{Error, Result};
use crate::response::{MaybeResponse, from_err};
use crate::server::{remote, spawn_round_duration_task};
use crate::{VERSION, env, res};
use dashmap::DashMap;
use either::Either;
use jiff::Zoned;
use nil_core::chat::Chat;
use nil_core::continent::Continent;
use nil_core::military::Military;
use nil_core::npc::bot::BotManager;
use nil_core::npc::precursor::PrecursorManager;
use nil_core::player::PlayerManager;
use nil_core::ranking::Ranking;
use nil_core::report::ReportManager;
use nil_core::round::Round;
use nil_core::world::config::WorldId;
use nil_core::world::{World, WorldOptions};
use nil_crypto::password::Password;
use nil_server_database::Database;
use nil_server_database::model::game::{GameWithBlob, NewGame};
use nil_server_database::sql_types::player_id::PlayerId;
use nil_server_types::ServerKind;
use nil_server_types::round::RoundDuration;
use semver::{Prerelease, Version};
use std::num::NonZeroU16;
use std::sync::{Arc, Weak};
use std::time::Duration;
use tap::TryConv;
use tokio::sync::RwLock;
use tokio::task::{spawn, spawn_blocking};

#[derive(Clone)]
pub struct App {
  server_kind: ServerKind,
  database: Option<Database>,
  worlds: Arc<DashMap<WorldId, Arc<RwLock<World>>>>,
  world_limit: NonZeroU16,
  world_limit_per_user: NonZeroU16,
}

#[bon::bon]
impl App {
  pub fn new_local(world: World) -> Self {
    let id = world.config().id();
    let app = Self {
      server_kind: ServerKind::Local { id },
      database: None,
      worlds: Arc::new(DashMap::new()),
      world_limit: NonZeroU16::MIN,
      world_limit_per_user: NonZeroU16::MIN,
    };

    app
      .worlds
      .insert(id, Arc::new(RwLock::new(world)));

    app
  }

  pub async fn new_remote(database_url: &str) -> Result<Self> {
    let worlds = Arc::new(DashMap::new());
    let database = Database::new(database_url).await?;

    let mut invalid_games = Vec::new();

    for game_id in database.get_game_ids().await? {
      if let Ok(game) = database.get_game_with_blob(game_id).await
        && has_valid_version(&game)
        && has_valid_age(&game)
        && let Ok(world) = game.to_world()
      {
        let world_id = world.config().id();
        let round_id = world.round().id();
        let is_round_idle = world.round().is_idle();

        let database = database.clone();
        let world = Arc::new(RwLock::new(world));
        let weak_world = Arc::downgrade(&world);

        if let Some(round_duration) = game.round_duration
          && !is_round_idle
        {
          spawn(spawn_round_duration_task(
            round_id,
            Weak::clone(&weak_world),
            round_duration.into(),
          ));
        }

        world.write().await.on_next_round(
          remote::on_next_round()
            .database(database)
            .weak_world(weak_world)
            .maybe_round_duration(game.round_duration)
            .call(),
        );

        worlds.insert(world_id, world);
      } else {
        tracing::warn!(invalid_game = %game_id);
        invalid_games.push(game_id);
      }
    }

    database.delete_games(invalid_games).await?;

    Ok(Self {
      server_kind: ServerKind::Remote,
      database: Some(database),
      worlds,
      world_limit: env::remote_world_limit(),
      world_limit_per_user: env::remote_world_limit_per_user(),
    })
  }

  #[inline]
  pub fn server_kind(&self) -> ServerKind {
    self.server_kind
  }

  /// # Panics
  ///
  /// Panics if the server is not remote.
  pub fn database(&self) -> Database {
    if let ServerKind::Remote = self.server_kind
      && let Some(database) = &self.database
    {
      database.clone()
    } else {
      panic!("Not a remote server")
    }
  }

  pub fn world_ids(&self) -> Vec<WorldId> {
    self
      .worlds
      .iter()
      .map(|entry| *entry.key())
      .collect()
  }

  #[inline]
  pub fn world_limit(&self) -> u16 {
    self.world_limit.get()
  }

  #[inline]
  pub fn world_limit_per_user(&self) -> u16 {
    self.world_limit_per_user.get()
  }

  /// Creates a new remote world with the given options.
  ///
  /// # Panics
  ///
  /// Panics if the server is not remote.
  #[builder]
  pub(crate) async fn create_remote(
    &self,
    #[builder(start_fn)] options: &WorldOptions,
    #[builder(into)] player_id: PlayerId,
    #[builder(into)] world_description: Option<String>,
    world_password: Option<Password>,
    round_duration: Option<RoundDuration>,
    server_version: Version,
  ) -> Result<WorldId> {
    self
      .check_remote_world_limit(player_id.clone())
      .await?;

    let database = self.database();
    let user = database.get_user(player_id).await?;

    let world = World::try_from(options)?;
    let world_id = world.config().id();
    let blob = world.to_bytes()?;

    NewGame::builder(world_id, blob)
      .created_by(user.id)
      .maybe_description(world_description)
      .maybe_password(world_password)
      .maybe_round_duration(round_duration)
      .server_version(server_version)
      .build()
      .await?
      .create(&database)
      .await?;

    let database = database.clone();
    let world = Arc::new(RwLock::new(world));

    world.write().await.on_next_round(
      remote::on_next_round()
        .database(database)
        .weak_world(Arc::downgrade(&world))
        .maybe_round_duration(round_duration)
        .call(),
    );

    self.worlds.insert(world_id, world);

    Ok(world_id)
  }

  /// Checks if the player can create a new remote world.
  async fn check_remote_world_limit(&self, player: PlayerId) -> Result<()> {
    let database = self.database();

    let limit = i64::from(self.world_limit.get());
    if database.count_games().await? >= limit {
      return Err(Error::WorldLimitReached);
    }

    let limit_per_user = i64::from(self.world_limit_per_user.get());
    if database.count_games_by_user(player).await? >= limit_per_user {
      return Err(Error::WorldLimitReached);
    }

    Ok(())
  }

  pub(crate) fn get(&self, id: WorldId) -> Result<Arc<RwLock<World>>> {
    self
      .worlds
      .get(&id)
      .map(|world| Arc::clone(&world))
      .ok_or_else(|| Error::WorldNotFound(id))
  }

  pub(crate) fn remove(&self, id: WorldId) -> Option<Arc<RwLock<World>>> {
    self.worlds.remove(&id).map(|it| it.1)
  }

  pub async fn world<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
  where
    F: FnOnce(&World) -> T,
  {
    match self.get(id) {
      Ok(world) => Either::Left(f(&*world.read().await)),
      Err(err) => Either::Right(from_err(err)),
    }
  }

  pub async fn world_mut<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
  where
    F: FnOnce(&mut World) -> T,
  {
    match self.get(id) {
      Ok(world) => Either::Left(f(&mut *world.write().await)),
      Err(err) => Either::Right(from_err(err)),
    }
  }

  pub async fn world_blocking<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
  where
    F: FnOnce(&World) -> T + Send + Sync + 'static,
    T: Send + Sync + 'static,
  {
    match self.get(id) {
      Ok(world) => {
        match spawn_blocking(move || f(&world.blocking_read())).await {
          Ok(value) => Either::Left(value),
          Err(err) => {
            tracing::error!(message = %err, error = ?err);
            Either::Right(res!(INTERNAL_SERVER_ERROR))
          }
        }
      }
      Err(err) => Either::Right(from_err(err)),
    }
  }

  pub async fn world_blocking_mut<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
  where
    F: FnOnce(&mut World) -> T + Send + Sync + 'static,
    T: Send + Sync + 'static,
  {
    match self.get(id) {
      Ok(world) => {
        match spawn_blocking(move || f(&mut world.blocking_write())).await {
          Ok(value) => Either::Left(value),
          Err(err) => {
            tracing::error!(message = %err, error = ?err);
            Either::Right(res!(INTERNAL_SERVER_ERROR))
          }
        }
      }
      Err(err) => Either::Right(from_err(err)),
    }
  }

  pub async fn bot_manager<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
  where
    F: FnOnce(&BotManager) -> T,
  {
    self
      .world(id, |world| f(world.bot_manager()))
      .await
  }

  pub async fn chat<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
  where
    F: FnOnce(&Chat) -> T,
  {
    self.world(id, |world| f(world.chat())).await
  }

  pub async fn continent<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
  where
    F: FnOnce(&Continent) -> T,
  {
    self
      .world(id, |world| f(world.continent()))
      .await
  }

  pub async fn military<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
  where
    F: FnOnce(&Military) -> T,
  {
    self
      .world(id, |world| f(world.military()))
      .await
  }

  pub async fn player_manager<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
  where
    F: FnOnce(&PlayerManager) -> T,
  {
    self
      .world(id, |world| f(world.player_manager()))
      .await
  }

  pub async fn precursor_manager<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
  where
    F: FnOnce(&PrecursorManager) -> T,
  {
    self
      .world(id, |world| f(world.precursor_manager()))
      .await
  }

  pub async fn ranking<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
  where
    F: FnOnce(&Ranking) -> T,
  {
    self
      .world(id, |world| f(world.ranking()))
      .await
  }

  pub async fn report_manager<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
  where
    F: FnOnce(&ReportManager) -> T,
  {
    self
      .world(id, |world| f(world.report_manager()))
      .await
  }

  pub async fn round<F, T>(&self, id: WorldId, f: F) -> MaybeResponse<T>
  where
    F: FnOnce(&Round) -> T,
  {
    self
      .world(id, |world| f(world.round()))
      .await
  }
}

fn has_valid_version(game: &GameWithBlob) -> bool {
  let Ok(version) = Version::parse(VERSION) else {
    unreachable!("Current version should always be valid")
  };

  let minor = if version.major == 0 { version.minor } else { 0 };
  let version_cmp = semver::Comparator {
    op: semver::Op::Caret,
    major: version.major,
    minor: Some(minor),
    patch: Some(0),
    pre: Prerelease::EMPTY,
  };

  version_cmp.matches(&game.server_version)
}

fn has_valid_age(game: &GameWithBlob) -> bool {
  let Ok(duration) = game
    .updated_at
    .duration_until(&Zoned::now())
    .try_conv::<Duration>()
  else {
    return false;
  };

  duration <= Duration::from_days(30)
}