dev-ops/fix-build-warnings

This commit is contained in:
Thilo Behnke
2022-06-16 14:45:42 +02:00
parent e44fd92bc5
commit daeb7312d4
16 changed files with 95 additions and 100 deletions

View File

@@ -1,10 +1,7 @@
pub mod collision {
use crate::game_object::game_object::GameObject;
use crate::geom::geom::Vector;
use crate::utils::utils::{Logger, LoggerFactory};
use std::alloc::handle_alloc_error;
use std::any::Any;
use std::cell::{Ref, RefCell, RefMut};
use std::cell::{RefCell};
use std::collections::HashMap;
use std::fmt::Debug;
use std::rc::Rc;
@@ -34,6 +31,7 @@ pub mod collision {
pub struct CollisionDetector {
config: CollisionDetectorConfig,
#[allow(dead_code)]
logger: Box<dyn Logger>,
}

View File

@@ -36,7 +36,7 @@ pub mod event {
pub struct NoopEventWriterImpl {}
impl EventWriterImpl for NoopEventWriterImpl {
fn write(&mut self, event: Event) -> Result<(), String> {
fn write(&mut self, _event: Event) -> Result<(), String> {
todo!()
}
}

View File

@@ -1,23 +1,20 @@
use std::cell::{RefCell};
use std::rc::Rc;
use crate::collision::collision::{
Collision, CollisionDetector, CollisionGroup, CollisionHandler, CollisionRegistry, Collisions,
CollisionDetector, CollisionGroup, CollisionHandler, CollisionRegistry, Collisions,
};
use crate::event::event::Event;
use crate::game_object::components::{DefaultGeomComp, DefaultPhysicsComp};
use crate::game_object::game_object::{DefaultGameObject, GameObject};
use crate::geom::geom::Vector;
use crate::geom::shape::{Shape, ShapeType};
use crate::geom::shape::{Shape};
use crate::pong::pong_collisions::{
handle_ball_bounds_collision, handle_player_ball_collision, handle_player_bound_collision,
};
use crate::pong::pong_events::{
DefaultPongEventWriter, GameObjUpdate, NoopPongEventWriter, PongEventType, PongEventWriter,
GameObjUpdate, NoopPongEventWriter, PongEventType, PongEventWriter,
};
use crate::utils::utils::{DefaultLoggerFactory, Logger, LoggerFactory, NoopLogger};
use std::borrow::{Borrow, BorrowMut};
use std::cell::{Cell, Ref, RefCell, RefMut};
use std::collections::HashMap;
use std::ops::Deref;
use std::rc::Rc;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InputType {
@@ -194,13 +191,16 @@ impl Field {
{
for obj in self.objs.iter().filter(|o| RefCell::borrow(o).is_dirty()) {
let mut obj = RefCell::borrow_mut(obj);
self.event_writer
let event_write_res = self.event_writer
.write(PongEventType::GameObjUpdate(GameObjUpdate {
obj_id: &obj.id().to_string(),
vel: obj.vel(),
orientation: obj.orientation(),
pos: obj.pos(),
}));
if let Err(e) = event_write_res {
self.logger.log(&*format!("Failed to write event logs: {}", e))
}
obj.set_dirty(false);
}
}

View File

@@ -1,7 +1,7 @@
pub mod game_object {
use crate::game_object::components::{GeomComp, PhysicsComp};
use crate::geom::geom::{BoundingBox, Vector};
use crate::geom::shape::{Shape, ShapeType};
use crate::geom::shape::{ShapeType};
use std::fmt::Debug;
pub trait GameObject: Debug {
@@ -124,7 +124,7 @@ pub mod game_object {
pub mod components {
use crate::geom::geom::{BoundingBox, Vector};
use crate::geom::shape::{
get_bounding_box, get_center, get_center_mut, get_orientation, get_orientation_mut, Shape,
get_bounding_box, get_center, get_center_mut, get_orientation, get_orientation_mut,
ShapeType,
};
use std::fmt::Debug;

View File

@@ -295,18 +295,22 @@ pub mod shape {
)
}
#[allow(dead_code)]
fn center(&self) -> &Vector {
&self.center
}
#[allow(dead_code)]
fn center_mut(&mut self) -> &mut Vector {
&mut self.center
}
#[allow(dead_code)]
fn orientation(&self) -> &Vector {
&self.orientation
}
#[allow(dead_code)]
fn orientation_mut(&mut self) -> &mut Vector {
&mut self.orientation
}

View File

@@ -2,8 +2,7 @@ pub mod pong_collisions {
use crate::game_object::game_object::GameObject;
use crate::geom::geom::Vector;
use crate::geom::shape::ShapeType;
use std::cell::{RefCell, RefMut};
use std::ops::Add;
use std::cell::{RefCell};
use std::rc::Rc;
pub fn handle_player_ball_collision(
@@ -70,7 +69,7 @@ pub mod pong_collisions {
ShapeType::Circle(_, radius) => radius,
};
let mut perpendicular = player_orientation.get_opposing_orthogonal(bound.orientation());
perpendicular.y *= (height + 1.);
perpendicular.y *= height + 1.;
let mut new_pos = bound.pos().clone();
new_pos.add(&perpendicular);
let player_pos = player.pos_mut();
@@ -84,7 +83,6 @@ pub mod pong_events {
use crate::event::event::{Event, EventWriter};
use crate::geom::geom::Vector;
use serde::Serialize;
use serde_json::json;
#[derive(Serialize)]
pub enum PongEventType<'a> {

View File

@@ -40,14 +40,8 @@ pub mod utils {
Box::new(self.clone())
}
fn set_name(&mut self, name: &str) {}
fn set_name(&mut self, _name: &str) {}
fn log(&self, msg: &str) {}
}
impl NoopLogger {
fn new() -> Box<dyn Logger> {
Box::new(NoopLogger {})
}
fn log(&self, _msg: &str) {}
}
}

View File

@@ -83,11 +83,11 @@ impl MockGameObject {
impl GameObject for MockGameObject {
fn id(&self) -> u16 {
self.id
todo!()
}
fn obj_type(&self) -> &str {
&*self.obj_type
todo!()
}
fn shape(&self) -> &ShapeType {
@@ -115,7 +115,7 @@ impl GameObject for MockGameObject {
}
fn bounding_box(&self) -> BoundingBox {
self.bounding_box.clone()
todo!()
}
fn vel(&self) -> &Vector {
@@ -129,4 +129,12 @@ impl GameObject for MockGameObject {
fn is_static(&self) -> bool {
todo!()
}
fn is_dirty(&self) -> bool {
todo!()
}
fn set_dirty(&mut self, is_dirty: bool) {
todo!()
}
}

View File

@@ -12,8 +12,9 @@ mod game_field_tests {
let inputs = vec![Input {
input: InputType::UP,
obj_id: 1,
player: 1
}];
field.tick(inputs);
field.tick(inputs, 1_000.);
let player = RefCell::borrow(
field
.objs()
@@ -32,8 +33,9 @@ mod game_field_tests {
let inputs = vec![Input {
input: InputType::DOWN,
obj_id: 1,
player: 1
}];
field.tick(inputs);
field.tick(inputs, 1_000.);
let objs = field.objs();
let player = objs
.iter()

View File

@@ -6,6 +6,8 @@ use pong::utils::utils::{DefaultLoggerFactory, NoopLogger};
use rstest::rstest;
use std::cell::RefCell;
use std::rc::Rc;
use pong::event::event::EventWriter;
use pong::pong::pong_events::NoopPongEventWriter;
#[rstest]
#[case(
@@ -53,7 +55,8 @@ pub fn should_correctly_handle_player_bounds_collision(
fn create_player(id: u16, x: u16, y: u16, orientation: Vector) -> Rc<RefCell<Box<dyn GameObject>>> {
let logger = DefaultLoggerFactory::noop();
let field = Field::new(logger);
let event_writer = NoopPongEventWriter::new();
let field = Field::new(logger, event_writer);
let mut player = DefaultGameObject::player(id, x, y, &field);
let player_orientation = player.orientation_mut();
player_orientation.x = orientation.x;
@@ -63,7 +66,8 @@ fn create_player(id: u16, x: u16, y: u16, orientation: Vector) -> Rc<RefCell<Box
fn get_bound(bound: Bound) -> Rc<RefCell<Box<dyn GameObject>>> {
let logger = DefaultLoggerFactory::noop();
let field = Field::new(logger);
let event_writer = NoopPongEventWriter::new();
let field = Field::new(logger, event_writer);
let bounds = DefaultGameObject::bounds(field.width, field.height);
return Rc::new(RefCell::new(
bounds.into_iter().find(|b| b.0 == bound).unwrap().inner(),

View File

@@ -1,5 +1,3 @@
use std::ptr::hash;
pub struct Hasher {}
impl Hasher {
pub fn hash(n: u16) -> String {

View File

@@ -1,30 +1,24 @@
use crate::kafka::{KafkaEventReaderImpl, KafkaSessionEventWriterImpl};
use crate::player::Player;
use crate::session::{Session, SessionManager};
use crate::utils::http_utils::{get_query_params, read_json_body};
use crate::utils::time_utils::now;
use futures::{sink::SinkExt, stream::StreamExt};
use hyper::server::conn::AddrStream;
use hyper::service::{make_service_fn, service_fn};
use hyper::{body, Body, Method, Request, Response, Server, StatusCode};
use hyper_tungstenite::tungstenite::{Error, Message};
use hyper_tungstenite::{tungstenite, HyperWebsocket};
use kafka::producer::Producer;
use pong::event::event::{Event, EventReader, EventWriter};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::convert::Infallible;
use std::fs::read;
use std::io::ErrorKind::NotFound;
use std::net::SocketAddr;
use std::str::FromStr;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use tokio::io::Sink;
use std::time::{Duration};
use futures::{sink::SinkExt, stream::StreamExt};
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use hyper::server::conn::AddrStream;
use hyper::service::{make_service_fn, service_fn};
use hyper_tungstenite::{HyperWebsocket};
use hyper_tungstenite::tungstenite::{Error, Message};
use serde::{Deserialize, Serialize};
use serde_json::json;
use tokio::sync::Mutex;
use tokio::task;
use tokio::time::sleep;
use crate::player::Player;
use crate::session::{Session, SessionManager};
use crate::utils::http_utils::{get_query_params, read_json_body};
pub struct HttpServer {
addr: [u8; 4],
port: u16,
@@ -42,11 +36,11 @@ impl HttpServer {
pub async fn run(self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let make_svc = make_service_fn(|socket: &AddrStream| {
let mut session_manager = Arc::clone(&self.session_manager);
let session_manager = Arc::clone(&self.session_manager);
let addr = socket.remote_addr();
async move {
Ok::<_, Infallible>(service_fn(move |req: Request<Body>| {
let mut session_manager = Arc::clone(&session_manager);
let session_manager = Arc::clone(&session_manager);
async move {
if hyper_tungstenite::is_upgrade_request(&req) {
println!(
@@ -131,7 +125,7 @@ async fn serve_websocket(
websocket: HyperWebsocket,
session_manager: Arc<Mutex<SessionManager>>,
) -> Result<(), Error> {
let mut websocket = websocket.await?;
let websocket = websocket.await?;
let (mut websocket_writer, mut websocket_reader) = websocket.split();
let session_manager = session_manager.lock().await;
@@ -282,7 +276,7 @@ async fn handle_get_session(
session_manager: &Arc<Mutex<SessionManager>>,
req: Request<Body>,
) -> Result<Response<Body>, Infallible> {
let mut locked = session_manager.lock().await;
let locked = session_manager.lock().await;
let query_params = get_query_params(&req);
let session_id = query_params.get("session_id");
if let None = session_id {
@@ -351,7 +345,7 @@ async fn handle_event_write(
session_manager: &Arc<Mutex<SessionManager>>,
mut req: Request<Body>,
) -> Result<Response<Body>, Infallible> {
let mut locked = session_manager.lock().await;
let locked = session_manager.lock().await;
let event = read_json_body::<SessionEventWriteDTO>(&mut req).await;
let writer = locked.get_session_writer(&event.session_id);
if let Err(e) = writer {
@@ -379,7 +373,7 @@ async fn handle_event_read(
session_manager: &Arc<Mutex<SessionManager>>,
mut req: Request<Body>,
) -> Result<Response<Body>, Infallible> {
let mut locked = session_manager.lock().await;
let locked = session_manager.lock().await;
let read_payload = read_json_body::<SessionReadDTO>(&mut req).await;
let reader = locked.get_session_reader(
&read_payload.session_id,

View File

@@ -1,17 +1,15 @@
use crate::hash::Hasher;
use crate::session::Session;
use hyper::{Body, Client, Method, Request, Uri};
use kafka::client::metadata::Topic;
use kafka::client::{KafkaClient, ProduceMessage};
use kafka::consumer::{Consumer, FetchOffset, GroupOffsetStorage, MessageSet};
use kafka::producer::{DefaultPartitioner, Partitioner, Producer, Record, RequiredAcks, Topics};
use pong::event::event::{Event, EventReaderImpl, EventWriter, EventWriterImpl};
use serde::Deserialize;
use std::hash::{BuildHasher, Hash};
use std::process::ExitStatus;
use std::str::FromStr;
use std::time::Duration;
use tokio::process::Command;
use hyper::{Body, Client, Method, Request, Uri};
use kafka::client::{ProduceMessage};
use kafka::consumer::{Consumer, FetchOffset, GroupOffsetStorage, MessageSet};
use kafka::producer::{Partitioner, Producer, Record, RequiredAcks, Topics};
use serde::Deserialize;
use pong::event::event::{Event, EventReaderImpl, EventWriterImpl};
use crate::session::Session;
pub struct KafkaSessionEventWriterImpl {
producer: Producer<SessionPartitioner>,
@@ -19,7 +17,7 @@ pub struct KafkaSessionEventWriterImpl {
impl KafkaSessionEventWriterImpl {
pub fn new(host: &str) -> KafkaSessionEventWriterImpl {
println!("Connecting session_writer producer to kafka host: {}", host);
let mut producer = Producer::from_hosts(vec![host.to_owned()])
let producer = Producer::from_hosts(vec![host.to_owned()])
.with_ack_timeout(Duration::from_secs(1))
.with_required_acks(RequiredAcks::One)
.with_partitioner(SessionPartitioner {})
@@ -35,7 +33,7 @@ pub struct KafkaDefaultEventWriterImpl {
impl KafkaDefaultEventWriterImpl {
pub fn new(host: &str) -> KafkaDefaultEventWriterImpl {
println!("Connecting default producer to kafka host: {}", host);
let mut producer = Producer::from_hosts(vec![host.to_owned()])
let producer = Producer::from_hosts(vec![host.to_owned()])
.with_ack_timeout(Duration::from_secs(1))
.with_required_acks(RequiredAcks::One)
.create()
@@ -100,7 +98,7 @@ impl KafkaEventReaderImpl {
pub fn new(host: &str) -> KafkaEventReaderImpl {
println!("Connecting consumer to kafka host: {}", host);
let mut consumer = Consumer::from_hosts(vec![host.to_owned()])
let consumer = Consumer::from_hosts(vec![host.to_owned()])
.with_topic("move".to_owned())
.with_topic("status".to_owned())
.with_topic("input".to_owned())
@@ -187,7 +185,7 @@ impl KafkaSessionEventReaderImpl {
) -> Result<KafkaSessionEventReaderImpl, String> {
let partitions = [session.id as i32];
let reader = KafkaEventReaderImpl::for_partitions(host, &partitions, topics);
if let Err(e) = reader {
if let Err(_) = reader {
return Err("Failed to create kafka session event reader".to_string());
}
let reader = reader.unwrap();
@@ -220,7 +218,7 @@ impl KafkaTopicManager {
}
pub async fn add_partition(&self) -> Result<u16, String> {
let mut client = Client::new();
let client = Client::new();
let request = Request::builder()
.method(Method::POST)
.uri(Uri::from_str(&self.partition_management_endpoint).unwrap())
@@ -278,7 +276,7 @@ struct PartitionApiDTO {
pub struct SessionPartitioner {}
impl Partitioner for SessionPartitioner {
fn partition(&mut self, topics: Topics, msg: &mut ProduceMessage) {
fn partition(&mut self, _topics: Topics, msg: &mut ProduceMessage) {
match msg.key {
Some(key) => {
let key = std::str::from_utf8(key).unwrap();

View File

@@ -1,4 +1,3 @@
use hyper::{Body, Request};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]

View File

@@ -1,18 +1,13 @@
use serde::{Deserialize, Serialize};
use pong::event::event::{Event, EventReader, EventWriter};
use crate::hash::Hasher;
use crate::kafka::{
KafkaDefaultEventWriterImpl, KafkaEventReaderImpl, KafkaSessionEventReaderImpl,
KafkaDefaultEventWriterImpl, KafkaSessionEventReaderImpl,
KafkaSessionEventWriterImpl, KafkaTopicManager,
};
use crate::player::Player;
use kafka::producer::Producer;
use pong::event::event::{Event, EventReader, EventWriter};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use tokio::sync::Mutex;
pub struct SessionManager {
kafka_host: String,
@@ -51,7 +46,10 @@ impl SessionManager {
let session_hash = Hasher::hash(session_id);
let session = Session::new(session_id, session_hash, player.clone());
println!("Successfully created session: {:?}", session);
self.write_to_producer(session_created(session.clone(), player.clone()));
let write_res = self.write_to_producer(session_created(session.clone(), player.clone()));
if let Err(e) = write_res {
eprintln!("Failed to write session created event for {:?} to producer: {}", session, e);
}
self.sessions.push(session.clone());
Ok(session)
}
@@ -88,7 +86,10 @@ impl SessionManager {
session.clone()
};
{
self.write_to_producer(session_joined(updated_session.clone(), player.clone()));
let write_res = self.write_to_producer(session_joined(updated_session.clone(), player.clone()));
if let Err(e) = write_res {
eprintln!("Failed to write session joined event for {:?} to producer: {}", updated_session, e);
}
};
println!("sessions = {:?}", self.sessions);
Ok(updated_session.clone())
@@ -230,6 +231,7 @@ impl SessionWriter {
}
pub struct SessionReader {
#[allow(dead_code)]
session: Session,
reader: EventReader,
}

View File

@@ -1,11 +1,7 @@
pub mod http_utils {
use hyper::body::Buf;
use hyper::{body, Body, Request};
use serde::de::DeserializeOwned;
use serde::Deserialize;
use std::borrow::BorrowMut;
use std::collections::HashMap;
use std::io::Read;
pub fn get_query_params(req: &Request<Body>) -> HashMap<&str, &str> {
let uri = req.uri();
@@ -25,7 +21,7 @@ pub mod http_utils {
where
T: DeserializeOwned,
{
let mut body = req.body_mut();
let body = req.body_mut();
let bytes = body::to_bytes(body).await.unwrap();
let body_str = std::str::from_utf8(&*bytes).unwrap();
serde_json::from_str::<T>(body_str).unwrap()