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
//! Far discovery is generation-bound, prefix-filtered and never guessed.
use serde_json::Value;
use std::collections::BTreeMap;
use std::num::NonZeroUsize;
use std::sync::{Mutex, MutexGuard};
#[path = "link_federated/projection.rs"]
mod projection;
/// Bounds checked before any peer-controlled discovery data is retained.
#[derive(Clone, Copy, Debug)]
pub struct ProjectionLimits {
/// Maximum snapshot bytes, bounding JSON parsing and retained contracts.
pub bytes: NonZeroUsize,
/// Maximum stations per snapshot, bounding directory indexing work.
pub stations: NonZeroUsize,
/// Maximum distinct links, bounding total discovery memory.
pub peers: NonZeroUsize,
}
/// Discovery refuses without leaking schema or message bytes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum DiscoveryError {
/// Input or retained discovery exceeded an operator bound.
#[error("far_topology_bound")]
Bound,
/// The far document is not a whole topology from its own device.
#[error("far_topology_invalid")]
Invalid,
/// A stale link generation or topology revision cannot replace current data.
#[error("far_topology_stale")]
Stale,
/// A poisoned registry cannot supply trusted discovery.
#[error("far_topology_unavailable")]
Unavailable,
/// The monotonic link generation is exhausted.
#[error("far_topology_generation_exhausted")]
Exhausted,
}
#[derive(Default)]
struct State {
generation: u64,
links: BTreeMap<String, FarLink>,
}
struct FarLink {
generation: u64,
peer: String,
prefixes: Vec<String>,
revision: Option<u64>,
document: Option<Value>,
}
/// One authoritative index used for topology, describe and service routing.
pub struct FarTopology {
limits: ProjectionLimits,
state: Mutex<State>,
}
impl std::fmt::Debug for FarTopology {
fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
out.debug_struct("FarTopology")
.field("limits", &self.limits)
.finish_non_exhaustive()
}
}
impl FarTopology {
/// Creates an empty index with required positive bounds.
#[must_use]
pub fn new(limits: ProjectionLimits) -> Self {
Self {
limits,
state: Mutex::default(),
}
}
fn lock(&self) -> Result<MutexGuard<'_, State>, DiscoveryError> {
self.state.lock().map_err(|_| DiscoveryError::Unavailable)
}
/// Binds this generation to the proved peer and configured export prefixes.
///
/// # Errors
/// Invalid identities/prefixes, peer bound, poisoned state or exhausted ids.
pub fn open(
&self,
link: &str,
peer: &str,
prefixes: Vec<String>,
) -> Result<u64, DiscoveryError> {
if link.is_empty()
|| peer.is_empty()
|| prefixes.is_empty()
|| link
.chars()
.chain(peer.chars())
.any(|character| character.is_control() || character.is_whitespace())
{
return Err(DiscoveryError::Invalid);
}
for prefix in &prefixes {
crate::auth_lys::SubjectBinding::new("wire".into(), prefix.clone(), prefix.clone())
.map_err(|_| DiscoveryError::Invalid)?;
if prefix == "liminal"
|| prefix.starts_with("liminal.")
|| prefix == "console"
|| prefix.starts_with("console.")
{
return Err(DiscoveryError::Invalid);
}
}
let mut state = self.lock()?;
if !state.links.contains_key(link) && state.links.len() >= self.limits.peers.get() {
return Err(DiscoveryError::Bound);
}
state.generation = state
.generation
.checked_add(1)
.ok_or(DiscoveryError::Exhausted)?;
let generation = state.generation;
state.links.insert(
link.into(),
FarLink {
generation,
peer: peer.into(),
prefixes,
revision: None,
document: None,
},
);
drop(state);
Ok(generation)
}
/// Accepts a whole far snapshot only from the current keyed generation.
///
/// # Errors
/// Oversize, malformed or forged document, stale revision/generation, or poisoned state.
pub fn update(
&self,
link: &str,
generation: u64,
bytes: &[u8],
) -> Result<bool, DiscoveryError> {
if bytes.len() > self.limits.bytes.get() {
return Err(DiscoveryError::Bound);
}
let document: Value = serde_json::from_slice(bytes).map_err(|_| DiscoveryError::Invalid)?;
let revision = projection::validate(&document, self.limits.stations.get())?;
let mut state = self.lock()?;
let far = state
.links
.get_mut(link)
.filter(|far| far.generation == generation)
.ok_or(DiscoveryError::Stale)?;
if far.revision.is_some_and(|previous| previous > revision) {
return Err(DiscoveryError::Stale);
}
if far.revision == Some(revision) {
return if far.document.as_ref() == Some(&document) {
Ok(false)
} else {
Err(DiscoveryError::Stale)
};
}
far.revision = Some(revision);
far.document = Some(document);
drop(state);
Ok(true)
}
/// Retires only this generation; a replaced carrier cannot remove its successor.
///
/// # Errors
/// The registry lock is poisoned.
pub fn close(&self, link: &str, generation: u64) -> Result<bool, DiscoveryError> {
let mut state = self.lock()?;
if state
.links
.get(link)
.is_some_and(|far| far.generation == generation)
{
state.links.remove(link);
drop(state);
Ok(true)
} else {
Ok(false)
}
}
/// Number of retained peer generations, including peers awaiting discovery.
///
/// # Errors
/// The registry lock is poisoned.
pub fn pending_peers(&self) -> Result<usize, DiscoveryError> {
Ok(self.lock()?.links.len())
}
/// Describes the actual far station serving an exported subject.
///
/// # Errors
/// The registry or a retained document is invalid.
pub fn describe(&self, subject: &str) -> Result<Option<Value>, DiscoveryError> {
let state = self.lock()?;
for (link, far) in &state.links {
for station in projection::stations(link, far)? {
if station["subjects"].as_array().is_some_and(|subjects| {
subjects.iter().any(|item| item.as_str() == Some(subject))
}) {
return Ok(Some(station));
}
}
}
drop(state);
Ok(None)
}
/// Projects only currently up links, preserving the supplied local revision.
/// A down record and the removal of its far stations are one atomic document.
///
/// # Errors
/// Malformed local/far topology, oversize output, encoding or registry failure.
pub fn project(&self, bytes: &[u8]) -> Result<Vec<u8>, DiscoveryError> {
projection::project(self, bytes)
}
}
fn reaches(prefix: &str, subject: &str) -> bool {
subject == prefix
|| subject
.strip_prefix(prefix)
.is_some_and(|suffix| suffix.starts_with('.'))
}