Skip to main content

ruma_client_api/delayed_events/
delayed_state_event.rs

1//! `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}/{txnId}`
2//!
3//! Send a delayed state event (a scheduled state event) to a room.
4//!
5//! This endpoint implements a previous iteration of MSC4140 at commit [`3ee73ab`], which adds an
6//! unstable query parameter to [`send_state_event`]. At the time of writing, this matches the
7//! current implementation of Synapse but the latest iteration of the MSC uses the
8//! [`send_delayed_event`] endpoint instead.
9//!
10//! [`3ee73ab`]: https://github.com/matrix-org/matrix-spec-proposals/blob/3ee73abe5f81252b00877cfb5db941ee9aa6c18d/proposals/4140-delayed-events-futures.md
11//! [`send_state_event`]: crate::state::send_state_event
12//! [`send_delayed_event`]: super::send_delayed_event
13
14pub mod msc4140 {
15    //! `/v3/` ([MSC])
16    //!
17    //! [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4140
18
19    use ruma_common::{
20        OwnedRoomId,
21        api::{auth_scheme::AccessToken, request, response},
22        metadata,
23        serde::Raw,
24    };
25    use ruma_events::{AnyStateEventContent, StateEventContent, StateEventType};
26    use serde_json::value::to_raw_value as to_raw_json_value;
27
28    use crate::delayed_events::DelayParameters;
29
30    metadata! {
31        method: PUT,
32        rate_limited: false,
33        authentication: AccessToken,
34        history: {
35            // We use the unstable prefix for the delay query parameter but the stable v3 endpoint.
36            unstable => "/_matrix/client/v3/rooms/{room_id}/state/{event_type}/{state_key}",
37        }
38    }
39
40    /// Request type for the `delayed_state_event` endpoint.
41    #[request]
42    pub struct Request {
43        /// The room to send the event to.
44        #[ruma_api(path)]
45        pub room_id: OwnedRoomId,
46
47        /// The type of event to send.
48        #[ruma_api(path)]
49        pub event_type: StateEventType,
50
51        /// The state_key for the state to send.
52        #[ruma_api(path)]
53        pub state_key: String,
54
55        /// Additional parameters to describe sending a delayed event.
56        ///
57        /// Only three combinations for `timeout` and `delay_parent_id` are possible.
58        /// The enum [`DelayParameters`] enforces this.
59        #[ruma_api(query_all)]
60        pub delay_parameters: DelayParameters,
61
62        /// The event content to send.
63        #[ruma_api(body)]
64        pub body: Raw<AnyStateEventContent>,
65    }
66
67    /// Response type for the `delayed_state_event` endpoint.
68    #[response]
69    pub struct Response {
70        /// The `delay_id` generated for this delayed event. Used to interact with delayed events.
71        pub delay_id: String,
72    }
73
74    impl Request {
75        /// Creates a new `Request` with the given room id, state_key delay_parameters and
76        /// event content.
77        ///
78        /// # Errors
79        ///
80        /// Since `Request` stores the request body in serialized form, this function can fail if
81        /// `T`s [`serde::Serialize`] implementation can fail.
82        pub fn new<T>(
83            room_id: OwnedRoomId,
84            state_key: String,
85            delay_parameters: DelayParameters,
86            content: &T,
87        ) -> serde_json::Result<Self>
88        where
89            T: StateEventContent,
90        {
91            Ok(Self {
92                room_id,
93                state_key,
94                event_type: content.event_type(),
95                delay_parameters,
96                body: Raw::from_json(to_raw_json_value(content)?),
97            })
98        }
99
100        /// Creates a new `Request` with the given room id, event type, state key,
101        /// delay parameters and raw event content.
102        pub fn new_raw(
103            room_id: OwnedRoomId,
104            state_key: String,
105            event_type: StateEventType,
106            delay_parameters: DelayParameters,
107            body: Raw<AnyStateEventContent>,
108        ) -> Self {
109            Self { room_id, event_type, state_key, body, delay_parameters }
110        }
111    }
112
113    impl Response {
114        /// Creates a new `Response` with the token required to control the delayed event.
115        pub fn new(delay_id: String) -> Self {
116            Self { delay_id }
117        }
118    }
119
120    #[cfg(all(test, feature = "client"))]
121    mod tests {
122        use std::borrow::Cow;
123
124        use ruma_common::{
125            api::{
126                MatrixVersion, OutgoingRequestExt as _, SupportedVersions,
127                auth_scheme::SendAccessToken,
128            },
129            owned_room_id,
130            serde::Raw,
131        };
132        use serde_json::{Value as JsonValue, json};
133        use web_time::Duration;
134
135        use super::Request;
136        use crate::delayed_events::DelayParameters;
137
138        fn create_delayed_event_request(
139            delay_parameters: DelayParameters,
140        ) -> (http::request::Parts, Vec<u8>) {
141            let supported = SupportedVersions {
142                versions: [MatrixVersion::V1_1].into(),
143                features: Default::default(),
144            };
145
146            Request::new_raw(
147                owned_room_id!("!roomid:example.org"),
148                "@userAsStateKey:example.org".to_owned(),
149                "com.example.custom_state".into(),
150                delay_parameters,
151                Raw::new(&json!({ "key": "value" })).unwrap().cast_unchecked(),
152            )
153            .try_into_http_request(
154                "https://homeserver.tld",
155                SendAccessToken::IfRequired("auth_tok"),
156                Cow::Owned(supported),
157            )
158            .unwrap()
159            .into_parts()
160        }
161
162        #[test]
163        fn serialize_delayed_state_request() {
164            let (parts, body) = create_delayed_event_request(DelayParameters::Timeout {
165                timeout: Duration::from_millis(1_234_321),
166            });
167            assert_eq!(
168                "https://homeserver.tld/_matrix/client/v3/rooms/!roomid:example.org/state/com.example.custom_state/@userAsStateKey:example.org?org.matrix.msc4140.delay=1234321",
169                parts.uri
170            );
171            assert_eq!("PUT", parts.method);
172            assert_eq!(
173                json!({ "key": "value" }),
174                serde_json::from_slice::<JsonValue>(&body).unwrap()
175            );
176        }
177    }
178}