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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.

// Parity Ethereum 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 Ethereum 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 Ethereum.  If not, see <http://www.gnu.org/licenses/>.

//! RPC Requests Statistics

use jsonrpc_core as core;
use jsonrpc_core::futures::future::{Either, FutureExt};
use log::debug;
use order_stat;
use parking_lot::RwLock;
use std::{
    fmt,
    sync::{
        atomic::{self, AtomicUsize},
        Arc,
    },
    time,
};

const RATE_SECONDS: usize = 10;
const STATS_SAMPLES: usize = 60;

struct RateCalculator {
    era: time::Instant,
    samples: [u16; RATE_SECONDS],
}

impl fmt::Debug for RateCalculator {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{} req/s", self.rate())
    }
}

impl Default for RateCalculator {
    fn default() -> Self {
        RateCalculator {
            era: time::Instant::now(),
            samples: [0; RATE_SECONDS],
        }
    }
}

impl RateCalculator {
    fn elapsed(&self) -> u64 { self.era.elapsed().as_secs() }

    pub fn tick(&mut self) -> u16 {
        if self.elapsed() >= RATE_SECONDS as u64 {
            self.era = time::Instant::now();
            self.samples[0] = 0;
        }

        let pos = self.elapsed() as usize % RATE_SECONDS;
        let next = (pos + 1) % RATE_SECONDS;
        self.samples[next] = 0;
        self.samples[pos] = self.samples[pos].saturating_add(1);
        self.samples[pos]
    }

    fn current_rate(&self) -> usize {
        let now = match self.elapsed() {
            i if i >= RATE_SECONDS as u64 => RATE_SECONDS,
            i => i as usize + 1,
        };
        let sum: usize = self.samples[0..now].iter().map(|x| *x as usize).sum();
        sum / now
    }

    pub fn rate(&self) -> usize {
        if self.elapsed() > RATE_SECONDS as u64 {
            0
        } else {
            self.current_rate()
        }
    }
}

struct StatsCalculator<T = u32> {
    filled: bool,
    idx: usize,
    samples: [T; STATS_SAMPLES],
}

impl<T: Default + Copy> Default for StatsCalculator<T> {
    fn default() -> Self {
        StatsCalculator {
            filled: false,
            idx: 0,
            samples: [T::default(); STATS_SAMPLES],
        }
    }
}

impl<T: fmt::Display + Default + Copy + Ord> fmt::Debug for StatsCalculator<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "median: {} ms", self.approximated_median())
    }
}

impl<T: Default + Copy + Ord> StatsCalculator<T> {
    pub fn add(&mut self, sample: T) {
        self.idx += 1;
        if self.idx >= STATS_SAMPLES {
            self.filled = true;
            self.idx = 0;
        }

        self.samples[self.idx] = sample;
    }

    /// Returns approximate of media
    pub fn approximated_median(&self) -> T {
        let mut copy = [T::default(); STATS_SAMPLES];
        copy.copy_from_slice(&self.samples);
        let bound = if self.filled {
            STATS_SAMPLES
        } else {
            self.idx + 1
        };

        let (_, &mut median) =
            order_stat::median_of_medians(&mut copy[0..bound]);
        median
    }
}

/// RPC Statistics
#[derive(Default, Debug)]
pub struct RpcStats {
    requests: RwLock<RateCalculator>,
    roundtrips: RwLock<StatsCalculator<u128>>,
    active_sessions: AtomicUsize,
}

impl RpcStats {
    /// Count session opened
    pub fn open_session(&self) {
        self.active_sessions.fetch_add(1, atomic::Ordering::SeqCst);
    }

    /// Count session closed.
    /// Silently overflows if closing unopened session.
    pub fn close_session(&self) {
        self.active_sessions.fetch_sub(1, atomic::Ordering::SeqCst);
    }

    /// Count request. Returns number of requests in current second.
    pub fn count_request(&self) -> u16 { self.requests.write().tick() }

