Skip to content

Commit

Permalink
Merge pull request #26 from Holo-Host/new-endpoint-208-b
Browse files Browse the repository at this point in the history
Endpoint 208 - /holoport/usage
  • Loading branch information
peeech authored Jun 20, 2024
2 parents d502d98 + ca221fa commit e1aab7e
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ pub async fn rocket() -> Rocket<Build> {
.mount(
"/holoport",
routes![
usage, // TODO!!
usage, // done
],
)
}
4 changes: 2 additions & 2 deletions src/routes/apps/hosted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use holofuel_types::fuel::Fuel;
use log::warn;
use std::{fmt, str::FromStr, time::Duration};

///
///
#[get("/hosted?<usage_interval>&<quantity>")]
pub async fn get_all(
usage_interval: i64,
Expand Down Expand Up @@ -200,7 +200,7 @@ impl Default for Earnings {
}
}

#[derive(Serialize, Deserialize, Debug, Clone, SerializedBytes)]
#[derive(Serialize, Deserialize, Debug, Clone, SerializedBytes, Default)]
#[serde(crate = "rocket::serde")]
pub struct HappStats {
// we can return this is you want to return all source_chain that were running on this holoport
Expand Down
69 changes: 64 additions & 5 deletions src/routes/holoport/usage.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,75 @@
use anyhow::Result;
use rocket::{
http::Status,
serde::json::Json,
serde::{json::Json, Deserialize, Serialize},
{get, State},
};

use crate::hpos::WsMutex;
use crate::hpos::{Ws, WsMutex};

/// Returns list of all host invoices as needed for the host-console-ui invoice page
/// -- includes optional invoice_set {all, unpaid, paid} param to allow querying the invoices by their status
#[get("/usage")]
pub async fn usage(wsm: &State<WsMutex>) -> Result<Json<()>, (Status, String)> {
#[get("/usage?<usage_interval>")]
pub async fn usage(
wsm: &State<WsMutex>,
usage_interval: i64,
) -> Result<Json<UsageResponse>, (Status, String)> {
let mut ws = wsm.lock().await;

Ok(Json(()))
Ok(Json(handle_usage(&mut ws, usage_interval).await.map_err(
|e| (Status::InternalServerError, e.to_string()),
)?))
}

async fn handle_usage(ws: &mut Ws, usage_interval: i64) -> Result<UsageResponse> {
let all_hosted_happs =
crate::handlers::hosted_happs::handle_get_all(usage_interval, None, ws).await?;

Ok(all_hosted_happs
.into_iter()
.fold(UsageResponse::default(), |acc, happ| {
if !happ.enabled {
// is this logic right? Isn't it possible for a happ to have some usage but now be disabled?
return acc;
}

let UsageResponse {
total_hosted_agents,
current_total_storage,
total_hosted_happs,
total_usage,
} = acc;

let TotalUsage { cpu, bandwidth } = total_usage;

let happ_usage = happ.usage.unwrap_or_default();

UsageResponse {
total_hosted_agents: total_hosted_agents + happ.source_chains.unwrap_or_default(),
current_total_storage: current_total_storage + happ_usage.disk_usage,
total_hosted_happs: total_hosted_happs + 1,
total_usage: TotalUsage {
cpu: cpu + happ_usage.cpu,
bandwidth: bandwidth + happ_usage.bandwidth,
},
}
}))
}

#[derive(Serialize, Deserialize, Default)]
#[serde(crate = "rocket::serde")]
#[serde(rename_all = "camelCase")]
pub struct UsageResponse {
total_hosted_agents: u16,
current_total_storage: u64,
total_hosted_happs: u16,
total_usage: TotalUsage,
}

#[derive(Serialize, Deserialize, Default)]
#[serde(crate = "rocket::serde")]
#[serde(rename_all = "camelCase")]
pub struct TotalUsage {
cpu: u64,
bandwidth: u64,
}
10 changes: 10 additions & 0 deletions tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,4 +263,14 @@ async fn install_components() {
let response_body = response.into_string().await.unwrap();
debug!("body: {:#?}", response_body);
assert_eq!(response_body, "[]");

// get usage report
let path = format!("/holoport/usage?usage_interval=5");
info!("calling {}", &path);
let response = client.get(path).dispatch().await;
debug!("status: {}", response.status());
assert_eq!(response.status(), Status::Ok);
let response_body = response.into_string().await.unwrap();
debug!("body: {:#?}", response_body);
assert_eq!(response_body, "{\"totalHostedAgents\":0,\"currentTotalStorage\":0,\"totalHostedHapps\":1,\"totalUsage\":{\"cpu\":108,\"bandwidth\":108}}");
}

0 comments on commit e1aab7e

Please sign in to comment.