tuwunel_service/turn/
mod.rs1mod 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
25pub struct Service {
29 services: SelfServices,
30
31 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
49enum Lookup {
54 Fresh(Credentials),
56
57 Due,
59
60 Held(Option<Credentials>),
62}
63
64const 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#[implement(Service)]
90#[tracing::instrument(level = "debug", skip_all)]
91pub async fn credentials(&self) -> Result<Credentials> {
92 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 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#[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
200fn 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."))) }