Skip to content

Commit

Permalink
chore: use shared api types to deserialize
Browse files Browse the repository at this point in the history
  • Loading branch information
yHSJ committed Nov 26, 2024
1 parent 9c88937 commit 9446d99
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 49 deletions.
15 changes: 5 additions & 10 deletions crates/rpc/src/bin/metric_exporter/routes/game/add_player.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,17 @@
use hydra_control_plane_rpc::model::cluster::{ConnectionInfo, NodeClient};
use hydra_control_plane_rpc::model::cluster::{
shared::AddPlayerLocalResponse, ConnectionInfo, NodeClient,
};
use pallas::ledger::addresses::Address;
use rocket::{get, http::Status, serde::json::Json, State};
use serde::Serialize;
use tracing::error;

use crate::LocalState;

#[derive(Serialize)]
pub struct AddPlayerResponse {
player_state: String,
admin_pkh: String,
}

#[get("/game/add_player?<address>")]
pub async fn add_player(
address: &str,
state: &State<LocalState>,
) -> Result<Json<AddPlayerResponse>, Status> {
) -> Result<Json<AddPlayerLocalResponse>, Status> {
let pkh = match Address::from_bech32(address).map_err(|_| Status::BadRequest)? {
Address::Shelley(shelley) => Ok(*shelley.payment().as_hash()),
_ => Err(Status::BadRequest),
Expand All @@ -34,7 +29,7 @@ pub async fn add_player(
.inspect_err(|err| error!("error adding player: {}", err))
.map_err(|_| Status::InternalServerError)?;

Ok(Json(AddPlayerResponse {
Ok(Json(AddPlayerLocalResponse {
player_state: format!("{}#1", hex::encode(tx_hash)),
admin_pkh: hex::encode(client.tx_builder.admin_pkh),
}))
Expand Down
18 changes: 8 additions & 10 deletions crates/rpc/src/bin/metric_exporter/routes/game/new_game.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
use anyhow::{anyhow, Context};
use hydra_control_plane_rpc::model::cluster::{ConnectionInfo, NodeClient};
use hydra_control_plane_rpc::model::cluster::{
shared::NewGameLocalResponse, ConnectionInfo, NodeClient,
};
use pallas::ledger::addresses::Address;
use rocket::{get, serde::json::Json, State};
use rocket_errors::anyhow::Result;
use serde::Serialize;
use tracing::info;

use crate::LocalState;

#[derive(Serialize)]
pub struct NewGameResponse {
player_state: String,
admin_pkh: String,
}

#[get("/game/new_game?<address>")]
pub async fn new_game(address: &str, state: &State<LocalState>) -> Result<Json<NewGameResponse>> {
pub async fn new_game(
address: &str,
state: &State<LocalState>,
) -> Result<Json<NewGameLocalResponse>> {
info!("Creating a new game for {}", address);

let pkh = match Address::from_bech32(address).context("invalid address")? {
Expand All @@ -34,7 +32,7 @@ pub async fn new_game(address: &str, state: &State<LocalState>) -> Result<Json<N
.await
.context("error creating new game")?;

Ok(Json(NewGameResponse {
Ok(Json(NewGameLocalResponse {
player_state: format!("{}#1", hex::encode(tx_hash)),
admin_pkh: hex::encode(client.tx_builder.admin_pkh),
}))
Expand Down
28 changes: 23 additions & 5 deletions crates/rpc/src/model/cluster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use serde::Deserialize;

mod crd;
mod node;
pub mod shared;

Check failure on line 15 in crates/rpc/src/model/cluster/mod.rs

View workflow job for this annotation

GitHub Actions / build (Linux-x86_64, ubuntu-latest, x86_64-unknown-linux-gnu, --locked --release)

file not found for module `shared`

pub use crd::*;
pub use node::*;
Expand Down Expand Up @@ -68,7 +69,11 @@ impl ClusterState {
let watcher_handle = tokio::spawn(async move {
let infinite_watch = rf.applied_objects().for_each(|node| {
if let Ok(node) = node {
if node.status.as_ref().is_some_and(|n| n.game_state != "Waiting") {
if node
.status
.as_ref()
.is_some_and(|n| n.game_state != "Waiting")
{
let id = node.metadata.name.as_ref().unwrap();
let mut claims = claims.lock().unwrap();
if claims.remove(id).is_some() {
Expand All @@ -93,23 +98,36 @@ impl ClusterState {

pub fn select_node_for_new_game(&self) -> anyhow::Result<Arc<HydraDoomNode>> {
let mut claimed = self.recently_claimed.lock().unwrap();
let node = self.store
let node = self
.store
.state()
.iter()
.filter(|n| {
let id = n.metadata.name.as_ref().unwrap();
let recently_claimed = claimed.get(id).unwrap_or(&false);
info!("checking node {}, recently claimed: {}, status: {}", id, recently_claimed, n.status.as_ref().map(|s| s.game_state.as_str()).unwrap_or("unknown"));
info!(
"checking node {}, recently claimed: {}, status: {}",
id,
recently_claimed,
n.status
.as_ref()
.map(|s| s.game_state.as_str())
.unwrap_or("unknown")
);
if let Some(status) = n.status.as_ref() {
!recently_claimed && status.node_state == "HeadIsOpen" && status.game_state == "Waiting"
!recently_claimed
&& status.node_state == "HeadIsOpen"
&& status.game_state == "Waiting"
} else {
false
}
})
.max_by_key(|n| n.metadata.creation_timestamp.clone())
.cloned()
.ok_or(anyhow::anyhow!("no available nodes found"))?;
claimed.entry(node.metadata.name.clone().expect("node without a name")).or_insert(true);
claimed
.entry(node.metadata.name.clone().expect("node without a name"))
.or_insert(true);
Ok(node)
}

Expand Down
16 changes: 4 additions & 12 deletions crates/rpc/src/routes/add_player.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use std::collections::HashMap;

use rocket::{get, http::Status, serde::json::Json, State};
use serde::Serialize;

use crate::model::cluster::ClusterState;
use crate::model::cluster::{shared::AddPlayerLocalResponse, ClusterState};

#[derive(Serialize)]
pub struct AddPlayerResponse {
Expand Down Expand Up @@ -35,19 +33,13 @@ pub async fn add_player(
let response = reqwest::get(url).await.map_err(|_| Status::BadGateway)?;

let body = response
.json::<HashMap<String, String>>()
.json::<AddPlayerLocalResponse>()
.await
.map_err(|_| Status::InternalServerError)?;

Ok(Json(AddPlayerResponse {
ip: external_url,
player_state: body
.get("player_state")
.ok_or(Status::InternalServerError)?
.to_owned(),
admin_pkh: body
.get("admin_pkh")
.ok_or(Status::InternalServerError)?
.to_owned(),
player_state: body.player_state,
admin_pkh: body.admin_pkh,
}))
}
17 changes: 5 additions & 12 deletions crates/rpc/src/routes/new_game.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
use std::collections::HashMap;

use anyhow::Context;
use rocket::{get, serde::json::Json, State};
use rocket_errors::anyhow::Result;
use serde::Serialize;
use tracing::info;

use crate::model::cluster::ClusterState;
use crate::model::cluster::{shared::NewGameLocalResponse, ClusterState};

#[derive(Serialize)]
pub struct NewGameResponse {
Expand Down Expand Up @@ -41,21 +39,16 @@ pub async fn new_game(address: &str, state: &State<ClusterState>) -> Result<Json
let response = reqwest::get(url)
.await
.context("failed to hit new_game metrics server endpoint")?;

let body = response
.json::<HashMap<String, String>>()
.json::<NewGameLocalResponse>()
.await
.context("http error")?;

Ok(Json(NewGameResponse {
game_id: node_id,
ip: external_url,
player_state: body
.get("player_state")
.context("missing player_state in response")?
.to_owned(),
admin_pkh: body
.get("admin_pkh")
.context("missing admin_pkh in response")?
.to_owned(),
player_state: body.player_state,
admin_pkh: body.admin_pkh,
}))
}

0 comments on commit 9446d99

Please sign in to comment.