Skip to content

Commit

Permalink
refactor: move server api data types to its own module
Browse files Browse the repository at this point in the history
  • Loading branch information
bochaco committed Jan 22, 2025
1 parent 3bfcb87 commit 3e85559
Show file tree
Hide file tree
Showing 11 changed files with 96 additions and 85 deletions.
66 changes: 1 addition & 65 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use super::{
node_actions::NodesActionsView,
node_instance::{ContainerId, NodeInstanceInfo},
nodes_list_view::NodesListView,
server_api_types::{AppSettings, BatchInProgress, Stats},
sort_nodes::{NodesSortStrategy, SortStrategyView},
stats::AggregatedStatsView,
};
Expand All @@ -26,7 +27,6 @@ use tokio::{
time::Instant,
};

use alloy::primitives::U256;
#[cfg(feature = "hydrate")]
use gloo_timers::future::sleep;
use leptos::prelude::*;
Expand All @@ -35,7 +35,6 @@ use leptos_router::{
components::{Route, Router, Routes},
StaticSegment,
};
use serde::{Deserialize, Serialize};
use std::{
collections::{HashMap, HashSet},
time::Duration,
Expand All @@ -47,48 +46,6 @@ extern "C" {
pub async fn get_addr_from_metamask() -> JsValue;
}

// Application settings values.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct AppSettings {
pub nodes_auto_upgrade: bool,
pub nodes_auto_upgrade_delay: Duration,
pub node_bin_version_polling_freq: Duration,
pub nodes_metrics_polling_freq: Duration,
pub rewards_balances_retrieval_freq: Duration,
pub l2_network_rpc_url: String,
pub token_contract_address: String,
pub lcd_display_enabled: bool,
pub lcd_device: String,
pub lcd_addr: String,
}

impl Default for AppSettings {
fn default() -> Self {
Self {
// Node auto-upgrading is disabled by default.
nodes_auto_upgrade: false,
// Delay 10 secs. between each node being auto-upgraded.
nodes_auto_upgrade_delay: Duration::from_secs(10),
// Check latest version of node binary every couple of hours.
node_bin_version_polling_freq: Duration::from_secs(60 * 60 * 2),
// How often to fetch metrics and node info from active/running nodes
nodes_metrics_polling_freq: Duration::from_secs(5),
// Retrieve balances every 15 mins.
rewards_balances_retrieval_freq: Duration::from_secs(60 * 15),
// Arbitrum Sepolia testnet.
l2_network_rpc_url: "https://sepolia-rollup.arbitrum.io/rpc".to_string(),
// ANT token contract on Arbitrum Sepolia testnet.
token_contract_address: "0xBE1802c27C324a28aeBcd7eeC7D734246C807194".to_string(),
// External LCD device disabled.
lcd_display_enabled: false,
// I2C bus number 1, i.e. device at /dev/i2c-1.
lcd_device: "1".to_string(),
// I2C backpack address 0x27, another common addr is: 0x3f. Check it out with 'sudo ic2detect -y <bus-number>'.
lcd_addr: "0x27".to_string(),
}
}
}

