Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add /summary route that returns stats and commit info #61

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions Cargo.lock

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

6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ opentelemetry_sdk = { version = "0.22.1", features = ["metrics", "rt-tokio"] }
opentelemetry-stdout = { version = "0.3.0", features = ["logs", "metrics", "trace"] }
opentelemetry-prometheus = "0.15.0"
prometheus = "0.13.3"

built = "0.7.2"

[patch.crates-io]
alloy-primitives = { git = "https://github.com/alloy-rs/core", rev = "7574bfc" }
Expand All @@ -98,3 +98,7 @@ opt-level = 3

[dev-dependencies]
alloy-node-bindings = { git = "https://github.com/alloy-rs/alloy", rev = "17633df" }


[build-dependencies]
built = { version = "0.7.2", features = ["git2"] }
3 changes: 3 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fn main() {
built::write_built_file().expect("Failed to acquire build-time information")
}
69 changes: 51 additions & 18 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,57 @@ curl http://localhost:7777/health
OK
```

### `GET /summary`

Returns information about the node

Example

```
curl -H "Authorization: abc" http://localhost:7777/summary

{
"commit_sha": "3d917f1",
"pkg_version": "0.1.0",
"active_premint_count": 1,
"total_premint_count": 1,
"node_info": {
"local_peer_id": "12D3KooWCY9tjLzwXeWgYe8smxyAhEj7x1TxGG7fMzDLGwzPLEuC",
"num_peers": 3,
"dht_peers": [
[
"/dnsaddr/mintpool-1.zora.co/p2p/12D3KooWLUCRp7EFvBRGqhZ3kfZT3BRHoxX3a2erBGY5Nm49ggqy",
"/dnsaddr/mintpool-1.zora.co"
],
[
"/dnsaddr/mintpool-3.zora.co/p2p/12D3KooWSgM2s7sJjKt7Tf3eXSDduszS6ZonaY444Yz7sNNVW7K9",
"/dnsaddr/mintpool-3.zora.co"
],
[
"/dnsaddr/mintpool-2.zora.co/p2p/12D3KooWEBYjav7N175YYuEsPFdm36vKywjktcaE1HFgMTnQNWmy",
"/dnsaddr/mintpool-2.zora.co"
]
],
"gossipsub_peers": [
"12D3KooWEBYjav7N175YYuEsPFdm36vKywjktcaE1HFgMTnQNWmy",
"12D3KooWLUCRp7EFvBRGqhZ3kfZT3BRHoxX3a2erBGY5Nm49ggqy",
"12D3KooWSgM2s7sJjKt7Tf3eXSDduszS6ZonaY444Yz7sNNVW7K9"
],
"all_external_addresses": [
[
"/dnsaddr/mintpool-1.zora.co"
],
[
"/dnsaddr/mintpool-3.zora.co"
],
[
"/dnsaddr/mintpool-2.zora.co"
]
]
}
}
```

### `GET /list-all`

List all premints stored by the node. Supports the following query params for filtering:
Expand Down Expand Up @@ -278,24 +329,6 @@ If the admin key is not set these routes are unreachable.

See `/submit-premint` for details, same route but without ratelimit

### `GET /admin/node`

Returns information about the node

Example

```
curl -H "Authorization: abc" http://localhost:7777/admin/node

