relay_server/services/relays.rs
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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use relay_auth::{PublicKey, RelayId};
use relay_config::{Config, RelayInfo};
use relay_system::{
Addr, BroadcastChannel, BroadcastResponse, BroadcastSender, FromMessage, Interface, Service,
};
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use crate::services::upstream::{Method, RequestPriority, SendQuery, UpstreamQuery, UpstreamRelay};
use crate::utils::{RetryBackoff, SleepHandle};
/// Resolves [`RelayInfo`] by it's [identifier](RelayId).
///
/// This message may fail if the upstream is not reachable repeatedly and Relay information cannot
/// be resolved.
#[derive(Debug)]
pub struct GetRelay {
/// The unique identifier of the Relay deployment.
///
/// This is part of the Relay credentials file and determined during setup.
pub relay_id: RelayId,
}
/// Response of a [`GetRelay`] message.
///
/// This is `Some` if the Relay is known by the upstream or `None` the Relay is unknown.
pub type GetRelayResult = Option<RelayInfo>;
/// Manages authentication information for downstream Relays.
#[derive(Debug)]
pub struct RelayCache(GetRelay, BroadcastSender<GetRelayResult>);
impl Interface for RelayCache {}
impl FromMessage<GetRelay> for RelayCache {
type Response = BroadcastResponse<GetRelayResult>;
fn from_message(message: GetRelay, sender: BroadcastSender<GetRelayResult>) -> Self {
Self(message, sender)
}
}
/// Compatibility format for deserializing [`GetRelaysResponse`] from the legacy endpoint.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicKeysResultCompatibility {
/// DEPRECATED. Legacy format only public key info.
#[serde(default, rename = "public_keys")]
pub public_keys: HashMap<RelayId, Option<PublicKey>>,
/// A map from Relay's identifier to its information.
///
/// Missing entries or explicit `None` both indicate that a Relay with this ID is not known by
/// the upstream and should not be authenticated.
#[serde(default)]
pub relays: HashMap<RelayId, Option<RelayInfo>>,
}
/// Response of the [`GetRelays`] upstream query.
///
/// Former versions of the endpoint returned a different response containing only public keys,
/// defined by [`PublicKeysResultCompatibility`]. Relay's own endpoint is allowed to skip this field
/// and return just the new information.
#[derive(Debug, Serialize, Deserialize)]
pub struct GetRelaysResponse {
/// A map from Relay's identifier to its information.
///
/// Missing entries or explicit `None` both indicate that a Relay with this ID is not known by
/// the upstream and should not be authenticated.
pub relays: HashMap<RelayId, Option<RelayInfo>>,
}
impl From<PublicKeysResultCompatibility> for GetRelaysResponse {
fn from(relays_info: PublicKeysResultCompatibility) -> Self {
let relays = if relays_info.relays.is_empty() && !relays_info.public_keys.is_empty() {
relays_info
.public_keys
.into_iter()
.map(|(id, pk)| (id, pk.map(RelayInfo::new)))
.collect()
} else {
relays_info.relays
};
Self { relays }
}
}
/// Upstream batch query to resolve information for Relays by ID.
#[derive(Debug, Deserialize, Serialize)]
pub struct GetRelays {
/// A list of Relay deployment identifiers to fetch.
pub relay_ids: Vec<RelayId>,
}
impl UpstreamQuery for GetRelays {
type Response = PublicKeysResultCompatibility;
fn method(&self) -> Method {
Method::POST
}
fn path(&self) -> Cow<'static, str> {
Cow::Borrowed("/api/0/relays/publickeys/")
}
fn priority() -> RequestPriority {
RequestPriority::High
}
fn retry() -> bool {
false
}
fn route(&self) -> &'static str {
"public_keys"
}
}
/// Cache entry with metadata.
#[derive(Debug)]
enum RelayState {
Exists {
relay: RelayInfo,
checked_at: Instant,
},
DoesNotExist {
checked_at: Instant,
},
}
impl RelayState {
/// Returns `true` if this cache entry is still valid.
fn is_valid_cache(&self, config: &Config) -> bool {
match *self {
RelayState::Exists { checked_at, .. } => {
checked_at.elapsed() < config.relay_cache_expiry()
}
RelayState::DoesNotExist { checked_at } => {
checked_at.elapsed() < config.cache_miss_expiry()
}
}
}
/// Returns `Some` if there is an existing entry.
///
/// This entry may be expired; use `is_valid_cache` to verify this.
fn as_option(&self) -> Option<&RelayInfo> {
match *self {
RelayState::Exists { ref relay, .. } => Some(relay),
_ => None,
}
}
/// Constructs a cache entry from an upstream response.
fn from_option(option: Option<RelayInfo>) -> Self {
match option {
Some(relay) => RelayState::Exists {
relay,
checked_at: Instant::now(),
},
None => RelayState::DoesNotExist {
checked_at: Instant::now(),
},
}
}
}
/// Result type of the background fetch task.
///
/// - `Ok`: The task succeeded and information from the response should be inserted into the cache.
/// - `Err`: The task failed and the channels should be placed back for the next fetch.
type FetchResult = Result<GetRelaysResponse, HashMap<RelayId, BroadcastChannel<GetRelayResult>>>;
/// Service implementing the [`RelayCache`] interface.
#[derive(Debug)]
pub struct RelayCacheService {
static_relays: HashMap<RelayId, RelayInfo>,
relays: HashMap<RelayId, RelayState>,
channels: HashMap<RelayId, BroadcastChannel<GetRelayResult>>,
fetch_channel: (mpsc::Sender<FetchResult>, mpsc::Receiver<FetchResult>),
backoff: RetryBackoff,
delay: SleepHandle,
config: Arc<Config>,
upstream_relay: Addr<UpstreamRelay>,
}
impl RelayCacheService {
/// Creates a new [`RelayCache`] service.
pub fn new(config: Arc<Config>, upstream_relay: Addr<UpstreamRelay>) -> Self {
Self {
static_relays: config.static_relays().clone(),
relays: HashMap::new(),
channels: HashMap::new(),
fetch_channel: mpsc::channel(1),
backoff: RetryBackoff::new(config.http_max_retry_interval()),
delay: SleepHandle::idle(),
config,
upstream_relay,
}
}
/// Returns a clone of the sender for the background fetch task.
fn fetch_tx(&self) -> mpsc::Sender<FetchResult> {
let (ref tx, _) = self.fetch_channel;
tx.clone()
}
/// Returns the backoff timeout for a batched upstream query.
///
/// If previous queries succeeded, this will be the general batch interval. Additionally, an
/// exponentially increasing backoff is used for retrying the upstream request.
fn next_backoff(&mut self) -> Duration {
self.config.downstream_relays_batch_interval() + self.backoff.next_backoff()
}
/// Schedules a batched upstream query with exponential backoff.
fn schedule_fetch(&mut self) {
let backoff = self.next_backoff();
self.delay.set(backoff);
}
/// Executes an upstream request to fetch information on downstream Relays.
///
/// This assumes that currently no request is running. If the upstream request fails or new
/// channels are pushed in the meanwhile, this will reschedule automatically.
fn fetch_relays(&mut self) {
let channels = std::mem::take(&mut self.channels);
relay_log::debug!(
"updating public keys for {} relays (attempt {})",
channels.len(),
self.backoff.attempt(),
);
let fetch_tx = self.fetch_tx();
let upstream_relay = self.upstream_relay.clone();
relay_system::spawn!(async move {
let request = GetRelays {
relay_ids: channels.keys().cloned().collect(),
};
let query_result = match upstream_relay.send(SendQuery(request)).await {
Ok(inner) => inner,
// Drop the channels to propagate the `SendError` up.
Err(_send_error) => return,
};
let fetch_result = match query_result {
Ok(response) => {
let response = GetRelaysResponse::from(response);
for (id, channel) in channels {
relay_log::debug!("relay {id} public key updated");
let info = response.relays.get(&id).unwrap_or(&None);
channel.send(info.clone());
}
Ok(response)
}
Err(error) => {
relay_log::error!(
error = &error as &dyn std::error::Error,
"error fetching public keys"
);
Err(channels)
}
};
fetch_tx.send(fetch_result).await.ok();
});
}
/// Handles results from the background fetch task.
fn handle_fetch_result(&mut self, result: FetchResult) {
match result {
Ok(response) => {
self.backoff.reset();
for (id, info) in response.relays {
self.relays.insert(id, RelayState::from_option(info));
}
}
Err(channels) => {
self.channels.extend(channels);
}
}
if !self.channels.is_empty() {
self.schedule_fetch();
}
}
/// Resolves information for a Relay and passes it to the sender.
///
/// Sends information immediately if it is available in the cache. Otherwise, this schedules a
/// delayed background fetch and attaches the sender to a broadcast channel.
fn get_or_fetch(&mut self, message: GetRelay, sender: BroadcastSender<GetRelayResult>) {
let relay_id = message.relay_id;
// First check the statically configured relays
if let Some(key) = self.static_relays.get(&relay_id) {
sender.send(Some(key.clone()));
return;
}
if let Some(key) = self.relays.get(&relay_id) {
if key.is_valid_cache(&self.config) {
sender.send(key.as_option().cloned());
return;
}
}
if self.config.credentials().is_none() {
relay_log::error!(
"no credentials configured. relay {relay_id} cannot send requests to this relay",
);
sender.send(None);
return;
}
relay_log::debug!("relay {relay_id} public key requested");
self.channels.entry(relay_id).or_default().attach(sender);
if !self.backoff.started() {
self.schedule_fetch();
}
}
}
impl Service for RelayCacheService {
type Interface = RelayCache;
async fn run(mut self, mut rx: relay_system::Receiver<Self::Interface>) {
relay_log::info!("key cache started");
loop {
tokio::select! {
// Prioritize flush over receiving messages to prevent starving.
biased;
Some(result) = self.fetch_channel.1.recv() => self.handle_fetch_result(result),
() = &mut self.delay => self.fetch_relays(),
Some(message) = rx.recv() => self.get_or_fetch(message.0, message.1),
else => break,
}
}
relay_log::info!("key cache stopped");
}
}