// Maximum number of metrics data points to be kept per node on DB cache.
pub const METRICS_MAX_SIZE_PER_CONTAINER: usize = 5_000;
// How often we poll the backedn to retrieve an up to date list of node instances.
Expand All @@ -108,19 +65,6 @@ pub enum BgTasksCmds {
CheckAllBalances,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Stats {
pub total_balance: U256,
pub total_nodes: usize,
pub active_nodes: usize,
pub inactive_nodes: usize,
pub connected_peers: usize,
pub shunned_count: usize,
pub estimated_net_size: usize,
pub stored_records: usize,
pub relevant_records: usize,
}

#[cfg(feature = "ssr")]
#[derive(Clone, FromRef, Debug)]
pub struct ServerGlobalState {
Expand All @@ -141,14 +85,6 @@ pub struct ServerGlobalState {
pub stats: Arc<Mutex<Stats>>,
}

#[derive(Clone, Default, Serialize, Deserialize)]
pub struct BatchInProgress {
pub created: u16,
pub total: u16,
pub auto_start: bool,
pub interval_secs: u64,
}

// List of nodes which status is temporarily immutable/locked,
// along with expiration information for when it should be unlocked.
#[cfg(feature = "ssr")]
Expand Down
3 changes: 2 additions & 1 deletion src/bg_tasks.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use super::{
app::{AppSettings, BgTasksCmds, ImmutableNodeStatus, Stats, METRICS_MAX_SIZE_PER_CONTAINER},
app::{BgTasksCmds, ImmutableNodeStatus, METRICS_MAX_SIZE_PER_CONTAINER},
db_client::DbClient,
docker_client::DockerClient,
lcd::display_stats_on_lcd,
metrics_client::{NodeMetricsClient, NodesMetrics},
node_instance::NodeInstanceInfo,
server_api::helper_upgrade_node_instance,
server_api_types::{AppSettings, Stats},
};
use alloy::{
primitives::{Address, U256},
Expand Down
2 changes: 1 addition & 1 deletion src/db_client.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::{
app::AppSettings,
metrics::{Metrics, NodeMetric},
node_instance::{ContainerId, NodeInstanceInfo, NodeStatus},
server_api_types::AppSettings,
};

use alloy::primitives::U256;
Expand Down
3 changes: 1 addition & 2 deletions src/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use crate::app::BatchInProgress;

use super::{
app::ClientGlobalState,
node_instance::{ContainerId, NodeInstanceInfo},
server_api::{
create_node_instance, delete_node_instance, prepare_node_instances_batch,
start_node_logs_stream,
},
server_api_types::BatchInProgress,
};

use alloy::primitives::U256;
Expand Down
2 changes: 1 addition & 1 deletion src/lcd.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::app::{AppSettings, BgTasksCmds};
use super::{app::BgTasksCmds, server_api_types::AppSettings};

use eyre::eyre;
use i2cdev::{
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ mod node_actions;
pub mod node_instance;
mod nodes_list_view;
mod server_api;
pub mod server_api_types;
mod settings;
mod sort_nodes;
mod stats;
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ async fn main() {
use axum::Router;
use formicaio::{
app::*, bg_tasks::spawn_bg_tasks, db_client::DbClient, docker_client::DockerClient,
metrics_client::NodesMetrics,
metrics_client::NodesMetrics, server_api_types::Stats,
};
use leptos::{logging, prelude::*};
use leptos_axum::{generate_route_list, LeptosRoutes};
Expand Down
3 changes: 2 additions & 1 deletion src/nodes_list_view.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::{
app::{BatchInProgress, ClientGlobalState},
app::ClientGlobalState,
chart_view::{node_metrics_update, ChartSeriesData, NodeChartView},
helpers::{node_logs_stream, show_alert_msg, truncated_balance_str},
icons::{
Expand All @@ -9,6 +9,7 @@ use super::{
node_actions::NodeAction,
node_instance::NodeInstanceInfo,
server_api::cancel_node_instances_batch,
server_api_types::BatchInProgress,
};

use alloy::primitives::utils::format_units;
Expand Down
18 changes: 6 additions & 12 deletions src/server_api.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use super::{
app::{BatchInProgress, Stats},
node_instance::{ContainerId, NodeInstanceInfo},
server_api_types::BatchInProgress,
server_api_types::NodesInstancesInfo,
};

use self::server_fn::codec::{ByteStream, Streaming};
use leptos::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[cfg(feature = "ssr")]
Expand All @@ -24,14 +24,6 @@ use std::time::Duration;
#[cfg(feature = "ssr")]
use tokio::{select, time::sleep};

#[derive(Clone, Serialize, Deserialize)]
pub struct NodesInstancesInfo {
pub latest_bin_version: Option<String>,
pub nodes: HashMap<String, NodeInstanceInfo>,
pub stats: Stats,
pub batch_in_progress: Option<BatchInProgress>,
}

// Obtain the list of existing nodes instances with their info
#[server(ListNodeInstances, "/api", "Url", "/list_nodes")]
pub async fn nodes_instances() -> Result<NodesInstancesInfo, ServerFnError> {
Expand Down Expand Up @@ -368,7 +360,7 @@ pub async fn node_metrics(

// Retrieve the settings
#[server(GetSettings, "/api", "Url", "/get_settings")]
pub async fn get_settings() -> Result<super::app::AppSettings, ServerFnError> {
pub async fn get_settings() -> Result<super::server_api_types::AppSettings, ServerFnError> {
let context = expect_context::<ServerGlobalState>();
let settings = context.db_client.get_settings().await;

Expand All @@ -377,7 +369,9 @@ pub async fn get_settings() -> Result<super::app::AppSettings, ServerFnError> {

// Update the settings
#[server(UpdateSettings, "/api", "Url", "/update_settings")]
pub async fn update_settings(settings: super::app::AppSettings) -> Result<(), ServerFnError> {
pub async fn update_settings(
settings: super::server_api_types::AppSettings,
) -> Result<(), ServerFnError> {
let context = expect_context::<ServerGlobalState>();
context.db_client.update_settings(&settings).await?;
context
Expand Down
79 changes: 79 additions & 0 deletions src/server_api_types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
use super::node_instance::NodeInstanceInfo;

use alloy::primitives::U256;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, time::Duration};

/// List of nodes, stats and currently running batch.
#[derive(Clone, Serialize, Deserialize)]
pub struct NodesInstancesInfo {
pub latest_bin_version: Option<String>,
pub nodes: HashMap<String, NodeInstanceInfo>,
pub stats: Stats,
pub batch_in_progress: Option<BatchInProgress>,
}

/// Application settings values.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct AppSettings {
pub nodes_auto_upgrade: bool,
pub nodes_auto_upgrade_delay: Duration,
pub node_bin_version_polling_freq: Duration,
pub nodes_metrics_polling_freq: Duration,
pub rewards_balances_retrieval_freq: Duration,
pub l2_network_rpc_url: String,
pub token_contract_address: String,
pub lcd_display_enabled: bool,
pub lcd_device: String,
pub lcd_addr: String,
}

impl Default for AppSettings {
fn default() -> Self {
Self {
// Node auto-upgrading is disabled by default.
nodes_auto_upgrade: false,
// Delay 10 secs. between each node being auto-upgraded.
nodes_auto_upgrade_delay: Duration::from_secs(10),
// Check latest version of node binary every couple of hours.
node_bin_version_polling_freq: Duration::from_secs(60 * 60 * 2),
// How often to fetch metrics and node info from active/running nodes
nodes_metrics_polling_freq: Duration::from_secs(5),
// Retrieve balances every 15 mins.
rewards_balances_retrieval_freq: Duration::from_secs(60 * 15),
// Arbitrum Sepolia testnet.
l2_network_rpc_url: "https://sepolia-rollup.arbitrum.io/rpc".to_string(),
// ANT token contract on Arbitrum Sepolia testnet.
token_contract_address: "0xBE1802c27C324a28aeBcd7eeC7D734246C807194".to_string(),
// External LCD device disabled.
lcd_display_enabled: false,
// I2C bus number 1, i.e. device at /dev/i2c-1.
lcd_device: "1".to_string(),
// I2C backpack address 0x27, another common addr is: 0x3f. Check it out with 'sudo ic2detect -y <bus-number>'.
lcd_addr: "0x27".to_string(),
}
}
}

/// Node stats collected by the backend and retrievable through the public server API.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Stats {
pub total_balance: U256,
pub total_nodes: usize,
pub active_nodes: usize,
pub inactive_nodes: usize,
pub connected_peers: usize,
pub shunned_count: usize,
pub estimated_net_size: usize,
pub stored_records: usize,
pub relevant_records: usize,
}

/// Information about any actively running nodes creation batch.
#[derive(Clone, Default, Serialize, Deserialize)]
pub struct BatchInProgress {
pub created: u16,
pub total: u16,
pub auto_start: bool,
pub interval_secs: u64,
}
2 changes: 1 addition & 1 deletion src/settings.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use super::{
app::AppSettings,
helpers::show_alert_msg,
icons::IconCancel,
server_api::{get_settings, update_settings},
server_api_types::AppSettings,
};

use alloy::primitives::Address;
Expand Down

0 comments on commit 3e85559

Please sign in to comment.