    /// Add roundtrip time (microseconds)
    pub fn add_roundtrip(&self, microseconds: u128) {
        self.roundtrips.write().add(microseconds)
    }

    /// Returns number of open sessions
    pub fn sessions(&self) -> usize {
        self.active_sessions.load(atomic::Ordering::Relaxed)
    }

    /// Returns requests rate
    pub fn requests_rate(&self) -> usize { self.requests.read().rate() }

    /// Returns approximated roundtrip in microseconds
    pub fn approximated_roundtrip(&self) -> u128 {
        self.roundtrips.read().approximated_median()
    }
}

/// Notifies about RPC activity.
pub trait ActivityNotifier: Send + Sync + 'static {
    /// Activity on RPC interface
    fn active(&self);
}

/// Stats-counting RPC middleware
pub struct Middleware<T: ActivityNotifier = ClientNotifier> {
    stats: Arc<RpcStats>,
    notifier: T,
}

impl<T: ActivityNotifier> Middleware<T> {
    /// Create new Middleware with stats counter and activity notifier.
    pub fn new(stats: Arc<RpcStats>, notifier: T) -> Self {
        Middleware { stats, notifier }
    }
}

impl<M: core::Metadata, T: ActivityNotifier> core::Middleware<M>
    for Middleware<T>
{
    type CallFuture = core::middleware::NoopCallFuture;
    type Future = core::FutureResponse;

    fn on_request<F, X>(
        &self, request: core::Request, meta: M, process: F,
    ) -> Either<Self::Future, X>
    where
        F: FnOnce(core::Request, M) -> X,
        X: core::futures::Future<Output = Option<core::Response>>
            + Send
            + 'static,
    {
        let start = time::Instant::now();

        self.notifier.active();
        self.stats.count_request();

        let id = match request {
            core::Request::Single(core::Call::MethodCall(ref call)) => {
                Some(call.id.clone())
            }
            _ => None,
        };
        let stats = self.stats.clone();

        let future = process(request, meta).map(move |res| {
            let time = start.elapsed().as_micros();
            if time > 10_000 {
                debug!(target: "rpc", "[{:?}] Took {}ms", id, time / 1_000);
            }
            stats.add_roundtrip(time);
            res
        });

        Either::Left(future.boxed())
    }
}

/// Client Notifier
pub struct ClientNotifier {
    //    pub client: Arc<::ethcore::client::Client>,
}

impl ActivityNotifier for ClientNotifier {
    fn active(&self) {
        //        self.client.keep_alive()
    }
}

#[cfg(test)]
mod tests {
    use super::{RateCalculator, RpcStats, StatsCalculator};

    #[test]
    fn should_calculate_rate() {
        // given
        let mut avg = RateCalculator::default();

        // when
        avg.tick();
        avg.tick();
        avg.tick();
        let rate = avg.rate();

        // then
        assert_eq!(rate, 3usize);
    }

    #[test]
    fn should_approximate_median() {
        // given
        let mut stats = StatsCalculator::default();
        stats.add(5);
        stats.add(100);
        stats.add(3);
        stats.add(15);
        stats.add(20);
        stats.add(6);

        // when
        let median = stats.approximated_median();

        // then
        assert_eq!(median, 5);
    }

    #[test]
    fn should_count_rpc_stats() {
        // given
        let stats = RpcStats::default();
        assert_eq!(stats.sessions(), 0);
        assert_eq!(stats.requests_rate(), 0);
        assert_eq!(stats.approximated_roundtrip(), 0);

        // when
        stats.open_session();
        stats.close_session();
        stats.open_session();
        stats.count_request();
        stats.count_request();
        stats.add_roundtrip(125);

        // then
        assert_eq!(stats.sessions(), 1);
        assert_eq!(stats.requests_rate(), 2);
        assert_eq!(stats.approximated_roundtrip(), 125);
    }

    #[test]
    fn should_be_sync_and_send() {
        let stats = RpcStats::default();
        is_sync(stats);
    }

    fn is_sync<F: Send + Sync>(x: F) { drop(x) }
}