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. 8
      server/build.rs
  2. 4
      server/src/allocator.rs
  3. 18
      server/src/command.rs
  4. 50
      server/src/db.rs
  5. 8
      server/src/games/config.rs
  6. 18
      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. 16
      server/src/logger/color_message.rs
  13. 52
      server/src/server.rs
  14. 2
      server/src/server/game.rs
  15. 16
      server/src/server/protos/common.rs
  16. 30
      server/src/server/protos/connection.rs
  17. 138
      server/src/server/protos/game.rs
  18. 28
      server/src/server/protos/lobby.rs
  19. 142
      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

8
server/build.rs

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

4
server/src/allocator.rs

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

18
server/src/command.rs

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

50
server/src/db.rs

@ -42,35 +42,33 @@ impl Db {
}
pub fn add_user(&mut self, name: String) -> Result<Uuid> {
loop {
let uuid = Uuid::new_v4();
// println!("{:?}", uuid.as_bytes().to_vec());
let res = self.conn.execute(
"INSERT INTO Users(uuid, name) VALUES(?, ?)",
params![uuid.as_bytes().to_vec(), name.to_string()],
); // Server crashes if uuids collide
if let Err(e) = res {
match e {
SqliteError::SqliteFailure(
rusqlite::ffi::Error {
code: ErrorCode::ConstraintViolation,
extended_code: _,
},
_,
) => {
log::error!("add_user db error (constraint violation): {}", e);
return Err(e.into());
}
e => {
log::error!("add_user db error: {}", e);
return Err(e.into());
}
let uuid = Uuid::new_v4();
// println!("{:?}", uuid.as_bytes().to_vec());
let res = self.conn.execute(
"INSERT INTO Users(uuid, name) VALUES(?, ?)",
params![uuid.as_bytes().to_vec(), name],
); // Server crashes if uuids collide
if let Err(e) = res {
match e {
SqliteError::SqliteFailure(
rusqlite::ffi::Error {
code: ErrorCode::ConstraintViolation,
extended_code: _,
},
_,
) => {
log::error!("add_user db error (constraint violation): {}", e);
return Err(e.into());
}
e => {
log::error!("add_user db error: {}", e);
return Err(e.into());
}
}
return Ok(uuid);
}
Ok(uuid)
}
// FIXME: return Results intead of crashing
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();
tokio::task::spawn_blocking(|| cache_image(p, folder));
}
for (
_,
for
Card {
image,
back_image,
other: _,
},
) in &self.available_cards
} in self.available_cards.values()
{
{
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());
let mut face_buf = Vec::new();
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)
.unwrap();
match std::fs::create_dir_all(cached.parent().unwrap()) {

18
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) {
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(
&card
.back_image
.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");
back.set_extension("png");
@ -97,15 +97,11 @@ impl std::fmt::Debug for Game {
pub fn load_games() -> Vec<Game> {
config::setup();
let mut games = Vec::new();
for file in read_dir("games").unwrap() {
if let Ok(folder) = file {
if folder.path().is_dir() {
for file in read_dir(folder.path()).unwrap() {
if let Ok(file) = file {
if file.file_name().to_str().unwrap() == "game.json" {
games.push(Game::load(folder.path()))
}
}
for folder in read_dir("games").unwrap().flatten() {
if folder.path().is_dir() {
for file in read_dir(folder.path()).unwrap().flatten() {
if file.file_name().to_str().unwrap() == "game.json" {
games.push(Game::load(folder.path()))
}
}
}

6
server/src/games/run.rs

@ -80,13 +80,13 @@ impl RunningGame {
.unwrap();
let mut players = HashMap::new();
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);
Self {
name,
piles: piles,
player_piles: player_piles,
piles,
player_piles,
functions,
current_player: Player::new(0, current_players.len() as u32),
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),
};
card_maybe
.map(|x| to_dynamic(x))
.unwrap_or(Ok(Dynamic::default()))
.map(to_dynamic)
.unwrap_or_else(|| Ok(Dynamic::default()))
}
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
.cards
.pop()
.map(|x| to_dynamic(x))
.unwrap_or(Ok(Dynamic::default())),
.map(to_dynamic)
.unwrap_or_else(|| Ok(Dynamic::default())),
super::CardIdx::Indexed(i) => to_dynamic(&pile.cards.remove(i)),
};
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 engine = setup_engine(conf);
Self {
engine,
ast,
engine,
has_turn_start,
}
}

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

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

8
server/src/logger.rs

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

16
server/src/logger/color_message.rs

@ -9,7 +9,7 @@ lazy_static! {
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 {
let mut s = String::new();
let mut highlight = false;
@ -26,19 +26,17 @@ pub fn print_line(message: &String, use_colors: bool, stdout: &mut std::io::Stdo
current
);
queue!(stdout, Print(styled)).unwrap();
s = String::new();
} else {
queue!(stdout, Print(s)).unwrap();
s = String::new();
}
s = String::new();
highlight = !highlight;
continue;
} else {
if !highlight {
if let Some(m) = ANSI_REGEX.find_at(message.as_str(), i) {
if i == m.start() {
current = m.as_str().to_string();
}
} else if !highlight {
if let Some(m) = ANSI_REGEX.find_at(message, i) {
if i == m.start() {
current = m.as_str().to_string();
}
}
}

52
server/src/server.rs

@ -103,6 +103,19 @@ pub async fn start(
// }
// }
type RunningGames = Arc<
RwLock<
HashMap<
u32,
RwLock<(
u32,
RunningGame,
votes::Modifiable<Option<protos::game::GameStatus>>,
)>,
>,
>,
>;
pub async fn serve(
mut pool: db::DbClient,
games: Vec<crate::games::Game>,
@ -111,19 +124,8 @@ pub async fn serve(
let properties = Arc::new(properties);
let games = Arc::new(games);
let voting = votes::VotingSystem::new(pool.clone().await);
let running_games: Arc<
RwLock<
HashMap<
u32,
RwLock<(
u32,
RunningGame,
votes::Modifiable<Option<protos::game::GameStatus>>,
)>,
>,
>,
> = Default::default();
let listener = TcpListener::bind(properties.addr.clone()).await?;
let running_games: RunningGames = Default::default();
let listener = TcpListener::bind(properties.addr).await?;
let socket_manager = Arc::new(SocketManager::new());
loop {
let (stream, addr) = listener.accept().await?;
@ -205,9 +207,9 @@ pub async fn serve(
&mut service_data,
writer
.take()
.ok_or(anyhow::anyhow!(
"Connect shouldn't be called more than once"
))
.ok_or_else(|| {
anyhow::anyhow!("Connect shouldn't be called more than once")
})
.unwrap(),
&socket_manager,
name,
@ -280,18 +282,7 @@ struct ServiceData {
properties: Arc<ServerProperties>,
games: Arc<Vec<crate::games::Game>>,
voting: VotingSystem,
running_games: Arc<
RwLock<
HashMap<
u32,
RwLock<(
u32,
RunningGame,
votes::Modifiable<Option<protos::game::GameStatus>>,
)>,
>,
>,
>,
running_games: RunningGames,
addr: SocketAddr,
db: db::DbClient,
}
@ -313,12 +304,13 @@ impl UserId {
}
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> {
self.0
.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 mut names = vec![];
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));
let names = names

16
server/src/server/protos/common.rs

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

30
server/src/server/protos/connection.rs

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

138
server/src/server/protos/game.rs

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

28
server/src/server/protos/lobby.rs

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

142
server/src/server/protos/protocol.rs

@ -1,89 +1,95 @@
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ClientServerPacket {
#[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>,
#[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>,
}
/// Nested message and enum types in `ClientServerPacket`.
pub mod client_server_packet {
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Data {
/// CONNECTION
#[prost(message, tag="1")]
QueryName(()),
#[prost(message, tag="2")]
Connect(super::super::common::Name),
#[prost(message, tag="3")]
Disconnect(()),
#[prost(message, tag="4")]
JoinLobby(super::super::connection::LobbyCode),
#[prost(message, tag="5")]
CreateLobby(super::super::connection::LobbyConfig),
#[prost(message, tag="6")]
QueryGames(()),
#[prost(message, tag="7")]
QueryPublicLobbies(()),
/// LOBBY
#[prost(message, tag="8")]
QueryUsers(()),
#[prost(message, tag="9")]
Vote(super::super::lobby::SingleVote),
#[prost(message, tag="10")]
Ready(()),
#[prost(message, tag="11")]
Leave(()),
/// GAME
#[prost(message, tag="12")]
QueryCardImage(super::super::game::CardKind),
#[prost(message, tag="13")]
CallOnClick(super::super::game::CardId),
#[prost(message, tag="14")]
QueryGameStatus(()),
}
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Data {
/// CONNECTION
#[prost(message, tag = "1")]
QueryName(()),
#[prost(message, tag = "2")]
Connect(super::super::common::Name),
#[prost(message, tag = "3")]
Disconnect(()),
#[prost(message, tag = "4")]
JoinLobby(super::super::connection::LobbyCode),
#[prost(message, tag = "5")]
CreateLobby(super::super::connection::LobbyConfig),
#[prost(message, tag = "6")]
QueryGames(()),
#[prost(message, tag = "7")]
QueryPublicLobbies(()),
/// LOBBY
#[prost(message, tag = "8")]
QueryUsers(()),
#[prost(message, tag = "9")]
Vote(super::super::lobby::SingleVote),
#[prost(message, tag = "10")]
Ready(()),
#[prost(message, tag = "11")]
Leave(()),
/// GAME
#[prost(message, tag = "12")]
QueryCardImage(super::super::game::CardKind),
#[prost(message, tag = "13")]
CallOnClick(super::super::game::CardId),
#[prost(message, tag = "14")]
QueryGameStatus(()),
}
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ServerClientPacket {
#[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>,
#[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>,
}
/// Nested message and enum types in `ServerClientPacket`.
pub mod server_client_packet {
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Data {
/// CONNECTION
#[prost(message, tag="1")]
ReturnName(super::super::common::Name),
#[prost(message, tag="2")]
ReturnConnect(super::super::connection::UserId),
#[prost(message, tag="3")]
ReturnCreateLobby(super::super::connection::LobbyCode),
#[prost(message, tag="4")]
ReturnGames(super::Games),
#[prost(message, tag="5")]
ReturnPublicLobbies(super::LobbyCodes),
/// LOBBY
#[prost(message, tag="6")]
ReturnUsers(super::Names),
#[prost(message, tag="7")]
LobbyStatus(super::super::lobby::LobbyStatus),
/// GAME
#[prost(message, tag="8")]
ReturnCardImage(super::super::game::Image),
#[prost(message, tag="9")]
GameStatus(super::super::game::GameStatus),
}
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Data {
/// CONNECTION
#[prost(message, tag = "1")]
ReturnName(super::super::common::Name),
#[prost(message, tag = "2")]
ReturnConnect(super::super::connection::UserId),
#[prost(message, tag = "3")]
ReturnCreateLobby(super::super::connection::LobbyCode),
#[prost(message, tag = "4")]
ReturnGames(super::Games),
#[prost(message, tag = "5")]
ReturnPublicLobbies(super::LobbyCodes),
/// LOBBY
#[prost(message, tag = "6")]
ReturnUsers(super::Names),
#[prost(message, tag = "7")]
LobbyStatus(super::super::lobby::LobbyStatus),
/// GAME
#[prost(message, tag = "8")]
ReturnCardImage(super::super::game::Image),
#[prost(message, tag = "9")]
GameStatus(super::super::game::GameStatus),
}
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Games {
#[prost(message, repeated, tag="1")]
pub games: ::prost::alloc::vec::Vec<super::connection::Game>,
#[prost(message, repeated, tag = "1")]
pub games: ::prost::alloc::vec::Vec<super::connection::Game>,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct LobbyCodes {
#[prost(message, repeated, tag="1")]
pub lobby_codes: ::prost::alloc::vec::Vec<super::connection::LobbyCode>,
#[prost(message, repeated, tag = "1")]
pub lobby_codes: ::prost::alloc::vec::Vec<super::connection::LobbyCode>,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Names {
#[prost(message, repeated, tag="1")]
pub names: ::prost::alloc::vec::Vec<super::common::Name>,
#[prost(message, repeated, tag = "1")]
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
.get(uuid)
.ok_or(anyhow!("Can't get socket with uuid {}", uuid))?
.ok_or_else(|| anyhow!("Can't get socket with uuid {}", uuid))?
.write()
.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);
type LastStatus = Arc<RwLock<HashMap<u32, Arc<RwLock<Modifiable<(Message, Option<SystemTime>)>>>>>>;
#[derive(Clone)]
pub struct VotingSystem {
conn: Arc<RwLock<db::DbClient>>,
// games: Arc<Vec<crate::games::Game>>,
// broadcast: broadcast::Sender<Message>,
last_status: Arc<RwLock<HashMap<u32, Arc<RwLock<Modifiable<(Message, Option<SystemTime>)>>>>>>,
last_status: LastStatus,
}
impl VotingSystem {
@ -80,6 +81,7 @@ impl VotingSystem {
timeout: Option<SystemTime>,
) {
let mut lock = self.last_status.write().await;
#[allow(clippy::map_entry)]
if lock.contains_key(&lobby) {
lock.get(&lobby)
.unwrap()

4
server/src/server_properties.rs

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

Loading…
Cancel
Save