Commit 3cfca0b884

3cfca0b8846cf119f4197b81ee7e73a1c2e17fba

parent: 777e85dc79

Unsigned

Darafei Praliaskouski <me@komzpa.net> · 2026-08-01 19:53 UTC
committer: <strk@kbt.io>

feat: continue threads across room upgrades

Layout: unified · split

Cargo.lock +1
@@ -4543,6 +4543,7 @@ dependencies = [
45434543 "mime_guess",
45444544 "qrcode",
45454545 "ruma-html",
4546 "serde",
45464547 "serde_json",
45474548 "sha2",
45484549 "strum",
Cargo.toml +1
@@ -38,6 +38,7 @@ chrono = "0.4.22"
3838dashmap = "6.1.0"
3939url = "2.3.1"
4040serde_json = "1.0.85"
41serde = { version = "1.0", features = ["derive"] }
4142strum = { version = "0.24.0", features = ["derive"] }
4243tokio = { version = "1.21.1", features = ["rt-multi-thread", "sync", "time"] }
4344tracing = "0.1.36"
src/commands/matrix_upload.rs +112 −20
@@ -6,7 +6,7 @@ use std::{
66};
77
88use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
9use matrix_sdk::ruma::OwnedRoomId;
9use matrix_sdk::ruma::{EventId, OwnedEventId, OwnedRoomId, RoomId};
1010use sha2::{Digest, Sha256};
1111use weechat::{
1212 buffer::Buffer,
@@ -131,12 +131,18 @@ impl MediaUpload {
131131
132132struct PendingMediaUpload {
133133 room: RoomHandle,
134 room_id: OwnedRoomId,
135 thread_root: Option<matrix_sdk::ruma::OwnedEventId>,
134 thread_root: Option<OwnedEventId>,
135 identity: UploadIdentity,
136136 upload: MediaUpload,
137137 last_activity: Instant,
138138}
139139
140#[derive(Clone, Debug, Eq, PartialEq)]
141struct UploadIdentity {
142 room_id: OwnedRoomId,
143 thread_root: Option<OwnedEventId>,
144}
145
140146#[derive(Default)]
141147struct UploadState {
142148 pending: BTreeMap<String, PendingMediaUpload>,
@@ -177,24 +183,31 @@ impl MatrixUploadCommand {
177183 fn current_context(
178184 &self,
179185 buffer: &Buffer,
180 ) -> Result<
181 (RoomHandle, Option<matrix_sdk::ruma::OwnedEventId>),
182 &'static str,
183 > {
186 ) -> Result<(RoomHandle, Option<OwnedEventId>, UploadIdentity), &'static str>
187 {
184188 let room = self
185189 .servers
186190 .find_room(buffer)
187191 .ok_or("command must be run in a Matrix room or thread buffer")?;
188 Ok((room, thread_root_from_buffer(buffer)))
192 let thread_root = thread_root_from_buffer(buffer);
193 let identity = upload_identity(
194 room.room_id(),
195 thread_root.as_deref(),
196 buffer
197 .get_localvar("matrix_continuation_source_room_id")
198 .as_deref(),
199 buffer
200 .get_localvar("matrix_continuation_source_thread_root")
201 .as_deref(),
202 );
203 Ok((room, thread_root, identity))
189204 }
190205
191206 fn matches_pending(
192207 pending: &PendingMediaUpload,
193 room: &RoomHandle,
194 thread_root: &Option<matrix_sdk::ruma::OwnedEventId>,
208 identity: &UploadIdentity,
195209 ) -> bool {
196 pending.room_id == room.room_id()
197 && pending.thread_root.as_ref() == thread_root.as_ref()
210 pending.identity == *identity
198211 }
199212
200213 fn begin(&self, buffer: &Buffer, args: &[&str]) {
@@ -211,7 +224,8 @@ impl MatrixUploadCommand {
211224 return;
212225 }
213226
214 let Ok((room, thread_root)) = self.current_context(buffer) else {
227 let Ok((room, thread_root, identity)) = self.current_context(buffer)
228 else {
215229 Self::report_error(
216230 buffer,
217231 "command must be run in a Matrix room or thread buffer",
@@ -242,9 +256,9 @@ impl MatrixUploadCommand {
242256 state.pending.insert(
243257 args[1].to_owned(),
244258 PendingMediaUpload {
245 room_id: room.room_id().to_owned(),
246259 room,
247260 thread_root,
261 identity,
248262 upload,
249263 last_activity: Instant::now(),
250264 },
@@ -267,7 +281,8 @@ impl MatrixUploadCommand {
267281 return;
268282 }
269283
270 let Ok((room, thread_root)) = self.current_context(buffer) else {
284 let Ok((_room, _thread_root, identity)) = self.current_context(buffer)
285 else {
271286 Self::report_error(buffer, "command must be run in the Matrix buffer that began the upload");
272287 return;
273288 };
@@ -280,7 +295,7 @@ impl MatrixUploadCommand {
280295 return;
281296 };
282297
283 if !Self::matches_pending(pending, &room, &thread_root) {
298 if !Self::matches_pending(pending, &identity) {
284299 Self::report_error(
285300 buffer,
286301 "upload buffer or thread does not match transfer id",
@@ -314,7 +329,8 @@ impl MatrixUploadCommand {
314329 return;
315330 }
316331
317 let Ok((room, thread_root)) = self.current_context(buffer) else {
332 let Ok((_room, _thread_root, identity)) = self.current_context(buffer)
333 else {
318334 Self::report_error(buffer, "command must be run in the Matrix buffer that began the upload");
319335 return;
320336 };
@@ -326,7 +342,7 @@ impl MatrixUploadCommand {
326342 Self::report_error(buffer, "no active upload");
327343 return;
328344 };
329 if !Self::matches_pending(pending, &room, &thread_root) {
345 if !Self::matches_pending(pending, &identity) {
330346 Self::report_error(
331347 buffer,
332348 "upload buffer or thread does not match transfer id",
@@ -370,7 +386,8 @@ impl MatrixUploadCommand {
370386 return;
371387 }
372388
373 let Ok((room, thread_root)) = self.current_context(buffer) else {
389 let Ok((_room, _thread_root, identity)) = self.current_context(buffer)
390 else {
374391 Self::report_error(buffer, "command must be run in the Matrix buffer that began the upload");
375392 return;
376393 };
@@ -381,7 +398,7 @@ impl MatrixUploadCommand {
381398 Self::report_error(buffer, "no active upload");
382399 return;
383400 };
384 if !Self::matches_pending(pending, &room, &thread_root) {
401 if !Self::matches_pending(pending, &identity) {
385402 Self::report_error(
386403 buffer,
387404 "upload buffer or thread does not match transfer id",
@@ -393,6 +410,31 @@ impl MatrixUploadCommand {
393410 }
394411}
395412
413fn upload_identity(
414 current_room_id: &RoomId,
415 current_thread_root: Option<&EventId>,
416 source_room_id: Option<&str>,
417 source_thread_root: Option<&str>,
418) -> UploadIdentity {
419 let source = source_room_id
420 .and_then(|room_id| RoomId::parse(room_id).ok())
421 .zip(
422 source_thread_root
423 .and_then(|event_id| EventId::parse(event_id).ok()),
424 );
425
426 match source {
427 Some((room_id, thread_root)) => UploadIdentity {
428 room_id,
429 thread_root: Some(thread_root),
430 },
431 None => UploadIdentity {
432 room_id: current_room_id.to_owned(),
433 thread_root: current_thread_root.map(ToOwned::to_owned),
434 },
435 }
436}
437
396438impl CommandRunCallback for MatrixUploadCommand {
397439 fn callback(
398440 &mut self,
@@ -605,4 +647,54 @@ mod tests {
605647 ));
606648 assert!(upload_is_expired(started, started + UPLOAD_IDLE_TIMEOUT));
607649 }
650
651 #[test]
652 fn adopted_thread_keeps_its_original_upload_identity() {
653 let source_room = RoomId::parse("!old:example.org").unwrap();
654 let source_root = EventId::parse("$old-root:example.org").unwrap();
655 let target_room = RoomId::parse("!new:example.org").unwrap();
656 let target_root = EventId::parse("$new-root:example.org").unwrap();
657
658 let before = upload_identity(
659 &source_room,
660 Some(source_root.as_ref()),
661 None,
662 None,
663 );
664 let after = upload_identity(
665 &target_room,
666 Some(target_root.as_ref()),
667 Some(source_room.as_str()),
668 Some(source_root.as_str()),
669 );
670
671 assert_eq!(before, after);
672 assert_ne!(after.room_id, target_room);
673 assert_ne!(after.thread_root.as_deref(), Some(target_root.as_ref()));
674 }
675
676 #[test]
677 fn incomplete_or_invalid_adoption_metadata_falls_back_safely() {
678 let room = RoomId::parse("!room:example.org").unwrap();
679 let root = EventId::parse("$root:example.org").unwrap();
680
681 for (source_room, source_root) in [
682 (Some("!old:example.org"), None),
683 (None, Some("$old-root:example.org")),
684 (Some("not-a-room"), Some("$old-root:example.org")),
685 ] {
686 assert_eq!(
687 upload_identity(
688 &room,
689 Some(root.as_ref()),
690 source_room,
691 source_root,
692 ),
693 UploadIdentity {
694 room_id: room.clone(),
695 thread_root: Some(root.clone()),
696 }
697 );
698 }
699 }
608700}
src/lib.rs +1
@@ -10,6 +10,7 @@ mod debug;
1010mod render;
1111mod room;
1212mod server;
13mod thread_continuation;
1314mod utils;
1415mod verification_buffer;
1516
src/room/mod.rs +324 −44
@@ -102,6 +102,8 @@ use crate::{
102102 config::{Config, RedactionStyle},
103103 connection::Connection,
104104 render::{Render, RenderedEvent, ReplyContext},
105 server::{InnerServer, MatrixServer, ThreadRoute},
106 thread_continuation::ThreadKey,
105107 utils::{Edit, VerificationEvent},
106108 PLUGIN_NAME,
107109};
@@ -244,6 +246,7 @@ pub struct MatrixRoom {
244246 room_id: OwnedRoomId,
245247 own_user_id: OwnedUserId,
246248 room: SharedRoom,
249 server: std::rc::Weak<InnerServer>,
247250 buffer: RoomBuffer,
248251
249252 config: Rc<RefCell<Config>>,
@@ -507,6 +510,16 @@ fn thread_root_from_encrypted_content(
507510 }
508511}
509512
513fn retarget_thread_content(
514 content: &mut RoomMessageEventContent,
515 thread_root: OwnedEventId,
516) {
517 content.relates_to = Some(Relation::Thread(Thread::plain(
518 thread_root.clone(),
519 thread_root,
520 )));
521}
522
510523fn thread_root_from_event(
511524 event: &AnySyncMessageLikeEvent,
512525) -> Option<OwnedEventId> {
@@ -559,6 +572,7 @@ impl RoomHandle {
559572 pub fn new(
560573 server_name: &str,
561574 runtime: Handle,
575 server: std::rc::Weak<InnerServer>,
562576 connection: &Rc<RefCell<Option<Connection>>>,
563577 config: Rc<RefCell<Config>>,
564578 room: Room,
@@ -615,6 +629,7 @@ impl RoomHandle {
615629 outgoing_messages: MessageQueue::new(),
616630 messages_in_flight: IntMutex::new(),
617631 room,
632 server,
618633 };
619634
620635 let buffer_name = format!("{}.{}", server_name, room_id);
@@ -737,6 +752,7 @@ impl RoomHandle {
737752 pub async fn restore(
738753 server_name: &str,
739754 runtime: Handle,
755 server: std::rc::Weak<InnerServer>,
740756 room: Room,
741757 connection: &Rc<RefCell<Option<Connection>>>,
742758 config: Rc<RefCell<Config>>,
@@ -750,6 +766,7 @@ impl RoomHandle {
750766 let room_buffer = Self::new(
751767 server_name,
752768 runtime.clone(),
769 server,
753770 connection,
754771 config,
755772 room_clone,
@@ -825,7 +842,10 @@ impl MatrixRoom {
825842 buffer: &Buffer,
826843 input: String,
827844 ) -> RoomMessageEventContent {
828 let thread_root = thread_root_from_buffer(buffer);
845 let thread_root = buffer
846 .get_localvar("matrix_continuation_source_thread_root")
847 .and_then(|root| EventId::parse(root.as_ref()).ok())
848 .or_else(|| thread_root_from_buffer(buffer));
829849 let latest_thread_event = thread_root.as_ref().and_then(|root| {
830850 self.latest_thread_event_ids.borrow().get(root).cloned()
831851 });
@@ -838,6 +858,40 @@ impl MatrixRoom {
838858 )
839859 }
840860
861 fn server(&self) -> Option<MatrixServer> {
862 self.server.upgrade().map(|inner| MatrixServer { inner })
863 }
864
865 fn adopt_thread_buffer(
866 &self,
867 source_root: &EventId,
868 target: &RoomHandle,
869 target_root: &EventId,
870 ) {
871 let Some(handle) = self.buffer.thread_buffer(source_root) else {
872 return;
873 };
874 self.buffer.remove_thread_buffer(source_root);
875 target
876 .buffer
877 .set_thread_buffer(target_root.to_owned(), handle.clone());
878 if let Ok(buffer) = handle.upgrade() {
879 buffer.set_localvar(
880 "matrix_continuation_source_room_id",
881 self.room_id.as_str(),
882 );
883 buffer.set_localvar(
884 "matrix_continuation_source_thread_root",
885 source_root.as_str(),
886 );
887 buffer.set_localvar("room_id", target.room_id().as_str());
888 buffer.set_localvar("thread_root", target_root.as_str());
889 target.buffer.seed_thread_buffer(target_root, &buffer);
890 target.buffer.sort_thread_messages(target_root);
891 }
892 target.fetch_thread_history(target_root.to_owned());
893 }
894
841895 pub(crate) fn mention_message_content(
842896 &self,
843897 buffer: &Buffer,
@@ -916,7 +970,33 @@ impl MatrixRoom {
916970 return None;
917971 }
918972
919 self.get_or_create_thread_buffer(thread_root)
973 let buffer = self.get_or_create_thread_buffer(thread_root);
974 if buffer.is_some() {
975 self.resume_thread_continuation(thread_root.to_owned());
976 }
977 buffer
978 }
979
980 fn resume_thread_continuation(&self, source_root: OwnedEventId) {
981 let source = RoomHandle {
982 inner: self.clone(),
983 };
984 Weechat::spawn(async move {
985 let Some(server) = source.server() else {
986 return;
987 };
988 let _guard = server.thread_continuation_send_guard().await;
989 let Ok(ThreadRoute::Current { room, thread_root }) =
990 server.resolve_thread_route(&source, &source_root).await
991 else {
992 return;
993 };
994 if room.room_id() != source.room_id() || thread_root != source_root
995 {
996 source.adopt_thread_buffer(&source_root, &room, &thread_root);
997 }
998 })
999 .detach();
9201000 }
9211001
9221002 pub fn close_thread_buffer(&self, buffer: &Buffer) -> bool {
@@ -1718,7 +1798,98 @@ impl MatrixRoom {
17181798 ///
17191799 /// buffer.send_message(content).await
17201800 /// ```
1721 pub async fn send_message(&self, content: RoomMessageEventContent) {
1801 pub async fn send_message(&self, mut content: RoomMessageEventContent) {
1802 let Some(source_root) =
1803 thread_root_from_content(&content).map(ToOwned::to_owned)
1804 else {
1805 if let Err(error) = self.send_message_direct(content).await {
1806 self.print_error(&error);
1807 }
1808 return;
1809 };
1810 let Some(server) = self.server() else {
1811 if let Err(error) = self.send_message_direct(content).await {
1812 self.print_error(&error);
1813 }
1814 return;
1815 };
1816 let _guard = server.thread_continuation_send_guard().await;
1817 let route = match server
1818 .resolve_thread_route(
1819 &RoomHandle {
1820 inner: self.clone(),
1821 },
1822 &source_root,
1823 )
1824 .await
1825 {
1826 Ok(route) => route,
1827 Err(error) => {
1828 self.print_error(&format!(
1829 "Failed to continue archived Matrix thread: {error}"
1830 ));
1831 return;
1832 }
1833 };
1834 match route {
1835 ThreadRoute::Current { room, thread_root } => {
1836 if room.room_id() != self.room_id()
1837 || thread_root != source_root
1838 {
1839 self.adopt_thread_buffer(&source_root, &room, &thread_root);
1840 retarget_thread_content(&mut content, thread_root);
1841 }
1842 if let Err(error) = room.send_message_direct(content).await {
1843 self.print_error(&error);
1844 }
1845 }
1846 ThreadRoute::CreateRoot {
1847 room,
1848 continuation_source,
1849 } => {
1850 if let Err(error) =
1851 server.verify_thread_continuation_store().await
1852 {
1853 self.print_error(&format!(
1854 "Cannot persist Matrix thread continuation: {error}"
1855 ));
1856 return;
1857 }
1858 content.relates_to = None;
1859 // Matrix assigns the event ID. The SDK store is proven writable
1860 // before sending, but the homeserver event and local mapping
1861 // cannot be committed atomically without persisting the full
1862 // arbitrary user payload as a recovery journal.
1863 match room.send_message_direct(content).await {
1864 Ok(target_root) => {
1865 let target_key =
1866 ThreadKey::new(room.room_id(), &target_root);
1867 if let Err(error) = server
1868 .persist_thread_continuation(
1869 continuation_source,
1870 target_key,
1871 )
1872 .await
1873 {
1874 self.print_error(&format!("Sent continuation root but failed to persist it: {error}"));
1875 return;
1876 }
1877 self.adopt_thread_buffer(
1878 &source_root,
1879 &room,
1880 &target_root,
1881 );
1882 }
1883 Err(error) => self.print_error(&error),
1884 }
1885 }
1886 }
1887 }
1888
1889 async fn send_message_direct(
1890 &self,
1891 content: RoomMessageEventContent,
1892 ) -> Result<OwnedEventId, String> {
17221893 let transaction_id = TransactionId::new();
17231894
17241895 let connection = self.connection.borrow().clone();
@@ -1747,15 +1918,17 @@ impl MatrixRoom {
17471918 .await;
17481919 self.outgoing_messages.finish_response(&r.event_id);
17491920 }
1921 Ok(r.event_id)
17501922 }
1751 Err(_e) => {
1923 Err(error) => {
17521924 // TODO: print out an error, remember to modify the local
17531925 // echo line if there is one.
17541926 self.outgoing_messages.remove(&transaction_id);
1927 Err(format!("Failed to send Matrix message: {error}"))
17551928 }
17561929 }
1757 } else if let Ok(buffer) = self.buffer_handle().upgrade() {
1758 buffer.print("Error not connected");
1930 } else {
1931 Err("Matrix server is not connected".to_owned())
17591932 }
17601933 }
17611934
@@ -2011,34 +2184,21 @@ impl MatrixRoom {
20112184
20122185 let content_type = mime_guess::from_path(&path).first_or_octet_stream();
20132186 let size = UInt::new(data.len() as u64);
2014 let config = attachment_config(
2015 AttachmentInfo::File(BaseFileInfo { size }),
2016 thread_root,
2017 );
2018
2019 let Some(connection) = self.connection.borrow().clone() else {
2020 self.print_error("Not connected. Please connect first.");
2021 return;
2022 };
2023
2024 match connection
2025 .spawn({
2026 let room = self.room();
2027 async move {
2028 room.send_attachment(filename, &content_type, data, config)
2029 .await
2030 }
2031 })
2187 let info = AttachmentInfo::File(BaseFileInfo { size });
2188 if let Err(error) = self
2189 .send_attachment_routed(
2190 filename,
2191 content_type,
2192 data,
2193 info,
2194 thread_root,
2195 )
20322196 .await
20332197 {
2034 Ok(_) => (),
2035 Err(e) => {
2036 self.print_error(&format!(
2037 "Failed to upload attachment {}: {}",
2038 path.display(),
2039 e
2040 ));
2041 }
2198 self.print_error(&format!(
2199 "Failed to upload attachment {}: {error}",
2200 path.display()
2201 ));
20422202 }
20432203 }
20442204
@@ -2058,14 +2218,116 @@ impl MatrixRoom {
20582218 } else {
20592219 AttachmentInfo::File(BaseFileInfo { size })
20602220 };
2061 let config = attachment_config(info, thread_root);
2221 if let Err(error) = self
2222 .send_attachment_routed(
2223 filename,
2224 content_type,
2225 data,
2226 info,
2227 thread_root,
2228 )
2229 .await
2230 {
2231 self.print_error(&format!(
2232 "Failed to upload Matrix attachment: {error}"
2233 ));
2234 }
2235 }
20622236
2063 let Some(connection) = self.connection.borrow().clone() else {
2064 self.print_error("Not connected. Please connect first.");
2065 return;
2237 async fn send_attachment_routed(
2238 &self,
2239 filename: String,
2240 content_type: mime::Mime,
2241 data: Vec<u8>,
2242 info: AttachmentInfo,
2243 source_root: Option<OwnedEventId>,
2244 ) -> Result<(), String> {
2245 let Some(source_root) = source_root else {
2246 self.send_attachment_direct(
2247 filename,
2248 content_type,
2249 data,
2250 info,
2251 None,
2252 )
2253 .await?;
2254 return Ok(());
2255 };
2256 let Some(server) = self.server() else {
2257 self.send_attachment_direct(
2258 filename,
2259 content_type,
2260 data,
2261 info,
2262 Some(source_root),
2263 )
2264 .await?;
2265 return Ok(());
20662266 };
2267 let _guard = server.thread_continuation_send_guard().await;
2268 match server
2269 .resolve_thread_route(
2270 &RoomHandle {
2271 inner: self.clone(),
2272 },
2273 &source_root,
2274 )
2275 .await?
2276 {
2277 ThreadRoute::Current { room, thread_root } => {
2278 if room.room_id() != self.room_id()
2279 || thread_root != source_root
2280 {
2281 self.adopt_thread_buffer(&source_root, &room, &thread_root);
2282 }
2283 room.send_attachment_direct(
2284 filename,
2285 content_type,
2286 data,
2287 info,
2288 Some(thread_root),
2289 )
2290 .await?;
2291 }
2292 ThreadRoute::CreateRoot {
2293 room,
2294 continuation_source,
2295 } => {
2296 server.verify_thread_continuation_store().await?;
2297 let target_root = room
2298 .send_attachment_direct(
2299 filename,
2300 content_type,
2301 data,
2302 info,
2303 None,
2304 )
2305 .await?;
2306 server
2307 .persist_thread_continuation(
2308 continuation_source,
2309 ThreadKey::new(room.room_id(), &target_root),
2310 )
2311 .await?;
2312 self.adopt_thread_buffer(&source_root, &room, &target_root);
2313 }
2314 }
2315 Ok(())
2316 }
20672317
2068 match connection
2318 async fn send_attachment_direct(
2319 &self,
2320 filename: String,
2321 content_type: mime::Mime,
2322 data: Vec<u8>,
2323 info: AttachmentInfo,
2324 thread_root: Option<OwnedEventId>,
2325 ) -> Result<OwnedEventId, String> {
2326 let config = attachment_config(info, thread_root);
2327 let Some(connection) = self.connection.borrow().clone() else {
2328 return Err("Matrix server is not connected".to_owned());
2329 };
2330 connection
20692331 .spawn({
20702332 let room = self.room();
20712333 async move {
@@ -2074,13 +2336,8 @@ impl MatrixRoom {
20742336 }
20752337 })
20762338 .await
2077 {
2078 Ok(_) => (),
2079 Err(e) => self.print_error(&format!(
2080 "Failed to upload Matrix attachment: {}",
2081 e
2082 )),
2083 }
2339 .map(|response| response.event_id)
2340 .map_err(|error| error.to_string())
20842341 }
20852342
20862343 /// Send out a typing notice.
@@ -3146,6 +3403,29 @@ mod tests {
31463403 );
31473404 }
31483405
3406 #[test]
3407 fn continued_thread_text_targets_only_the_successor_root() {
3408 let old_root = EventId::parse("$old-root:example.org").unwrap();
3409 let new_root = EventId::parse("$new-root:example.org").unwrap();
3410 let mut content = make_text_message_content(
3411 "continued body".to_owned(),
3412 false,
3413 Some(old_root),
3414 None,
3415 );
3416
3417 retarget_thread_content(&mut content, new_root.clone());
3418
3419 let Some(Relation::Thread(thread)) = content.relates_to else {
3420 panic!("continued text must remain a proper Matrix thread reply");
3421 };
3422 assert_eq!(thread.event_id, new_root);
3423 assert_eq!(
3424 thread.in_reply_to.expect("fallback target").event_id,
3425 new_root
3426 );
3427 }
3428
31493429 #[test]
31503430 fn historical_thread_event_keeps_its_root() {
31513431 let event: AnyTimelineEvent =
src/server.rs +164 −4
@@ -58,7 +58,7 @@ use chrono::{offset::Utc, DateTime};
5858use std::{
5959 cell::{Ref, RefCell, RefMut},
6060 cmp::Reverse,
61 collections::HashMap,
61 collections::{HashMap, HashSet},
6262 io::Write,
6363 path::{Path, PathBuf},
6464 rc::{Rc, Weak},
@@ -88,7 +88,7 @@ use matrix_sdk::{
8888 OwnedDeviceId, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId,
8989 OwnedRoomOrAliasId, OwnedUserId, RoomAliasId, RoomId, UserId,
9090 },
91 Client, Error, SessionTokens,
91 Client, Error, RoomState, SessionTokens,
9292};
9393
9494use weechat::{
@@ -103,6 +103,7 @@ use crate::{
103103 config::ServerBuffer,
104104 connection::{Connection, InteractiveAuthInfo},
105105 room::RoomHandle,
106 thread_continuation::{ThreadContinuationState, ThreadKey},
106107 verification_buffer::VerificationBuffer,
107108 ConfigHandle, Servers, PLUGIN_NAME,
108109};
@@ -198,7 +199,7 @@ pub struct LoginInfo {
198199
199200#[derive(Clone)]
200201pub struct MatrixServer {
201 inner: Rc<InnerServer>,
202 pub(crate) inner: Rc<InnerServer>,
202203}
203204
204205impl std::ops::Deref for MatrixServer {
@@ -217,6 +218,7 @@ impl std::fmt::Debug for MatrixServer {
217218}
218219
219220pub struct InnerServer {
221 self_weak: RefCell<Weak<InnerServer>>,
220222 servers: Servers,
221223 server_name: Rc<str>,
222224 rooms: Rc<RefCell<HashMap<OwnedRoomId, RoomHandle>>>,
@@ -228,6 +230,19 @@ pub struct InnerServer {
228230 connection: Rc<RefCell<Option<Connection>>>,
229231 server_buffer: Rc<RefCell<Option<BufferHandle>>>,
230232 verification_buffers: Rc<RefCell<HashMap<String, VerificationBuffer>>>,
233 thread_continuations: tokio::sync::Mutex<Option<ThreadContinuationState>>,
234 thread_continuation_send_lock: tokio::sync::Mutex<()>,
235}
236
237pub(crate) enum ThreadRoute {
238 Current {
239 room: RoomHandle,
240 thread_root: matrix_sdk::ruma::OwnedEventId,
241 },
242 CreateRoot {
243 room: RoomHandle,
244 continuation_source: ThreadKey,
245 },
231246}
232247
233248impl MatrixServer {
@@ -240,6 +255,7 @@ impl MatrixServer {
240255 let server_name: Rc<str> = name.to_string().into();
241256
242257 let server = InnerServer {
258 self_weak: RefCell::new(Weak::new()),
243259 servers,
244260 server_name: server_name.clone(),
245261 rooms: Rc::new(RefCell::new(HashMap::new())),
@@ -251,9 +267,12 @@ impl MatrixServer {
251267 connection: Rc::new(RefCell::new(None)),
252268 server_buffer: Rc::new(RefCell::new(None)),
253269 verification_buffers: Rc::new(RefCell::new(HashMap::new())),
270 thread_continuations: tokio::sync::Mutex::new(None),
271 thread_continuation_send_lock: tokio::sync::Mutex::new(()),
254272 };
255273
256 let server = server.into();
274 let server: Rc<InnerServer> = server.into();
275 *server.self_weak.borrow_mut() = Rc::downgrade(&server);
257276
258277 MatrixServer::create_server_conf(&server_name, server_section, &server);
259278
@@ -809,6 +828,145 @@ impl InnerServer {
809828 self.rooms.borrow().values().cloned().collect()
810829 }
811830
831 pub(crate) async fn thread_continuation_send_guard(
832 &self,
833 ) -> tokio::sync::MutexGuard<'_, ()> {
834 self.thread_continuation_send_lock.lock().await
835 }
836
837 async fn loaded_thread_continuations(
838 &self,
839 ) -> Result<
840 tokio::sync::MutexGuard<'_, Option<ThreadContinuationState>>,
841 String,
842 > {
843 let client = self
844 .get_client()
845 .ok_or_else(|| "Matrix server is not connected".to_owned())?;
846 let mut state = self.thread_continuations.lock().await;
847 if state.is_none() {
848 *state = Some(ThreadContinuationState::load(&client).await?);
849 }
850 Ok(state)
851 }
852
853 async fn joined_room_handle(
854 &self,
855 room_id: &RoomId,
856 ) -> Result<RoomHandle, String> {
857 let client = self
858 .get_client()
859 .ok_or_else(|| "Matrix server is not connected".to_owned())?;
860 let room = match client.get_room(room_id) {
861 Some(room) if room.state() == RoomState::Joined => room,
862 _ => client.join_room_by_id(room_id).await.map_err(|error| {
863 format!("failed to join replacement room {room_id}: {error}")
864 })?,
865 };
866 if room.state() != RoomState::Joined {
867 return Err(format!("replacement room {room_id} is not joined"));
868 }
869 Ok(self.get_or_create_room(room_id))
870 }
871
872 pub(crate) async fn resolve_thread_route(
873 &self,
874 source_room: &RoomHandle,
875 source_root: &matrix_sdk::ruma::EventId,
876 ) -> Result<ThreadRoute, String> {
877 let source = ThreadKey::new(source_room.room_id(), source_root);
878 let effective_source = self
879 .loaded_thread_continuations()
880 .await?
881 .as_ref()
882 .expect("continuation state was loaded")
883 .resolve(&source)?
884 .unwrap_or(source);
885
886 let client = self
887 .get_client()
888 .ok_or_else(|| "Matrix server is not connected".to_owned())?;
889 let effective_room = if effective_source.room_id
890 == source_room.room_id()
891 && effective_source.thread_root == source_root
892 {
893 source_room.clone()
894 } else {
895 self.joined_room_handle(&effective_source.room_id).await?
896 };
897 let mut current = effective_room.room();
898 let mut visited = HashSet::from([current.room_id().to_owned()]);
899 let mut upgraded = false;
900
901 for _ in 0..32 {
902 let Some(successor) = current.successor_room() else {
903 return if upgraded {
904 Ok(ThreadRoute::CreateRoot {
905 room: self
906 .joined_room_handle(current.room_id())
907 .await?,
908 continuation_source: effective_source,
909 })
910 } else {
911 Ok(ThreadRoute::Current {
912 room: effective_room,
913 thread_root: effective_source.thread_root,
914 })
915 };
916 };
917 if !visited.insert(successor.room_id.clone()) {
918 return Err("cyclic Matrix room upgrade chain".to_owned());
919 }
920 current = match client.get_room(&successor.room_id) {
921 Some(room) if room.state() == RoomState::Joined => room,
922 _ => client.join_room_by_id(&successor.room_id).await.map_err(
923 |error| {
924 format!(
925 "failed to join replacement room {}: {error}",
926 successor.room_id
927 )
928 },
929 )?,
930 };
931 upgraded = true;
932 }
933
934 Err("Matrix room upgrade chain is too deep".to_owned())
935 }
936
937 pub(crate) async fn persist_thread_continuation(
938 &self,
939 source: ThreadKey,
940 target: ThreadKey,
941 ) -> Result<(), String> {
942 let client = self
943 .get_client()
944 .ok_or_else(|| "Matrix server is not connected".to_owned())?;
945 let mut state = self.loaded_thread_continuations().await?;
946 let state = state.as_mut().expect("continuation state was loaded");
947 let previous = state.clone();
948 state.insert(source, target)?;
949 if let Err(error) = state.save(&client).await {
950 *state = previous;
951 return Err(error);
952 }
953 Ok(())
954 }
955
956 pub(crate) async fn verify_thread_continuation_store(
957 &self,
958 ) -> Result<(), String> {
959 let client = self
960 .get_client()
961 .ok_or_else(|| "Matrix server is not connected".to_owned())?;
962 let state = self.loaded_thread_continuations().await?;
963 state
964 .as_ref()
965 .expect("continuation state was loaded")
966 .save(&client)
967 .await
968 }
969
812970 pub fn verifications(&self) -> Vec<VerificationBuffer> {
813971 self.verification_buffers
814972 .borrow()
@@ -844,6 +1002,7 @@ impl InnerServer {
8441002 let buffer = RoomHandle::new(
8451003 &self.server_name,
8461004 self.servers.runtime().to_owned(),
1005 self.self_weak.borrow().clone(),
8471006 &self.connection,
8481007 self.config.inner.clone(),
8491008 room,
@@ -957,6 +1116,7 @@ impl InnerServer {
9571116 match RoomHandle::restore(
9581117 &self.server_name,
9591118 self.servers.runtime().to_owned(),
1119 self.self_weak.borrow().clone(),
9601120 room,
9611121 &self.connection,
9621122 self.config.inner.clone(),
src/thread_continuation.rs added +210
@@ -0,0 +1,210 @@
1use std::collections::{HashMap, HashSet};
2
3use matrix_sdk::{
4 ruma::{EventId, OwnedEventId, OwnedRoomId, RoomId},
5 Client,
6};
7use serde::{Deserialize, Serialize};
8
9const STORE_KEY: &[u8] = b"org.weechat.matrix.thread_continuations.v1";
10const MAX_UPGRADE_DEPTH: usize = 32;
11
12#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
13pub(crate) struct ThreadKey {
14 pub room_id: OwnedRoomId,
15 pub thread_root: OwnedEventId,
16}
17
18impl ThreadKey {
19 pub(crate) fn new(room_id: &RoomId, thread_root: &EventId) -> Self {
20 Self {
21 room_id: room_id.to_owned(),
22 thread_root: thread_root.to_owned(),
23 }
24 }
25}
26
27#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
28pub(crate) struct ThreadContinuation {
29 pub source: ThreadKey,
30 pub target: ThreadKey,
31}
32
33#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
34pub(crate) struct ThreadContinuationState {
35 continuations: Vec<ThreadContinuation>,
36}
37
38impl ThreadContinuationState {
39 pub(crate) async fn load(client: &Client) -> Result<Self, String> {
40 let Some(bytes) = client
41 .state_store()
42 .get_custom_value(STORE_KEY)
43 .await
44 .map_err(|error| error.to_string())?
45 else {
46 return Ok(Self::default());
47 };
48
49 let state: Self = serde_json::from_slice(&bytes).map_err(|error| {
50 format!("invalid persisted thread continuation data: {error}")
51 })?;
52 state.validate()?;
53 Ok(state)
54 }
55
56 pub(crate) async fn save(&self, client: &Client) -> Result<(), String> {
57 self.validate()?;
58 let bytes =
59 serde_json::to_vec(self).map_err(|error| error.to_string())?;
60 client
61 .state_store()
62 .set_custom_value_no_read(STORE_KEY, bytes)
63 .await
64 .map_err(|error| error.to_string())
65 }
66
67 pub(crate) fn resolve(
68 &self,
69 source: &ThreadKey,
70 ) -> Result<Option<ThreadKey>, String> {
71 let by_source: HashMap<_, _> = self
72 .continuations
73 .iter()
74 .map(|continuation| (&continuation.source, &continuation.target))
75 .collect();
76 let mut current = source;
77 let mut visited = HashSet::new();
78
79 for _ in 0..MAX_UPGRADE_DEPTH {
80 let Some(target) = by_source.get(current) else {
81 return Ok((current != source).then(|| current.clone()));
82 };
83 if !visited.insert(current.clone()) {
84 return Err(
85 "cyclic Matrix thread continuation mapping".to_owned()
86 );
87 }
88 current = target;
89 }
90
91 Err("Matrix thread continuation chain is too deep".to_owned())
92 }
93
94 pub(crate) fn insert(
95 &mut self,
96 source: ThreadKey,
97 target: ThreadKey,
98 ) -> Result<(), String> {
99 if source == target {
100 return Err(
101 "Matrix thread continuation cannot point to itself".to_owned()
102 );
103 }
104 if let Some(existing) = self
105 .continuations
106 .iter()
107 .find(|continuation| continuation.source == source)
108 {
109 return (existing.target == target).then_some(()).ok_or_else(
110 || {
111 "Matrix thread already has a different continuation"
112 .to_owned()
113 },
114 );
115 }
116
117 self.continuations.push(ThreadContinuation {
118 source: source.clone(),
119 target,
120 });
121 if let Err(error) = self.validate() {
122 self.continuations
123 .retain(|continuation| continuation.source != source);
124 return Err(error);
125 }
126 Ok(())
127 }
128
129 fn validate(&self) -> Result<(), String> {
130 let mut sources = HashSet::new();
131 for continuation in &self.continuations {
132 if continuation.source == continuation.target {
133 return Err(
134 "Matrix thread continuation cannot point to itself"
135 .to_owned(),
136 );
137 }
138 if !sources.insert(&continuation.source) {
139 return Err(
140 "duplicate Matrix thread continuation source".to_owned()
141 );
142 }
143 }
144 for source in sources {
145 self.resolve(source)?;
146 }
147 Ok(())
148 }
149}
150
151#[cfg(test)]
152mod tests {
153 use matrix_sdk::ruma::{EventId, RoomId};
154
155 use super::{ThreadContinuationState, ThreadKey};
156
157 fn key(room: &str, event: &str) -> ThreadKey {
158 ThreadKey {
159 room_id: RoomId::parse(room).unwrap(),
160 thread_root: EventId::parse(event).unwrap(),
161 }
162 }
163
164 #[test]
165 fn zero_predecessor_has_no_route() {
166 let state = ThreadContinuationState::default();
167 assert_eq!(
168 None,
169 state
170 .resolve(&key("!a:example.org", "$a:example.org"))
171 .unwrap()
172 );
173 }
174
175 #[test]
176 fn persisted_mapping_round_trips_and_reuses_latest_target() {
177 let source = key("!a:example.org", "$a:example.org");
178 let middle = key("!b:example.org", "$b:example.org");
179 let target = key("!c:example.org", "$c:example.org");
180 let mut state = ThreadContinuationState::default();
181 state.insert(source.clone(), middle.clone()).unwrap();
182 state.insert(middle, target.clone()).unwrap();
183
184 let encoded = serde_json::to_vec(&state).unwrap();
185 let restored: ThreadContinuationState =
186 serde_json::from_slice(&encoded).unwrap();
187 restored.validate().unwrap();
188 assert_eq!(Some(target), restored.resolve(&source).unwrap());
189 }
190
191 #[test]
192 fn duplicate_creation_is_idempotent_but_conflicts_are_rejected() {
193 let source = key("!a:example.org", "$a:example.org");
194 let target = key("!b:example.org", "$b:example.org");
195 let other = key("!b:example.org", "$other:example.org");
196 let mut state = ThreadContinuationState::default();
197 state.insert(source.clone(), target.clone()).unwrap();
198 state.insert(source.clone(), target).unwrap();
199 assert!(state.insert(source, other).is_err());
200 }
201
202 #[test]
203 fn malformed_cycle_is_rejected() {
204 let first = key("!a:example.org", "$a:example.org");
205 let second = key("!b:example.org", "$b:example.org");
206 let mut state = ThreadContinuationState::default();
207 state.insert(first.clone(), second.clone()).unwrap();
208 assert!(state.insert(second, first).is_err());
209 }
210}