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
use std::{default::Default, ops::Deref};
use crate::{expire_map::Key, ExpireMap, OnExpire};
pub trait Caller<Ctx, K> {
fn ttl() -> u8;
fn call(&mut self, ctx: &Ctx, key: &K) -> u8;
fn fail(&mut self, ctx: &Ctx, key: &K);
}
#[derive(Default)]
pub struct Retry<C> {
n: u8,
caller: C,
}
impl<Ctx, K, C: Caller<Ctx, K>> OnExpire<Ctx, K> for Retry<C> {
fn on_expire(&mut self, ctx: &Ctx, key: &K) -> u8 {
let n = self.n.wrapping_sub(1);
if n == 0 {
self.caller.fail(ctx, key);
0
} else {
self.n = n;
self.caller.call(ctx, key)
}
}
}
pub trait Task<Ctx, K> = Caller<Ctx, K>;
pub struct RetryMap<Ctx, K: Key, C: Task<Ctx, K>> {
pub expire: ExpireMap<Ctx, K, Retry<C>>,
}
impl<Ctx, K: Key, C: Task<Ctx, K>> Clone for RetryMap<Ctx, K, C> {
fn clone(&self) -> Self {
Self {
expire: self.expire.clone(),
}
}
}
impl<Ctx, K: Key, C: Task<Ctx, K>> RetryMap<Ctx, K, C> {
pub fn new(ctx: Ctx) -> Self {
Self {
expire: ExpireMap::new(ctx),
}
}
pub fn remove(&self, key: K) -> Option<C> {
if let Some(r) = self.expire.remove(key) {
Some(r.caller)
} else {
None
}
}
pub fn insert(&self, key: K, mut caller: C, retry: u8) {
caller.call(&self.ctx, &key);
self
.expire
.insert(key, Retry { n: retry, caller }, C::ttl());
}
}
impl<Ctx, K: Key, C: Task<Ctx, K>> Deref for RetryMap<Ctx, K, C> {
type Target = ExpireMap<Ctx, K, Retry<C>>;
fn deref(&self) -> &<Self as Deref>::Target {
&self.expire
}
}