tuwunel_service/rooms/spaces/
cache.rs1use std::time::SystemTime;
2
3use ruma::{
4 RoomId,
5 api::{
6 client::space::SpaceHierarchyRoomsChunk,
7 federation::space::SpaceHierarchyParentSummary as ParentSummary,
8 },
9};
10use serde::{Deserialize, Serialize};
11use tuwunel_core::{Result, at, debug, implement, utils::rand::time_from_now_secs};
12use tuwunel_database::{Deserialized, Json};
13
14use super::is_summary_serializable;
15
16#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
17#[serde(rename_all = "snake_case")]
18pub(super) enum Provenance {
19 #[default]
20 Unknown,
21 Local,
22 Remote,
23}
24
25#[derive(Debug, Deserialize, Serialize)]
26pub(super) struct Cached {
27 pub(super) expires: SystemTime,
28 pub(super) summary: Option<ParentSummary>,
29 #[serde(default)]
30 pub(super) provenance: Provenance,
31}
32
33#[implement(super::Service)]
35#[inline]
36#[tracing::instrument(name = "evict", level = "debug", skip_all, fields(room_id))]
37pub fn cache_evict(&self, room_id: &RoomId) { self.db.roomid_spacehierarchy.remove(room_id); }
38
39#[implement(super::Service)]
40#[tracing::instrument(
41 level = "debug",
42 skip(self, summary),
43 fields(summary = summary.is_some())
44)]
45pub(super) fn cache_put(
46 &self,
47 room_id: &RoomId,
48 summary: Option<&ParentSummary>,
49 provenance: Provenance,
50) {
51 debug!(?room_id, "cache put");
52 self.db.roomid_spacehierarchy.raw_put(
53 room_id,
54 Json(Cached {
55 expires: self.generate_ttl(),
56 summary: summary.cloned().filter(is_summary_serializable),
57 provenance,
58 }),
59 );
60}
61
62#[implement(super::Service)]
63#[tracing::instrument(
64 level = "trace",
65 skip(self),
66 err(level = "debug"),
67 ret(level = "trace")
68)]
69pub(super) async fn cache_get(&self, room_id: &RoomId) -> Result<Cached> {
70 self.db
71 .roomid_spacehierarchy
72 .get(room_id)
73 .await
74 .deserialized::<Json<Cached>>()
75 .map(at!(0))
76}
77
78impl From<Cached> for Option<SpaceHierarchyRoomsChunk> {
81 #[inline]
82 fn from(value: Cached) -> Self {
83 value
84 .summary
85 .map(|ParentSummary { children_state, summary }: ParentSummary| {
86 SpaceHierarchyRoomsChunk { children_state, summary }
87 })
88 }
89}
90
91#[implement(super::Service)]
92#[inline]
93fn generate_ttl(&self) -> SystemTime {
94 time_from_now_secs(
95 self.services.config.cache.space_hierarchy.ttl_min
96 ..self.services.config.cache.space_hierarchy.ttl_max,
97 )
98}