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::{channel::oneshot, vec::NonEmptyVec, Span};
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 /// Notified when data is available, and must validate it.
115 pub trait Consumer: Clone + Send + 'static {
116 /// Type used to key data requested from peers.
117 type Key: Span;
118
119 /// Type of data to retrieve.
120 type Value;
121
122 /// Type used to track subscribers on fetch keys.
123 type Subscriber: Clone + Eq + Send + 'static;
124
125 /// Deliver data to the consumer.
126 ///
127 /// Returns a receiver that resolves to `true` if the data is valid for the key.
128 ///
129 /// The returned receiver may be dropped before completion if the application
130 /// cancels the fetch via [`Resolver::retain`]. When this happens, the
131 /// resolver discards the validation result.
132 ///
133 /// Implementations of [`Resolver`] must only invoke `deliver` for keys that were
134 /// previously requested via [`Resolver::fetch`] (or [`TargetedResolver`] variants).
135 ///
136 /// `delivery` contains the peer-visible key and the retained subscribers
137 /// for the fetch. Subscribers decide who should observe a valid response;
138 /// they do not define peer validity.
139 fn deliver(
140 &mut self,
141 delivery: Delivery<Self::Key, Self::Subscriber>,
142 value: Self::Value,
143 ) -> oneshot::Receiver<bool>;
144 }
145
146 /// Responsible for fetching data and notifying a `Consumer`.
147 pub trait Resolver: Clone + Send + 'static {
148 /// Type used to key data requested from peers.
149 type Key: Span;
150
151 /// Type used to track subscribers on fetch keys.
152 ///
153 /// Implementations that also own the [`Consumer`] should supply subscribers to
154 /// [`Consumer::deliver`] when a fetch resolves.
155 type Subscriber: Clone + Eq + Send + 'static;
156
157 /// Initiate a fetch.
158 ///
159 /// The resolver fetches and delivers the key. The subscriber is
160 /// retained and supplied to [`Consumer::deliver`] when the fetch resolves.
161 /// If multiple subscribers are attached to the same key,
162 /// the fetch is retained as long as at least one subscriber satisfies the
163 /// latest [`retain`](Self::retain) predicate.
164 ///
165 /// Passing a bare key is supported when `Subscriber: Default`.
166 fn fetch<F>(&mut self, key: F) -> Feedback
167 where
168 F: Into<Fetch<Self::Key, Self::Subscriber>> + Send;
169
170 /// Initiate fetches for a batch of keys.
171 fn fetch_all<F>(&mut self, keys: Vec<F>) -> Feedback
172 where
173 F: Into<Fetch<Self::Key, Self::Subscriber>> + Send;
174
175 /// Retain only fetch subscribers satisfying the predicate.
176 ///
177 /// The predicate receives the peer-visible key and subscriber.
178 ///
179 /// Fetches not retained are canceled. If response validation is in
180 /// progress, cancellation may drop the [`Consumer::deliver`] future
181 /// before it reports whether the data was valid.
182 fn retain(
183 &mut self,
184 predicate: impl Fn(&Self::Key, &Self::Subscriber) -> bool + Send + 'static,
185 ) -> Feedback;
186 }
187
188 /// Extension for resolvers that accept target peer hints.
189 pub trait TargetedResolver: Resolver {
190 /// Type used to identify peers for targeted fetch hints.
191 type PublicKey: PublicKey;
192
193 /// Initiate a fetch with target peer hints.
194 ///
195 /// Implementations define whether target hints persist through retries,
196 /// merge with existing in-progress fetches, or are discarded.
197 fn fetch_targeted(
198 &mut self,
199 fetch: impl Into<Fetch<Self::Key, Self::Subscriber>> + Send,
200 targets: NonEmptyVec<Self::PublicKey>,
201 ) -> Feedback;
202
203 /// Initiate fetches for multiple keys, each with their own target hints.
204 ///
205 /// See [`fetch_targeted`](Self::fetch_targeted) for details on target behavior.
206 fn fetch_all_targeted<F>(
207 &mut self,
208 keys: Vec<(F, NonEmptyVec<Self::PublicKey>)>,
209 ) -> Feedback
210 where
211 F: Into<Fetch<Self::Key, Self::Subscriber>> + Send;
212 }
213});