Skip to content

Commit

Permalink
Add HTTP Info
Browse files Browse the repository at this point in the history
  • Loading branch information
herr-seppia committed Oct 26, 2023
1 parent fd3a267 commit 50e7bda
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 16 deletions.
4 changes: 4 additions & 0 deletions node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,10 @@ impl<N: Network, DB: database::DB, VM: vm::VMExecution> Node<N, DB, VM> {
self.network.clone()
}

pub fn vm(&self) -> Arc<RwLock<VM>> {
self.vm_handler.clone()
}

/// Sets up and runs a list of services.
pub async fn spawn_all(
&self,
Expand Down
4 changes: 4 additions & 0 deletions node/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,10 @@ impl<const N: usize> Kadcast<N> {
pub async fn alive_nodes(&self, amount: usize) -> Vec<SocketAddr> {
self.peer.alive_nodes(amount).await
}

pub fn conf(&self) -> &Config {
&self.conf
}
}

#[async_trait]
Expand Down
6 changes: 6 additions & 0 deletions rusk/src/lib/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,10 @@ impl RuskNode {
pub fn db(&self) -> Arc<tokio::sync::RwLock<Backend>> {
self.0.database() as Arc<tokio::sync::RwLock<Backend>>
}
pub fn network(&self) -> Arc<tokio::sync::RwLock<Kadcast<255>>> {
self.0.network() as Arc<tokio::sync::RwLock<Kadcast<255>>>
}
pub fn vm(&self) -> Arc<tokio::sync::RwLock<Rusk>> {
self.0.vm() as Arc<tokio::sync::RwLock<Rusk>>
}
}
25 changes: 22 additions & 3 deletions rusk/src/lib/http/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use serde_json::json;
use super::event::{
Event, MessageRequest, MessageResponse, RequestData, ResponseData, Target,
};
use crate::http::RuskNode;
use crate::{http::RuskNode, VERSION, VERSION_BUILD};

const GQL_VAR_PREFIX: &str = "rusk-gqlvar-";

Expand Down Expand Up @@ -61,6 +61,7 @@ impl RuskNode {
let amount = request.event.data.as_string().trim().parse()?;
self.alive_nodes(amount).await
}
(Target::Host(_), "Chain", "info") => self.get_info().await,
_ => anyhow::bail!("Unsupported"),
}
}
Expand Down Expand Up @@ -90,7 +91,8 @@ impl RuskNode {
}
let data = serde_json::to_string(&data)
.map_err(|e| anyhow::anyhow!("Cannot parse response {e}"))?;
Ok(data.into())

Ok(ResponseData::Json(data))
}

async fn propagate_tx(&self, tx: &[u8]) -> anyhow::Result<ResponseData> {
Expand All @@ -108,6 +110,23 @@ impl RuskNode {
async fn alive_nodes(&self, amount: usize) -> anyhow::Result<ResponseData> {
let nodes = self.0.network().read().await.alive_nodes(amount).await;
let nodes: Vec<_> = nodes.iter().map(|n| n.to_string()).collect();
Ok(serde_json::to_string(&nodes)?.into())
let response = serde_json::to_string(&nodes)?;

Ok(ResponseData::Json(response))
}

async fn get_info(&self) -> anyhow::Result<ResponseData> {
let mut info: HashMap<&str, serde_json::Value> = HashMap::new();
info.insert("version", VERSION.as_str().into());
info.insert("version_build", VERSION_BUILD.as_str().into());

let n_conf = self.network().read().await.conf().clone();
info.insert("bootstrapping_nodes", n_conf.bootstrapping_nodes.into());
info.insert("chain_id", n_conf.kadcast_id.into());
info.insert("kadcast_address", n_conf.public_address.into());

let response = serde_json::to_string(&info)?;

Ok(ResponseData::Json(response))
}
}
36 changes: 26 additions & 10 deletions rusk/src/lib/http/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::str::FromStr;
use std::sync::mpsc;
use tungstenite::http::{response, HeaderValue};

/// A request sent by the websocket client.
#[derive(Debug, Serialize, Deserialize)]
Expand Down Expand Up @@ -194,6 +195,8 @@ impl MessageResponse {
.body(hyper::Body::from(error.to_string()))?);
}

let mut headers = HashMap::new();

let body = {
match self.data {
ResponseData::Binary(wrapper) => {
Expand All @@ -204,19 +207,30 @@ impl MessageResponse {
Body::from(data)
}
ResponseData::Text(text) => Body::from(text),
ResponseData::Channel(channel) => Body::wrap_stream(
stream::iter(channel).map(move |e| match is_binary {
true => Ok::<_, anyhow::Error>(e),
false => Ok::<_, anyhow::Error>(
hex::encode(e).as_bytes().to_vec(),
),
}), // Ok::<_, anyhow::Error>),
),
ResponseData::Json(text) => {
headers.insert(CONTENT_TYPE, CONTENT_TYPE_JSON);
Body::from(text)
}
ResponseData::Channel(channel) => {
Body::wrap_stream(stream::iter(channel).map(move |e| {
match is_binary {
true => Ok::<_, anyhow::Error>(e),
false => Ok::<_, anyhow::Error>(
hex::encode(e).as_bytes().to_vec(),
),
}
}))
}
ResponseData::None => Body::empty(),
}
};

Ok(hyper::Response::new(body))
let mut response = hyper::Response::new(body);
for (k, v) in headers {
response
.headers_mut()
.insert(k, HeaderValue::from_str(v).unwrap());
}
Ok(response)
}

pub fn set_header(&mut self, key: &str, value: serde_json::Value) {
Expand Down Expand Up @@ -276,6 +290,7 @@ impl From<Vec<u8>> for RequestData {
pub enum ResponseData {
Binary(BinaryWrapper),
Text(String),
Json(String),
#[serde(skip)]
Channel(mpsc::Receiver<Vec<u8>>),
#[default]
Expand Down Expand Up @@ -348,6 +363,7 @@ impl Event {
}
const CONTENT_TYPE: &str = "Content-Type";
const CONTENT_TYPE_BINARY: &str = "application/octet-stream";
const CONTENT_TYPE_JSON: &str = "application/json";

fn parse_len(bytes: &[u8]) -> anyhow::Result<(usize, &[u8])> {
if bytes.len() < 4 {
Expand Down
8 changes: 5 additions & 3 deletions rusk/src/lib/http/rusk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ use dusk_bytes::Serializable;
use node::vm::VMExecution;
use rusk_prover::{LocalProver, Prover};
use serde::Serialize;
use std::collections::HashMap;
use std::sync::{mpsc, Arc};
use std::thread;
use tokio::task;
use tungstenite::http::response;

use rusk_abi::ContractId;

use crate::Rusk;
use crate::{Rusk, VERSION, VERSION_BUILD};

use super::event::{
Event, MessageRequest, MessageResponse, RequestData, ResponseData, Target,
Expand Down Expand Up @@ -50,7 +52,6 @@ impl Rusk {
(Target::Host(_), "rusk", "prove_wfco") => {
Ok(LocalProver.prove_wfco(request.event_data())?.into())
}

(Target::Host(_), "rusk", "provisioners") => {
self.get_provisioners()
}
Expand Down Expand Up @@ -121,7 +122,8 @@ impl Rusk {
})
.collect::<Vec<_>>();

Ok(serde_json::to_string(&prov)?.into())
let response = serde_json::to_string(&prov)?;
Ok(ResponseData::Json(response))
}
}

Expand Down

0 comments on commit 50e7bda

Please sign in to comment.