referrerpolicy=no-referrer-when-downgrade

pallet_revive_eth_rpc/apis/
health_api.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17//! Heatlh JSON-RPC methods.
18
19use crate::*;
20use jsonrpsee::{core::RpcResult, proc_macros::rpc};
21use sc_rpc_api::system::helpers::Health;
22
23#[rpc(server, client)]
24pub trait SystemHealthRpc {
25	/// Proxy the substrate chain system_health RPC call.
26	#[method(name = "system_health")]
27	async fn system_health(&self) -> RpcResult<Health>;
28
29	///Returns the number of peers currently connected to the client.
30	#[method(name = "net_peerCount")]
31	async fn net_peer_count(&self) -> RpcResult<U64>;
32}
33
34pub struct SystemHealthRpcServerImpl {
35	client: client::Client,
36}
37
38impl SystemHealthRpcServerImpl {
39	pub fn new(client: client::Client) -> Self {
40		Self { client }
41	}
42}
43
44#[async_trait]
45impl SystemHealthRpcServer for SystemHealthRpcServerImpl {
46	async fn system_health(&self) -> RpcResult<Health> {
47		let (sync_state, health) =
48			tokio::try_join!(self.client.sync_state(), self.client.system_health())?;
49
50		let latest = self.client.latest_block().await.number();
51
52		// Compare against `latest + 1` to avoid a false positive if the health check runs
53		// immediately after a new block is produced but before the cache updates.
54		if sync_state.current_block > latest + 1 {
55			log::warn!(
56				target: LOG_TARGET,
57				"Client is out of sync. Current block: {}, latest cache block: {latest}",
58				sync_state.current_block,
59			);
60			return Err(ErrorCode::InternalError.into());
61		}
62
63		Ok(Health {
64			peers: health.peers,
65			is_syncing: health.is_syncing,
66			should_have_peers: health.should_have_peers,
67		})
68	}
69
70	async fn net_peer_count(&self) -> RpcResult<U64> {
71		let health = self.client.system_health().await?;
72		Ok((health.peers as u64).into())
73	}
74}