Skip to main content

heika_peer/
book.rs

1//! 住所録。知っているノードのアドレスと、それぞれを今使っているか、続けて失敗した回数、次に試してよい時刻、ban の
2//! 期限。しまう記録([`KnownPeer`])にもする。アドレスはどこにも出さない。
3
4use std::collections::BTreeMap;
5use std::time::{Duration, Instant};
6
7/// つなぎに行けなかったか、通信に失敗して外したアドレスを、次に試すまで空ける時間の始めと上限。続けて
8/// 失敗するたびに倍にする
9const RETRY_START: Duration = Duration::from_secs(60);
10const RETRY_MAX: Duration = Duration::from_secs(3600);
11/// 確かめられないものを返したアドレスに、つながない長さ(秒)。住所録にしまって、始め直しても覚えておく
12pub const BAN_SECONDS: u64 = 7 * 24 * 60 * 60;
13
14/// 知っているノードのアドレスと、それぞれを今使っているか、次にいつ試してよいか。アドレスはどこにも出さない
15pub struct Book {
16    entries: Vec<Candidate>,
17}
18
19struct Candidate {
20    address: String,
21    /// つないでいるか、つなぎに行っている
22    in_use: bool,
23    /// 確かめられないものを返したので、この時刻(UNIX 秒と、この実行での時刻)までつながない
24    banned: Option<(u64, Instant)>,
25    /// 続けて失敗した回数
26    failures: u32,
27    /// 最後につながった時刻(UNIX 秒)
28    last_success: u64,
29    /// 次に試してよい時刻
30    ready_at: Instant,
31}
32
33impl Book {
34    pub fn new(addresses: Vec<String>, now: Instant) -> Self {
35        let mut candidates = Self {
36            entries: Vec::new(),
37        };
38        for address in addresses {
39            if candidates.find(&address).is_none() {
40                candidates.entries.push(Candidate::new(address, now));
41            }
42        }
43        candidates
44    }
45
46    /// しまってあった住所録から作る。続けて失敗していたものは、その回数に応じて空けてから試す。`unix`(今の
47    /// UNIX 秒)でまだ ban の続いているものは試さない
48    pub fn load(known: Vec<(String, KnownPeer)>, now: Instant, unix: u64) -> Self {
49        let mut candidates = Self::new(Vec::new(), now);
50        for (address, record) in known {
51            candidates.insert(address.clone(), now);
52            if let Some(candidate) = candidates.find(&address) {
53                candidate.last_success = record.last_success;
54                candidate.failures = record.failures;
55                if record.banned_until > unix {
56                    let left = Duration::from_secs(record.banned_until - unix);
57                    candidate.banned = Some((record.banned_until, now + left));
58                }
59                if record.failures > 0 {
60                    candidate.ready_at = now + backoff(record.failures);
61                }
62            }
63        }
64        candidates
65    }
66
67    /// 知らないアドレスなら足して真を返す。もう [`MAX_CANDIDATES`] 件あれば足さない
68    pub fn insert(&mut self, address: String, now: Instant) -> bool {
69        let new = self.find(&address).is_none() && self.entries.len() < MAX_CANDIDATES;
70        if new {
71            self.entries.push(Candidate::new(address, now));
72        }
73        new
74    }
75
76    /// しまう住所録。確からしいものから [`MAX_KNOWN`] 件と、ban しているもの([`MAX_KNOWN`] 件まで)
77    pub fn records(&self) -> Vec<(String, KnownPeer)> {
78        let now = Instant::now();
79        let record = |candidate: &Candidate| {
80            (
81                candidate.address.clone(),
82                KnownPeer {
83                    last_success: candidate.last_success,
84                    failures: candidate.failures,
85                    banned_until: candidate
86                        .banned
87                        .filter(|_| candidate.is_banned(now))
88                        .map_or(0, |(until, _)| until),
89                },
90            )
91        };
92        let known: BTreeMap<String, KnownPeer> = self
93            .entries
94            .iter()
95            .filter(|candidate| !candidate.is_banned(now))
96            .map(record)
97            .collect();
98        let mut records: Vec<(String, KnownPeer)> = best(&known, MAX_KNOWN)
99            .into_iter()
100            .map(|address| {
101                let record = known[&address];
102                (address, record)
103            })
104            .collect();
105        records.extend(
106            self.entries
107                .iter()
108                .filter(|candidate| candidate.is_banned(now))
109                .take(MAX_KNOWN)
110                .map(record),
111        );
112        records
113    }
114
115    fn find(&mut self, address: &str) -> Option<&mut Candidate> {
116        self.entries
117            .iter_mut()
118            .find(|candidate| candidate.address == address)
119    }
120
121    pub fn insert_in_use(&mut self, address: &str, now: Instant) {
122        if self.find(address).is_none() {
123            self.entries.push(Candidate::new(address.to_owned(), now));
124        }
125        if let Some(candidate) = self.find(address) {
126            candidate.in_use = true;
127        }
128    }
129
130    /// 知っているノードの数(ban しているものを除く)
131    pub fn known(&self) -> usize {
132        let now = Instant::now();
133        self.entries
134            .iter()
135            .filter(|candidate| !candidate.is_banned(now))
136            .count()
137    }
138
139    /// 今試してよいアドレスのうち、続けて失敗した回数が一番少ないものを使用中にして返す。なければ `None`
140    pub fn take(&mut self, now: Instant) -> Option<String> {
141        let candidate = self
142            .entries
143            .iter_mut()
144            .filter(|candidate| {
145                !candidate.in_use && !candidate.is_banned(now) && candidate.ready_at <= now
146            })
147            .min_by_key(|candidate| {
148                (
149                    candidate.failures,
150                    std::cmp::Reverse(candidate.last_success),
151                )
152            })?;
153        candidate.in_use = true;
154        Some(candidate.address.clone())
155    }
156
157    /// つながった。`unix` はその時刻(UNIX 秒)
158    pub fn connected(&mut self, address: &str, unix: u64) {
159        if let Some(candidate) = self.find(address) {
160            candidate.failures = 0;
161            candidate.last_success = unix;
162        }
163    }
164
165    /// 罰さずに外した(入れ替えなど)。失敗は数えず、すぐまた試してよい
166    pub fn release(&mut self, address: &str) {
167        if let Some(candidate) = self.find(address) {
168            candidate.in_use = false;
169        }
170    }
171
172    /// つなぎに行けなかったか、通信に失敗して外した。間を空けてから、また試す
173    pub fn failed(&mut self, address: &str, now: Instant) {
174        if let Some(candidate) = self.find(address) {
175            candidate.in_use = false;
176            candidate.failures += 1;
177            candidate.ready_at = now + backoff(candidate.failures);
178        }
179    }
180
181    /// 確かめられないものを返したので外した。今(`now`、UNIX 秒で `unix`)から [`BAN_SECONDS`] は試さない
182    pub fn ban(&mut self, address: &str, now: Instant, unix: u64) {
183        if let Some(candidate) = self.find(address) {
184            candidate.in_use = false;
185            candidate.banned = Some((unix + BAN_SECONDS, now + Duration::from_secs(BAN_SECONDS)));
186        }
187    }
188}
189
190/// `failures` 回続けて失敗したアドレスを、次に試すまで空ける時間
191fn backoff(failures: u32) -> Duration {
192    RETRY_START
193        .saturating_mul(2u32.saturating_pow(failures.saturating_sub(1)))
194        .min(RETRY_MAX)
195}
196
197impl Candidate {
198    fn is_banned(&self, now: Instant) -> bool {
199        self.banned.is_some_and(|(_, ends)| ends > now)
200    }
201
202    fn new(address: String, now: Instant) -> Self {
203        Self {
204            address,
205            in_use: false,
206            banned: None,
207            failures: 0,
208            last_success: 0,
209            ready_at: now,
210        }
211    }
212}
213
214/// 始めるときに、住所録の確からしいもの([`best`])から並べてつないでみる数
215pub const FIRST_TRIES: usize = 16;
216
217/// 住所録のアドレスを、確からしい順(続けて失敗した回数が少なく、最後につながったのが新しい順)に `count` 個
218pub fn best(known: &BTreeMap<String, KnownPeer>, count: usize) -> Vec<String> {
219    let mut sorted: Vec<(&String, &KnownPeer)> = known.iter().collect();
220    sorted.sort_by_key(|(_, record)| (record.failures, std::cmp::Reverse(record.last_success)));
221    sorted
222        .into_iter()
223        .take(count)
224        .map(|(address, _)| address.clone())
225        .collect()
226}
227
228/// 住所録の1件。DB にしまう
229#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
230pub struct KnownPeer {
231    /// 最後につながった時刻(UNIX 秒)。つながったことがなければ 0
232    pub last_success: u64,
233    /// 続けて失敗した回数
234    pub failures: u32,
235    /// この時刻(UNIX 秒)まで、つながない。ban していなければ 0
236    pub banned_until: u64,
237}
238
239impl KnownPeer {
240    pub fn to_bytes(self) -> Vec<u8> {
241        let mut bytes = self.last_success.to_le_bytes().to_vec();
242        bytes.extend_from_slice(&self.failures.to_le_bytes());
243        bytes.extend_from_slice(&self.banned_until.to_le_bytes());
244        bytes
245    }
246
247    /// 読めなければ `None`。ban を足す前の 12 バイトのものも読む
248    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
249        if bytes.len() != 12 && bytes.len() != 20 {
250            return None;
251        }
252        Some(Self {
253            last_success: u64::from_le_bytes(bytes[..8].try_into().ok()?),
254            failures: u32::from_le_bytes(bytes[8..12].try_into().ok()?),
255            banned_until: match bytes.get(12..) {
256                Some(rest) if !rest.is_empty() => u64::from_le_bytes(rest.try_into().ok()?),
257                _ => 0,
258            },
259        })
260    }
261}
262
263/// しまう住所録の件数の上限。確からしいものから残す
264pub const MAX_KNOWN: usize = 1000;
265
266/// メモリに持つ住所録の件数の上限。ピアの一覧で、いくらでも足させないため
267pub const MAX_CANDIDATES: usize = 2 * MAX_KNOWN;
268
269/// ピアの一覧1つから住所録に足す数の上限
270pub const MAX_LISTED: usize = 256;
271
272/// ホストとポートから、つなぐときのアドレスを作る。IPv6 のアドレスは角括弧で包む
273pub fn endpoint(host: &str, port: u16) -> String {
274    if host.contains(':') && !host.starts_with('[') {
275        format!("[{host}]:{port}")
276    } else {
277        format!("{host}:{port}")
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284
285    #[test]
286    fn candidates_wait_longer_after_each_failure_and_never_retry_a_banned_one() {
287        let start = Instant::now();
288        let mut candidates = Book::new(vec!["a".to_owned(), "b".to_owned()], start);
289        candidates.insert_in_use("seed", start);
290        assert_eq!(candidates.take(start).as_deref(), Some("a"));
291        assert_eq!(candidates.take(start).as_deref(), Some("b"));
292        // 使用中のものは、ほかに返さない
293        assert_eq!(candidates.take(start), None);
294        candidates.failed("a", start);
295        candidates.ban("b", start, 1000);
296        candidates.failed("seed", start);
297        candidates.failed("seed", start);
298        assert_eq!(candidates.take(start), None);
299        // 1 回失敗した a は 1 分後に、2 回の seed は 2 分後に試してよくなる。b は二度と出てこない
300        let later = start + RETRY_START;
301        assert_eq!(candidates.take(later).as_deref(), Some("a"));
302        assert_eq!(candidates.take(later), None);
303        candidates.connected("a", 1);
304        candidates.failed("a", later);
305        let much_later = later + RETRY_MAX;
306        assert_eq!(candidates.take(much_later).as_deref(), Some("a"));
307        assert_eq!(candidates.take(much_later).as_deref(), Some("seed"));
308        assert_eq!(candidates.take(much_later), None);
309    }
310
311    #[test]
312    fn known_peers_round_trip_and_keep_the_most_likely_first() {
313        let record = KnownPeer {
314            last_success: 1_792_270_000,
315            failures: 3,
316            banned_until: 1_792_870_000,
317        };
318        assert_eq!(KnownPeer::from_bytes(&record.to_bytes()), Some(record));
319        // ban を足す前の 12 バイトも読む
320        assert_eq!(
321            KnownPeer::from_bytes(&record.to_bytes()[..12]),
322            Some(KnownPeer {
323                banned_until: 0,
324                ..record
325            })
326        );
327        assert_eq!(KnownPeer::from_bytes(&[0; 11]), None);
328        assert_eq!(KnownPeer::from_bytes(&[0; 13]), None);
329        let start = Instant::now();
330        let known = |last_success, failures| KnownPeer {
331            last_success,
332            failures,
333            banned_until: 0,
334        };
335        let mut candidates = Book::load(
336            vec![
337                ("old".to_owned(), known(100, 0)),
338                ("new".to_owned(), known(200, 0)),
339                ("failing".to_owned(), known(300, 2)),
340                ("never".to_owned(), known(0, 0)),
341            ],
342            start,
343            1000,
344        );
345        // 失敗の少ないものから、同じなら最後につながったのが新しいものから試す。失敗していたものは空けてから
346        assert_eq!(candidates.take(start).as_deref(), Some("new"));
347        assert_eq!(candidates.take(start).as_deref(), Some("old"));
348        assert_eq!(candidates.take(start).as_deref(), Some("never"));
349        assert_eq!(candidates.take(start), None);
350        assert_eq!(
351            candidates.take(start + backoff(2)).as_deref(),
352            Some("failing")
353        );
354        candidates.connected("never", 400);
355        candidates.ban("old", start, 1000);
356        let records = candidates.records();
357        let order: Vec<&str> = records
358            .iter()
359            .map(|(address, _)| address.as_str())
360            .collect();
361        // ban したものは、期限を付けて最後にしまう
362        assert_eq!(order, ["never", "new", "failing", "old"]);
363        assert_eq!(records[0].1, known(400, 0));
364        assert_eq!(records[3].1.banned_until, 1000 + BAN_SECONDS);
365        // しまったものから作り直すと、期限まではつながず、過ぎたらつなぐ
366        let take_all = |unix| {
367            let mut loaded = Book::load(records.clone(), start, unix);
368            std::iter::from_fn(|| loaded.take(start)).collect::<Vec<_>>()
369        };
370        assert!(!take_all(1000 + BAN_SECONDS - 1).contains(&"old".to_owned()));
371        assert!(take_all(1000 + BAN_SECONDS).contains(&"old".to_owned()));
372    }
373
374    #[test]
375    fn a_ban_ends_while_running_and_the_book_has_a_limit() {
376        let start = Instant::now();
377        let mut candidates = Book::new(vec!["a".to_owned()], start);
378        assert_eq!(candidates.take(start).as_deref(), Some("a"));
379        candidates.ban("a", start, 1000);
380        let ends = start + Duration::from_secs(BAN_SECONDS);
381        assert_eq!(candidates.take(ends - Duration::from_secs(1)), None);
382        assert_eq!(candidates.take(ends).as_deref(), Some("a"));
383        for index in 0..MAX_CANDIDATES * 2 {
384            candidates.insert(format!("n{index}"), start);
385        }
386        assert_eq!(candidates.entries.len(), MAX_CANDIDATES);
387        assert!(!candidates.insert("more".to_owned(), start));
388    }
389
390    #[test]
391    fn ipv6_hosts_are_bracketed() {
392        assert_eq!(endpoint("2001:db8::1", 7900), "[2001:db8::1]:7900");
393        assert_eq!(endpoint("[2001:db8::1]", 7900), "[2001:db8::1]:7900");
394        assert_eq!(endpoint("node.example", 7900), "node.example:7900");
395        assert_eq!(endpoint("192.0.2.1", 7900), "192.0.2.1:7900");
396    }
397
398    #[test]
399    fn retries_stop_growing_at_the_maximum() {
400        let start = Instant::now();
401        let mut candidates = Book::new(vec!["a".to_owned()], start);
402        for _ in 0..40 {
403            assert!(candidates.take(start + RETRY_MAX * 100).is_some());
404            candidates.failed("a", start);
405        }
406        assert_eq!(
407            candidates.take(start + RETRY_MAX - Duration::from_secs(1)),
408            None
409        );
410        assert!(candidates.take(start + RETRY_MAX).is_some());
411    }
412}