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
use kitsune2_api::{
AccessDecision, BlockTarget, DynBlocks, DynPeerStore, K2Result, PeerAccess,
PeerAccessState, Timestamp, Url,
};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Duration;
/// Core implementation of the [`PeerAccessState`] trait.
pub struct CorePeerAccessState {
decisions: Arc<RwLock<HashMap<Url, PeerAccess>>>,
abort_handle: tokio::task::AbortHandle,
}
impl Drop for CorePeerAccessState {
fn drop(&mut self) {
tracing::info!(
"CorePeerAccessState is being dropped, aborting background task"
);
self.abort_handle.abort();
}
}
impl CorePeerAccessState {
/// Create a new instance of the [`CorePeerAccessState`].
pub fn new(peer_store: DynPeerStore, blocks: DynBlocks) -> K2Result<Self> {
let decisions = Arc::new(RwLock::new(HashMap::new()));
peer_store.register_peer_update_listener(Arc::new({
let peer_store = Arc::downgrade(&peer_store);
let blocks = Arc::downgrade(&blocks);
let decisions = decisions.clone();
move |agent_info| {
let peer_store = peer_store.clone();
let blocks = blocks.clone();
let decisions = decisions.clone();
Box::pin(async move {
let Some(peer_store) = peer_store.upgrade() else {
tracing::info!("PeerStore dropped, cannot make access decision");
return;
};
let Some(blocks) = blocks.upgrade() else {
tracing::info!("Blocks dropped, cannot make access decision");
return;
};
let peer_url = match agent_info.url.clone() {
Some(url) => url,
None => {
if !agent_info.is_tombstone {
tracing::warn!("AgentInfo has no URL: {:?}", agent_info);
}
return;
}
};
tracing::debug!("Making access decision for peer URL: {:?}", peer_url);
// fetch peers by url
let agents_by_url: Vec<_> = match peer_store
.get_by_url(peer_url.clone())
.await {
Ok(peers) => peers.into_iter()
.map(|agent| BlockTarget::Agent(agent.agent.clone()))
.collect(),
Err(e) => {
tracing::error!(
"Failed to get agents by url {:?}: {:?}",
peer_url,
e
);
return;
}
};
if agents_by_url.is_empty() {
tracing::debug!("No agents found for url, clearing decision because they will be treated as blocked anyway: {:?}", peer_url);
// Any existing decision can be removed
decisions
.write()
.expect("poisoned")
.remove(&peer_url);
} else {
let any_blocked = match blocks.is_any_blocked(agents_by_url).await {
Ok(any_blocked) => any_blocked,
Err(e) => {
tracing::error!(
"Failed to check block status for url {:?}: {:?}",
peer_url,
e
);
return;
}
};
let access = if any_blocked {
PeerAccess {
decision: AccessDecision::Blocked,
decided_at: Timestamp::now(),
}
} else {
PeerAccess {
decision: AccessDecision::Granted,
decided_at: Timestamp::now(),
}
};
tracing::debug!("Access decision for peer URL {peer_url:?}: {:?}", access.decision);
decisions
.write()
.expect("poisoned")
.insert(peer_url, access.clone());
}
})
}
}))?;
let abort_handle = tokio::task::spawn({
let decisions = decisions.clone();
async move {
loop {
// Agent information is expected to be updated regularly. If updates aren't
// received then the access decisions will become stale and can be pruned.
tokio::time::sleep(Duration::from_secs(60 * 60)).await;
let result = Timestamp::now() - Duration::from_secs(60 * 60);
let Ok(old) = result else {
tracing::warn!("Failed to compute old timestamp for pruning access decisions");
continue;
};
decisions.write().expect("poisoned").retain(|_, v| {
v.decided_at > old
});
}
}
}).abort_handle();
Ok(Self {
decisions,
abort_handle,
})
}
}
impl std::fmt::Debug for CorePeerAccessState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CorePeerAccessState").finish()
}
}
impl PeerAccessState for CorePeerAccessState {
fn get_access_decision(
&self,
peer_url: Url,
) -> K2Result<Option<PeerAccess>> {
let decision = self
.decisions
.read()
.expect("poisoned")
.get(&peer_url)
.cloned();
Ok(decision)
}
}