src/thread_continuation.rs

main
weechat-matrix-rs/src/thread_continuation.rs history · blame · raw

208 lines · 6605 bytes

17 symbols in this file
  1use std::collections::{HashMap, HashSet};
  2
  3use matrix_sdk::ruma::{EventId, OwnedEventId, OwnedRoomId, RoomId};
  4use serde::{Deserialize, Serialize};
  5
  6use crate::connection::Connection;
  7
  8const STORE_KEY: &[u8] = b"org.weechat.matrix.thread_continuations.v1";
  9const MAX_UPGRADE_DEPTH: usize = 32;
 10
 11#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
 12pub(crate) struct ThreadKey {
 13    pub room_id: OwnedRoomId,
 14    pub thread_root: OwnedEventId,
 15}
 16
 17impl ThreadKey {
 18    pub(crate) fn new(room_id: &RoomId, thread_root: &EventId) -> Self {
 19        Self {
 20            room_id: room_id.to_owned(),
 21            thread_root: thread_root.to_owned(),
 22        }
 23    }
 24}
 25
 26#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
 27pub(crate) struct ThreadContinuation {
 28    pub source: ThreadKey,
 29    pub target: ThreadKey,
 30}
 31
 32#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
 33pub(crate) struct ThreadContinuationState {
 34    continuations: Vec<ThreadContinuation>,
 35}
 36
 37impl ThreadContinuationState {
 38    pub(crate) async fn load(connection: &Connection) -> Result<Self, String> {
 39        let Some(bytes) = connection
 40            .get_custom_store_value(STORE_KEY.to_vec())
 41            .await?
 42        else {
 43            return Ok(Self::default());
 44        };
 45
 46        let state: Self = serde_json::from_slice(&bytes).map_err(|error| {
 47            format!("invalid persisted thread continuation data: {error}")
 48        })?;
 49        state.validate()?;
 50        Ok(state)
 51    }
 52
 53    pub(crate) async fn save(
 54        &self,
 55        connection: &Connection,
 56    ) -> Result<(), String> {
 57        self.validate()?;
 58        let bytes =
 59            serde_json::to_vec(self).map_err(|error| error.to_string())?;
 60        connection
 61            .set_custom_store_value(STORE_KEY.to_vec(), bytes)
 62            .await
 63    }
 64
 65    pub(crate) fn resolve(
 66        &self,
 67        source: &ThreadKey,
 68    ) -> Result<Option<ThreadKey>, String> {
 69        let by_source: HashMap<_, _> = self
 70            .continuations
 71            .iter()
 72            .map(|continuation| (&continuation.source, &continuation.target))
 73            .collect();
 74        let mut current = source;
 75        let mut visited = HashSet::new();
 76
 77        for _ in 0..MAX_UPGRADE_DEPTH {
 78            let Some(target) = by_source.get(current) else {
 79                return Ok((current != source).then(|| current.clone()));
 80            };
 81            if !visited.insert(current.clone()) {
 82                return Err(
 83                    "cyclic Matrix thread continuation mapping".to_owned()
 84                );
 85            }
 86            current = target;
 87        }
 88
 89        Err("Matrix thread continuation chain is too deep".to_owned())
 90    }
 91
 92    pub(crate) fn insert(
 93        &mut self,
 94        source: ThreadKey,
 95        target: ThreadKey,
 96    ) -> Result<(), String> {
 97        if source == target {
 98            return Err(
 99                "Matrix thread continuation cannot point to itself".to_owned()
100            );
101        }
102        if let Some(existing) = self
103            .continuations
104            .iter()
105            .find(|continuation| continuation.source == source)
106        {
107            return (existing.target == target).then_some(()).ok_or_else(
108                || {
109                    "Matrix thread already has a different continuation"
110                        .to_owned()
111                },
112            );
113        }
114
115        self.continuations.push(ThreadContinuation {
116            source: source.clone(),
117            target,
118        });
119        if let Err(error) = self.validate() {
120            self.continuations
121                .retain(|continuation| continuation.source != source);
122            return Err(error);
123        }
124        Ok(())
125    }
126
127    fn validate(&self) -> Result<(), String> {
128        let mut sources = HashSet::new();
129        for continuation in &self.continuations {
130            if continuation.source == continuation.target {
131                return Err(
132                    "Matrix thread continuation cannot point to itself"
133                        .to_owned(),
134                );
135            }
136            if !sources.insert(&continuation.source) {
137                return Err(
138                    "duplicate Matrix thread continuation source".to_owned()
139                );
140            }
141        }
142        for source in sources {
143            self.resolve(source)?;
144        }
145        Ok(())
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use matrix_sdk::ruma::{EventId, RoomId};
152
153    use super::{ThreadContinuationState, ThreadKey};
154
155    fn key(room: &str, event: &str) -> ThreadKey {
156        ThreadKey {
157            room_id: RoomId::parse(room).unwrap(),
158            thread_root: EventId::parse(event).unwrap(),
159        }
160    }
161
162    #[test]
163    fn zero_predecessor_has_no_route() {
164        let state = ThreadContinuationState::default();
165        assert_eq!(
166            None,
167            state
168                .resolve(&key("!a:example.org", "$a:example.org"))
169                .unwrap()
170        );
171    }
172
173    #[test]
174    fn persisted_mapping_round_trips_and_reuses_latest_target() {
175        let source = key("!a:example.org", "$a:example.org");
176        let middle = key("!b:example.org", "$b:example.org");
177        let target = key("!c:example.org", "$c:example.org");
178        let mut state = ThreadContinuationState::default();
179        state.insert(source.clone(), middle.clone()).unwrap();
180        state.insert(middle, target.clone()).unwrap();
181
182        let encoded = serde_json::to_vec(&state).unwrap();
183        let restored: ThreadContinuationState =
184            serde_json::from_slice(&encoded).unwrap();
185        restored.validate().unwrap();
186        assert_eq!(Some(target), restored.resolve(&source).unwrap());
187    }
188
189    #[test]
190    fn duplicate_creation_is_idempotent_but_conflicts_are_rejected() {
191        let source = key("!a:example.org", "$a:example.org");
192        let target = key("!b:example.org", "$b:example.org");
193        let other = key("!b:example.org", "$other:example.org");
194        let mut state = ThreadContinuationState::default();
195        state.insert(source.clone(), target.clone()).unwrap();
196        state.insert(source.clone(), target).unwrap();
197        assert!(state.insert(source, other).is_err());
198    }
199
200    #[test]
201    fn malformed_cycle_is_rejected() {
202        let first = key("!a:example.org", "$a:example.org");
203        let second = key("!b:example.org", "$b:example.org");
204        let mut state = ThreadContinuationState::default();
205        state.insert(first.clone(), second.clone()).unwrap();
206        assert!(state.insert(second, first).is_err());
207    }
208}