Skip to main content

tuwunel_service/rendezvous/
mod.rs

1//! In-memory rendezvous session exchange.
2//!
3//! The service holds short-lived client rendezvous payloads, conditional validators, recorded
4//! transactions, and per-client rate-limit buckets. Sessions are bounded in count and intentionally
5//! disappear on restart.
6
7use std::{
8	cmp::max,
9	collections::{BTreeMap, HashMap, VecDeque},
10	net::IpAddr,
11	str,
12	sync::{Arc, Mutex, RwLock},
13	time::{Duration, Instant, SystemTime, UNIX_EPOCH},
14};
15
16use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD as b64};
17use bytes::Bytes;
18use http::StatusCode;
19use ruma::{
20	OwnedTransactionId, TransactionId,
21	api::error::{ErrorKind, LimitExceededErrorData},
22};
23use tuwunel_core::{
24	Error, Result,
25	arrayvec::ArrayString,
26	implement,
27	utils::{hash::sha256::concat, rand::string_array, time::duration_since_epoch},
28};
29
30/// Fixed-capacity identifier for a rendezvous session.
31///
32/// New sessions receive a random 32-character ASCII identifier.
33pub type SessionId = ArrayString<SESSION_ID_LENGTH>;
34
35/// Quoted HTTP entity tag for rendezvous payload state.
36///
37/// The fixed capacity holds the encoded digest and its surrounding quotation marks.
38pub type Etag = ArrayString<ETAG_LENGTH>;
39type Sessions = BTreeMap<SessionId, Session>;
40type Ratelimiter = Mutex<HashMap<IpAddr, (Instant, f64)>>;
41type Transactions = VecDeque<(OwnedTransactionId, Etag)>;
42
43/// Stores bounded rendezvous sessions and request rate-limit state.
44///
45/// Both stores are process-local and shared through locks. Expired sessions are removed lazily
46/// during creation, retrieval, or conditional mutation.
47pub struct Service {
48	sessions: RwLock<Sessions>,
49	// At most 4096 short-lived per-IP buckets.
50	ratelimiter: Ratelimiter,
51	services: Arc<crate::services::OnceServices>,
52}
53
54/// Complete process-local state for one rendezvous session.
55///
56/// Creation time determines capacity eviction, while modification and expiration times drive HTTP
57/// metadata and lifecycle decisions.
58struct Session {
59	data: Bytes,
60	etag: Etag,
61	created: SystemTime,
62	last_modified: SystemTime,
63	expires_at: SystemTime,
64	transactions: Transactions,
65}
66
67/// HTTP metadata associated with a rendezvous payload.
68///
69/// The entity tag and modification time identify the current representation. Expiration determines
70/// how long the session remains active.
71#[derive(Clone, Copy, Debug, Eq, PartialEq)]
72pub struct Meta {
73	/// Quoted entity tag for conditional requests.
74	pub etag: Etag,
75
76	/// Absolute time at which the session expires.
77	pub expires_at: SystemTime,
78
79	/// Last payload modification time.
80	pub last_modified: SystemTime,
81}
82
83/// Outcome of retrieving a rendezvous session.
84///
85/// A matching conditional validator returns metadata without cloning the payload. Missing and
86/// expired sessions share the not-found outcome.
87#[derive(Clone, Debug, Eq, PartialEq)]
88pub enum Get {
89	/// Current payload and its HTTP metadata.
90	Data {
91		/// Opaque rendezvous payload.
92		data: Bytes,
93
94		/// Metadata describing the returned representation.
95		meta: Meta,
96	},
97
98	/// Metadata for a representation matching the request validator.
99	NotModified(Meta),
100
101	/// Session was absent or expired.
102	NotFound,
103}
104
105/// Outcome of conditionally replacing a rendezvous payload.
106///
107/// Accepted updates return the metadata of the state they settled on, including idempotent
108/// retries. Each transport defines what counts as a retry, and any other stale validator returns
109/// the existing metadata as a precondition failure.
110#[derive(Clone, Copy, Debug, Eq, PartialEq)]
111pub enum Put {
112	/// Replacement or idempotent retry was accepted.
113	Accepted(Meta),
114
115	/// Validator was stale and the request was not a retry.
116	PreconditionFailed(Meta),
117
118	/// Session was absent or expired.
119	NotFound,
120}
121
122/// A single send attempt under a sequence token.
123///
124/// The transaction ID identifies a retry of the attempt within its session, and a client changing
125/// the token or the payload makes a new attempt.
126#[derive(Clone, Copy, Debug)]
127pub struct Attempt<'a> {
128	/// Client-chosen identifier, scoped to the rendezvous session.
129	pub txn_id: &'a TransactionId,
130
131	/// Unquoted token of the state this attempt replaces.
132	pub sequence_token: &'a str,
133}
134
135const SESSION_ID_LENGTH: usize = 32;
136const ETAG_VALUE_LENGTH: usize = 43;
137const ETAG_LENGTH: usize = ETAG_VALUE_LENGTH + 2;
138const MILLIS_PER_SECOND: u64 = 1000;
139const MAX_HTTP_DATE_SECONDS: u64 = 253_402_300_799;
140const MONOTONIC_STEP: Duration = Duration::from_millis(1);
141const RATELIMIT_MAP_CAP: usize = 4096;
142const MAX_TRANSACTIONS: usize = 100;
143
144#[cfg(test)]
145mod tests;
146
147impl crate::Service for Service {
148	fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
149		Ok(Arc::new(Self {
150			sessions: RwLock::new(Sessions::new()),
151			ratelimiter: Mutex::new(HashMap::new()),
152			services: args.services.clone(),
153		}))
154	}
155
156	fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
157}
158
159/// Charges one request against a client's rendezvous rate-limit bucket.
160///
161/// Buckets refill at the configured rate up to the configured burst size. A depleted bucket returns
162/// a limit-exceeded request error, and the per-client table remains bounded.
163#[implement(Service)]
164pub fn check_rate_limit(&self, client: IpAddr) -> Result {
165	let config = &self.services.server.config;
166	let rate = f64::from(config.rendezvous.rc_per_second.max(1));
167	let burst = f64::from(config.rendezvous.rc_burst_count.max(1));
168
169	check_bucket_at(&self.ratelimiter, client, rate, burst, Instant::now())
170}
171
172fn check_bucket_at(
173	table: &Ratelimiter,
174	client: IpAddr,
175	rate: f64,
176	burst: f64,
177	now: Instant,
178) -> Result {
179	let mut buckets = table.lock()?;
180
181	if buckets.len() >= RATELIMIT_MAP_CAP && !buckets.contains_key(&client) {
182		let mut oldest = None;
183
184		buckets.retain(|client, (last, tokens)| {
185			let refilled = now
186				.duration_since(*last)
187				.as_secs_f64()
188				.mul_add(rate, *tokens);
189			let retain = refilled < burst;
190
191			if retain && oldest.is_none_or(|(_, oldest_at)| *last < oldest_at) {
192				oldest = Some((*client, *last));
193			}
194
195			retain
196		});
197
198		if buckets.len() >= RATELIMIT_MAP_CAP
199			&& let Some((oldest, _)) = oldest
200		{
201			buckets.remove(&oldest);
202		}
203	}
204
205	let (last_time, tokens) = buckets.entry(client).or_insert((now, burst));
206	let new_tokens = now
207		.duration_since(*last_time)
208		.as_secs_f64()
209		.mul_add(rate, *tokens)
210		.min(burst);
211
212	if new_tokens < 1.0 {
213		return Err(Error::Request(
214			ErrorKind::LimitExceeded(LimitExceededErrorData { retry_after: None }),
215			"Too many rendezvous requests.".into(),
216			StatusCode::TOO_MANY_REQUESTS,
217		));
218	}
219
220	*last_time = now;
221	*tokens = new_tokens - 1.0;
222
223	Ok(())
224}
225
226/// Creates a rendezvous session for an opaque payload.
227///
228/// Expired sessions are pruned first, then the oldest live sessions are evicted to honor the
229/// configured capacity, with an effective minimum of one. The returned metadata describes the
230/// newly stored representation.
231///
232/// # Panics
233///
234/// Panics if the session lock has been poisoned.
235#[implement(Service)]
236pub fn create(&self, data: Bytes) -> (SessionId, Meta) {
237	let config = &self.services.server.config;
238	let ttl = Duration::from_secs(config.rendezvous.session_ttl);
239
240	self.create_at(data, SystemTime::now(), ttl, config.rendezvous.max_sessions)
241}
242
243#[implement(Service)]
244fn create_at(
245	&self,
246	data: Bytes,
247	now: SystemTime,
248	ttl: Duration,
249	max_sessions: usize,
250) -> (SessionId, Meta) {
251	let capacity = max_sessions.max(1);
252	let mut id = string_array::<SESSION_ID_LENGTH>();
253	let expires_at = expires_at(now, ttl);
254
255	let mut sessions = self.sessions.write().expect("locked for writing");
256
257	sessions.retain(|_, session| session.is_live(now));
258	while sessions.contains_key(id.as_str()) {
259		id = string_array::<SESSION_ID_LENGTH>();
260	}
261
262	while sessions.len() >= capacity {
263		let Some(id) = sessions
264			.iter()
265			.min_by_key(|(_, session)| session.created)
266			.map(|(id, _)| *id)
267		else {
268			break;
269		};
270
271		sessions.remove(&id);
272	}
273
274	let session = Session {
275		etag: etag(id.as_str(), &data, now),
276		data,
277		created: now,
278		last_modified: now,
279		expires_at,
280		transactions: Transactions::new(),
281	};
282
283	let meta = session.meta();
284
285	sessions.insert(id, session);
286
287	(id, meta)
288}
289
290/// Retrieves a rendezvous payload with optional entity-tag validation.
291///
292/// A matching tag or wildcard returns [`Get::NotModified`]; otherwise a live session returns its
293/// data. Expired sessions are removed and reported as not found.
294///
295/// # Panics
296///
297/// Panics if the session lock has been poisoned.
298#[implement(Service)]
299pub fn get(&self, id: &str, if_none_match: Option<&str>) -> Get {
300	self.get_at(id, if_none_match, SystemTime::now())
301}
302
303#[implement(Service)]
304fn get_at(&self, id: &str, if_none_match: Option<&str>, now: SystemTime) -> Get {
305	{
306		let sessions = self.sessions.read().expect("locked for reading");
307
308		match sessions.get(id) {
309			| Some(session) if session.is_live(now) => {
310				return get_outcome(session, if_none_match);
311			},
312			| Some(_) => {},
313			| None => return Get::NotFound,
314		}
315	}
316
317	let mut sessions = self.sessions.write().expect("locked for writing");
318	if sessions
319		.get(id)
320		.is_some_and(|session| !session.is_live(now))
321	{
322		sessions.remove(id);
323
324		return Get::NotFound;
325	}
326
327	sessions
328		.get(id)
329		.map_or(Get::NotFound, |session| get_outcome(session, if_none_match))
330}
331
332/// Conditionally replaces a rendezvous payload using a quoted entity tag.
333///
334/// A matching validator stores the new payload and advances its metadata. A stale validator accepts
335/// identical data as a retry that only refreshes expiration, and rejects different data with the
336/// current metadata.
337///
338/// # Panics
339///
340/// Panics if the session lock has been poisoned.
341#[implement(Service)]
342pub fn put(&self, id: &str, if_match: &str, data: Bytes) -> Put {
343	let ttl = Duration::from_secs(self.services.server.config.rendezvous.session_ttl);
344
345	self.put_at(id, if_match, data, SystemTime::now(), ttl)
346}
347
348#[implement(Service)]
349fn put_at(&self, id: &str, if_match: &str, data: Bytes, now: SystemTime, ttl: Duration) -> Put {
350	self.update_at(id, now, |session| {
351		match etag_matches(if_match, &session.etag) {
352			| true => session.replace(id, data, now, ttl),
353			| false if data == session.data => session.expires_at = expires_at(now, ttl),
354			| false => return Put::PreconditionFailed(session.meta()),
355		}
356
357		Put::Accepted(session.meta())
358	})
359}
360
361/// Conditionally replaces a rendezvous payload for one send attempt.
362///
363/// A transaction the session has recorded returns its recorded token and changes nothing. Otherwise
364/// the sequence token must match, whatever the data, and a replacement records the transaction.
365/// A session remembers only its newest transactions, so a long-evicted retry is judged as new.
366///
367/// # Panics
368///
369/// Panics if the session lock has been poisoned.
370#[implement(Service)]
371pub fn put_token(&self, id: &str, attempt: Attempt<'_>, data: Bytes) -> Put {
372	let ttl = Duration::from_secs(self.services.server.config.rendezvous.session_ttl);
373
374	self.put_token_at(id, attempt, data, SystemTime::now(), ttl)
375}
376
377#[implement(Service)]
378fn put_token_at(
379	&self,
380	id: &str,
381	attempt: Attempt<'_>,
382	data: Bytes,
383	now: SystemTime,
384	ttl: Duration,
385) -> Put {
386	self.update_at(id, now, |session| match session.recorded(attempt.txn_id) {
387		| Some(recorded) => Put::Accepted(recorded),
388		| None if attempt.sequence_token != etag_value(&session.etag) =>
389			Put::PreconditionFailed(session.meta()),
390		| None => {
391			session.replace(id, data, now, ttl);
392			session.record(attempt.txn_id);
393
394			Put::Accepted(session.meta())
395		},
396	})
397}
398
399/// Runs a conditional update on a live session at a supplied time.
400///
401/// An expired session is removed and reported as not found before the update can see it.
402#[implement(Service)]
403fn update_at<Update>(&self, id: &str, now: SystemTime, update: Update) -> Put
404where
405	Update: FnOnce(&mut Session) -> Put,
406{
407	let mut sessions = self.sessions.write().expect("locked for writing");
408
409	if sessions
410		.get(id)
411		.is_some_and(|session| !session.is_live(now))
412	{
413		sessions.remove(id);
414
415		return Put::NotFound;
416	}
417
418	sessions.get_mut(id).map_or(Put::NotFound, update)
419}
420
421/// Looks up the outcome recorded for a transaction of a live session.
422///
423/// A caller can answer a retried send before validating its request. [`Self::put_token`] checks the
424/// record again under the write lock, which settles two racing retries.
425///
426/// # Panics
427///
428/// Panics if the session lock has been poisoned.
429#[implement(Service)]
430pub fn recorded(&self, id: &str, txn_id: &TransactionId) -> Option<Meta> {
431	self.recorded_at(id, txn_id, SystemTime::now())
432}
433
434#[implement(Service)]
435fn recorded_at(&self, id: &str, txn_id: &TransactionId, now: SystemTime) -> Option<Meta> {
436	self.sessions
437		.read()
438		.expect("locked for reading")
439		.get(id)
440		.filter(|session| session.is_live(now))
441		.and_then(|session| session.recorded(txn_id))
442}
443
444#[implement(Session)]
445fn recorded(&self, txn_id: &TransactionId) -> Option<Meta> {
446	self.transactions
447		.iter()
448		.find(|(recorded, _)| recorded == txn_id)
449		.map(|(_, etag)| Meta { etag: *etag, ..self.meta() })
450}
451
452#[implement(Session)]
453fn replace(&mut self, id: &str, data: Bytes, now: SystemTime, ttl: Duration) {
454	self.last_modified = next_last_modified(now, self.last_modified);
455	self.etag = etag(id, &data, self.last_modified);
456	self.expires_at = expires_at(now, ttl);
457	self.data = data;
458}
459
460#[implement(Session)]
461fn record(&mut self, txn_id: &TransactionId) {
462	if self.transactions.len() >= MAX_TRANSACTIONS {
463		self.transactions.pop_front();
464	}
465
466	self.transactions
467		.push_back((txn_id.to_owned(), self.etag));
468}
469
470#[implement(Session)]
471#[inline]
472fn is_live(&self, now: SystemTime) -> bool { self.expires_at > now }
473
474/// Deletes a rendezvous session regardless of expiration.
475///
476/// The return value reports whether any stored session was removed, including an expired one.
477///
478/// # Panics
479///
480/// Panics if the session lock has been poisoned.
481#[implement(Service)]
482pub fn delete(&self, id: &str) -> bool {
483	self.sessions
484		.write()
485		.expect("locked for writing")
486		.remove(id)
487		.is_some()
488}
489
490/// Deletes a rendezvous session and reports whether it was active.
491///
492/// Expired sessions are still removed but return `false`. An absent session also returns `false`.
493///
494/// # Panics
495///
496/// Panics if the session lock has been poisoned.
497#[implement(Service)]
498pub fn delete_if_active(&self, id: &str) -> bool {
499	self.delete_if_active_at(id, SystemTime::now())
500}
501
502#[implement(Service)]
503fn delete_if_active_at(&self, id: &str, now: SystemTime) -> bool {
504	self.sessions
505		.write()
506		.expect("locked for writing")
507		.remove(id)
508		.is_some_and(|session| session.is_live(now))
509}
510
511/// Returns the unquoted sequence token for this representation.
512///
513/// The token is the digest value contained by the HTTP entity tag.
514///
515/// # Panics
516///
517/// Panics if [`Self::etag`] does not contain matching quotation marks.
518#[implement(Meta)]
519#[must_use]
520#[inline]
521pub fn sequence_token(&self) -> &str { etag_value(&self.etag) }
522
523fn etag_value(etag: &Etag) -> &str {
524	etag.as_str()
525		.strip_prefix('"')
526		.and_then(|value| value.strip_suffix('"'))
527		.expect("ETag is quoted")
528}
529
530/// Returns the remaining lifetime of the session.
531///
532/// Expired sessions report [`Duration::ZERO`] rather than a negative duration.
533#[implement(Meta)]
534#[must_use]
535#[inline]
536pub fn expires_in(&self) -> Duration { self.expires_in_at(SystemTime::now()) }
537
538#[implement(Meta)]
539fn expires_in_at(&self, now: SystemTime) -> Duration {
540	self.expires_at
541		.duration_since(now)
542		.unwrap_or_default()
543}
544
545#[implement(Session)]
546#[inline]
547fn meta(&self) -> Meta {
548	Meta {
549		etag: self.etag,
550		expires_at: self.expires_at,
551		last_modified: self.last_modified,
552	}
553}
554
555fn expires_at(now: SystemTime, ttl: Duration) -> SystemTime {
556	let latest = UNIX_EPOCH
557		.checked_add(Duration::from_secs(MAX_HTTP_DATE_SECONDS))
558		.expect("latest HTTP date should fit in SystemTime");
559
560	now.checked_add(ttl)
561		.map_or(latest, |expires_at| expires_at.min(latest))
562}
563
564fn next_last_modified(now: SystemTime, previous: SystemTime) -> SystemTime {
565	previous
566		.checked_add(MONOTONIC_STEP)
567		.map_or(now, |next| max(now, next))
568}
569
570fn etag(id: &str, data: &Bytes, last_modified: SystemTime) -> Etag {
571	let elapsed = duration_since_epoch(last_modified);
572	let millis = elapsed
573		.as_secs()
574		.saturating_mul(MILLIS_PER_SECOND)
575		.saturating_add(u64::from(elapsed.subsec_millis()));
576
577	let timestamp = millis.to_be_bytes();
578	let digest = concat([id.as_bytes(), data.as_ref(), timestamp.as_slice()].into_iter());
579	let mut encoded = [0_u8; ETAG_VALUE_LENGTH];
580	let len = b64
581		.encode_slice(digest, &mut encoded)
582		.expect("ETag buffer has exact capacity");
583
584	let encoded = str::from_utf8(&encoded[..len]).expect("base64url is valid UTF-8");
585
586	Etag::try_from(format_args!("\"{encoded}\"")).expect("ETag has exact capacity")
587}
588
589fn get_outcome(session: &Session, if_none_match: Option<&str>) -> Get {
590	let meta = session.meta();
591
592	if if_none_match.is_some_and(|candidate| etag_matches(candidate, &session.etag)) {
593		Get::NotModified(meta)
594	} else {
595		Get::Data { data: session.data.clone(), meta }
596	}
597}
598
599fn etag_matches(candidate: &str, etag: &Etag) -> bool {
600	candidate == "*" || candidate == etag.as_str()
601}