referrerpolicy=no-referrer-when-downgrade
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.

// Parity Bridges Common is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Parity Bridges Common is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common.  If not, see <http://www.gnu.org/licenses/>.

use crate::{Chain, Client, Error as SubstrateError};

use async_std::sync::{Arc, RwLock};
use async_trait::async_trait;
use codec::Decode;
use num_traits::One;
use relay_utils::metrics::{
	metric_name, register, F64SharedRef, Gauge, Metric, PrometheusError, Registry,
	StandaloneMetric, F64,
};
use sp_core::storage::{StorageData, StorageKey};
use sp_runtime::{traits::UniqueSaturatedInto, FixedPointNumber, FixedU128};
use std::{marker::PhantomData, time::Duration};

/// Storage value update interval (in blocks).
const UPDATE_INTERVAL_IN_BLOCKS: u32 = 5;

/// Fied-point storage value and the way it is decoded from the raw storage value.
pub trait FloatStorageValue: 'static + Clone + Send + Sync {
	/// Type of the value.
	type Value: FixedPointNumber;
	/// Try to decode value from the raw storage value.
	fn decode(
		&self,
		maybe_raw_value: Option<StorageData>,
	) -> Result<Option<Self::Value>, SubstrateError>;
}

/// Implementation of `FloatStorageValue` that expects encoded `FixedU128` value and returns `1` if
/// value is missing from the storage.
#[derive(Clone, Debug, Default)]
pub struct FixedU128OrOne;

impl FloatStorageValue for FixedU128OrOne {
	type Value = FixedU128;

	fn decode(
		&self,
		maybe_raw_value: Option<StorageData>,
	) -> Result<Option<Self::Value>, SubstrateError> {
		maybe_raw_value
			.map(|raw_value| {
				FixedU128::decode(&mut &raw_value.0[..])
					.map_err(SubstrateError::ResponseParseFailed)
					.map(Some)
			})
			.unwrap_or_else(|| Ok(Some(FixedU128::one())))
	}
}

/// Metric that represents fixed-point runtime storage value as float gauge.
#[derive(Clone, Debug)]
pub struct FloatStorageValueMetric<C, Clnt, V> {
	value_converter: V,
	client: Clnt,
	storage_key: StorageKey,
	metric: Gauge<F64>,
	shared_value_ref: F64SharedRef,
	_phantom: PhantomData<(C, V)>,
}

impl<C, Clnt, V> FloatStorageValueMetric<C, Clnt, V> {
	/// Create new metric.
	pub fn new(
		value_converter: V,
		client: Clnt,
		storage_key: StorageKey,
		name: String,
		help: String,
	) -> Result<Self, PrometheusError> {
		let shared_value_ref = Arc::new(RwLock::new(None));
		Ok(FloatStorageValueMetric {
			value_converter,
			client,
			storage_key,
			metric: Gauge::new(metric_name(None, &name), help)?,
			shared_value_ref,
			_phantom: Default::default(),
		})
	}

	/// Get shared reference to metric value.
	pub fn shared_value_ref(&self) -> F64SharedRef {
		self.shared_value_ref.clone()
	}
}

impl<C: Chain, Clnt: Client<C>, V: FloatStorageValue> Metric
	for FloatStorageValueMetric<C, Clnt, V>
{
	fn register(&self, registry: &Registry) -> Result<(), PrometheusError> {
		register(self.metric.clone(), registry).map(drop)
	}
}

#[async_trait]
impl<C: Chain, Clnt: Client<C>, V: FloatStorageValue> StandaloneMetric
	for FloatStorageValueMetric<C, Clnt, V>
{
	fn update_interval(&self) -> Duration {
		C::AVERAGE_BLOCK_INTERVAL * UPDATE_INTERVAL_IN_BLOCKS
	}

	async fn update(&self) {
		let value = async move {
			let best_header_hash = self.client.best_header_hash().await?;
			let maybe_storage_value = self
				.client
				.raw_storage_value(best_header_hash, self.storage_key.clone())
				.await?;
			self.value_converter.decode(maybe_storage_value).map(|maybe_fixed_point_value| {
				maybe_fixed_point_value.map(|fixed_point_value| {
					fixed_point_value.into_inner().unique_saturated_into() as f64 /
						V::Value::DIV.unique_saturated_into() as f64
				})
			})
		}
		.await
		.map_err(|e| e.to_string());

		relay_utils::metrics::set_gauge_value(&self.metric, value.clone());
		*self.shared_value_ref.write().await = value.ok().and_then(|x| x);
	}
}