Skip to main content

tuwunel_service/resolver/
cache.rs

1use std::{net::IpAddr, sync::Arc, time::SystemTime};
2
3use futures::{Stream, StreamExt, future::join};
4use ruma::ServerName;
5use serde::{Deserialize, Serialize};
6use tuwunel_core::{
7	Result,
8	arrayvec::ArrayVec,
9	at, err, implement,
10	utils::{math::Expected, rand, stream::TryIgnore},
11};
12use tuwunel_database::{Cbor, Deserialized, Map};
13
14use super::{DestString, FedDest};
15
16pub struct Cache {
17	destinations: Arc<Map>,
18	overrides: Arc<Map>,
19}
20
21/// A server name's discovered federation destination, cached until `expire`.
22///
23/// The route kind (`srv`) has no serde default on purpose: rows written before
24/// it fail to decode, so their destination is rediscovered rather than guessed.
25#[derive(Clone, Debug, Deserialize, Serialize)]
26pub struct CachedDest {
27	/// Authority federation requests are addressed to, with its port.
28	pub dest: FedDest,
29
30	/// The server name or its well-known delegate, with port.
31	pub host: DestString,
32
33	/// When the entry lapses and the destination is discovered again.
34	pub expire: SystemTime,
35
36	/// Whether destination discovery selected an SRV route.
37	pub srv: bool,
38}
39
40#[derive(Clone, Debug, Deserialize, Serialize)]
41pub struct CachedOverride {
42	pub ips: IpAddrs,
43	pub port: u16,
44	pub expire: SystemTime,
45	pub overriding: Option<DestString>,
46}
47
48pub type IpAddrs = ArrayVec<IpAddr, MAX_IPS>;
49pub(crate) const MAX_IPS: usize = 3;
50
51impl Cache {
52	pub(super) fn new(args: &crate::Args<'_>) -> Arc<Self> {
53		Arc::new(Self {
54			destinations: args.db["servername_destination"].clone(),
55			overrides: args.db["servername_override"].clone(),
56		})
57	}
58}
59
60#[implement(Cache)]
61pub async fn clear(&self) { join(self.clear_destinations(), self.clear_overrides()).await; }
62
63#[implement(Cache)]
64pub async fn clear_destinations(&self) { self.destinations.clear().await; }
65
66#[implement(Cache)]
67pub async fn clear_overrides(&self) { self.overrides.clear().await; }
68
69#[implement(Cache)]
70pub fn del_destination(&self, name: &ServerName) { self.destinations.remove(name); }
71
72#[implement(Cache)]
73pub fn del_override(&self, name: &str) { self.overrides.remove(name); }
74
75#[implement(Cache)]
76pub fn set_destination(&self, name: &ServerName, dest: &CachedDest) {
77	self.destinations.raw_put(name, Cbor(dest));
78}
79
80#[implement(Cache)]
81pub fn set_override(&self, name: &str, over: &CachedOverride) {
82	self.overrides.raw_put(name, Cbor(over));
83}
84
85#[implement(Cache)]
86#[must_use]
87pub async fn has_destination(&self, destination: &ServerName) -> bool {
88	self.get_destination(destination).await.is_ok()
89}
90
91/// Whether a valid override for `name` already points at `hostname`.
92///
93/// Only SRV routes write overrides, so a row that does not match is replaced
94/// rather than reused.
95#[implement(Cache)]
96#[must_use]
97pub async fn has_override(&self, name: &str, hostname: &str) -> bool {
98	self.get_override(name)
99		.await
100		.is_ok_and(|cached| cached.covers(hostname))
101}
102
103/// Whether this override is valid and points at `hostname`.
104///
105/// A plain row (no `overriding`) is left by an older release and never matches.
106#[implement(CachedOverride)]
107#[inline]
108#[must_use]
109pub fn covers(&self, hostname: &str) -> bool {
110	self.valid() && self.overriding.as_deref() == Some(hostname)
111}
112
113#[implement(Cache)]
114pub async fn get_destination(&self, name: &ServerName) -> Result<CachedDest> {
115	self.destinations
116		.get(name)
117		.await
118		.deserialized::<Cbor<_>>()
119		.map(at!(0))
120		.into_iter()
121		.find(CachedDest::valid)
122		.ok_or(err!(Request(NotFound("Expired from cache"))))
123}
124
125#[implement(Cache)]
126pub async fn get_override(&self, name: &str) -> Result<CachedOverride> {
127	self.overrides
128		.get(name)
129		.await
130		.deserialized::<Cbor<_>>()
131		.map(at!(0))
132}
133
134#[implement(Cache)]
135pub fn destinations(&self) -> impl Stream<Item = (&ServerName, CachedDest)> + Send + '_ {
136	self.destinations
137		.stream()
138		.ignore_err()
139		.map(|item: (&ServerName, Cbor<_>)| (item.0, item.1.0))
140}
141
142#[implement(Cache)]
143pub fn overrides(&self) -> impl Stream<Item = (&ServerName, CachedOverride)> + Send + '_ {
144	self.overrides
145		.stream()
146		.ignore_err()
147		.map(|item: (&ServerName, Cbor<_>)| (item.0, item.1.0))
148}
149
150impl CachedDest {
151	#[inline]
152	#[must_use]
153	pub fn valid(&self) -> bool { self.expire > SystemTime::now() }
154
155	#[must_use]
156	pub(crate) fn default_expire() -> SystemTime {
157		rand::time_from_now_secs(60 * 60 * 18..60 * 60 * 36)
158	}
159
160	#[inline]
161	#[must_use]
162	pub fn size(&self) -> usize {
163		self.dest
164			.size()
165			.expected_add(self.host.len())
166			.expected_add(size_of_val(&self.expire))
167			.expected_add(size_of_val(&self.srv))
168	}
169}
170
171impl CachedOverride {
172	#[inline]
173	#[must_use]
174	pub fn valid(&self) -> bool { self.expire > SystemTime::now() }
175
176	#[must_use]
177	pub(crate) fn default_expire() -> SystemTime {
178		rand::time_from_now_secs(60 * 60 * 6..60 * 60 * 12)
179	}
180
181	#[inline]
182	#[must_use]
183	pub fn size(&self) -> usize { size_of_val(self) }
184}