Browse Source

Fix all clippy lints

main
ThePerkinrex 5 years ago
parent
commit
1126683f79
No known key found for this signature in database GPG Key ID: FD81DE6D75E20917
  1. 4
      server/build.rs
  2. 4
      server/src/allocator.rs
  3. 8
      server/src/command.rs
  4. 6
      server/src/db.rs
  5. 8
      server/src/games/config.rs
  6. 12
      server/src/games/mod.rs
  7. 6
      server/src/games/run.rs
  8. 8
      server/src/games/run/engine.rs
  9. 2
      server/src/games/run/functions.rs
  10. 8
      server/src/games/run/types.rs
  11. 8
      server/src/logger.rs
  12. 12
      server/src/logger/color_message.rs
  13. 48
      server/src/server.rs
  14. 2
      server/src/server/game.rs
  15. 8
      server/src/server/protos/common.rs
  16. 14
      server/src/server/protos/connection.rs
  17. 52
      server/src/server/protos/game.rs
  18. 14
      server/src/server/protos/lobby.rs
  19. 62
      server/src/server/protos/protocol.rs
  20. 2
      server/src/server/socket_manager.rs
  21. 4
      server/src/server/votes.rs
  22. 4
      server/src/server_properties.rs

4
server/build.rs

@ -4,13 +4,11 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("cargo:rerun-if-changed=../protobuf/"); println!("cargo:rerun-if-changed=../protobuf/");
println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=build.rs");
let mut files = Vec::new(); let mut files = Vec::new();
for f in read_dir("../protobuf").unwrap() { for f in read_dir("../protobuf").unwrap().flatten() {
if let Ok(f) = f {
if f.path().is_file() && f.path().extension().map(|x| x == "proto").unwrap_or(false) { if f.path().is_file() && f.path().extension().map(|x| x == "proto").unwrap_or(false) {
files.push(f.path()); files.push(f.path());
} }
} }
}
if let Err(e) = prost_build::Config::new() if let Err(e) = prost_build::Config::new()
.out_dir("src/server/protos") .out_dir("src/server/protos")
.compile_protos( .compile_protos(

4
server/src/allocator.rs

@ -14,7 +14,7 @@ unsafe impl GlobalAlloc for Allocator {
if !ret.is_null() { if !ret.is_null() {
ALLOCATED.fetch_add(layout.size(), SeqCst); ALLOCATED.fetch_add(layout.size(), SeqCst);
} }
return ret; ret
} }
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
@ -32,7 +32,7 @@ impl Allocator {
#[global_allocator] #[global_allocator]
static ALLOCATOR: Allocator = Allocator; static ALLOCATOR: Allocator = Allocator;
static UNITS: (&'static str, &'static [(&'static str, usize)]) = ( static UNITS: (&str, &[(&str, usize)]) = (
"b", "b",
&[ &[
("B", 8), ("B", 8),

8
server/src/command.rs

@ -2,11 +2,9 @@ use std::fs::read_dir;
pub fn command_handler(command: String) -> String { pub fn command_handler(command: String) -> String {
if command == "reload_cache" { if command == "reload_cache" {
for file in read_dir("games").unwrap() { for folder in read_dir("games").unwrap().flatten() {
if let Ok(folder) = file {
if folder.path().is_dir() { if folder.path().is_dir() {
for file in read_dir(folder.path()).unwrap() { for file in read_dir(folder.path()).unwrap().flatten() {
if let Ok(file) = file {
if file.file_name().to_str().unwrap() == "game.json" { if file.file_name().to_str().unwrap() == "game.json" {
let conf = crate::games::Config::load(file.path()); let conf = crate::games::Config::load(file.path());
log::info!("Reloading caches for {}", conf.name); log::info!("Reloading caches for {}", conf.name);
@ -16,7 +14,5 @@ pub fn command_handler(command: String) -> String {
} }
} }
} }
}
}
command command
} }

6
server/src/db.rs

@ -42,12 +42,11 @@ impl Db {
} }
pub fn add_user(&mut self, name: String) -> Result<Uuid> { pub fn add_user(&mut self, name: String) -> Result<Uuid> {
loop {
let uuid = Uuid::new_v4(); let uuid = Uuid::new_v4();
// println!("{:?}", uuid.as_bytes().to_vec()); // println!("{:?}", uuid.as_bytes().to_vec());
let res = self.conn.execute( let res = self.conn.execute(
"INSERT INTO Users(uuid, name) VALUES(?, ?)", "INSERT INTO Users(uuid, name) VALUES(?, ?)",
params![uuid.as_bytes().to_vec(), name.to_string()], params![uuid.as_bytes().to_vec(), name],
); // Server crashes if uuids collide ); // Server crashes if uuids collide
if let Err(e) = res { if let Err(e) = res {
@ -69,8 +68,7 @@ impl Db {
} }
} }
return Ok(uuid); Ok(uuid)
}
} }
// FIXME: return Results intead of crashing // FIXME: return Results intead of crashing
pub fn get_users_in_lobby_where_user_is(&mut self, uuid: Uuid) -> Vec<String> { pub fn get_users_in_lobby_where_user_is(&mut self, uuid: Uuid) -> Vec<String> {

8
server/src/games/config.rs

@ -77,14 +77,12 @@ impl Config {
let folder = folder.clone(); let folder = folder.clone();
tokio::task::spawn_blocking(|| cache_image(p, folder)); tokio::task::spawn_blocking(|| cache_image(p, folder));
} }
for ( for
_,
Card { Card {
image, image,
back_image, back_image,
other: _, other: _,
}, } in self.available_cards.values()
) in &self.available_cards
{ {
{ {
let folder = folder.clone(); let folder = folder.clone();
@ -128,7 +126,7 @@ fn cache_image<P1: AsRef<Path>, P2: AsRef<Path>>(p: P1, folder: P2) {
// log::info!("Updating cache for: {}", original.display()); // log::info!("Updating cache for: {}", original.display());
let mut face_buf = Vec::new(); let mut face_buf = Vec::new();
image::open(&original) image::open(&original)
.expect(&format!("Error loading the image in {:?}", original)) .unwrap_or_else(|e| panic!("Error loading the image in {:?} ({})", original, e))
.write_to(&mut face_buf, image::ImageOutputFormat::Png) .write_to(&mut face_buf, image::ImageOutputFormat::Png)
.unwrap(); .unwrap();
match std::fs::create_dir_all(cached.parent().unwrap()) { match std::fs::create_dir_all(cached.parent().unwrap()) {

12
server/src/games/mod.rs

@ -59,12 +59,12 @@ impl Game {
pub fn get_card_paths(&self, image: &str) -> (std::path::PathBuf, std::path::PathBuf) { pub fn get_card_paths(&self, image: &str) -> (std::path::PathBuf, std::path::PathBuf) {
let card = &self.conf.available_cards[image]; let card = &self.conf.available_cards[image];
let mut front = self.folder.join(".cache").join(&card.image).to_path_buf(); let mut front = self.folder.join(".cache").join(&card.image);
let mut back = self.folder.join(".cache").join( let mut back = self.folder.join(".cache").join(
&card &card
.back_image .back_image
.as_ref() .as_ref()
.unwrap_or(self.conf.default_back.as_ref().unwrap()), .unwrap_or_else(|| self.conf.default_back.as_ref().unwrap()),
); );
front.set_extension("png"); front.set_extension("png");
back.set_extension("png"); back.set_extension("png");
@ -97,18 +97,14 @@ impl std::fmt::Debug for Game {
pub fn load_games() -> Vec<Game> { pub fn load_games() -> Vec<Game> {
config::setup(); config::setup();
let mut games = Vec::new(); let mut games = Vec::new();
for file in read_dir("games").unwrap() { for folder in read_dir("games").unwrap().flatten() {
if let Ok(folder) = file {
if folder.path().is_dir() { if folder.path().is_dir() {
for file in read_dir(folder.path()).unwrap() { for file in read_dir(folder.path()).unwrap().flatten() {
if let Ok(file) = file {
if file.file_name().to_str().unwrap() == "game.json" { if file.file_name().to_str().unwrap() == "game.json" {
games.push(Game::load(folder.path())) games.push(Game::load(folder.path()))
} }
} }
} }
} }
}
}
games games
} }

6
server/src/games/run.rs

@ -80,13 +80,13 @@ impl RunningGame {
.unwrap(); .unwrap();
let mut players = HashMap::new(); let mut players = HashMap::new();
for (i, player) in current_players.iter().enumerate() { for (i, player) in current_players.iter().enumerate() {
players.insert(player.clone(), i as u32); players.insert(*player, i as u32);
} }
log::info!("Players in game {}: {:?}", name, players); log::info!("Players in game {}: {:?}", name, players);
Self { Self {
name, name,
piles: piles, piles,
player_piles: player_piles, player_piles,
functions, functions,
current_player: Player::new(0, current_players.len() as u32), current_player: Player::new(0, current_players.len() as u32),
data: other, data: other,

8
server/src/games/run/engine.rs

@ -97,8 +97,8 @@ fn get_card_from_id(data: &mut Map, card: CardId) -> Result<Dynamic, Box<rhai::E
super::CardIdx::Indexed(i) => pile.cards.get(i), super::CardIdx::Indexed(i) => pile.cards.get(i),
}; };
card_maybe card_maybe
.map(|x| to_dynamic(x)) .map(to_dynamic)
.unwrap_or(Ok(Dynamic::default())) .unwrap_or_else(|| Ok(Dynamic::default()))
} }
fn pop_card_from_id(data_dyn: &mut Map, card: CardId) -> Result<Dynamic, Box<rhai::EvalAltResult>> { fn pop_card_from_id(data_dyn: &mut Map, card: CardId) -> Result<Dynamic, Box<rhai::EvalAltResult>> {
@ -116,8 +116,8 @@ fn pop_card_from_id(data_dyn: &mut Map, card: CardId) -> Result<Dynamic, Box<rha
super::CardIdx::Bottom => pile super::CardIdx::Bottom => pile
.cards .cards
.pop() .pop()
.map(|x| to_dynamic(x)) .map(to_dynamic)
.unwrap_or(Ok(Dynamic::default())), .unwrap_or_else(|| Ok(Dynamic::default())),
super::CardIdx::Indexed(i) => to_dynamic(&pile.cards.remove(i)), super::CardIdx::Indexed(i) => to_dynamic(&pile.cards.remove(i)),
}; };
dynamic = to_dynamic(&data)?; dynamic = to_dynamic(&data)?;

2
server/src/games/run/functions.rs

@ -34,8 +34,8 @@ impl Functions {
let has_turn_start = fns.contains(&"turn_start".to_string()); let has_turn_start = fns.contains(&"turn_start".to_string());
let engine = setup_engine(conf); let engine = setup_engine(conf);
Self { Self {
engine,
ast, ast,
engine,
has_turn_start, has_turn_start,
} }
} }

8
server/src/games/run/types.rs

@ -236,12 +236,6 @@ impl RunningPile {
other.insert(k, v); other.insert(k, v);
} }
Ok(Self { Ok(Self { name, cards, face_down, visible, other })
cards,
other,
face_down,
visible,
name,
})
} }
} }

8
server/src/logger.rs

@ -99,10 +99,7 @@ fn colored_formatter(d: fern::Dispatch) -> fern::Dispatch {
.debug(Color::BrightBlack) .debug(Color::BrightBlack)
// depending on the terminals color scheme, this is the same as the background color // depending on the terminals color scheme, this is the same as the background color
.trace(Color::BrightBlack); .trace(Color::BrightBlack);
let colors_level = colors_line let colors_level = colors_line.info(Color::Green).debug(Color::BrightBlack);
.clone()
.info(Color::Green)
.debug(Color::BrightBlack);
d.format( d.format(
move |out: fern::FormatCallback, message: _, record: &log::Record| { move |out: fern::FormatCallback, message: _, record: &log::Record| {
out.finish(format_args!( out.finish(format_args!(
@ -144,6 +141,7 @@ where
T: Send + 'static, T: Send + 'static,
F: Fn(String) -> T + Send + 'static, F: Fn(String) -> T + Send + 'static,
{ {
#[allow(clippy::new_ret_no_self)]
fn new( fn new(
handler: F, handler: F,
use_colors: bool, use_colors: bool,
@ -367,7 +365,7 @@ impl<T> LimitedVec<T> {
.and_then(|x| x.checked_sub(self.pos)) .and_then(|x| x.checked_sub(self.pos))
.unwrap_or(0) .unwrap_or(0)
}; };
let mut end = self.inner.len().checked_sub(self.pos).unwrap_or(0); let mut end = self.inner.len().saturating_sub(self.pos);
if end < self.inner.len() { if end < self.inner.len() {
end = self.inner.len() end = self.inner.len()
} }

12
server/src/logger/color_message.rs

@ -9,7 +9,7 @@ lazy_static! {
pub static ref ANSI_REGEX: Regex = Regex::new(ANSI_RE).unwrap(); pub static ref ANSI_REGEX: Regex = Regex::new(ANSI_RE).unwrap();
} }
pub fn print_line(message: &String, use_colors: bool, stdout: &mut std::io::Stdout) { pub fn print_line(message: &str, use_colors: bool, stdout: &mut std::io::Stdout) {
if use_colors { if use_colors {
let mut s = String::new(); let mut s = String::new();
let mut highlight = false; let mut highlight = false;
@ -26,22 +26,20 @@ pub fn print_line(message: &String, use_colors: bool, stdout: &mut std::io::Stdo
current current
); );
queue!(stdout, Print(styled)).unwrap(); queue!(stdout, Print(styled)).unwrap();
s = String::new();
} else { } else {
queue!(stdout, Print(s)).unwrap(); queue!(stdout, Print(s)).unwrap();
s = String::new();
} }
s = String::new();
highlight = !highlight; highlight = !highlight;
continue; continue;
} else { } else if !highlight {
if !highlight { if let Some(m) = ANSI_REGEX.find_at(message, i) {
if let Some(m) = ANSI_REGEX.find_at(message.as_str(), i) {
if i == m.start() { if i == m.start() {
current = m.as_str().to_string(); current = m.as_str().to_string();
} }
} }
} }
}
i += 1; i += 1;
s.push(c); s.push(c);
} }

48
server/src/server.rs

@ -103,15 +103,7 @@ pub async fn start(
// } // }
// } // }
pub async fn serve( type RunningGames = Arc<
mut pool: db::DbClient,
games: Vec<crate::games::Game>,
properties: crate::server_properties::ServerProperties,
) -> Result<(), std::io::Error> {
let properties = Arc::new(properties);
let games = Arc::new(games);
let voting = votes::VotingSystem::new(pool.clone().await);
let running_games: Arc<
RwLock< RwLock<
HashMap< HashMap<
u32, u32,
@ -122,8 +114,18 @@ pub async fn serve(
)>, )>,
>, >,
>, >,
> = Default::default(); >;
let listener = TcpListener::bind(properties.addr.clone()).await?;
pub async fn serve(
mut pool: db::DbClient,
games: Vec<crate::games::Game>,
properties: crate::server_properties::ServerProperties,
) -> Result<(), std::io::Error> {
let properties = Arc::new(properties);
let games = Arc::new(games);
let voting = votes::VotingSystem::new(pool.clone().await);
let running_games: RunningGames = Default::default();
let listener = TcpListener::bind(properties.addr).await?;
let socket_manager = Arc::new(SocketManager::new()); let socket_manager = Arc::new(SocketManager::new());
loop { loop {
let (stream, addr) = listener.accept().await?; let (stream, addr) = listener.accept().await?;
@ -205,9 +207,9 @@ pub async fn serve(
&mut service_data, &mut service_data,
writer writer
.take() .take()
.ok_or(anyhow::anyhow!( .ok_or_else(|| {
"Connect shouldn't be called more than once" anyhow::anyhow!("Connect shouldn't be called more than once")
)) })
.unwrap(), .unwrap(),
&socket_manager, &socket_manager,
name, name,
@ -280,18 +282,7 @@ struct ServiceData {
properties: Arc<ServerProperties>, properties: Arc<ServerProperties>,
games: Arc<Vec<crate::games::Game>>, games: Arc<Vec<crate::games::Game>>,
voting: VotingSystem, voting: VotingSystem,
running_games: Arc< running_games: RunningGames,
RwLock<
HashMap<
u32,
RwLock<(
u32,
RunningGame,
votes::Modifiable<Option<protos::game::GameStatus>>,
)>,
>,
>,
>,
addr: SocketAddr, addr: SocketAddr,
db: db::DbClient, db: db::DbClient,
} }
@ -313,12 +304,13 @@ impl UserId {
} }
pub fn get(self) -> Result<Uuid> { pub fn get(self) -> Result<Uuid> {
self.0.ok_or(anyhow::anyhow!("User should have connected")) self.0
.ok_or_else(|| anyhow::anyhow!("User should have connected"))
} }
pub fn get_ref(&self) -> Result<&Uuid> { pub fn get_ref(&self) -> Result<&Uuid> {
self.0 self.0
.as_ref() .as_ref()
.ok_or(anyhow::anyhow!("User should have connected")) .ok_or_else(|| anyhow::anyhow!("User should have connected"))
} }
} }

2
server/src/server/game.rs

@ -26,7 +26,7 @@ pub(super) async fn get_status(data: &mut ServiceData) -> Result<GameStatus> {
let game = &game_lock.1; let game = &game_lock.1;
let mut names = vec![]; let mut names = vec![];
for (uuid, id) in &game.players { for (uuid, id) in &game.players {
names.push((data.db.get_name_for_uuid(uuid.clone()).await, *id)) names.push((data.db.get_name_for_uuid(*uuid).await, *id))
} }
names.sort_by(|(_, a), (_, b)| a.cmp(b)); names.sort_by(|(_, a), (_, b)| a.cmp(b));
let names = names let names = names

8
server/src/server/protos/common.rs

@ -1,17 +1,17 @@
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct Name { pub struct Name {
#[prost(string, tag="1")] #[prost(string, tag = "1")]
pub name: ::prost::alloc::string::String, pub name: ::prost::alloc::string::String,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct LastStatusTimestamp { pub struct LastStatusTimestamp {
#[prost(message, optional, tag="1")] #[prost(message, optional, tag = "1")]
pub time: ::core::option::Option<::prost_types::Timestamp>, pub time: ::core::option::Option<::prost_types::Timestamp>,
#[prost(uint32, tag="2")] #[prost(uint32, tag = "2")]
pub lobby: u32, pub lobby: u32,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct HasNewStatus { pub struct HasNewStatus {
#[prost(bool, tag="1")] #[prost(bool, tag = "1")]
pub value: bool, pub value: bool,
} }

14
server/src/server/protos/connection.rs

@ -11,28 +11,28 @@
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct Game { pub struct Game {
#[prost(string, tag="1")] #[prost(string, tag = "1")]
pub name: ::prost::alloc::string::String, pub name: ::prost::alloc::string::String,
#[prost(string, tag="2")] #[prost(string, tag = "2")]
pub version: ::prost::alloc::string::String, pub version: ::prost::alloc::string::String,
#[prost(string, repeated, tag="3")] #[prost(string, repeated, tag = "3")]
pub authors: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, pub authors: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
#[prost(uint32, tag="4")] #[prost(uint32, tag = "4")]
pub id: u32, pub id: u32,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct UserId { pub struct UserId {
#[prost(string, tag="1")] #[prost(string, tag = "1")]
pub id: ::prost::alloc::string::String, pub id: ::prost::alloc::string::String,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct LobbyConfig { pub struct LobbyConfig {
/// repeated uint32 allowed_games = 2; /// repeated uint32 allowed_games = 2;
#[prost(bool, tag="1")] #[prost(bool, tag = "1")]
pub public: bool, pub public: bool,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct LobbyCode { pub struct LobbyCode {
#[prost(uint32, tag="1")] #[prost(uint32, tag = "1")]
pub code: u32, pub code: u32,
} }

52
server/src/server/protos/game.rs

@ -8,97 +8,97 @@
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct CardKind { pub struct CardKind {
#[prost(string, tag="1")] #[prost(string, tag = "1")]
pub kind: ::prost::alloc::string::String, pub kind: ::prost::alloc::string::String,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct Image { pub struct Image {
#[prost(bytes="vec", tag="1")] #[prost(bytes = "vec", tag = "1")]
pub face: ::prost::alloc::vec::Vec<u8>, pub face: ::prost::alloc::vec::Vec<u8>,
#[prost(bytes="vec", tag="2")] #[prost(bytes = "vec", tag = "2")]
pub back: ::prost::alloc::vec::Vec<u8>, pub back: ::prost::alloc::vec::Vec<u8>,
#[prost(string, tag="3")] #[prost(string, tag = "3")]
pub kind: ::prost::alloc::string::String, pub kind: ::prost::alloc::string::String,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct CardIndex { pub struct CardIndex {
#[prost(oneof="card_index::Pos", tags="1, 2, 3")] #[prost(oneof = "card_index::Pos", tags = "1, 2, 3")]
pub pos: ::core::option::Option<card_index::Pos>, pub pos: ::core::option::Option<card_index::Pos>,
} }
/// Nested message and enum types in `CardIndex`. /// Nested message and enum types in `CardIndex`.
pub mod card_index { pub mod card_index {
#[derive(Clone, PartialEq, ::prost::Oneof)] #[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Pos { pub enum Pos {
#[prost(uint32, tag="1")] #[prost(uint32, tag = "1")]
Index(u32), Index(u32),
#[prost(message, tag="2")] #[prost(message, tag = "2")]
Top(()), Top(()),
#[prost(message, tag="3")] #[prost(message, tag = "3")]
Bottom(()), Bottom(()),
} }
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct PileKind { pub struct PileKind {
#[prost(oneof="pile_kind::Kind", tags="1, 2")] #[prost(oneof = "pile_kind::Kind", tags = "1, 2")]
pub kind: ::core::option::Option<pile_kind::Kind>, pub kind: ::core::option::Option<pile_kind::Kind>,
} }
/// Nested message and enum types in `PileKind`. /// Nested message and enum types in `PileKind`.
pub mod pile_kind { pub mod pile_kind {
#[derive(Clone, PartialEq, ::prost::Oneof)] #[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Kind { pub enum Kind {
#[prost(uint32, tag="1")] #[prost(uint32, tag = "1")]
Owned(u32), Owned(u32),
#[prost(message, tag="2")] #[prost(message, tag = "2")]
Common(()), Common(()),
} }
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct CardId { pub struct CardId {
#[prost(message, optional, tag="1")] #[prost(message, optional, tag = "1")]
pub pile_kind: ::core::option::Option<PileKind>, pub pile_kind: ::core::option::Option<PileKind>,
#[prost(string, tag="2")] #[prost(string, tag = "2")]
pub pile_name: ::prost::alloc::string::String, pub pile_name: ::prost::alloc::string::String,
#[prost(message, optional, tag="3")] #[prost(message, optional, tag = "3")]
pub card_index: ::core::option::Option<CardIndex>, pub card_index: ::core::option::Option<CardIndex>,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct GameStatus { pub struct GameStatus {
/// {a: [""], b:[""]} /// {a: [""], b:[""]}
#[prost(message, optional, tag="1")] #[prost(message, optional, tag = "1")]
pub common_piles: ::core::option::Option<game_status::Piles>, pub common_piles: ::core::option::Option<game_status::Piles>,
/// [{...}, {...}] /// [{...}, {...}]
#[prost(message, repeated, tag="2")] #[prost(message, repeated, tag = "2")]
pub player_piles: ::prost::alloc::vec::Vec<game_status::Piles>, pub player_piles: ::prost::alloc::vec::Vec<game_status::Piles>,
#[prost(message, repeated, tag="3")] #[prost(message, repeated, tag = "3")]
pub names: ::prost::alloc::vec::Vec<super::common::Name>, pub names: ::prost::alloc::vec::Vec<super::common::Name>,
#[prost(uint32, tag="4")] #[prost(uint32, tag = "4")]
pub current_turn: u32, pub current_turn: u32,
} }
/// Nested message and enum types in `GameStatus`. /// Nested message and enum types in `GameStatus`.
pub mod game_status { pub mod game_status {
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct Card { pub struct Card {
#[prost(message, optional, tag="1")] #[prost(message, optional, tag = "1")]
pub kind: ::core::option::Option<super::CardKind>, pub kind: ::core::option::Option<super::CardKind>,
#[prost(bool, tag="2")] #[prost(bool, tag = "2")]
pub visible: bool, pub visible: bool,
#[prost(string, tag="3")] #[prost(string, tag = "3")]
pub uuid: ::prost::alloc::string::String, pub uuid: ::prost::alloc::string::String,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct Pile { pub struct Pile {
#[prost(message, repeated, tag="1")] #[prost(message, repeated, tag = "1")]
pub cards: ::prost::alloc::vec::Vec<Card>, pub cards: ::prost::alloc::vec::Vec<Card>,
#[prost(bool, tag="2")] #[prost(bool, tag = "2")]
pub face_down: bool, pub face_down: bool,
#[prost(bool, tag="3")] #[prost(bool, tag = "3")]
pub visible: bool, pub visible: bool,
#[prost(string, tag="4")] #[prost(string, tag = "4")]
pub name: ::prost::alloc::string::String, pub name: ::prost::alloc::string::String,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct Piles { pub struct Piles {
#[prost(map="string, message", tag="1")] #[prost(map = "string, message", tag = "1")]
pub piles: ::std::collections::HashMap<::prost::alloc::string::String, Pile>, pub piles: ::std::collections::HashMap<::prost::alloc::string::String, Pile>,
} }
} }

14
server/src/server/protos/lobby.rs

@ -10,24 +10,24 @@
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct Vote { pub struct Vote {
#[prost(string, tag="1")] #[prost(string, tag = "1")]
pub player: ::prost::alloc::string::String, pub player: ::prost::alloc::string::String,
#[prost(uint32, tag="2")] #[prost(uint32, tag = "2")]
pub game: u32, pub game: u32,
#[prost(bool, tag="3")] #[prost(bool, tag = "3")]
pub ready: bool, pub ready: bool,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct SingleVote { pub struct SingleVote {
#[prost(uint32, tag="2")] #[prost(uint32, tag = "2")]
pub game: u32, pub game: u32,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct LobbyStatus { pub struct LobbyStatus {
#[prost(message, repeated, tag="1")] #[prost(message, repeated, tag = "1")]
pub names: ::prost::alloc::vec::Vec<super::common::Name>, pub names: ::prost::alloc::vec::Vec<super::common::Name>,
#[prost(message, repeated, tag="2")] #[prost(message, repeated, tag = "2")]
pub votes: ::prost::alloc::vec::Vec<Vote>, pub votes: ::prost::alloc::vec::Vec<Vote>,
#[prost(bool, tag="3")] #[prost(bool, tag = "3")]
pub is_starting: bool, pub is_starting: bool,
} }

62
server/src/server/protos/protocol.rs

@ -1,6 +1,9 @@
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct ClientServerPacket { pub struct ClientServerPacket {
#[prost(oneof="client_server_packet::Data", tags="1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14")] #[prost(
oneof = "client_server_packet::Data",
tags = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14"
)]
pub data: ::core::option::Option<client_server_packet::Data>, pub data: ::core::option::Option<client_server_packet::Data>,
} }
/// Nested message and enum types in `ClientServerPacket`. /// Nested message and enum types in `ClientServerPacket`.
@ -8,41 +11,44 @@ pub mod client_server_packet {
#[derive(Clone, PartialEq, ::prost::Oneof)] #[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Data { pub enum Data {
/// CONNECTION /// CONNECTION
#[prost(message, tag="1")] #[prost(message, tag = "1")]
QueryName(()), QueryName(()),
#[prost(message, tag="2")] #[prost(message, tag = "2")]
Connect(super::super::common::Name), Connect(super::super::common::Name),
#[prost(message, tag="3")] #[prost(message, tag = "3")]
Disconnect(()), Disconnect(()),
#[prost(message, tag="4")] #[prost(message, tag = "4")]
JoinLobby(super::super::connection::LobbyCode), JoinLobby(super::super::connection::LobbyCode),
#[prost(message, tag="5")] #[prost(message, tag = "5")]
CreateLobby(super::super::connection::LobbyConfig), CreateLobby(super::super::connection::LobbyConfig),
#[prost(message, tag="6")] #[prost(message, tag = "6")]
QueryGames(()), QueryGames(()),
#[prost(message, tag="7")] #[prost(message, tag = "7")]
QueryPublicLobbies(()), QueryPublicLobbies(()),
/// LOBBY /// LOBBY
#[prost(message, tag="8")] #[prost(message, tag = "8")]
QueryUsers(()), QueryUsers(()),
#[prost(message, tag="9")] #[prost(message, tag = "9")]
Vote(super::super::lobby::SingleVote), Vote(super::super::lobby::SingleVote),
#[prost(message, tag="10")] #[prost(message, tag = "10")]
Ready(()), Ready(()),
#[prost(message, tag="11")] #[prost(message, tag = "11")]
Leave(()), Leave(()),
/// GAME /// GAME
#[prost(message, tag="12")] #[prost(message, tag = "12")]
QueryCardImage(super::super::game::CardKind), QueryCardImage(super::super::game::CardKind),
#[prost(message, tag="13")] #[prost(message, tag = "13")]
CallOnClick(super::super::game::CardId), CallOnClick(super::super::game::CardId),
#[prost(message, tag="14")] #[prost(message, tag = "14")]
QueryGameStatus(()), QueryGameStatus(()),
} }
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct ServerClientPacket { pub struct ServerClientPacket {
#[prost(oneof="server_client_packet::Data", tags="1, 2, 3, 4, 5, 6, 7, 8, 9")] #[prost(
oneof = "server_client_packet::Data",
tags = "1, 2, 3, 4, 5, 6, 7, 8, 9"
)]
pub data: ::core::option::Option<server_client_packet::Data>, pub data: ::core::option::Option<server_client_packet::Data>,
} }
/// Nested message and enum types in `ServerClientPacket`. /// Nested message and enum types in `ServerClientPacket`.
@ -50,40 +56,40 @@ pub mod server_client_packet {
#[derive(Clone, PartialEq, ::prost::Oneof)] #[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Data { pub enum Data {
/// CONNECTION /// CONNECTION
#[prost(message, tag="1")] #[prost(message, tag = "1")]
ReturnName(super::super::common::Name), ReturnName(super::super::common::Name),
#[prost(message, tag="2")] #[prost(message, tag = "2")]
ReturnConnect(super::super::connection::UserId), ReturnConnect(super::super::connection::UserId),
#[prost(message, tag="3")] #[prost(message, tag = "3")]
ReturnCreateLobby(super::super::connection::LobbyCode), ReturnCreateLobby(super::super::connection::LobbyCode),
#[prost(message, tag="4")] #[prost(message, tag = "4")]
ReturnGames(super::Games), ReturnGames(super::Games),
#[prost(message, tag="5")] #[prost(message, tag = "5")]
ReturnPublicLobbies(super::LobbyCodes), ReturnPublicLobbies(super::LobbyCodes),
/// LOBBY /// LOBBY
#[prost(message, tag="6")] #[prost(message, tag = "6")]
ReturnUsers(super::Names), ReturnUsers(super::Names),
#[prost(message, tag="7")] #[prost(message, tag = "7")]
LobbyStatus(super::super::lobby::LobbyStatus), LobbyStatus(super::super::lobby::LobbyStatus),
/// GAME /// GAME
#[prost(message, tag="8")] #[prost(message, tag = "8")]
ReturnCardImage(super::super::game::Image), ReturnCardImage(super::super::game::Image),
#[prost(message, tag="9")] #[prost(message, tag = "9")]
GameStatus(super::super::game::GameStatus), GameStatus(super::super::game::GameStatus),
} }
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct Games { pub struct Games {
#[prost(message, repeated, tag="1")] #[prost(message, repeated, tag = "1")]
pub games: ::prost::alloc::vec::Vec<super::connection::Game>, pub games: ::prost::alloc::vec::Vec<super::connection::Game>,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct LobbyCodes { pub struct LobbyCodes {
#[prost(message, repeated, tag="1")] #[prost(message, repeated, tag = "1")]
pub lobby_codes: ::prost::alloc::vec::Vec<super::connection::LobbyCode>, pub lobby_codes: ::prost::alloc::vec::Vec<super::connection::LobbyCode>,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct Names { pub struct Names {
#[prost(message, repeated, tag="1")] #[prost(message, repeated, tag = "1")]
pub names: ::prost::alloc::vec::Vec<super::common::Name>, pub names: ::prost::alloc::vec::Vec<super::common::Name>,
} }

2
server/src/server/socket_manager.rs

@ -74,7 +74,7 @@ impl SocketManager {
{ {
let mut lock = lock let mut lock = lock
.get(uuid) .get(uuid)
.ok_or(anyhow!("Can't get socket with uuid {}", uuid))? .ok_or_else(|| anyhow!("Can't get socket with uuid {}", uuid))?
.write() .write()
.await; .await;
lock.write(message).await?; lock.write(message).await?;

4
server/src/server/votes.rs

@ -44,13 +44,14 @@ impl<T> Modifiable<T> {
} }
const STATUS_TIMEOUT: Duration = Duration::from_secs(120); const STATUS_TIMEOUT: Duration = Duration::from_secs(120);
type LastStatus = Arc<RwLock<HashMap<u32, Arc<RwLock<Modifiable<(Message, Option<SystemTime>)>>>>>>;
#[derive(Clone)] #[derive(Clone)]
pub struct VotingSystem { pub struct VotingSystem {
conn: Arc<RwLock<db::DbClient>>, conn: Arc<RwLock<db::DbClient>>,
// games: Arc<Vec<crate::games::Game>>, // games: Arc<Vec<crate::games::Game>>,
// broadcast: broadcast::Sender<Message>, // broadcast: broadcast::Sender<Message>,
last_status: Arc<RwLock<HashMap<u32, Arc<RwLock<Modifiable<(Message, Option<SystemTime>)>>>>>>, last_status: LastStatus,
} }
impl VotingSystem { impl VotingSystem {
@ -80,6 +81,7 @@ impl VotingSystem {
timeout: Option<SystemTime>, timeout: Option<SystemTime>,
) { ) {
let mut lock = self.last_status.write().await; let mut lock = self.last_status.write().await;
#[allow(clippy::map_entry)]
if lock.contains_key(&lobby) { if lock.contains_key(&lobby) {
lock.get(&lobby) lock.get(&lobby)
.unwrap() .unwrap()

4
server/src/server_properties.rs

@ -11,8 +11,8 @@ pub struct ServerProperties {
pub addr: SocketAddr, pub addr: SocketAddr,
#[serde(default = "default_colors")] #[serde(default = "default_colors")]
pub use_colors: bool, pub use_colors: bool,
#[serde(alias="$schema", default = "default_schema")] #[serde(alias = "$schema", default = "default_schema")]
schema: String schema: String,
} }
impl ServerProperties { impl ServerProperties {

Loading…
Cancel
Save