Skip to main content

tuwunel_service/turn/
mod.rs

1//! Fetches TURN credentials from an external provider.
2//!
3//! One set of credentials is shared by every user and renewed after half its
4//! lifetime, so the provider sees a bounded number of requests however many
5//! clients ask. A failed fetch pauses further attempts for a minute, while any
6//! unexpired credentials keep being served.
7
8mod provider;
9#[cfg(test)]
10mod tests;
11
12use std::{
13	module_path,
14	sync::Arc,
15	time::{Duration, Instant},
16};
17
18use async_trait::async_trait;
19use ruma::api::client::voip::get_turn_server_info::v3::Response as Credentials;
20use tokio::sync::Mutex;
21use tuwunel_core::{Error, Result, config::turn::Provider, err, implement, warn};
22
23use crate::{Args, SelfServices, service::make_name};
24
25/// Shares one set of externally issued TURN credentials among all users.
26///
27/// Its lock also makes concurrent callers wait for one fetch.
28pub struct Service {
29	services: SelfServices,
30
31	/// One entry, replaced after half the provider's lifetime, and kept out of
32	/// the database because it holds a secret.
33	cache: Mutex<Cache>,
34}
35
36#[derive(Default)]
37struct Cache {
38	origin: String,
39	entry: Option<Entry>,
40	failed: Option<Instant>,
41}
42
43struct Entry {
44	credentials: Credentials,
45	renews: Instant,
46	expires: Instant,
47}
48
49/// What the cache offers a caller.
50///
51/// Only a fetch that is due goes to the provider; the other cases are answered
52/// from the cache.
53enum Lookup {
54	/// Credentials young enough to serve without renewal.
55	Fresh(Credentials),
56
57	/// A fetch is due.
58	Due,
59
60	/// A recent failure holds fetches back; whatever is still unexpired is served.
61	Held(Option<Credentials>),
62}
63
64/// Pause after a failed fetch before the provider is asked again.
65///
66/// Some clients retry every few seconds while the endpoint fails, and the pause
67/// keeps them from turning a provider outage into a stream of requests to it.
68const RETRY_DELAY: Duration = Duration::from_mins(1);
69
70#[async_trait]
71impl crate::Service for Service {
72	fn build(args: &Args<'_>) -> Result<Arc<Self>> {
73		Ok(Arc::new(Self {
74			services: args.services.clone(),
75			cache: Mutex::default(),
76		}))
77	}
78
79	async fn clear_cache(&self) { *self.cache.lock().await = Cache::default(); }
80
81	fn name(&self) -> &str { make_name(module_path!()) }
82}
83
84/// Returns TURN credentials from the configured provider.
85///
86/// Cached credentials are served until half their lifetime has passed, then
87/// renewed. When the renewal fails, what is still unexpired at that moment is
88/// served, or else 502; with no provider configured the answer is 404.
89#[implement(Service)]
90#[tracing::instrument(level = "debug", skip_all)]
91pub async fn credentials(&self) -> Result<Credentials> {
92	// A snapshot, because the provider settings stay borrowed across the fetch.
93	let config = Arc::clone(&self.services.server.config);
94	let provider = config
95		.turn
96		.provider()
97		.ok_or_else(|| err!(Request(NotFound("No TURN credential provider is configured."))))?;
98
99	let origin = origin(provider);
100	let mut cache = self.cache.lock().await;
101	let now = Instant::now();
102	match cache.lookup(origin, now) {
103		| Lookup::Fresh(credentials) => return Ok(credentials),
104		| Lookup::Held(remaining) => return remaining.ok_or_else(unavailable),
105		| Lookup::Due => {},
106	}
107
108	match self.fetch(&config.turn, provider).await {
109		| Ok(credentials) => {
110			*cache = Cache::fetched(origin, credentials.clone(), now);
111			Ok(credentials)
112		},
113		| Err(error) => {
114			warn!(%error, "Failed to fetch TURN credentials");
115			let failed = Instant::now();
116			cache.record_failure(origin, failed);
117			cache.remaining(failed).ok_or_else(unavailable)
118		},
119	}
120}
121
122#[implement(Cache)]
123fn lookup(&self, origin: &str, now: Instant) -> Lookup {
124	if self.origin != origin {
125		return Lookup::Due;
126	}
127
128	let fresh = self
129		.entry
130		.as_ref()
131		.is_some_and(|entry| now < entry.renews);
132
133	let held = self.failed.is_some_and(|failed| {
134		now.saturating_duration_since(failed)
135			.lt(&RETRY_DELAY)
136	});
137
138	match (fresh, held) {
139		| (true, _) => self
140			.remaining(now)
141			.map_or(Lookup::Due, Lookup::Fresh),
142		| (false, true) => Lookup::Held(self.remaining(now)),
143		| (false, false) => Lookup::Due,
144	}
145}
146
147#[implement(Cache)]
148fn remaining(&self, now: Instant) -> Option<Credentials> {
149	self.entry
150		.as_ref()
151		.and_then(|entry| entry.remaining(now))
152}
153
154impl Entry {
155	/// The cached credentials with their lifetime cut to what is left of it.
156	///
157	/// Expired credentials yield `None`.
158	fn remaining(&self, now: Instant) -> Option<Credentials> {
159		self.expires
160			.checked_duration_since(now)
161			.filter(|ttl| !ttl.is_zero())
162			.map(|ttl| Credentials { ttl, ..self.credentials.clone() })
163	}
164}
165
166#[implement(Cache)]
167fn fetched(origin: &str, credentials: Credentials, now: Instant) -> Self {
168	let half = credentials.ttl.checked_div(2).unwrap_or_default();
169	let entry = Entry {
170		renews: now.checked_add(half).unwrap_or(now),
171		expires: now.checked_add(credentials.ttl).unwrap_or(now),
172		credentials,
173	};
174
175	Self {
176		origin: origin.to_owned(),
177		entry: Some(entry),
178		failed: None,
179	}
180}
181
182/// Records a failed fetch from `origin`.
183///
184/// What another provider left in the cache is discarded, so a failure never
185/// holds back a provider it did not come from.
186#[implement(Cache)]
187fn record_failure(&mut self, origin: &str, at: Instant) {
188	let entry = self
189		.entry
190		.take()
191		.filter(|_| self.origin == origin);
192
193	*self = Self {
194		origin: origin.to_owned(),
195		entry,
196		failed: Some(at),
197	};
198}
199
200/// Identifies the provider cached credentials came from.
201///
202/// A reload that names another provider then finds nothing cached for it.
203fn origin(provider: Provider<'_>) -> &str {
204	match provider {
205		| Provider::Endpoint(_, url) => url.as_str(),
206		| Provider::Cloudflare(_, key_id) => key_id,
207	}
208}
209
210fn unavailable() -> Error { err!(Request(ConnectionFailed("TURN credentials are unavailable."))) }