1use std::{
10 collections::BTreeMap,
11 net::IpAddr,
12 sync::{Arc, Mutex},
13 time::Duration,
14};
15
16use time::{OffsetDateTime, format_description::well_known::Rfc3339};
17use tokio::time::Instant;
18
19use super::Room;
20use crate::{
21 RoomInstanceId,
22 engine::{
23 obligation::{Obligation, TryComplete, Work},
24 sync::lock_unpoisoned,
25 },
26};
27
28#[cfg(any(test, feature = "testing-transport"))]
29#[path = "directory/TESTS/test_support.rs"]
30mod test_support;
31
32fn rfc3339_now() -> String {
33 match OffsetDateTime::now_utc().format(&Rfc3339) {
34 Ok(timestamp) => timestamp,
35 Err(_error) => String::from("1970-01-01T00:00:00Z"),
36 }
37}
38
39#[derive(Debug, Clone)]
44pub(crate) struct RoomDirectoryEntry {
45 pub room: Arc<Room>,
46 pub lifecycle: RoomLifecycle,
47 pub create_date: String,
48 pub remote_address: IpAddr,
49}
50
51impl RoomDirectoryEntry {
52 fn new(
53 room: Arc<Room>,
54 remote_address: IpAddr,
55 reservation_ttl: Duration,
56 departure_grace: Duration,
57 ) -> Self {
58 Self {
59 room,
60 lifecycle: RoomLifecycle::new(reservation_ttl, departure_grace),
61 create_date: rfc3339_now(),
62 remote_address,
63 }
64 }
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68enum RoomLifecyclePhase {
69 Reservation { expires_at: Instant },
70 Alive,
71 Grace { expires_at: Instant },
72 Closing,
73}
74
75#[derive(Debug)]
82struct RoomLifecycleState {
83 active_mutations: usize,
85 pending_removal: Option<RoomRemovalPolicy>,
87 reservation_ttl: Duration,
89 departure_grace: Duration,
91 phase: RoomLifecyclePhase,
92}
93
94impl RoomLifecycleState {
95 fn new(reservation_ttl: Duration, departure_grace: Duration) -> Self {
96 Self {
97 active_mutations: 0,
98 pending_removal: None,
99 reservation_ttl,
100 departure_grace,
101 phase: RoomLifecyclePhase::Reservation {
102 expires_at: Instant::now() + reservation_ttl,
103 },
104 }
105 }
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub(crate) enum ExpiryReason {
110 ReservationLapsed,
112 GraceElapsed,
114}
115
116#[derive(Debug, Clone)]
122pub(crate) struct RoomLifecycle {
123 state: Arc<Mutex<RoomLifecycleState>>,
124}
125
126impl RoomLifecycle {
127 pub(crate) fn new(reservation_ttl: Duration, departure_grace: Duration) -> Self {
128 Self {
129 state: Arc::new(Mutex::new(RoomLifecycleState::new(
130 reservation_ttl,
131 departure_grace,
132 ))),
133 }
134 }
135
136 pub(crate) fn claim_expired_room(&self) -> Option<ExpiryReason> {
138 let mut state = lock_unpoisoned(&self.state);
139 let expiry_reason = match state.phase {
140 RoomLifecyclePhase::Reservation { expires_at } if expires_at <= Instant::now() => {
141 Some(ExpiryReason::ReservationLapsed)
142 }
143 RoomLifecyclePhase::Grace { expires_at } if expires_at <= Instant::now() => {
144 Some(ExpiryReason::GraceElapsed)
145 }
146 _ => None,
147 };
148 if state.active_mutations == 0 && expiry_reason.is_some() {
149 state.phase = RoomLifecyclePhase::Closing;
150 drop(state);
151 return expiry_reason;
152 }
153 None
154 }
155
156 pub(crate) fn renew_reservation(&self) {
158 let mut state = lock_unpoisoned(&self.state);
159 if matches!(
160 state.phase,
161 RoomLifecyclePhase::Reservation { .. } | RoomLifecyclePhase::Grace { .. }
162 ) {
163 state.phase = RoomLifecyclePhase::Reservation {
164 expires_at: Instant::now() + state.reservation_ttl,
165 }
166 }
167 }
168
169 #[must_use]
175 pub(crate) fn begin(&self) -> Option<RoomLifecycleLease> {
176 let mut state = lock_unpoisoned(&self.state);
177 if matches!(state.phase, RoomLifecyclePhase::Closing)
178 || matches!(state.pending_removal, Some(RoomRemovalPolicy::Immediately))
179 {
180 return None;
181 }
182 state.active_mutations = state.active_mutations.checked_add(1)?;
183 let lease = RoomLifecycleLease(Obligation::new(LeaseWork {
184 state: Arc::clone(&self.state),
185 released: false,
186 }));
187 drop(state);
188 Some(lease)
189 }
190}
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
193pub(crate) enum RoomRemovalPolicy {
194 AfterGrace,
195 Immediately,
196}
197
198#[derive(Debug)]
204#[must_use = "room lifecycle leases must finish their obligation"]
205pub(crate) struct RoomLifecycleLease(Obligation<LeaseWork>);
206
207impl RoomLifecycleLease {
208 #[must_use]
210 pub(crate) fn finish(
211 self,
212 on_empty: Option<RoomRemovalPolicy>,
213 room_can_be_removed: bool,
214 ) -> bool {
215 self.0
217 .try_complete((on_empty, room_can_be_removed))
218 .unwrap_or_default()
219 }
220
221 pub(crate) fn clear_expiration(&self) {
222 lock_unpoisoned(&self.0.work().state).phase = RoomLifecyclePhase::Alive;
223 }
224}
225
226#[derive(Debug)]
228struct LeaseWork {
229 state: Arc<Mutex<RoomLifecycleState>>,
231 released: bool,
233}
234
235impl LeaseWork {
236 #[must_use]
237 fn release(&mut self, on_empty: Option<RoomRemovalPolicy>, room_can_be_removed: bool) -> bool {
238 if self.released {
239 return false;
240 }
241 self.released = true;
242 let mut state = lock_unpoisoned(&self.state);
243 let removal_policy = match state.pending_removal.max(on_empty) {
245 Some(RoomRemovalPolicy::AfterGrace) if state.departure_grace.is_zero() => {
246 Some(RoomRemovalPolicy::Immediately)
247 }
248 policy => policy,
249 };
250
251 state.active_mutations = state.active_mutations.saturating_sub(1);
252 if state.active_mutations > 0 {
253 if on_empty.is_some() && room_can_be_removed {
254 state.pending_removal = removal_policy;
255 }
256 return false;
257 }
258 state.pending_removal = None;
261 if !room_can_be_removed {
262 return false;
263 }
264
265 match removal_policy {
266 Some(RoomRemovalPolicy::Immediately) => {
267 state.phase = RoomLifecyclePhase::Closing;
268 true
269 }
270 Some(RoomRemovalPolicy::AfterGrace) => {
271 if matches!(state.phase, RoomLifecyclePhase::Alive) {
272 state.phase = RoomLifecyclePhase::Grace {
273 expires_at: Instant::now() + state.departure_grace,
274 };
275 }
276 false
277 }
278 None => false,
279 }
280 }
281}
282
283impl Work for LeaseWork {
284 fn label(&self) -> &'static str {
285 "room lifecycle lease"
286 }
287}
288
289impl TryComplete<(Option<RoomRemovalPolicy>, bool)> for LeaseWork {
290 type Output = bool;
291
292 fn try_complete(
293 mut self,
294 (on_empty, room_can_be_removed): (Option<RoomRemovalPolicy>, bool),
295 ) -> Result<bool, Self> {
296 Ok(self.release(on_empty, room_can_be_removed))
297 }
298}
299
300impl Drop for LeaseWork {
301 fn drop(&mut self) {
302 let _ = self.release(None, false);
303 }
304}
305
306#[derive(Debug, Default)]
307pub(crate) struct RoomDirectory {
308 by_uuid: BTreeMap<String, RoomDirectoryEntry>,
309 uuid_by_instance: BTreeMap<RoomInstanceId, String>,
310 uuid_by_reservation: BTreeMap<(IpAddr, String), String>,
313}
314
315impl RoomDirectory {
316 #[must_use]
317 pub(crate) fn get_by_uuid(&self, uuid: &str) -> Option<Arc<Room>> {
318 self.by_uuid.get(uuid).map(|entry| Arc::clone(&entry.room))
319 }
320
321 #[must_use]
322 pub(crate) fn entry(&self, uuid: &str) -> Option<&RoomDirectoryEntry> {
323 self.by_uuid.get(uuid)
324 }
325
326 #[must_use]
327 pub(crate) fn entry_by_reservation(
328 &self,
329 remote_address: IpAddr,
330 issuer: &str,
331 ) -> Option<&RoomDirectoryEntry> {
332 let uuid = self
333 .uuid_by_reservation
334 .get(&(remote_address, issuer.to_owned()))?;
335 self.by_uuid.get(uuid)
336 }
337
338 #[must_use]
339 pub(crate) fn get_by_instance_id(&self, room_instance_id: RoomInstanceId) -> Option<Arc<Room>> {
340 let uuid = self.uuid_by_instance.get(&room_instance_id)?;
341 self.get_by_uuid(uuid)
342 }
343
344 #[must_use]
345 pub(crate) fn entries(&self) -> Vec<RoomDirectoryEntry> {
346 self.by_uuid.values().cloned().collect()
347 }
348
349 #[must_use]
350 pub(crate) fn rooms(&self) -> Vec<Arc<Room>> {
351 self.by_uuid
352 .values()
353 .map(|entry| Arc::clone(&entry.room))
354 .collect()
355 }
356
357 pub(crate) fn insert(
358 &mut self,
359 room: Arc<Room>,
360 remote_address: IpAddr,
361 reservation_ttl: Duration,
362 departure_grace: Duration,
363 ) {
364 let room_id = room.uuid().to_owned();
365 self.uuid_by_reservation
366 .insert((remote_address, room.issuer().to_owned()), room_id.clone());
367 self.uuid_by_instance
368 .insert(room.instance_id(), room_id.clone());
369 self.by_uuid.insert(
370 room_id,
371 RoomDirectoryEntry::new(room, remote_address, reservation_ttl, departure_grace),
372 );
373 }
374
375 pub(crate) fn remove_if_current(&mut self, uuid: &str, room: &Arc<Room>) -> bool {
376 let Some(remote_address) = self
377 .by_uuid
378 .get(uuid)
379 .filter(|entry| Arc::ptr_eq(&entry.room, room))
380 .map(|entry| entry.remote_address)
381 else {
382 return false;
383 };
384 self.by_uuid.remove(uuid);
385 self.uuid_by_reservation
386 .remove(&(remote_address, room.issuer().to_owned()));
387 self.uuid_by_instance.remove(&room.instance_id());
388 true
389 }
390}