Commit 3cfca0b884
Unsigned
Layout: unified · split
Cargo.lock +1
| @@ -4543,6 +4543,7 @@ dependencies = [ | ||
| 4543 | 4543 | "mime_guess", |
| 4544 | 4544 | "qrcode", |
| 4545 | 4545 | "ruma-html", |
| 4546 | "serde", | |
| 4546 | 4547 | "serde_json", |
| 4547 | 4548 | "sha2", |
| 4548 | 4549 | "strum", |
Cargo.toml +1
| @@ -38,6 +38,7 @@ chrono = "0.4.22" | ||
| 38 | 38 | dashmap = "6.1.0" |
| 39 | 39 | url = "2.3.1" |
| 40 | 40 | serde_json = "1.0.85" |
| 41 | serde = { version = "1.0", features = ["derive"] } | |
| 41 | 42 | strum = { version = "0.24.0", features = ["derive"] } |
| 42 | 43 | tokio = { version = "1.21.1", features = ["rt-multi-thread", "sync", "time"] } |
| 43 | 44 | tracing = "0.1.36" |
src/commands/matrix_upload.rs +112 −20
| @@ -6,7 +6,7 @@ use std::{ | ||
| 6 | 6 | }; |
| 7 | 7 | |
| 8 | 8 | use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; |
| 9 | use matrix_sdk::ruma::OwnedRoomId; | |
| 9 | use matrix_sdk::ruma::{EventId, OwnedEventId, OwnedRoomId, RoomId}; | |
| 10 | 10 | use sha2::{Digest, Sha256}; |
| 11 | 11 | use weechat::{ |
| 12 | 12 | buffer::Buffer, |
| @@ -131,12 +131,18 @@ impl MediaUpload { | ||
| 131 | 131 | |
| 132 | 132 | struct PendingMediaUpload { |
| 133 | 133 | room: RoomHandle, |
| 134 | room_id: OwnedRoomId, | |
| 135 | thread_root: Option<matrix_sdk::ruma::OwnedEventId>, | |
| 134 | thread_root: Option<OwnedEventId>, | |
| 135 | identity: UploadIdentity, | |
| 136 | 136 | upload: MediaUpload, |
| 137 | 137 | last_activity: Instant, |
| 138 | 138 | } |
| 139 | 139 | |
| 140 | #[derive(Clone, Debug, Eq, PartialEq)] | |
| 141 | struct UploadIdentity { | |
| 142 | room_id: OwnedRoomId, | |
| 143 | thread_root: Option<OwnedEventId>, | |
| 144 | } | |
| 145 | ||
| 140 | 146 | #[derive(Default)] |
| 141 | 147 | struct UploadState { |
| 142 | 148 | pending: BTreeMap<String, PendingMediaUpload>, |
| @@ -177,24 +183,31 @@ impl MatrixUploadCommand { | ||
| 177 | 183 | fn current_context( |
| 178 | 184 | &self, |
| 179 | 185 | buffer: &Buffer, |
| 180 | ) -> Result< | |
| 181 | (RoomHandle, Option<matrix_sdk::ruma::OwnedEventId>), | |
| 182 | &'static str, | |
| 183 | > { | |
| 186 | ) -> Result<(RoomHandle, Option<OwnedEventId>, UploadIdentity), &'static str> | |
| 187 | { | |
| 184 | 188 | let room = self |
| 185 | 189 | .servers |
| 186 | 190 | .find_room(buffer) |
| 187 | 191 | .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)) | |
| 189 | 204 | } |
| 190 | 205 | |
| 191 | 206 | fn matches_pending( |
| 192 | 207 | pending: &PendingMediaUpload, |
| 193 | room: &RoomHandle, | |
| 194 | thread_root: &Option<matrix_sdk::ruma::OwnedEventId>, | |
| 208 | identity: &UploadIdentity, | |
| 195 | 209 | ) -> bool { |
| 196 | pending.room_id == room.room_id() | |
| 197 | && pending.thread_root.as_ref() == thread_root.as_ref() | |
| 210 | pending.identity == *identity | |
| 198 | 211 | } |
| 199 | 212 | |
| 200 | 213 | fn begin(&self, buffer: &Buffer, args: &[&str]) { |
| @@ -211,7 +224,8 @@ impl MatrixUploadCommand { | ||
| 211 | 224 | return; |
| 212 | 225 | } |
| 213 | 226 | |
| 214 | let Ok((room, thread_root)) = self.current_context(buffer) else { | |
| 227 | let Ok((room, thread_root, identity)) = self.current_context(buffer) | |
| 228 | else { | |
| 215 | 229 | Self::report_error( |
| 216 | 230 | buffer, |
| 217 | 231 | "command must be run in a Matrix room or thread buffer", |
| @@ -242,9 +256,9 @@ impl MatrixUploadCommand { | ||
| 242 | 256 | state.pending.insert( |
| 243 | 257 | args[1].to_owned(), |
| 244 | 258 | PendingMediaUpload { |
| 245 | room_id: room.room_id().to_owned(), | |
| 246 | 259 | room, |
| 247 | 260 | thread_root, |
| 261 | identity, | |
| 248 | 262 | upload, |
| 249 | 263 | last_activity: Instant::now(), |
| 250 | 264 | }, |
| @@ -267,7 +281,8 @@ impl MatrixUploadCommand { | ||
| 267 | 281 | return; |
| 268 | 282 | } |
| 269 | 283 | |
| 270 | let Ok((room, thread_root)) = self.current_context(buffer) else { | |
| 284 | let Ok((_room, _thread_root, identity)) = self.current_context(buffer) | |
| 285 | else { | |
| 271 | 286 | Self::report_error(buffer, "command must be run in the Matrix buffer that began the upload"); |
| 272 | 287 | return; |
| 273 | 288 | }; |
| @@ -280,7 +295,7 @@ impl MatrixUploadCommand { | ||
| 280 | 295 | return; |
| 281 | 296 | }; |
| 282 | 297 | |
| 283 | if !Self::matches_pending(pending, &room, &thread_root) { | |
| 298 | if !Self::matches_pending(pending, &identity) { | |
| 284 | 299 | Self::report_error( |
| 285 | 300 | buffer, |
| 286 | 301 | "upload buffer or thread does not match transfer id", |
| @@ -314,7 +329,8 @@ impl MatrixUploadCommand { | ||
| 314 | 329 | return; |
| 315 | 330 | } |
| 316 | 331 | |
| 317 | let Ok((room, thread_root)) = self.current_context(buffer) else { | |
| 332 | let Ok((_room, _thread_root, identity)) = self.current_context(buffer) | |
| 333 | else { | |
| 318 | 334 | Self::report_error(buffer, "command must be run in the Matrix buffer that began the upload"); |
| 319 | 335 | return; |
| 320 | 336 | }; |
| @@ -326,7 +342,7 @@ impl MatrixUploadCommand { | ||
| 326 | 342 | Self::report_error(buffer, "no active upload"); |
| 327 | 343 | return; |
| 328 | 344 | }; |
| 329 | if !Self::matches_pending(pending, &room, &thread_root) { | |
| 345 | if !Self::matches_pending(pending, &identity) { | |
| 330 | 346 | Self::report_error( |
| 331 | 347 | buffer, |
| 332 | 348 | "upload buffer or thread does not match transfer id", |
| @@ -370,7 +386,8 @@ impl MatrixUploadCommand { | ||
| 370 | 386 | return; |
| 371 | 387 | } |
| 372 | 388 | |
| 373 | let Ok((room, thread_root)) = self.current_context(buffer) else { | |
| 389 | let Ok((_room, _thread_root, identity)) = self.current_context(buffer) | |
| 390 | else { | |
| 374 | 391 | Self::report_error(buffer, "command must be run in the Matrix buffer that began the upload"); |
| 375 | 392 | return; |
| 376 | 393 | }; |
| @@ -381,7 +398,7 @@ impl MatrixUploadCommand { | ||
| 381 | 398 | Self::report_error(buffer, "no active upload"); |
| 382 | 399 | return; |
| 383 | 400 | }; |
| 384 | if !Self::matches_pending(pending, &room, &thread_root) { | |
| 401 | if !Self::matches_pending(pending, &identity) { | |
| 385 | 402 | Self::report_error( |
| 386 | 403 | buffer, |
| 387 | 404 | "upload buffer or thread does not match transfer id", |
| @@ -393,6 +410,31 @@ impl MatrixUploadCommand { | ||
| 393 | 410 | } |
| 394 | 411 | } |
| 395 | 412 | |
| 413 | fn 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 | ||
| 396 | 438 | impl CommandRunCallback for MatrixUploadCommand { |
| 397 | 439 | fn callback( |
| 398 | 440 | &mut self, |
| @@ -605,4 +647,54 @@ mod tests { | ||
| 605 | 647 | )); |
| 606 | 648 | assert!(upload_is_expired(started, started + UPLOAD_IDLE_TIMEOUT)); |
| 607 | 649 | } |
| 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 | } | |
| 608 | 700 | } |
src/lib.rs +1
| @@ -10,6 +10,7 @@ mod debug; | ||
| 10 | 10 | mod render; |
| 11 | 11 | mod room; |
| 12 | 12 | mod server; |
| 13 | mod thread_continuation; | |
| 13 | 14 | mod utils; |
| 14 | 15 | mod verification_buffer; |
| 15 | 16 | |
src/room/mod.rs +324 −44
| @@ -102,6 +102,8 @@ use crate::{ | ||
| 102 | 102 | config::{Config, RedactionStyle}, |
| 103 | 103 | connection::Connection, |
| 104 | 104 | render::{Render, RenderedEvent, ReplyContext}, |
| 105 | server::{InnerServer, MatrixServer, ThreadRoute}, | |
| 106 | thread_continuation::ThreadKey, | |
| 105 | 107 | utils::{Edit, VerificationEvent}, |
| 106 | 108 | PLUGIN_NAME, |
| 107 | 109 | }; |
| @@ -244,6 +246,7 @@ pub struct MatrixRoom { | ||
| 244 | 246 | room_id: OwnedRoomId, |
| 245 | 247 | own_user_id: OwnedUserId, |
| 246 | 248 | room: SharedRoom, |
| 249 | server: std::rc::Weak<InnerServer>, | |
| 247 | 250 | buffer: RoomBuffer, |
| 248 | 251 | |
| 249 | 252 | config: Rc<RefCell<Config>>, |
| @@ -507,6 +510,16 @@ fn thread_root_from_encrypted_content( | ||
| 507 | 510 | } |
| 508 | 511 | } |
| 509 | 512 | |
| 513 | fn 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 | ||
| 510 | 523 | fn thread_root_from_event( |
| 511 | 524 | event: &AnySyncMessageLikeEvent, |
| 512 | 525 | ) -> Option<OwnedEventId> { |
| @@ -559,6 +572,7 @@ impl RoomHandle { | ||
| 559 | 572 | pub fn new( |
| 560 | 573 | server_name: &str, |
| 561 | 574 | runtime: Handle, |
| 575 | server: std::rc::Weak<InnerServer>, | |
| 562 | 576 | connection: &Rc<RefCell<Option<Connection>>>, |
| 563 | 577 | config: Rc<RefCell<Config>>, |
| 564 | 578 | room: Room, |
| @@ -615,6 +629,7 @@ impl RoomHandle { | ||
| 615 | 629 | outgoing_messages: MessageQueue::new(), |
| 616 | 630 | messages_in_flight: IntMutex::new(), |
| 617 | 631 | room, |
| 632 | server, | |
| 618 | 633 | }; |
| 619 | 634 | |
| 620 | 635 | let buffer_name = format!("{}.{}", server_name, room_id); |
| @@ -737,6 +752,7 @@ impl RoomHandle { | ||
| 737 | 752 | pub async fn restore( |
| 738 | 753 | server_name: &str, |
| 739 | 754 | runtime: Handle, |
| 755 | server: std::rc::Weak<InnerServer>, | |
| 740 | 756 | room: Room, |
| 741 | 757 | connection: &Rc<RefCell<Option<Connection>>>, |
| 742 | 758 | config: Rc<RefCell<Config>>, |
| @@ -750,6 +766,7 @@ impl RoomHandle { | ||
| 750 | 766 | let room_buffer = Self::new( |
| 751 | 767 | server_name, |
| 752 | 768 | runtime.clone(), |
| 769 | server, | |
| 753 | 770 | connection, |
| 754 | 771 | config, |
| 755 | 772 | room_clone, |
| @@ -825,7 +842,10 @@ impl MatrixRoom { | ||
| 825 | 842 | buffer: &Buffer, |
| 826 | 843 | input: String, |
| 827 | 844 | ) -> 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)); | |
| 829 | 849 | let latest_thread_event = thread_root.as_ref().and_then(|root| { |
| 830 | 850 | self.latest_thread_event_ids.borrow().get(root).cloned() |
| 831 | 851 | }); |
| @@ -838,6 +858,40 @@ impl MatrixRoom { | ||
| 838 | 858 | ) |
| 839 | 859 | } |
| 840 | 860 | |
| 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 | ||
| 841 | 895 | pub(crate) fn mention_message_content( |
| 842 | 896 | &self, |
| 843 | 897 | buffer: &Buffer, |
| @@ -916,7 +970,33 @@ impl MatrixRoom { | ||
| 916 | 970 | return None; |
| 917 | 971 | } |
| 918 | 972 | |
| 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(); | |
| 920 | 1000 | } |
| 921 | 1001 | |
| 922 | 1002 | pub fn close_thread_buffer(&self, buffer: &Buffer) -> bool { |
| @@ -1718,7 +1798,98 @@ impl MatrixRoom { | ||
| 1718 | 1798 | /// |
| 1719 | 1799 | /// buffer.send_message(content).await |
| 1720 | 1800 | /// ``` |
| 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> { | |
| 1722 | 1893 | let transaction_id = TransactionId::new(); |
| 1723 | 1894 | |
| 1724 | 1895 | let connection = self.connection.borrow().clone(); |
| @@ -1747,15 +1918,17 @@ impl MatrixRoom { | ||
| 1747 | 1918 | .await; |
| 1748 | 1919 | self.outgoing_messages.finish_response(&r.event_id); |
| 1749 | 1920 | } |
| 1921 | Ok(r.event_id) | |
| 1750 | 1922 | } |
| 1751 | Err(_e) => { | |
| 1923 | Err(error) => { | |
| 1752 | 1924 | // TODO: print out an error, remember to modify the local |
| 1753 | 1925 | // echo line if there is one. |
| 1754 | 1926 | self.outgoing_messages.remove(&transaction_id); |
| 1927 | Err(format!("Failed to send Matrix message: {error}")) | |
| 1755 | 1928 | } |
| 1756 | 1929 | } |
| 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()) | |
| 1759 | 1932 | } |
| 1760 | 1933 | } |
| 1761 | 1934 | |
| @@ -2011,34 +2184,21 @@ impl MatrixRoom { | ||
| 2011 | 2184 | |
| 2012 | 2185 | let content_type = mime_guess::from_path(&path).first_or_octet_stream(); |
| 2013 | 2186 | 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 | ) | |
| 2032 | 2196 | .await |
| 2033 | 2197 | { |
| 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 | )); | |
| 2042 | 2202 | } |
| 2043 | 2203 | } |
| 2044 | 2204 | |
| @@ -2058,14 +2218,116 @@ impl MatrixRoom { | ||
| 2058 | 2218 | } else { |
| 2059 | 2219 | AttachmentInfo::File(BaseFileInfo { size }) |
| 2060 | 2220 | }; |
| 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 | } | |
| 2062 | 2236 | |
| 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(()); | |
| 2066 | 2266 | }; |
| 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 | } | |
| 2067 | 2317 | |
| 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 | |
| 2069 | 2331 | .spawn({ |
| 2070 | 2332 | let room = self.room(); |
| 2071 | 2333 | async move { |
| @@ -2074,13 +2336,8 @@ impl MatrixRoom { | ||
| 2074 | 2336 | } |
| 2075 | 2337 | }) |
| 2076 | 2338 | .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()) | |
| 2084 | 2341 | } |
| 2085 | 2342 | |
| 2086 | 2343 | /// Send out a typing notice. |
| @@ -3146,6 +3403,29 @@ mod tests { | ||
| 3146 | 3403 | ); |
| 3147 | 3404 | } |
| 3148 | 3405 | |
| 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 | ||
| 3149 | 3429 | #[test] |
| 3150 | 3430 | fn historical_thread_event_keeps_its_root() { |
| 3151 | 3431 | let event: AnyTimelineEvent = |
src/server.rs +164 −4
| @@ -58,7 +58,7 @@ use chrono::{offset::Utc, DateTime}; | ||
| 58 | 58 | use std::{ |
| 59 | 59 | cell::{Ref, RefCell, RefMut}, |
| 60 | 60 | cmp::Reverse, |
| 61 | collections::HashMap, | |
| 61 | collections::{HashMap, HashSet}, | |
| 62 | 62 | io::Write, |
| 63 | 63 | path::{Path, PathBuf}, |
| 64 | 64 | rc::{Rc, Weak}, |
| @@ -88,7 +88,7 @@ use matrix_sdk::{ | ||
| 88 | 88 | OwnedDeviceId, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, |
| 89 | 89 | OwnedRoomOrAliasId, OwnedUserId, RoomAliasId, RoomId, UserId, |
| 90 | 90 | }, |
| 91 | Client, Error, SessionTokens, | |
| 91 | Client, Error, RoomState, SessionTokens, | |
| 92 | 92 | }; |
| 93 | 93 | |
| 94 | 94 | use weechat::{ |
| @@ -103,6 +103,7 @@ use crate::{ | ||
| 103 | 103 | config::ServerBuffer, |
| 104 | 104 | connection::{Connection, InteractiveAuthInfo}, |
| 105 | 105 | room::RoomHandle, |
| 106 | thread_continuation::{ThreadContinuationState, ThreadKey}, | |
| 106 | 107 | verification_buffer::VerificationBuffer, |
| 107 | 108 | ConfigHandle, Servers, PLUGIN_NAME, |
| 108 | 109 | }; |
| @@ -198,7 +199,7 @@ pub struct LoginInfo { | ||
| 198 | 199 | |
| 199 | 200 | #[derive(Clone)] |
| 200 | 201 | pub struct MatrixServer { |
| 201 | inner: Rc<InnerServer>, | |
| 202 | pub(crate) inner: Rc<InnerServer>, | |
| 202 | 203 | } |
| 203 | 204 | |
| 204 | 205 | impl std::ops::Deref for MatrixServer { |
| @@ -217,6 +218,7 @@ impl std::fmt::Debug for MatrixServer { | ||
| 217 | 218 | } |
| 218 | 219 | |
| 219 | 220 | pub struct InnerServer { |
| 221 | self_weak: RefCell<Weak<InnerServer>>, | |
| 220 | 222 | servers: Servers, |
| 221 | 223 | server_name: Rc<str>, |
| 222 | 224 | rooms: Rc<RefCell<HashMap<OwnedRoomId, RoomHandle>>>, |
| @@ -228,6 +230,19 @@ pub struct InnerServer { | ||
| 228 | 230 | connection: Rc<RefCell<Option<Connection>>>, |
| 229 | 231 | server_buffer: Rc<RefCell<Option<BufferHandle>>>, |
| 230 | 232 | 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 | ||
| 237 | pub(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 | }, | |
| 231 | 246 | } |
| 232 | 247 | |
| 233 | 248 | impl MatrixServer { |
| @@ -240,6 +255,7 @@ impl MatrixServer { | ||
| 240 | 255 | let server_name: Rc<str> = name.to_string().into(); |
| 241 | 256 | |
| 242 | 257 | let server = InnerServer { |
| 258 | self_weak: RefCell::new(Weak::new()), | |
| 243 | 259 | servers, |
| 244 | 260 | server_name: server_name.clone(), |
| 245 | 261 | rooms: Rc::new(RefCell::new(HashMap::new())), |
| @@ -251,9 +267,12 @@ impl MatrixServer { | ||
| 251 | 267 | connection: Rc::new(RefCell::new(None)), |
| 252 | 268 | server_buffer: Rc::new(RefCell::new(None)), |
| 253 | 269 | 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(()), | |
| 254 | 272 | }; |
| 255 | 273 | |
| 256 | let server = server.into(); | |
| 274 | let server: Rc<InnerServer> = server.into(); | |
| 275 | *server.self_weak.borrow_mut() = Rc::downgrade(&server); | |
| 257 | 276 | |
| 258 | 277 | MatrixServer::create_server_conf(&server_name, server_section, &server); |
| 259 | 278 | |
| @@ -809,6 +828,145 @@ impl InnerServer { | ||
| 809 | 828 | self.rooms.borrow().values().cloned().collect() |
| 810 | 829 | } |
| 811 | 830 | |
| 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 | ||
| 812 | 970 | pub fn verifications(&self) -> Vec<VerificationBuffer> { |
| 813 | 971 | self.verification_buffers |
| 814 | 972 | .borrow() |
| @@ -844,6 +1002,7 @@ impl InnerServer { | ||
| 844 | 1002 | let buffer = RoomHandle::new( |
| 845 | 1003 | &self.server_name, |
| 846 | 1004 | self.servers.runtime().to_owned(), |
| 1005 | self.self_weak.borrow().clone(), | |
| 847 | 1006 | &self.connection, |
| 848 | 1007 | self.config.inner.clone(), |
| 849 | 1008 | room, |
| @@ -957,6 +1116,7 @@ impl InnerServer { | ||
| 957 | 1116 | match RoomHandle::restore( |
| 958 | 1117 | &self.server_name, |
| 959 | 1118 | self.servers.runtime().to_owned(), |
| 1119 | self.self_weak.borrow().clone(), | |
| 960 | 1120 | room, |
| 961 | 1121 | &self.connection, |
| 962 | 1122 | self.config.inner.clone(), |
src/thread_continuation.rs added +210
| @@ -0,0 +1,210 @@ | ||
| 1 | use std::collections::{HashMap, HashSet}; | |
| 2 | ||
| 3 | use matrix_sdk::{ | |
| 4 | ruma::{EventId, OwnedEventId, OwnedRoomId, RoomId}, | |
| 5 | Client, | |
| 6 | }; | |
| 7 | use serde::{Deserialize, Serialize}; | |
| 8 | ||
| 9 | const STORE_KEY: &[u8] = b"org.weechat.matrix.thread_continuations.v1"; | |
| 10 | const MAX_UPGRADE_DEPTH: usize = 32; | |
| 11 | ||
| 12 | #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] | |
| 13 | pub(crate) struct ThreadKey { | |
| 14 | pub room_id: OwnedRoomId, | |
| 15 | pub thread_root: OwnedEventId, | |
| 16 | } | |
| 17 | ||
| 18 | impl 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)] | |
| 28 | pub(crate) struct ThreadContinuation { | |
| 29 | pub source: ThreadKey, | |
| 30 | pub target: ThreadKey, | |
| 31 | } | |
| 32 | ||
| 33 | #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] | |
| 34 | pub(crate) struct ThreadContinuationState { | |
| 35 | continuations: Vec<ThreadContinuation>, | |
| 36 | } | |
| 37 | ||
| 38 | impl 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)] | |
| 152 | mod 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 | } | |