-
Notifications
You must be signed in to change notification settings - Fork 2
feat: implement redis caching actor #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from 3 commits
7a13df6
a915c49
dd4e78a
40bc5cb
9125dd0
fe1638f
190ad90
43f1268
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -23,3 +23,4 @@ listenfd = "0.3" | |
| failure = "0.1" | ||
| futures = "0.1" | ||
| url = "1.7" | ||
| redis = "0.24.0" | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,10 @@ | ||
| pub mod client_ws_actor; | ||
| pub mod game_actor; | ||
| pub mod redis_actor; | ||
|
|
||
| pub use client_ws_actor::ClientWsActor; | ||
| pub use game_actor::GameActor; | ||
|
|
||
| pub mod room_manager_actor; | ||
| pub use room_manager_actor::{CreateRoom, JoinRoom, ListRooms, RoomManagerActor}; | ||
| pub use redis_actor::RedisActor; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| use std::collections::HashMap; | ||
|
|
||
| use actix::prelude::*; | ||
| use redis::{Client, Commands, Connection}; | ||
|
|
||
| use crate::models::messages::{SetScoreboardCommand, GetScoreboardCommand}; | ||
|
|
||
| #[derive(Debug)] | ||
| pub struct RedisActor { | ||
| client: Client, | ||
| } | ||
|
|
||
| impl RedisActor { | ||
|
haongo138 marked this conversation as resolved.
Outdated
|
||
| pub fn new(redis_url: String) -> RedisActor { | ||
| let client = Client::open(redis_url).expect("Failed to create Redis client"); | ||
| RedisActor { client } | ||
| } | ||
| } | ||
|
|
||
| impl Actor for RedisActor { | ||
| type Context = Context<Self>; | ||
| } | ||
|
|
||
| impl Handler<SetScoreboardCommand> for RedisActor { | ||
| type Result = Result<(), redis::RedisError>; | ||
|
|
||
| fn handle(&mut self, msg: SetScoreboardCommand, _: &mut Self::Context) -> Self::Result { | ||
| let mut con: Connection = self.client.get_connection()?; | ||
| let query_key = format!("room:{}:scoreboard", msg.room_token); | ||
| for (player_id, points) in &msg.scoreboard { | ||
| con.zadd(query_key.clone(), *points as f64, *player_id)?; | ||
| } | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| impl Handler<GetScoreboardCommand> for RedisActor { | ||
| type Result = Result<HashMap<u32, u32>, redis::RedisError>; | ||
|
|
||
| fn handle(&mut self, msg: GetScoreboardCommand, _: &mut Self::Context) -> Self::Result { | ||
| let mut con: Connection = self.client.get_connection()?; | ||
| let query_key = format!("room:{}:scoreboard", msg.0); | ||
| let scoreboard: Vec<(String, String)> = con.zrevrange_withscores(query_key, 0, -1)?; | ||
| let mut result = HashMap::new(); | ||
| for (total_points_str, player_id_str) in scoreboard { | ||
| let player_id = player_id_str.parse::<u32>().unwrap_or_default(); | ||
| let total_points = total_points_str.parse::<f64>().unwrap_or_default() as u32; | ||
| result.insert(player_id, total_points); | ||
| } | ||
|
|
||
| Ok(result) | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,9 +1,9 @@ | ||
| use crate::{ | ||
| actors::{ClientWsActor, CreateRoom, JoinRoom, ListRooms}, | ||
| models::messages::ServerCommand, | ||
| models::messages::{GetScoreboardCommand, ServerCommand}, | ||
| AppState, | ||
| }; | ||
| use actix_web::{http::StatusCode, HttpRequest, Query, State}; | ||
| use actix_web::{http::StatusCode, HttpRequest, Path, Query, State}; | ||
| use futures::Future; | ||
|
|
||
| #[derive(Debug, Deserialize)] | ||
|
|
@@ -13,6 +13,17 @@ pub struct QueryString { | |
| name: String, | ||
| } | ||
|
|
||
| #[derive(Serialize, Deserialize)] | ||
| struct ScoreboardEntry { | ||
| player_id: u32, | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we expose more data? how about name, sth like that. We can't show the data just the id
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks, I just pushed my refactor to include more info ( |
||
| total_points: u32, | ||
| } | ||
|
|
||
| #[derive(Serialize, Deserialize)] | ||
| struct ScoreboardResponse { | ||
| scoreboard: Vec<ScoreboardEntry>, | ||
| } | ||
|
|
||
| pub fn socket_handler( | ||
| (req, state, query): (HttpRequest<AppState>, State<AppState>, Query<QueryString>), | ||
| ) -> Result<actix_web::HttpResponse, actix_web::Error> { | ||
|
|
@@ -107,3 +118,26 @@ pub fn list_rooms_handler( | |
| Err(_) => Err(actix_web::error::ErrorBadRequest("Failed to list rooms")), | ||
| } | ||
| } | ||
|
|
||
| pub fn get_room_scoreboard( | ||
| (_req, state, path): (HttpRequest<AppState>, State<AppState>, Path<String>), | ||
| ) -> Result<actix_web::HttpResponse, actix_web::Error> { | ||
| let room_token = path.into_inner(); | ||
| let result = state.redis_actor_addr.send(GetScoreboardCommand(room_token)).wait().unwrap(); | ||
| match result { | ||
| Ok(scoreboard) => { | ||
| let scoreboard_response: ScoreboardResponse = ScoreboardResponse { | ||
| scoreboard: scoreboard | ||
| .into_iter() | ||
| .map(|(player_id, total_points)| ScoreboardEntry { player_id, total_points }) | ||
| .collect(), | ||
| }; | ||
| let body = serde_json::to_string(&scoreboard_response)?; | ||
| Ok(actix_web::HttpResponse::with_body(StatusCode::OK, body)) | ||
| }, | ||
| Err(e) => Err(actix_web::error::ErrorBadRequest(format!( | ||
| "Failed to get room's scoreboard: {}", | ||
| e | ||
| ))), | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.