commonware_resolver/lib.rs
1//! Resolve data identified by a fixed-length key.
2
3#![doc(
4 html_logo_url = "https://commonware.xyz/imgs/rustdoc_logo.svg",
5 html_favicon_url = "https://commonware.xyz/favicon.ico"
6)]
7
8commonware_macros::stability_scope!(BETA {
9 use commonware_actor::Feedback;
10 use commonware_cryptography::PublicKey;
11 use commonware_utils::{Span, channel::oneshot, vec::NonEmptyVec};
12 use core::cmp::Ordering;
13
14 pub mod delivery;
15 mod ingress;
16 pub mod opaque;
17 pub mod p2p;
18 mod subscribers;
19
20 /// A key to fetch data for a subscriber.
21 #[derive(Clone, Debug)]
22 pub struct Fetch<K, S = ()> {
23 /// The peer-visible key.
24 pub key: K,
25 /// Subscriber attached to the key.
26 pub subscriber: S,
27 /// Trace span carried from issuance to delivery.
28 pub span: tracing::Span,
29 }
30
31 impl<K: PartialEq, S: PartialEq> PartialEq for Fetch<K, S> {
32 fn eq(&self, other: &Self) -> bool {
33 self.key == other.key && self.subscriber == other.subscriber
34 }
35 }
36
37 impl<K: Eq, S: Eq> Eq for Fetch<K, S> {}
38
39 impl<K: PartialOrd, S: PartialOrd> PartialOrd for Fetch<K, S> {
40 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
41 match self.key.partial_cmp(&other.key)? {
42 Ordering::Equal => self.subscriber.partial_cmp(&other.subscriber),
43 ordering => Some(ordering),
44 }
45 }
46 }
47
48 impl<K: Ord, S: Ord> Ord for Fetch<K, S> {
49 fn cmp(&self, other: &Self) -> Ordering {
50 self.key
51 .cmp(&other.key)
52 .then_with(|| self.subscriber.cmp(&other.subscriber))
53 }
54 }
55
56 impl<K, S: Default> From<K> for Fetch<K, S> {
57 fn from(key: K) -> Self {
58 Self {
59 key,
60 subscriber: S::default(),
61 span: tracing::Span::none(),
62 }
63 }
64 }
65
66 /// Data delivered for a resolved fetch.
67 #[derive(Clone, Debug)]
68 pub struct Delivery<K, S> {
69 /// The peer-visible key used to validate the response.
70 pub key: K,
71 /// Subscribers that were still retained when the response arrived, each
72 /// paired with the trace span of the fetch that requested it.
73 pub subscribers: NonEmptyVec<(S, tracing::Span)>,
74 }
75
76 impl<K: PartialEq, S: PartialEq> PartialEq for Delivery<K, S> {
77 fn eq(&self, other: &Self) -> bool {
78 self.key == other.key
79 && self.subscribers.len() == other.subscribers.len()
80 && self
81 .subscribers
82 .iter()
83 .zip(other.subscribers.iter())
84 .all(|((a, _), (b, _))| a == b)
85 }
86 }
87
88 impl<K: Eq, S: Eq> Eq for Delivery<K, S> {}
89
90 impl<K: PartialOrd, S: PartialOrd> PartialOrd for Delivery<K, S> {
91 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
92 match self.key.partial_cmp(&other.key)? {
93 Ordering::Equal => self
94 .subscribers
95 .iter()
96 .map(|(subscriber, _)| subscriber)
97 .partial_cmp(other.subscribers.iter().map(|(subscriber, _)| subscriber)),
98 ordering => Some(ordering),
99 }
100 }
101 }
102
103 impl<K: Ord, S: Ord> Ord for Delivery<K, S> {
104 fn cmp(&self, other: &Self) -> Ordering {
105 self.key.cmp(&other.key).then_with(|| {
106 self.subscribers
107 .iter()
108 .map(|(subscriber, _)| subscriber)
109 .cmp(other.subscribers.iter().map(|(subscriber, _)| subscriber))
110 })
111 }
112 }
113
114 /// Consumer disposition for a delivered response.
115 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
116 pub enum Outcome {
117 /// The response is invalid for the peer-visible key.
118 ///
119 /// Network resolvers may penalize the serving peer before retrying.
120 Invalid,
121
122 /// The response is valid and satisfies every delivered subscriber.
123 Complete,
124
125 /// The peer-visible key admits multiple valid responses, and this response does not
126 /// satisfy every delivered subscriber.
127 ///
128 /// The resolver retries the key without penalizing the serving peer so another response
129 /// can be tried.
130 Ambiguous,
131
132 /// The consumer no longer needs the key, so the response does not need to be validated.
133 ///
134 /// The resolver retires the key and all of its subscribers without retrying or
135 /// attributing the response to its source.
136 Ignored,
137 }
138
139 impl From<bool> for Outcome {
140 fn from(valid: bool) -> Self {
141 if valid { Self::Complete } else { Self::Invalid }
142 }
143 }
144
145 /// Determines the disposition of data returned for a fetch.
146 pub trait Consumer: Clone + Send + 'static {
147 /// Type used to key data requested from peers.
148 type Key: Span;
149
150 /// Type of data to retrieve.
151 type Value;
152
153 /// Type used to track subscribers on fetch keys.
154 type Subscriber: Clone + Eq + Send + 'static;
155
156 /// Delivery disposition returned after validation.
157 ///
158 /// Consumers that only distinguish valid and invalid data may use
159 /// `bool`, which maps to [`crate::Outcome::Complete`] and
160 /// [`crate::Outcome::Invalid`].
161 type Outcome: Into<crate::Outcome> + Send + 'static;
162
163 /// Deliver data to the consumer.
164 ///
165 /// Returns a receiver that reports whether the response completes the
166 /// delivery, is invalid, is valid but leaves subscribers unresolved, or
167 /// can be ignored because the key is no longer needed.
168 ///
169 /// The returned receiver may be dropped before completion if the application
170 /// cancels the fetch via [`Resolver::retain`]. When this happens, the
171 /// resolver discards the validation result.
172 ///
173 /// If the consumer drops the sender without reporting a verdict, the
174 /// response is handed to the remaining subscribers, or the key is retired
175 /// without penalizing its source when none remain. The subscribers in the
176 /// dropped delivery are not retried.
177 ///
178 /// Implementations of [`Resolver`] must only invoke `deliver` for keys that were
179 /// previously requested via [`Resolver::fetch`] (or [`TargetedResolver`] variants).
180 ///
181 /// `delivery` contains the peer-visible key and the retained subscribers
182 /// for the fetch. Subscribers decide who should observe a valid response;
183 /// they do not define peer validity.
184 fn deliver(
185 &mut self,
186 delivery: Delivery<Self::Key, Self::Subscriber>,
187 value: Self::Value,
188 ) -> oneshot::Receiver<Self::Outcome>;
189 }
190
191 /// Responsible for fetching data and notifying a `Consumer`.
192 pub trait Resolver: Clone + Send + 'static {
193 /// Type used to key data requested from peers.
194 type Key: Span;
195
196 /// Type used to track subscribers on fetch keys.
197 ///
198 /// Implementations that also own the [`Consumer`] should supply subscribers to
199 /// [`Consumer::deliver`] when a fetch resolves.
200 type Subscriber: Clone + Eq + Send + 'static;
201
202 /// Initiate a fetch.
203 ///
204 /// The resolver fetches and delivers the key. The subscriber is
205 /// retained and supplied to [`Consumer::deliver`] when the fetch resolves.
206 /// If multiple subscribers are attached to the same key,
207 /// the fetch is retained as long as at least one subscriber satisfies the
208 /// latest [`retain`](Self::retain) predicate.
209 ///
210 /// Passing a bare key is supported when `Subscriber: Default`.
211 fn fetch<F>(&mut self, key: F) -> Feedback
212 where
213 F: Into<Fetch<Self::Key, Self::Subscriber>> + Send;
214
215 /// Initiate fetches for a batch of keys.
216 fn fetch_all<F>(&mut self, keys: Vec<F>) -> Feedback
217 where
218 F: Into<Fetch<Self::Key, Self::Subscriber>> + Send;
219
220 /// Retain only fetch subscribers satisfying the predicate.
221 ///
222 /// The predicate receives the peer-visible key and subscriber.
223 ///
224 /// Fetches not retained are canceled. If response validation is in
225 /// progress, cancellation may drop the [`Consumer::deliver`] future
226 /// before it reports whether the data was valid.
227 fn retain(
228 &mut self,
229 predicate: impl Fn(&Self::Key, &Self::Subscriber) -> bool + Send + 'static,
230 ) -> Feedback;
231 }
232
233 /// Extension for resolvers that accept target peer hints.
234 pub trait TargetedResolver: Resolver {
235 /// Type used to identify peers for targeted fetch hints.
236 type PublicKey: PublicKey;
237
238 /// Initiate a fetch with target peer hints.
239 ///
240 /// Implementations define whether target hints persist through retries,
241 /// merge with existing in-progress fetches, or are discarded.
242 fn fetch_targeted(
243 &mut self,
244 fetch: impl Into<Fetch<Self::Key, Self::Subscriber>> + Send,
245 targets: NonEmptyVec<Self::PublicKey>,
246 ) -> Feedback;
247
248 /// Initiate fetches for multiple keys, each with their own target hints.
249 ///
250 /// See [`fetch_targeted`](Self::fetch_targeted) for details on target behavior.
251 fn fetch_all_targeted<F>(
252 &mut self,
253 keys: Vec<(F, NonEmptyVec<Self::PublicKey>)>,
254 ) -> Feedback
255 where
256 F: Into<Fetch<Self::Key, Self::Subscriber>> + Send;
257 }
258});