Skip to content

Commit

Permalink
[api] bring in health check
Browse files Browse the repository at this point in the history
This is the only required service that lives both on json and api, so
just bringing it over -- will delete the other one shortly
  • Loading branch information
davidiw committed Mar 1, 2022
1 parent 2162cff commit 3d016b1
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 16 deletions.
2 changes: 1 addition & 1 deletion api/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ impl Context {
}

pub fn health_check_route(&self) -> BoxedFilter<(impl Reply,)> {
diem_json_rpc::runtime::health_check_route(self.db.clone())
super::health_check::health_check_route(self.db.clone())
}

pub fn jsonrpc_routes(&self) -> BoxedFilter<(impl Reply,)> {
Expand Down
64 changes: 64 additions & 0 deletions api/src/health_check.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use anyhow::{ensure, Result};
use std::{
ops::Sub,
sync::Arc,
time::{Duration, SystemTime, UNIX_EPOCH},
};
use storage_interface::MoveDbReader;
use warp::{filters::BoxedFilter, reject, Filter, Reply};

// HealthCheckParams is optional params for different layer's health check.
// If no param is provided, server return 200 by default to indicate HTTP server is running health.
#[derive(serde::Deserialize)]
struct HealthCheckParams {
// Health check returns 200 when this param is provided and meet the following condition:
// server latest ledger info timestamp >= server current time timestamp - duration_secs
pub duration_secs: Option<u64>,
}

#[derive(Debug)]
struct HealthCheckError;
impl reject::Reject for HealthCheckError {}

pub fn health_check_route(health_diem_db: Arc<dyn MoveDbReader>) -> BoxedFilter<(impl Reply,)> {
warp::path!("-" / "healthy")
.and(warp::path::end())
.and(warp::query().map(move |params: HealthCheckParams| params))
.and(warp::any().map(move || health_diem_db.clone()))
.and(warp::any().map(SystemTime::now))
.and_then(health_check)
.boxed()
}

async fn health_check(
params: HealthCheckParams,
db: Arc<dyn MoveDbReader>,
now: SystemTime,
) -> Result<Box<dyn warp::Reply>, warp::Rejection> {
if let Some(duration) = params.duration_secs {
let ledger_info = db
.get_latest_ledger_info()
.map_err(|_| reject::custom(HealthCheckError))?;
let timestamp = ledger_info.ledger_info().timestamp_usecs();

check_latest_ledger_info_timestamp(duration, timestamp, now)
.map_err(|_| reject::custom(HealthCheckError))?;
}
Ok(Box::new("diem-node:ok"))
}

pub fn check_latest_ledger_info_timestamp(
duration_sec: u64,
timestamp_usecs: u64,
now: SystemTime,
) -> Result<()> {
let timestamp = Duration::from_micros(timestamp_usecs);
let expectation = now
.sub(Duration::from_secs(duration_sec))
.duration_since(UNIX_EPOCH)?;
ensure!(timestamp >= expectation);
Ok(())
}
1 change: 1 addition & 0 deletions api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
mod accounts;
mod context;
mod events;
mod health_check;
mod index;
pub(crate) mod log;
mod metrics;
Expand Down
1 change: 0 additions & 1 deletion api/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,6 @@ mod tests {

use diem_config::config::NodeConfig;
use diem_types::chain_id::ChainId;
use serde_json::json;

use crate::{
runtime::bootstrap,
Expand Down
12 changes: 0 additions & 12 deletions api/src/tests/index_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,18 +51,6 @@ async fn test_health_check() {
assert_eq!(resp.status(), 200)
}

#[tokio::test]
async fn test_enable_jsonrpc_api() {
let context = new_test_context();
let resp = context
.post(
"/",
json!({"jsonrpc": "2.0", "method": "get_metadata", "id": 1}),
)
.await;
assert_eq!(resp["result"]["version"].as_u64().unwrap(), 0)
}

#[tokio::test]
async fn test_openapi_spec() {
let context = new_test_context();
Expand Down
3 changes: 1 addition & 2 deletions api/src/tests/test_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use diem_api_types::{
mime_types, HexEncodedBytes, TransactionOnChainData, X_DIEM_CHAIN_ID, X_DIEM_LEDGER_TIMESTAMP,
X_DIEM_LEDGER_VERSION,
};
use diem_config::config::{ApiConfig, JsonRpcConfig, RoleType};
use diem_config::config::{ApiConfig, RoleType};
use diem_crypto::{hash::HashValue, SigningKey};
use diem_genesis_tool::validator_builder::{RootKeys, ValidatorBuilder};
use diem_global_constants::OWNER_ACCOUNT;
Expand Down Expand Up @@ -74,7 +74,6 @@ pub fn new_test_context() -> TestContext {
db.clone(),
mempool.ac_client.clone(),
RoleType::Validator,
JsonRpcConfig::default(),
ApiConfig::default(),
),
rng,
Expand Down

0 comments on commit 3d016b1

Please sign in to comment.