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
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
// This file is part of OpenEthereum.

// OpenEthereum 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.

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

//! Deprecation notice for RPC methods.
//!
//! Displays a warning but avoids spamming the log.

use std::{
    collections::HashMap,
    time::{Duration, Instant},
};

use parking_lot::RwLock;

/// Deprecation messages
pub mod msgs {
    pub const ACCOUNTS: Option<&str> =
        Some("Account management is being phased out see #9997 for alternatives.");
}

type MethodName = &'static str;

const PRINT_INTERVAL: Duration = Duration::from_secs(60);

/// Displays a deprecation notice without spamming the log.
pub struct DeprecationNotice<T = fn() -> Instant> {
    now: T,
    next_warning_at: RwLock<HashMap<String, Instant>>,
    printer: Box<dyn Fn(MethodName, Option<&str>) + Send + Sync>,
}

impl Default for DeprecationNotice {
    fn default() -> Self {
        Self::new(Instant::now, |method, more| {
            let more = more
                .map(|x| format!(": {}", x))
                .unwrap_or_else(|| ".".into());
            warn!(target: "rpc", "{} is deprecated and will be removed in future versions{}", method, more);
        })
    }
}

impl<N: Fn() -> Instant> DeprecationNotice<N> {
    /// Create new deprecation notice printer with custom display and interval.
    pub fn new<T>(now: N, printer: T) -> Self
    where
        T: Fn(MethodName, Option<&str>) + Send + Sync + 'static,
    {
        DeprecationNotice {
            now,
            next_warning_at: Default::default(),
            printer: Box::new(printer),
        }
    }

    /// Print deprecation notice for given method and with some additional details (explanations).
    pub fn print<'a, T: Into<Option<&'a str>>>(&self, method: MethodName, details: T) {
        let now = (self.now)();
        match self.next_warning_at.read().get(method) {
            Some(next) if *next > now => return,
            _ => {}
        }

        self.next_warning_at
            .write()
            .insert(method.to_owned(), now + PRINT_INTERVAL);
        (self.printer)(method, details.into());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::sync::Arc;

    #[test]
    fn should_throttle_printing() {
        let saved = Arc::new(RwLock::new(None));
        let s = saved.clone();
        let printer = move |method: MethodName, more: Option<&str>| {
            *s.write() = Some((method, more.map(|s| s.to_owned())));
        };

        let now = Arc::new(RwLock::new(Instant::now()));
        let n = now.clone();
        let get_now = || n.read().clone();
        let notice = DeprecationNotice::new(get_now, printer);

        let details = Some("See issue #123456");
        notice.print("eth_test", details.clone());
        // printer shouldn't be called
        notice.print("eth_test", None);
        assert_eq!(
            saved.read().clone().unwrap(),
            ("eth_test", details.as_ref().map(|x| x.to_string()))
        );
        // but calling a different method is fine
        notice.print("eth_test2", None);
        assert_eq!(saved.read().clone().unwrap(), ("eth_test2", None));

        // wait and call again
        *now.write() = Instant::now() + PRINT_INTERVAL;
        notice.print("eth_test", None);
        assert_eq!(saved.read().clone().unwrap(), ("eth_test", None));
    }
}