Commit 88f3bc7057
Unsigned
Layout: unified · split
src/connection.rs +129
| @@ -170,6 +170,65 @@ impl Connection { | |||
| 170 | .expect("Tokio error while sending a message") | 170 | .expect("Tokio error while sending a message") |
| 171 | } | 171 | } |
| 172 | 172 | ||
| 173 | async fn try_spawn<F>(&self, future: F) -> Result<F::Output, String> | ||
| 174 | where | ||
| 175 | F: Future + Send + 'static, | ||
| 176 | F::Output: Send + 'static, | ||
| 177 | { | ||
| 178 | self.runtime() | ||
| 179 | .spawn(future) | ||
| 180 | .await | ||
| 181 | .map_err(|error| format!("Matrix runtime task failed: {error}")) | ||
| 182 | } | ||
| 183 | |||
| 184 | /// Read plugin-owned data from the Matrix state store on its Tokio runtime. | ||
| 185 | /// | ||
| 186 | /// Matrix SDK stores may use Tokio-backed pools internally. Keeping this | ||
| 187 | /// operation here prevents callers running on WeeChat's local executor from | ||
| 188 | /// polling those futures directly and aborting across the plugin FFI boundary. | ||
| 189 | pub async fn get_custom_store_value( | ||
| 190 | &self, | ||
| 191 | key: Vec<u8>, | ||
| 192 | ) -> Result<Option<Vec<u8>>, String> { | ||
| 193 | let client = self.client().clone(); | ||
| 194 | self.try_spawn(async move { | ||
| 195 | client | ||
| 196 | .state_store() | ||
| 197 | .get_custom_value(&key) | ||
| 198 | .await | ||
| 199 | .map_err(|error| error.to_string()) | ||
| 200 | }) | ||
| 201 | .await? | ||
| 202 | } | ||
| 203 | |||
| 204 | /// Persist plugin-owned data on the Matrix SDK Tokio runtime. | ||
| 205 | pub async fn set_custom_store_value( | ||
| 206 | &self, | ||
| 207 | key: Vec<u8>, | ||
| 208 | value: Vec<u8>, | ||
| 209 | ) -> Result<(), String> { | ||
| 210 | let client = self.client().clone(); | ||
| 211 | self.try_spawn(async move { | ||
| 212 | client | ||
| 213 | .state_store() | ||
| 214 | .set_custom_value_no_read(&key, value) | ||
| 215 | .await | ||
| 216 | .map_err(|error| error.to_string()) | ||
| 217 | }) | ||
| 218 | .await? | ||
| 219 | } | ||
| 220 | |||
| 221 | /// Join a room on the Matrix SDK Tokio runtime. | ||
| 222 | pub async fn join_room_on_runtime( | ||
| 223 | &self, | ||
| 224 | room_id: OwnedRoomId, | ||
| 225 | ) -> Result<Room, String> { | ||
| 226 | let client = self.client().clone(); | ||
| 227 | self.try_spawn(async move { client.join_room_by_id(&room_id).await }) | ||
| 228 | .await? | ||
| 229 | .map_err(|error| error.to_string()) | ||
| 230 | } | ||
| 231 | |||
| 173 | pub fn shutdown(&self) { | 232 | pub fn shutdown(&self) { |
| 174 | let runtime = self.runtime(); | 233 | let runtime = self.runtime(); |
| 175 | 234 | ||
| @@ -998,3 +1057,73 @@ impl Drop for Connection { | |||
| 998 | } | 1057 | } |
| 999 | } | 1058 | } |
| 1000 | } | 1059 | } |
| 1060 | |||
| 1061 | #[cfg(test)] | ||
| 1062 | mod runtime_boundary_tests { | ||
| 1063 | use std::{cell::RefCell, fs, path::Path, rc::Rc}; | ||
| 1064 | |||
| 1065 | use tokio::runtime::Runtime; | ||
| 1066 | |||
| 1067 | use super::Connection; | ||
| 1068 | |||
| 1069 | fn rust_sources(path: &Path, files: &mut Vec<std::path::PathBuf>) { | ||
| 1070 | for entry in fs::read_dir(path).expect("source directory is readable") { | ||
| 1071 | let path = entry.expect("source entry is readable").path(); | ||
| 1072 | if path.is_dir() { | ||
| 1073 | rust_sources(&path, files); | ||
| 1074 | } else if path | ||
| 1075 | .extension() | ||
| 1076 | .is_some_and(|extension| extension == "rs") | ||
| 1077 | { | ||
| 1078 | files.push(path); | ||
| 1079 | } | ||
| 1080 | } | ||
| 1081 | } | ||
| 1082 | |||
| 1083 | #[test] | ||
| 1084 | fn matrix_sdk_async_io_is_owned_by_connection_runtime() { | ||
| 1085 | let source_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); | ||
| 1086 | let connection = source_root.join("connection.rs"); | ||
| 1087 | let mut files = Vec::new(); | ||
| 1088 | rust_sources(&source_root, &mut files); | ||
| 1089 | |||
| 1090 | for path in files { | ||
| 1091 | if path == connection { | ||
| 1092 | continue; | ||
| 1093 | } | ||
| 1094 | let source = | ||
| 1095 | fs::read_to_string(&path).expect("Rust source is readable"); | ||
| 1096 | let compact = source | ||
| 1097 | .chars() | ||
| 1098 | .filter(|character| !character.is_whitespace()) | ||
| 1099 | .collect::<String>(); | ||
| 1100 | for forbidden in [".state_store()", ".join_room_by_id("] { | ||
| 1101 | assert!( | ||
| 1102 | !compact.contains(forbidden), | ||
| 1103 | "{} calls {forbidden} outside connection.rs; route Matrix SDK async I/O through Connection", | ||
| 1104 | path.display() | ||
| 1105 | ); | ||
| 1106 | } | ||
| 1107 | } | ||
| 1108 | } | ||
| 1109 | |||
| 1110 | #[test] | ||
| 1111 | fn fallible_runtime_boundary_contains_task_panics() { | ||
| 1112 | let runtime = Rc::new(Runtime::new().expect("test runtime starts")); | ||
| 1113 | let connection = Connection { | ||
| 1114 | receiver_task: Rc::new(RefCell::new(None)), | ||
| 1115 | sync_task: Rc::new(RefCell::new(None)), | ||
| 1116 | client: None, | ||
| 1117 | runtime: Some(runtime.clone()), | ||
| 1118 | }; | ||
| 1119 | |||
| 1120 | let error = | ||
| 1121 | runtime | ||
| 1122 | .block_on(connection.try_spawn(async { | ||
| 1123 | panic!("simulated Matrix SDK task panic") | ||
| 1124 | })) | ||
| 1125 | .expect_err("task panic becomes an error"); | ||
| 1126 | |||
| 1127 | assert!(error.contains("task") && error.contains("panicked")); | ||
| 1128 | } | ||
| 1129 | } | ||
src/render.rs +29
| @@ -66,6 +66,8 @@ pub enum ReplyContext { | |||
| 66 | 66 | ||
| 67 | impl RenderedEvent { | 67 | impl RenderedEvent { |
| 68 | const MSG_TAGS: &'static [&'static str] = &["notify_message"]; | 68 | const MSG_TAGS: &'static [&'static str] = &["notify_message"]; |
| 69 | const BACKLOG_TAGS: &'static [&'static str] = | ||
| 70 | &["notify_none", "no_highlight"]; | ||
| 69 | const SELF_TAGS: &'static [&'static str] = | 71 | const SELF_TAGS: &'static [&'static str] = |
| 70 | &["notify_none", "no_highlight", "self_msg"]; | 72 | &["notify_none", "no_highlight", "self_msg"]; |
| 71 | 73 | ||
| @@ -77,6 +79,10 @@ impl RenderedEvent { | |||
| 77 | self.add_tags(Self::MSG_TAGS) | 79 | self.add_tags(Self::MSG_TAGS) |
| 78 | } | 80 | } |
| 79 | 81 | ||
| 82 | pub fn add_backlog_tags(self) -> Self { | ||
| 83 | self.add_tags(Self::BACKLOG_TAGS) | ||
| 84 | } | ||
| 85 | |||
| 80 | fn add_tags(mut self, tags: &[&str]) -> Self { | 86 | fn add_tags(mut self, tags: &[&str]) -> Self { |
| 81 | for line in &mut self.content.lines { | 87 | for line in &mut self.content.lines { |
| 82 | line.tags.extend(tags.iter().map(|tag| tag.to_string())) | 88 | line.tags.extend(tags.iter().map(|tag| tag.to_string())) |
| @@ -1982,4 +1988,27 @@ mod tests { | |||
| 1982 | assert_eq!(rendered.lines.len(), 1); | 1988 | assert_eq!(rendered.lines.len(), 1); |
| 1983 | assert_eq!(rendered.lines[0].message, "literal <b> text"); | 1989 | assert_eq!(rendered.lines[0].message, "literal <b> text"); |
| 1984 | } | 1990 | } |
| 1991 | |||
| 1992 | #[test] | ||
| 1993 | fn backlog_tags_suppress_notifications_and_highlights() { | ||
| 1994 | let rendered = RenderedEvent { | ||
| 1995 | message_timestamp: 0, | ||
| 1996 | prefix: "alice\t".to_owned(), | ||
| 1997 | content: RenderedContent::new(vec![RenderedLine { | ||
| 1998 | tags: vec!["matrix_text".to_owned()], | ||
| 1999 | message: "old mention of Darafei".to_owned(), | ||
| 2000 | }]), | ||
| 2001 | } | ||
| 2002 | .add_backlog_tags(); | ||
| 2003 | |||
| 2004 | assert!(rendered.content.lines[0] | ||
| 2005 | .tags | ||
| 2006 | .contains(&"notify_none".to_owned())); | ||
| 2007 | assert!(rendered.content.lines[0] | ||
| 2008 | .tags | ||
| 2009 | .contains(&"no_highlight".to_owned())); | ||
| 2010 | assert!(!rendered.content.lines[0] | ||
| 2011 | .tags | ||
| 2012 | .contains(&"notify_message".to_owned())); | ||
| 2013 | } | ||
| 1985 | } | 2014 | } |
src/room/mod.rs +2 −2
| @@ -2788,7 +2788,7 @@ impl MatrixRoom { | |||
| 2788 | self.print_rendered_event_for_relation( | 2788 | self.print_rendered_event_for_relation( |
| 2789 | Some(event.event_id()), | 2789 | Some(event.event_id()), |
| 2790 | Some(thread_root), | 2790 | Some(thread_root), |
| 2791 | rendered, | 2791 | rendered.add_backlog_tags(), |
| 2792 | ); | 2792 | ); |
| 2793 | } | 2793 | } |
| 2794 | } | 2794 | } |
| @@ -3107,7 +3107,7 @@ impl MatrixRoom { | |||
| 3107 | self.print_rendered_event_for_relation( | 3107 | self.print_rendered_event_for_relation( |
| 3108 | Some(event.event_id()), | 3108 | Some(event.event_id()), |
| 3109 | thread_root.as_deref(), | 3109 | thread_root.as_deref(), |
| 3110 | rendered, | 3110 | rendered.add_backlog_tags(), |
| 3111 | ); | 3111 | ); |
| 3112 | } | 3112 | } |
| 3113 | } | 3113 | } |
src/server.rs +45 −34
| @@ -840,28 +840,38 @@ impl InnerServer { | |||
| 840 | tokio::sync::MutexGuard<'_, Option<ThreadContinuationState>>, | 840 | tokio::sync::MutexGuard<'_, Option<ThreadContinuationState>>, |
| 841 | String, | 841 | String, |
| 842 | > { | 842 | > { |
| 843 | let client = self | 843 | let connection = self |
| 844 | .get_client() | 844 | .connection() |
| 845 | .ok_or_else(|| "Matrix server is not connected".to_owned())?; | 845 | .ok_or_else(|| "Matrix server is not connected".to_owned())?; |
| 846 | let mut state = self.thread_continuations.lock().await; | 846 | let needs_load = self.thread_continuations.lock().await.is_none(); |
| 847 | if state.is_none() { | 847 | if needs_load { |
| 848 | *state = Some(ThreadContinuationState::load(&client).await?); | 848 | let loaded = ThreadContinuationState::load(&connection).await?; |
| 849 | let mut state = self.thread_continuations.lock().await; | ||
| 850 | if state.is_none() { | ||
| 851 | *state = Some(loaded); | ||
| 852 | } | ||
| 849 | } | 853 | } |
| 850 | Ok(state) | 854 | Ok(self.thread_continuations.lock().await) |
| 851 | } | 855 | } |
| 852 | 856 | ||
| 853 | async fn joined_room_handle( | 857 | async fn joined_room_handle( |
| 854 | &self, | 858 | &self, |
| 855 | room_id: &RoomId, | 859 | room_id: &RoomId, |
| 856 | ) -> Result<RoomHandle, String> { | 860 | ) -> Result<RoomHandle, String> { |
| 857 | let client = self | 861 | let connection = self |
| 858 | .get_client() | 862 | .connection() |
| 859 | .ok_or_else(|| "Matrix server is not connected".to_owned())?; | 863 | .ok_or_else(|| "Matrix server is not connected".to_owned())?; |
| 864 | let client = connection.client().clone(); | ||
| 860 | let room = match client.get_room(room_id) { | 865 | let room = match client.get_room(room_id) { |
| 861 | Some(room) if room.state() == RoomState::Joined => room, | 866 | Some(room) if room.state() == RoomState::Joined => room, |
| 862 | _ => client.join_room_by_id(room_id).await.map_err(|error| { | 867 | _ => connection |
| 863 | format!("failed to join replacement room {room_id}: {error}") | 868 | .join_room_on_runtime(room_id.to_owned()) |
| 864 | })?, | 869 | .await |
| 870 | .map_err(|error| { | ||
| 871 | format!( | ||
| 872 | "failed to join replacement room {room_id}: {error}" | ||
| 873 | ) | ||
| 874 | })?, | ||
| 865 | }; | 875 | }; |
| 866 | if room.state() != RoomState::Joined { | 876 | if room.state() != RoomState::Joined { |
| 867 | return Err(format!("replacement room {room_id} is not joined")); | 877 | return Err(format!("replacement room {room_id} is not joined")); |
| @@ -919,14 +929,7 @@ impl InnerServer { | |||
| 919 | } | 929 | } |
| 920 | current = match client.get_room(&successor.room_id) { | 930 | current = match client.get_room(&successor.room_id) { |
| 921 | Some(room) if room.state() == RoomState::Joined => room, | 931 | Some(room) if room.state() == RoomState::Joined => room, |
| 922 | _ => client.join_room_by_id(&successor.room_id).await.map_err( | 932 | _ => self.joined_room_handle(&successor.room_id).await?.room(), |
| 923 | |error| { | ||
| 924 | format!( | ||
| 925 | "failed to join replacement room {}: {error}", | ||
| 926 | successor.room_id | ||
| 927 | ) | ||
| 928 | }, | ||
| 929 | )?, | ||
| 930 | }; | 933 | }; |
| 931 | upgraded = true; | 934 | upgraded = true; |
| 932 | } | 935 | } |
| @@ -939,15 +942,22 @@ impl InnerServer { | |||
| 939 | source: ThreadKey, | 942 | source: ThreadKey, |
| 940 | target: ThreadKey, | 943 | target: ThreadKey, |
| 941 | ) -> Result<(), String> { | 944 | ) -> Result<(), String> { |
| 942 | let client = self | 945 | let connection = self |
| 943 | .get_client() | 946 | .connection() |
| 944 | .ok_or_else(|| "Matrix server is not connected".to_owned())?; | 947 | .ok_or_else(|| "Matrix server is not connected".to_owned())?; |
| 945 | let mut state = self.loaded_thread_continuations().await?; | 948 | let mut state_guard = self.loaded_thread_continuations().await?; |
| 946 | let state = state.as_mut().expect("continuation state was loaded"); | 949 | let (previous, next) = { |
| 947 | let previous = state.clone(); | 950 | let state = state_guard.as_mut().ok_or_else(|| { |
| 948 | state.insert(source, target)?; | 951 | "continuation state failed to load".to_owned() |
| 949 | if let Err(error) = state.save(&client).await { | 952 | })?; |
| 950 | *state = previous; | 953 | let previous = state.clone(); |
| 954 | state.insert(source, target)?; | ||
| 955 | (previous, state.clone()) | ||
| 956 | }; | ||
| 957 | drop(state_guard); | ||
| 958 | if let Err(error) = next.save(&connection).await { | ||
| 959 | let mut state = self.thread_continuations.lock().await; | ||
| 960 | *state = Some(previous); | ||
| 951 | return Err(error); | 961 | return Err(error); |
| 952 | } | 962 | } |
| 953 | Ok(()) | 963 | Ok(()) |
| @@ -956,15 +966,16 @@ impl InnerServer { | |||
| 956 | pub(crate) async fn verify_thread_continuation_store( | 966 | pub(crate) async fn verify_thread_continuation_store( |
| 957 | &self, | 967 | &self, |
| 958 | ) -> Result<(), String> { | 968 | ) -> Result<(), String> { |
| 959 | let client = self | 969 | let connection = self |
| 960 | .get_client() | 970 | .connection() |
| 961 | .ok_or_else(|| "Matrix server is not connected".to_owned())?; | 971 | .ok_or_else(|| "Matrix server is not connected".to_owned())?; |
| 962 | let state = self.loaded_thread_continuations().await?; | 972 | let state_guard = self.loaded_thread_continuations().await?; |
| 963 | state | 973 | let state = state_guard |
| 964 | .as_ref() | 974 | .as_ref() |
| 965 | .expect("continuation state was loaded") | 975 | .ok_or_else(|| "continuation state failed to load".to_owned())? |
| 966 | .save(&client) | 976 | .clone(); |
| 967 | .await | 977 | drop(state_guard); |
| 978 | state.save(&connection).await | ||
| 968 | } | 979 | } |
| 969 | 980 | ||
| 970 | pub fn verifications(&self) -> Vec<VerificationBuffer> { | 981 | pub fn verifications(&self) -> Vec<VerificationBuffer> { |
src/thread_continuation.rs +13 −15
| @@ -1,11 +1,10 @@ | |||
| 1 | use std::collections::{HashMap, HashSet}; | 1 | use std::collections::{HashMap, HashSet}; |
| 2 | 2 | ||
| 3 | use matrix_sdk::{ | 3 | use matrix_sdk::ruma::{EventId, OwnedEventId, OwnedRoomId, RoomId}; |
| 4 | ruma::{EventId, OwnedEventId, OwnedRoomId, RoomId}, | ||
| 5 | Client, | ||
| 6 | }; | ||
| 7 | use serde::{Deserialize, Serialize}; | 4 | use serde::{Deserialize, Serialize}; |
| 8 | 5 | ||
| 6 | use crate::connection::Connection; | ||
| 7 | |||
| 9 | const STORE_KEY: &[u8] = b"org.weechat.matrix.thread_continuations.v1"; | 8 | const STORE_KEY: &[u8] = b"org.weechat.matrix.thread_continuations.v1"; |
| 10 | const MAX_UPGRADE_DEPTH: usize = 32; | 9 | const MAX_UPGRADE_DEPTH: usize = 32; |
| 11 | 10 | ||
| @@ -36,12 +35,10 @@ pub(crate) struct ThreadContinuationState { | |||
| 36 | } | 35 | } |
| 37 | 36 | ||
| 38 | impl ThreadContinuationState { | 37 | impl ThreadContinuationState { |
| 39 | pub(crate) async fn load(client: &Client) -> Result<Self, String> { | 38 | pub(crate) async fn load(connection: &Connection) -> Result<Self, String> { |
| 40 | let Some(bytes) = client | 39 | let Some(bytes) = connection |
| 41 | .state_store() | 40 | .get_custom_store_value(STORE_KEY.to_vec()) |
| 42 | .get_custom_value(STORE_KEY) | 41 | .await? |
| 43 | .await | ||
| 44 | .map_err(|error| error.to_string())? | ||
| 45 | else { | 42 | else { |
| 46 | return Ok(Self::default()); | 43 | return Ok(Self::default()); |
| 47 | }; | 44 | }; |
| @@ -53,15 +50,16 @@ impl ThreadContinuationState { | |||
| 53 | Ok(state) | 50 | Ok(state) |
| 54 | } | 51 | } |
| 55 | 52 | ||
| 56 | pub(crate) async fn save(&self, client: &Client) -> Result<(), String> { | 53 | pub(crate) async fn save( |
| 54 | &self, | ||
| 55 | connection: &Connection, | ||
| 56 | ) -> Result<(), String> { | ||
| 57 | self.validate()?; | 57 | self.validate()?; |
| 58 | let bytes = | 58 | let bytes = |
| 59 | serde_json::to_vec(self).map_err(|error| error.to_string())?; | 59 | serde_json::to_vec(self).map_err(|error| error.to_string())?; |
| 60 | client | 60 | connection |
| 61 | .state_store() | 61 | .set_custom_store_value(STORE_KEY.to_vec(), bytes) |
| 62 | .set_custom_value_no_read(STORE_KEY, bytes) | ||
| 63 | .await | 62 | .await |
| 64 | .map_err(|error| error.to_string()) | ||
| 65 | } | 63 | } |
| 66 | 64 | ||
| 67 | pub(crate) fn resolve( | 65 | pub(crate) fn resolve( |