{
"local_peer_id": "12D3KooWPjceQrSwdWXPyLLeABRXmuqt69Rg3sBYbU1Nft9HyQ6X",
"num_peers": 0,
"dht_peers": [],
"gossipsub_peers": [],
"all_external_addresses": []
}
```

### `POST /admin/add-peer`

Sends the node a peer address to connect to
Expand Down
55 changes: 0 additions & 55 deletions src/api/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,58 +77,3 @@ pub async fn add_peer(
),
}
}

pub async fn node_info(
State(state): State<AppState>,
) -> Result<Json<NodeInfoResponse>, StatusCode> {
let (snd, rcv) = tokio::sync::oneshot::channel();
match state
.controller
.send_command(ControllerCommands::ReturnNetworkState { channel: snd })
.await
{
Ok(_) => match rcv.await {
Ok(info) => Ok(Json(NodeInfoResponse::from(info))),
Err(_e) => Err(StatusCode::INTERNAL_SERVER_ERROR),
},
Err(_e) => Err(StatusCode::INTERNAL_SERVER_ERROR),
}
}

#[derive(Serialize)]
pub struct NodeInfoResponse {
pub local_peer_id: String,
pub num_peers: u64,
pub dht_peers: Vec<Vec<String>>,
pub gossipsub_peers: Vec<String>,
pub all_external_addresses: Vec<Vec<String>>,
}

impl From<NetworkState> for NodeInfoResponse {
fn from(state: NetworkState) -> Self {
let NetworkState {
local_peer_id,
network_info,
dht_peers,
gossipsub_peers,
all_external_addresses,
..
} = state;
let dht_peers = dht_peers
.into_iter()
.map(|peer| peer.iter().map(|p| p.to_string()).collect())
.collect();
let gossipsub_peers = gossipsub_peers.into_iter().map(|p| p.to_string()).collect();
let all_external_addresses = all_external_addresses
.into_iter()
.map(|peer| peer.into_iter().map(|p| p.to_string()).collect())
.collect();
Self {
local_peer_id: local_peer_id.to_string(),
num_peers: network_info.num_peers() as u64,
dht_peers,
gossipsub_peers,
all_external_addresses,
}
}
}
2 changes: 1 addition & 1 deletion src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ pub fn router_with_defaults(config: &Config) -> Router<AppState> {
.route("/get-one", get(routes::get_one))
.route("/get-one/:kind/:id", get(routes::get_by_id_and_kind))
.route("/submit-premint", post(routes::submit_premint))
.route("/summary", get(routes::summary))
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(|error: BoxError| async move {
Expand Down Expand Up @@ -78,7 +79,6 @@ pub fn router_with_defaults(config: &Config) -> Router<AppState> {

pub fn with_admin_routes(state: AppState, router: Router<AppState>) -> Router<AppState> {
let admin = Router::new()
.route("/admin/node", get(admin::node_info))
.route("/admin/add-peer", post(admin::add_peer))
// admin submit premint route is not rate limited (allows for operator to send high volume of premints)
.route("/admin/submit-premint", post(routes::submit_premint))
Expand Down
87 changes: 87 additions & 0 deletions src/api/routes.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::api::AppState;
use crate::controller::ControllerCommands;
use crate::p2p::NetworkState;
use crate::rules::Results;
use crate::storage;
use crate::storage::{get_for_id_and_kind, QueryOptions};
Expand All @@ -8,6 +9,7 @@ use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::Json;
use serde::Serialize;
use sqlx::{Executor, Row};

pub async fn list_all(
State(state): State<AppState>,
Expand Down Expand Up @@ -117,3 +119,88 @@ pub enum APIResponse {
Error { message: String },
Success { message: String },
}

pub async fn summary(State(state): State<AppState>) -> Result<Json<SummaryResponse>, StatusCode> {
let (snd, rcv) = tokio::sync::oneshot::channel();
match state
.controller
.send_command(ControllerCommands::ReturnNetworkState { channel: snd })
.await
{
Ok(_) => match rcv.await {
Ok(info) => {
let total = state
.db
.fetch_one("SELECT COUNT(*) as count FROM premints")
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.get::<i64, _>("count");
let active = state
.db
.fetch_one("SELECT COUNT(*) as count FROM premints WHERE seen_on_chain = false")
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.get::<i64, _>("count");

Ok(Json(SummaryResponse {
commit_sha: crate::built_info::GIT_COMMIT_HASH_SHORT
.unwrap_or_default()
.to_string(),
pkg_version: crate::built_info::PKG_VERSION.to_string(),
active_premint_count: active as u64,
total_premint_count: total as u64,
node_info: info.into(),
}))
}
Err(_e) => Err(StatusCode::INTERNAL_SERVER_ERROR),
},
Err(_e) => Err(StatusCode::INTERNAL_SERVER_ERROR),
}
}

#[derive(Serialize)]
pub struct SummaryResponse {
pub commit_sha: String,
pub pkg_version: String,
pub active_premint_count: u64,
pub total_premint_count: u64,
pub node_info: NodeInfoResponse,
}

#[derive(Serialize)]
pub struct NodeInfoResponse {
pub local_peer_id: String,
pub num_peers: u64,
pub dht_peers: Vec<Vec<String>>,
pub gossipsub_peers: Vec<String>,
pub all_external_addresses: Vec<Vec<String>>,
}

impl From<NetworkState> for NodeInfoResponse {
fn from(state: NetworkState) -> Self {
let NetworkState {
local_peer_id,
network_info,
dht_peers,
gossipsub_peers,
all_external_addresses,
..
} = state;
let dht_peers = dht_peers
.into_iter()
.map(|peer| peer.iter().map(|p| p.to_string()).collect())
.collect();
let gossipsub_peers = gossipsub_peers.into_iter().map(|p| p.to_string()).collect();
let all_external_addresses = all_external_addresses
.into_iter()
.map(|peer| peer.into_iter().map(|p| p.to_string()).collect())
.collect();
Self {
local_peer_id: local_peer_id.to_string(),
num_peers: network_info.num_peers() as u64,
dht_peers,
gossipsub_peers,
all_external_addresses,
}
}
}
2 changes: 0 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::collections::HashMap;
use std::env;
use std::str::FromStr;

use envconfig::Envconfig;
Expand Down
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,7 @@ pub mod run;
pub mod stdin;
pub mod storage;
pub mod types;

pub mod built_info {
include!(concat!(env!("OUT_DIR"), "/built.rs"));
}
2 changes: 1 addition & 1 deletion src/p2p.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use libp2p::gossipsub::Version;
use libp2p::identity::Keypair;
use libp2p::kad::store::MemoryStore;
use libp2p::kad::GetProvidersOk::FoundProviders;
use libp2p::kad::{Addresses, GetProvidersOk, QueryResult, RecordKey};
use libp2p::kad::{Addresses, QueryResult, RecordKey};
use libp2p::multiaddr::Protocol;
use libp2p::swarm::{ConnectionId, NetworkBehaviour, NetworkInfo, SwarmEvent};
use libp2p::{gossipsub, kad, noise, tcp, yamux, Multiaddr, PeerId};
Expand Down
2 changes: 1 addition & 1 deletion src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use eyre::WrapErr;
use serde::Deserialize;
use sqlx::sqlite::SqliteConnectOptions;
use sqlx::Row;
use sqlx::{Encode, QueryBuilder, Sqlite, SqlitePool};
use sqlx::{QueryBuilder, Sqlite, SqlitePool};
use std::str::FromStr;

async fn init_db(config: &Config) -> SqlitePool {
Expand Down
Loading