Skip to content

Commit

Permalink
(#78) Network Viewer - New API JSON-RPC getModulesConfig
Browse files Browse the repository at this point in the history
  • Loading branch information
mario4tier committed Oct 16, 2023
1 parent bdbb2e1 commit 7420134
Show file tree
Hide file tree
Showing 17 changed files with 618 additions and 65 deletions.
4 changes: 2 additions & 2 deletions rust/demo-app/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions rust/suibase/crates/suibase-daemon/src/admin_controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use crate::basic_types::*;
use crate::network_monitor::NetMonTx;
use crate::proxy_server::ProxyServer;
use crate::shared_types::{
Globals, GlobalsProxyMT, GlobalsStatusMT, GlobalsWorkdirsMT, InputPort, WorkdirProxyConfig,
WorkdirsST,
Globals, GlobalsProxyMT, GlobalsStatusMT, GlobalsWorkdirsMT, GlobalsWorkdirsST, InputPort,
WorkdirProxyConfig,
};
use crate::workdirs_watcher::WorkdirsWatcher;
use crate::workers::ShellWorker;
Expand Down Expand Up @@ -468,7 +468,7 @@ fn test_load_config_from_suibase_default() {
// Note: More of a functional test. Suibase need to be installed.

// Test a known "standard" localnet suibase.yaml
let workdirs = WorkdirsST::new();
let workdirs = GlobalsWorkdirsST::new();
let mut path = std::path::PathBuf::from(workdirs.suibase_home());
path.push("scripts");
path.push("defaults");
Expand Down
30 changes: 22 additions & 8 deletions rust/suibase/crates/suibase-daemon/src/api/api_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ use crate::api::impl_general_api::GeneralApiImpl;
use super::ProxyApiServer;
use crate::api::impl_proxy_api::ProxyApiImpl;

use super::ModulesApiServer;
use crate::api::impl_modules_api::ModulesApiImpl;

use hyper::Method;
use jsonrpsee::{
core::server::rpc_module::Methods,
Expand Down Expand Up @@ -119,17 +122,28 @@ impl JSONRPCServer {

let mut all_methods = Methods::new();

let proxy_api = ProxyApiImpl::new(self.globals.proxy.clone(), self.admctrl_tx.clone());
let proxy_methods = proxy_api.into_rpc();
{
let api = ProxyApiImpl::new(self.globals.proxy.clone(), self.admctrl_tx.clone());
let methods = api.into_rpc();
if let Err(e) = all_methods.merge(methods) {
log::error!("Error merging ProxyApiImpl methods: {}", e);
}
}

if let Err(e) = all_methods.merge(proxy_methods) {
log::error!("Error merging proxy_methods: {}", e);
{
let api = GeneralApiImpl::new(self.globals.clone(), self.admctrl_tx.clone());
let methods = api.into_rpc();
if let Err(e) = all_methods.merge(methods) {
log::error!("Error merging GeneralApiImpl methods: {}", e);
}
}

let general_api = GeneralApiImpl::new(self.globals.clone(), self.admctrl_tx.clone());
let general_methods = general_api.into_rpc();
if let Err(e) = all_methods.merge(general_methods) {
log::error!("Error merging general_methods: {}", e);
{
let api = ModulesApiImpl::new(self.globals.clone(), self.admctrl_tx.clone());
let methods = api.into_rpc();
if let Err(e) = all_methods.merge(methods) {
log::error!("Error merging ModulesApiImpl methods: {}", e);
}
}

let start_result = server.start(all_methods);
Expand Down
9 changes: 9 additions & 0 deletions rust/suibase/crates/suibase-daemon/src/api/def_header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ impl<T: Clone + PartialEq> Versioned<T> {
&self.uuid
}

// write access
pub fn get_mut_data(&mut self) -> &mut T {
&mut self.data
}

pub fn get_mut_uuid(&mut self) -> &mut UuidST {
&mut self.uuid
}

// Write version into a Header structure.
pub fn init_header_uuids(&self, header: &mut Header) {
let (method_uuid, data_uuid) = self.uuid.get();
Expand Down
156 changes: 156 additions & 0 deletions rust/suibase/crates/suibase-daemon/src/api/def_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,71 @@ impl Default for StatusResponse {
}
}

#[serde_as]
#[derive(Clone, Debug, JsonSchema, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SuiEvents {
pub message: String,
pub timestamp: String,
}

impl SuiEvents {
pub fn new(label: String) -> Self {
Self {
message: label,
timestamp: "".to_string(),
}
}
}

#[serde_as]
#[derive(Clone, Debug, JsonSchema, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SuiEventsResponse {
pub header: Header,

#[serde(skip_serializing_if = "Option::is_none")]
pub events: Option<Vec<SuiEvents>>,
}

impl SuiEventsResponse {
pub fn new() -> Self {
Self {
header: Header::default(),
events: None,
}
}
}

impl Default for SuiEventsResponse {
fn default() -> Self {
Self::new()
}
}

#[serde_as]
#[derive(Clone, Debug, JsonSchema, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SuccessResponse {
pub header: Header,
pub success: bool,
}

impl SuccessResponse {
pub fn new() -> Self {
Self {
header: Header::default(),
success: false,
}
}
}

impl Default for SuccessResponse {
fn default() -> Self {
Self::new()
}
}

#[rpc(server)]
pub trait ProxyApi {
/// Returns data about all the RPC/Websocket links
Expand All @@ -238,6 +303,67 @@ pub trait ProxyApi {
async fn fs_change(&self, path: String) -> RpcResult<InfoResponse>;
}

#[serde_as]
#[derive(Clone, Debug, JsonSchema, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ModuleConfig {
pub name: Option<String>, // "localnet process", "proxy server", "multi-link RPC" etc...
pub id: Option<String>, // OK, DOWN, DEGRADED
}

impl ModuleConfig {
pub fn new() -> Self {
Self {
name: None,
id: None,
}
}
}

impl Default for ModuleConfig {
fn default() -> Self {
Self::new()
}
}

#[serde_as]
#[derive(Clone, Debug, JsonSchema, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ModulesConfigResponse {
pub header: Header,

// Last publish instance of each module.
#[serde(skip_serializing_if = "Option::is_none")]
pub modules: Option<Vec<ModuleConfig>>,

// This is the output when the option 'display' is true.
// Will also change the default to false for all the other fields.
#[serde(skip_serializing_if = "Option::is_none")]
pub display: Option<String>,

// This is the output when the option 'debug' is true.
// Will also change the default to true for the other fields.
#[serde(skip_serializing_if = "Option::is_none")]
pub debug: Option<String>,
}

impl ModulesConfigResponse {
pub fn new() -> Self {
Self {
header: Header::default(),
modules: None,
display: None,
debug: None,
}
}
}

impl Default for ModulesConfigResponse {
fn default() -> Self {
Self::new()
}
}

#[rpc(server)]
pub trait GeneralApi {
#[method(name = "getStatus")]
Expand All @@ -251,3 +377,33 @@ pub trait GeneralApi {
data_uuid: Option<String>,
) -> RpcResult<StatusResponse>;
}

#[rpc(server)]
pub trait ModulesApi {
#[method(name = "getEvents")]
async fn get_events(
&self,
workdir: String,
after_ts: Option<String>,
last_ts: Option<String>,
) -> RpcResult<SuiEventsResponse>;

#[method(name = "getModulesConfig")]
async fn get_modules_config(
&self,
workdir: String,
data: Option<bool>,
display: Option<bool>,
debug: Option<bool>,
method_uuid: Option<String>,
data_uuid: Option<String>,
) -> RpcResult<ModulesConfigResponse>;

#[method(name = "publish")]
async fn publish(
&self,
workdir: String,
module_name: String,
module_id: String,
) -> RpcResult<SuccessResponse>;
}
27 changes: 12 additions & 15 deletions rust/suibase/crates/suibase-daemon/src/api/impl_general_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use axum::async_trait;

use anyhow::Result;

//use clap::Indices;
use futures::future::ok;
use jsonrpsee::core::RpcResult;

Expand All @@ -15,12 +14,11 @@ use crate::admin_controller::{
};
use crate::basic_types::{TargetServerIdx, WorkdirIdx};
use crate::shared_types::{
Globals, GlobalsProxyMT, GlobalsStatusMT, GlobalsStatusOneWorkdirST, ServerStats, TargetServer,
UuidST, Workdir,
Globals, GlobalsProxyMT, GlobalsStatusMT, GlobalsWorkdirStatusST, GlobalsWorkdirsST,
ServerStats, TargetServer, UuidST, Workdir,
};

use super::{GeneralApiServer, RpcServerError, StatusResponse, StatusService};
use super::{LinkStats, LinksResponse, LinksSummary, RpcInputError};
use super::{GeneralApiServer, RpcInputError, RpcServerError, StatusResponse, StatusService};

use super::def_header::{Header, Versioned};

Expand Down Expand Up @@ -239,23 +237,22 @@ impl GeneralApiServer for GeneralApiImpl {
let data = data.unwrap_or(!(debug || display));

// Verify workdir param is OK and get its corresponding workdir_idx.
let workdir_idx = {
let workdirs_guard = self.globals.workdirs.read().await;
let workdirs = &*workdirs_guard;
let workdir_idx = match workdirs.find_workdir(workdir.as_str()) {
Some((workdir_idx, _workdir_object)) => workdir_idx,
None => {
return Err(RpcInputError::InvalidParams("workdir".to_string(), workdir).into())
}
};
workdir_idx
let workdir_idx = match GlobalsWorkdirsST::find_workdir_idx_by_name(&self.globals, &workdir)
.await
{
Some(workdir_idx) => workdir_idx,
None => return Err(RpcInputError::InvalidParams("workdir".to_string(), workdir).into()),
};

// Initialize some of the header fields of the response.
let mut resp = StatusResponse::new();
resp.header.method = "getStatus".to_string();
resp.header.key = Some(workdir.clone());

// TODO: Consider refactoring as follow:
// get_data_if_no_change(request_uuids,resp)
// set_data_when_changed(new_data: T,resp)

// Check if GlobalsStatus need to be refresh, if not, then
// just return what is already loaded in-memory.
//let now = tokio::time::Instant::now();
Expand Down
Loading

0 comments on commit 7420134

Please sign in to comment.