ruma_common/api/
metadata.rs

1use std::{
2    cmp::Ordering,
3    collections::{BTreeMap, BTreeSet},
4    fmt::Display,
5    str::FromStr,
6};
7
8use bytes::BufMut;
9use http::Method;
10use ruma_macros::StringEnum;
11
12use super::{auth_scheme::AuthScheme, error::UnknownVersionError, path_builder::PathBuilder};
13use crate::{PrivOwnedStr, RoomVersionId, api::error::IntoHttpError, serde::slice_to_buf};
14
15/// Convenient constructor for [`Metadata`] implementation.
16///
17/// ## Definition
18///
19/// By default, `Metadata` is implemented on a type named `Request` that is in scope. This can be
20/// overridden by adding `@for MyType` at the beginning of the declaration.
21///
22/// The rest of the definition of the macro is made to look like a struct, with the following
23/// fields:
24///
25/// * `method` - The HTTP method to use for the endpoint. Its value must be one of the associated
26///   constants of [`http::Method`]. In most cases it should be one of `GET`, `POST`, `PUT` or
27///   `DELETE`.
28/// * `rate_limited` - Whether the endpoint should be rate-limited, according to the specification.
29///   Its value must be a `bool`.
30/// * `authentication` - The type of authentication that is required for the endpoint, according to
31///   the specification. The type must be in scope and implement [`AuthScheme`].
32///
33/// And either of the following fields to define the path(s) of the endpoint.
34///
35/// * `history` - The history of the paths of the endpoint. This should be used for endpoints from
36///   Matrix APIs that have a `/versions` endpoint that returns a list a [`MatrixVersion`]s and
37///   possibly features, like the Client-Server API or the Identity Service API. However, a few
38///   endpoints from those APIs shouldn't use this field because they cannot be versioned, like the
39///   `/versions` or the `/.well-known` endpoints.
40///
41///   Its definition is made to look like match arms and must include at least one arm. The match
42///   arms accept the following syntax:
43///
44///   * `unstable => "unstable/endpoint/path/{variable}"` - An unstable version of the endpoint as
45///     defined in the MSC that adds it, if the MSC does **NOT** define an unstable feature in the
46///     `unstable_features` field of the client-server API's `/versions` endpoint.
47///   * `unstable("org.bar.unstable_feature") => "unstable/endpoint/path/{variable}"` - An unstable
48///     version of the endpoint as defined in the MSC that adds it, if the MSC defines an unstable
49///     feature in the `unstable_features` field of the client-server API's `/versions` endpoint.
50///   * `1.0 | stable("org.bar.feature.stable") => "stable/endpoint/path/{variable}"` - A stable
51///     version of the endpoint as defined in an MSC or the Matrix specification. The match arm can
52///     be a Matrix version, a stable feature, or both separated by `|`.
53///
54///     A stable feature can be defined in an MSC alongside an unstable feature, and can be found in
55///     the `unstable_features` field of the client-server API's `/versions` endpoint. It is meant
56///     to be used by homeservers if they want to declare stable support for a feature before they
57///     can declare support for a whole Matrix version that supports it.
58///
59///   * `1.2 => deprecated` - The Matrix version that deprecated the endpoint, if any. It must be
60///     preceded by a match arm with a stable path and a different Matrix version.
61///   * `1.3 => removed` - The Matrix version that removed the endpoint, if any. It must be preceded
62///     by a match arm with a deprecation and a different Matrix version.
63///
64///   A Matrix version is a `float` representation of the version that looks like `major.minor`.
65///   It must match one of the variants of [`MatrixVersion`]. For example `1.0` matches
66///   [`MatrixVersion::V1_0`], `1.1` matches [`MatrixVersion::V1_1`], etc.
67///
68///   It is expected that the match arms are ordered by descending age. Usually the older unstable
69///   paths would be before the newer unstable paths, then we would find the stable paths, and
70///   finally the deprecation and removal.
71///
72///   The following checks occur at compile time:
73///
74///   * All unstable and stable paths contain the same variables (or lack thereof).
75///   * Matrix versions in match arms are all different and in ascending order.
76///
77///   This field is represented as the [`VersionHistory`](super::path_builder::VersionHistory) type
78///   in the generated implementation.
79/// * `path` - The only path of the endpoint. This should be used for endpoints from Matrix APIs
80///   that do NOT have a `/versions` endpoint that returns a list a [`MatrixVersion`]s, like the
81///   Server-Server API or the Appservice API. It should also be used for endpoints that cannot be
82///   versioned, like the `/versions` or the `/.well-known` endpoints.
83///
84///   Its value must be a static string representing the path, like `"endpoint/path/{variable}"`.
85///
86///   This field is represented as the [`SinglePath`](super::path_builder::SinglePath) type in the
87///   generated implementation.
88///
89/// ## Example
90///
91/// ```
92/// use ruma_common::{
93///     api::auth_scheme::{AccessToken, NoAuthentication},
94///     metadata,
95/// };
96///
97/// /// A Request with a path version history.
98/// pub struct Request {
99///     body: Vec<u8>,
100/// }
101///
102/// metadata! {
103///     method: GET,
104///     rate_limited: true,
105///     authentication: AccessToken,
106///
107///     history: {
108///         unstable => "/_matrix/unstable/org.bar.msc9000/baz",
109///         unstable("org.bar.msc9000.v1") => "/_matrix/unstable/org.bar.msc9000.v1/qux",
110///         1.0 | stable("org.bar.msc9000.stable") => "/_matrix/media/r0/qux",
111///         1.1 => "/_matrix/media/v3/qux",
112///         1.2 => deprecated,
113///         1.3 => removed,
114///     }
115/// };
116///
117/// /// A request with a single path.
118/// pub struct MySinglePathRequest {
119///     body: Vec<u8>,
120/// }
121///
122/// metadata! {
123///     @for MySinglePathRequest,
124///
125///     method: GET,
126///     rate_limited: false,
127///     authentication: NoAuthentication,
128///     path: "/_matrix/key/query",
129/// };
130/// ```
131#[doc(hidden)]
132#[macro_export]
133macro_rules! metadata {
134    ( @for $request_type:ty, $( $field:ident: $rhs:tt ),+ $(,)? ) => {
135        #[allow(deprecated)]
136        impl $crate::api::Metadata for $request_type {
137            $( $crate::metadata!(@field $field: $rhs); )+
138        }
139    };
140
141    ( $( $field:ident: $rhs:tt ),+ $(,)? ) => {
142        $crate::metadata!{ @for Request, $( $field: $rhs),+ }
143    };
144
145    ( @field method: $method:ident ) => {
146        const METHOD: $crate::exports::http::Method = $crate::exports::http::Method::$method;
147    };
148
149    ( @field rate_limited: $rate_limited:literal ) => { const RATE_LIMITED: bool = $rate_limited; };
150
151    ( @field authentication: $scheme:path ) => {
152        type Authentication = $scheme;
153    };
154
155    ( @field path: $path:literal ) => {
156        type PathBuilder = $crate::api::path_builder::SinglePath;
157        const PATH_BUILDER: $crate::api::path_builder::SinglePath = $crate::api::path_builder::SinglePath::new($path);
158    };
159
160    ( @field history: {
161        $( unstable $(($unstable_feature:literal))? => $unstable_path:literal, )*
162        $( stable ($stable_feature_only:literal) => $stable_feature_path:literal, )*
163        $( $version:literal $(| stable ($stable_feature:literal))? => $stable_rhs:tt, )*
164    } ) => {
165        $crate::metadata! {
166            @history_impl
167            $( unstable $( ($unstable_feature) )? => $unstable_path, )*
168            $( stable ($stable_feature_only) => $stable_feature_path, )*
169            // Flip left and right to avoid macro parsing ambiguities
170            $( $stable_rhs = $version $( | stable ($stable_feature) )?, )*
171        }
172    };
173
174    ( @history_impl
175        $( unstable $(($unstable_feature:literal))? => $unstable_path:literal, )*
176        $( stable ($stable_feature_only:literal) => $stable_feature_path:literal, )*
177        $( $stable_path:literal = $version:literal $(| stable ($stable_feature:literal))?, )*
178        $( deprecated = $deprecated_version:literal, )?
179        $( removed = $removed_version:literal, )?
180    ) => {
181        type PathBuilder = $crate::api::path_builder::VersionHistory;
182        const PATH_BUILDER: $crate::api::path_builder::VersionHistory = $crate::api::path_builder::VersionHistory::new(
183            &[ $(($crate::metadata!(@optional_feature $($unstable_feature)?), $unstable_path)),* ],
184            &[
185                $((
186                    $crate::metadata!(@stable_path_selector stable($stable_feature_only)),
187                    $stable_feature_path
188                ),)*
189                $((
190                    $crate::metadata!(@stable_path_selector $version $( | stable($stable_feature) )?),
191                    $stable_path
192                ),)*
193            ],
194            $crate::metadata!(@optional_version $( $deprecated_version )?),
195            $crate::metadata!(@optional_version $( $removed_version )?),
196        );
197    };
198
199    ( @optional_feature ) => { None };
200    ( @optional_feature $feature:literal ) => { Some($feature) };
201    ( @stable_path_selector stable($feature:literal)) => {
202        $crate::api::path_builder::StablePathSelector::Feature($feature)
203    };
204    ( @stable_path_selector $version:literal | stable($feature:literal)) => {
205        $crate::api::path_builder::StablePathSelector::FeatureAndVersion {
206            feature: $feature,
207            version: $crate::api::MatrixVersion::from_lit(stringify!($version)),
208        }
209    };
210    ( @stable_path_selector $version:literal) => {
211        $crate::api::path_builder::StablePathSelector::Version(
212            $crate::api::MatrixVersion::from_lit(stringify!($version))
213        )
214    };
215    ( @optional_version ) => { None };
216    ( @optional_version $version:literal ) => { Some($crate::api::MatrixVersion::from_lit(stringify!($version))) }
217}
218
219/// Metadata about an API endpoint.
220pub trait Metadata: Sized {
221    /// The HTTP method used by this endpoint.
222    const METHOD: Method;
223
224    /// Whether or not this endpoint is rate limited by the server.
225    const RATE_LIMITED: bool;
226
227    /// What authentication scheme the server uses for this endpoint.
228    type Authentication: AuthScheme;
229
230    /// The type used to build an endpoint's path.
231    type PathBuilder: PathBuilder;
232
233    /// All info pertaining to an endpoint's path.
234    const PATH_BUILDER: Self::PathBuilder;
235
236    /// Returns an empty request body for this Matrix request.
237    ///
238    /// For `GET` requests, it returns an entirely empty buffer, for others it returns an empty JSON
239    /// object (`{}`).
240    fn empty_request_body<B>() -> B
241    where
242        B: Default + BufMut,
243    {
244        if Self::METHOD == Method::GET { Default::default() } else { slice_to_buf(b"{}") }
245    }
246
247    /// Generate the endpoint URL for this endpoint.
248    fn make_endpoint_url(
249        path_builder_input: <Self::PathBuilder as PathBuilder>::Input<'_>,
250        base_url: &str,
251        path_args: &[&dyn Display],
252        query_string: &str,
253    ) -> Result<String, IntoHttpError> {
254        Self::PATH_BUILDER.make_endpoint_url(path_builder_input, base_url, path_args, query_string)
255    }
256
257    /// The list of path parameters in the metadata.
258    ///
259    /// Used for `#[test]`s generated by the API macros.
260    #[doc(hidden)]
261    fn _path_parameters() -> Vec<&'static str> {
262        Self::PATH_BUILDER._path_parameters()
263    }
264}
265
266/// The Matrix versions Ruma currently understands to exist.
267///
268/// Matrix, since fall 2021, has a quarterly release schedule, using a global `vX.Y` versioning
269/// scheme. Usually `Y` is bumped for new backwards compatible changes, but `X` can be bumped
270/// instead when a large number of `Y` changes feel deserving of a major version increase.
271///
272/// Every new version denotes stable support for endpoints in a *relatively* backwards-compatible
273/// manner.
274///
275/// Matrix has a deprecation policy, read more about it here: <https://spec.matrix.org/latest/#deprecation-policy>.
276///
277/// Ruma keeps track of when endpoints are added, deprecated, and removed. It'll automatically
278/// select the right endpoint stability variation to use depending on which Matrix versions you
279/// pass to [`try_into_http_request`](super::OutgoingRequest::try_into_http_request), see its
280/// respective documentation for more information.
281///
282/// The `PartialOrd` and `Ord` implementations of this type sort the variants by release date. A
283/// newer release is greater than an older release.
284///
285/// `MatrixVersion::is_superset_of()` is used to keep track of compatibility between versions.
286#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
287#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
288pub enum MatrixVersion {
289    /// Matrix 1.0 was a release prior to the global versioning system and does not correspond to a
290    /// version of the Matrix specification.
291    ///
292    /// It matches the following per-API versions:
293    ///
294    /// * Client-Server API: r0.5.0 to r0.6.1
295    /// * Identity Service API: r0.2.0 to r0.3.0
296    ///
297    /// The other APIs are not supported because they do not have a `GET /versions` endpoint.
298    ///
299    /// See <https://spec.matrix.org/latest/#legacy-versioning>.
300    V1_0,
301
302    /// Version 1.1 of the Matrix specification, released in Q4 2021.
303    ///
304    /// See <https://spec.matrix.org/v1.1/>.
305    V1_1,
306
307    /// Version 1.2 of the Matrix specification, released in Q1 2022.
308    ///
309    /// See <https://spec.matrix.org/v1.2/>.
310    V1_2,
311
312    /// Version 1.3 of the Matrix specification, released in Q2 2022.
313    ///
314    /// See <https://spec.matrix.org/v1.3/>.
315    V1_3,
316
317    /// Version 1.4 of the Matrix specification, released in Q3 2022.
318    ///
319    /// See <https://spec.matrix.org/v1.4/>.
320    V1_4,
321
322    /// Version 1.5 of the Matrix specification, released in Q4 2022.
323    ///
324    /// See <https://spec.matrix.org/v1.5/>.
325    V1_5,
326
327    /// Version 1.6 of the Matrix specification, released in Q1 2023.
328    ///
329    /// See <https://spec.matrix.org/v1.6/>.
330    V1_6,
331
332    /// Version 1.7 of the Matrix specification, released in Q2 2023.
333    ///
334    /// See <https://spec.matrix.org/v1.7/>.
335    V1_7,
336
337    /// Version 1.8 of the Matrix specification, released in Q3 2023.
338    ///
339    /// See <https://spec.matrix.org/v1.8/>.
340    V1_8,
341
342    /// Version 1.9 of the Matrix specification, released in Q4 2023.
343    ///
344    /// See <https://spec.matrix.org/v1.9/>.
345    V1_9,
346
347    /// Version 1.10 of the Matrix specification, released in Q1 2024.
348    ///
349    /// See <https://spec.matrix.org/v1.10/>.
350    V1_10,
351
352    /// Version 1.11 of the Matrix specification, released in Q2 2024.
353    ///
354    /// See <https://spec.matrix.org/v1.11/>.
355    V1_11,
356
357    /// Version 1.12 of the Matrix specification, released in Q3 2024.
358    ///
359    /// See <https://spec.matrix.org/v1.12/>.
360    V1_12,
361
362    /// Version 1.13 of the Matrix specification, released in Q4 2024.
363    ///
364    /// See <https://spec.matrix.org/v1.13/>.
365    V1_13,
366
367    /// Version 1.14 of the Matrix specification, released in Q1 2025.
368    ///
369    /// See <https://spec.matrix.org/v1.14/>.
370    V1_14,
371
372    /// Version 1.15 of the Matrix specification, released in Q2 2025.
373    ///
374    /// See <https://spec.matrix.org/v1.15/>.
375    V1_15,
376
377    /// Version 1.16 of the Matrix specification, released in Q3 2025.
378    ///
379    /// See <https://spec.matrix.org/v1.16/>.
380    V1_16,
381}
382
383impl TryFrom<&str> for MatrixVersion {
384    type Error = UnknownVersionError;
385
386    fn try_from(value: &str) -> Result<MatrixVersion, Self::Error> {
387        use MatrixVersion::*;
388
389        Ok(match value {
390            // Identity service API versions between Matrix 1.0 and 1.1.
391            // They might match older client-server API versions but that should not be a problem in practice.
392            "r0.2.0" | "r0.2.1" | "r0.3.0" |
393            // Client-server API versions between Matrix 1.0 and 1.1.
394            "r0.5.0" | "r0.6.0" | "r0.6.1" => V1_0,
395            "v1.1" => V1_1,
396            "v1.2" => V1_2,
397            "v1.3" => V1_3,
398            "v1.4" => V1_4,
399            "v1.5" => V1_5,
400            "v1.6" => V1_6,
401            "v1.7" => V1_7,
402            "v1.8" => V1_8,
403            "v1.9" => V1_9,
404            "v1.10" => V1_10,
405            "v1.11" => V1_11,
406            "v1.12" => V1_12,
407            "v1.13" => V1_13,
408            "v1.14" => V1_14,
409            "v1.15" => V1_15,
410            "v1.16" => V1_16,
411            _ => return Err(UnknownVersionError),
412        })
413    }
414}
415
416impl FromStr for MatrixVersion {
417    type Err = UnknownVersionError;
418
419    fn from_str(s: &str) -> Result<Self, Self::Err> {
420        Self::try_from(s)
421    }
422}
423
424impl MatrixVersion {
425    /// Checks whether a version is compatible with another.
426    ///
427    /// Currently, all versions of Matrix are considered backwards compatible with all the previous
428    /// versions, so this is equivalent to `self >= other`. This behaviour may change in the future,
429    /// if a new release is considered to be breaking compatibility with the previous ones.
430    ///
431    /// > ⚠ Matrix has a deprecation policy, and Matrix versioning is not as straightforward as this
432    /// > function makes it out to be. This function only exists to prune breaking changes between
433    /// > versions, and versions too new for `self`.
434    pub fn is_superset_of(self, other: Self) -> bool {
435        self >= other
436    }
437
438    /// Get a string representation of this Matrix version.
439    ///
440    /// This is the string that can be found in the response to one of the `GET /versions`
441    /// endpoints. Parsing this string will give the same variant.
442    ///
443    /// Returns `None` for [`MatrixVersion::V1_0`] because it can match several per-API versions.
444    pub const fn as_str(self) -> Option<&'static str> {
445        let string = match self {
446            MatrixVersion::V1_0 => return None,
447            MatrixVersion::V1_1 => "v1.1",
448            MatrixVersion::V1_2 => "v1.2",
449            MatrixVersion::V1_3 => "v1.3",
450            MatrixVersion::V1_4 => "v1.4",
451            MatrixVersion::V1_5 => "v1.5",
452            MatrixVersion::V1_6 => "v1.6",
453            MatrixVersion::V1_7 => "v1.7",
454            MatrixVersion::V1_8 => "v1.8",
455            MatrixVersion::V1_9 => "v1.9",
456            MatrixVersion::V1_10 => "v1.10",
457            MatrixVersion::V1_11 => "v1.11",
458            MatrixVersion::V1_12 => "v1.12",
459            MatrixVersion::V1_13 => "v1.13",
460            MatrixVersion::V1_14 => "v1.14",
461            MatrixVersion::V1_15 => "v1.15",
462            MatrixVersion::V1_16 => "v1.16",
463        };
464
465        Some(string)
466    }
467
468    /// Decompose the Matrix version into its major and minor number.
469    const fn into_parts(self) -> (u8, u8) {
470        match self {
471            MatrixVersion::V1_0 => (1, 0),
472            MatrixVersion::V1_1 => (1, 1),
473            MatrixVersion::V1_2 => (1, 2),
474            MatrixVersion::V1_3 => (1, 3),
475            MatrixVersion::V1_4 => (1, 4),
476            MatrixVersion::V1_5 => (1, 5),
477            MatrixVersion::V1_6 => (1, 6),
478            MatrixVersion::V1_7 => (1, 7),
479            MatrixVersion::V1_8 => (1, 8),
480            MatrixVersion::V1_9 => (1, 9),
481            MatrixVersion::V1_10 => (1, 10),
482            MatrixVersion::V1_11 => (1, 11),
483            MatrixVersion::V1_12 => (1, 12),
484            MatrixVersion::V1_13 => (1, 13),
485            MatrixVersion::V1_14 => (1, 14),
486            MatrixVersion::V1_15 => (1, 15),
487            MatrixVersion::V1_16 => (1, 16),
488        }
489    }
490
491    /// Try to turn a pair of (major, minor) version components back into a `MatrixVersion`.
492    const fn from_parts(major: u8, minor: u8) -> Result<Self, UnknownVersionError> {
493        match (major, minor) {
494            (1, 0) => Ok(MatrixVersion::V1_0),
495            (1, 1) => Ok(MatrixVersion::V1_1),
496            (1, 2) => Ok(MatrixVersion::V1_2),
497            (1, 3) => Ok(MatrixVersion::V1_3),
498            (1, 4) => Ok(MatrixVersion::V1_4),
499            (1, 5) => Ok(MatrixVersion::V1_5),
500            (1, 6) => Ok(MatrixVersion::V1_6),
501            (1, 7) => Ok(MatrixVersion::V1_7),
502            (1, 8) => Ok(MatrixVersion::V1_8),
503            (1, 9) => Ok(MatrixVersion::V1_9),
504            (1, 10) => Ok(MatrixVersion::V1_10),
505            (1, 11) => Ok(MatrixVersion::V1_11),
506            (1, 12) => Ok(MatrixVersion::V1_12),
507            (1, 13) => Ok(MatrixVersion::V1_13),
508            (1, 14) => Ok(MatrixVersion::V1_14),
509            (1, 15) => Ok(MatrixVersion::V1_15),
510            (1, 16) => Ok(MatrixVersion::V1_16),
511            _ => Err(UnknownVersionError),
512        }
513    }
514
515    /// Constructor for use by the `metadata!` macro.
516    ///
517    /// Accepts string literals and parses them.
518    #[doc(hidden)]
519    pub const fn from_lit(lit: &'static str) -> Self {
520        use konst::{option, primitive::parse_u8, result, string};
521
522        let major: u8;
523        let minor: u8;
524
525        let mut lit_iter = string::split(lit, ".").next();
526
527        {
528            let (checked_first, checked_split) = option::unwrap!(lit_iter); // First iteration always succeeds
529
530            major = result::unwrap_or_else!(parse_u8(checked_first), |_| panic!(
531                "major version is not a valid number"
532            ));
533
534            lit_iter = checked_split.next();
535        }
536
537        match lit_iter {
538            Some((checked_second, checked_split)) => {
539                minor = result::unwrap_or_else!(parse_u8(checked_second), |_| panic!(
540                    "minor version is not a valid number"
541                ));
542
543                lit_iter = checked_split.next();
544            }
545            None => panic!("could not find dot to denote second number"),
546        }
547
548        if lit_iter.is_some() {
549            panic!("version literal contains more than one dot")
550        }
551
552        result::unwrap_or_else!(Self::from_parts(major, minor), |_| panic!(
553            "not a valid version literal"
554        ))
555    }
556
557    // Internal function to do ordering in const-fn contexts
558    pub(super) const fn const_ord(&self, other: &Self) -> Ordering {
559        let self_parts = self.into_parts();
560        let other_parts = other.into_parts();
561
562        use konst::primitive::cmp::cmp_u8;
563
564        let major_ord = cmp_u8(self_parts.0, other_parts.0);
565        if major_ord.is_ne() { major_ord } else { cmp_u8(self_parts.1, other_parts.1) }
566    }
567
568    // Internal function to check if this version is the legacy (v1.0) version in const-fn contexts
569    pub(super) const fn is_legacy(&self) -> bool {
570        let self_parts = self.into_parts();
571
572        use konst::primitive::cmp::cmp_u8;
573
574        cmp_u8(self_parts.0, 1).is_eq() && cmp_u8(self_parts.1, 0).is_eq()
575    }
576
577    /// Get the default [`RoomVersionId`] for this `MatrixVersion`.
578    pub fn default_room_version(&self) -> RoomVersionId {
579        match self {
580            // <https://spec.matrix.org/historical/index.html#complete-list-of-room-versions>
581            MatrixVersion::V1_0
582            // <https://spec.matrix.org/v1.1/rooms/#complete-list-of-room-versions>
583            | MatrixVersion::V1_1
584            // <https://spec.matrix.org/v1.2/rooms/#complete-list-of-room-versions>
585            | MatrixVersion::V1_2 => RoomVersionId::V6,
586            // <https://spec.matrix.org/v1.3/rooms/#complete-list-of-room-versions>
587            MatrixVersion::V1_3
588            // <https://spec.matrix.org/v1.4/rooms/#complete-list-of-room-versions>
589            | MatrixVersion::V1_4
590            // <https://spec.matrix.org/v1.5/rooms/#complete-list-of-room-versions>
591            | MatrixVersion::V1_5 => RoomVersionId::V9,
592            // <https://spec.matrix.org/v1.6/rooms/#complete-list-of-room-versions>
593            MatrixVersion::V1_6
594            // <https://spec.matrix.org/v1.7/rooms/#complete-list-of-room-versions>
595            | MatrixVersion::V1_7
596            // <https://spec.matrix.org/v1.8/rooms/#complete-list-of-room-versions>
597            | MatrixVersion::V1_8
598            // <https://spec.matrix.org/v1.9/rooms/#complete-list-of-room-versions>
599            | MatrixVersion::V1_9
600            // <https://spec.matrix.org/v1.10/rooms/#complete-list-of-room-versions>
601            | MatrixVersion::V1_10
602            // <https://spec.matrix.org/v1.11/rooms/#complete-list-of-room-versions>
603            | MatrixVersion::V1_11
604            // <https://spec.matrix.org/v1.12/rooms/#complete-list-of-room-versions>
605            | MatrixVersion::V1_12
606            // <https://spec.matrix.org/v1.13/rooms/#complete-list-of-room-versions>
607            | MatrixVersion::V1_13 => RoomVersionId::V10,
608            // <https://spec.matrix.org/v1.14/rooms/#complete-list-of-room-versions>
609            | MatrixVersion::V1_14
610            // <https://spec.matrix.org/v1.15/rooms/#complete-list-of-room-versions>
611            | MatrixVersion::V1_15 => RoomVersionId::V11,
612            // <https://spec.matrix.org/v1.16/rooms/#complete-list-of-room-versions>
613            MatrixVersion::V1_16 => RoomVersionId::V12,
614        }
615    }
616}
617
618/// The list of Matrix versions and features supported by a homeserver.
619#[derive(Debug, Clone)]
620#[allow(clippy::exhaustive_structs)]
621pub struct SupportedVersions {
622    /// The Matrix versions that are supported by the homeserver.
623    ///
624    /// This set contains only known versions.
625    pub versions: BTreeSet<MatrixVersion>,
626
627    /// The features that are supported by the homeserver.
628    ///
629    /// This matches the `unstable_features` field of the `/versions` endpoint, without the boolean
630    /// value.
631    pub features: BTreeSet<FeatureFlag>,
632}
633
634impl SupportedVersions {
635    /// Construct a `SupportedVersions` from the parts of a `/versions` response.
636    ///
637    /// Matrix versions that can't be parsed to a `MatrixVersion`, and features with the boolean
638    /// value set to `false` are discarded.
639    pub fn from_parts(versions: &[String], unstable_features: &BTreeMap<String, bool>) -> Self {
640        Self {
641            versions: versions.iter().flat_map(|s| s.parse::<MatrixVersion>()).collect(),
642            features: unstable_features
643                .iter()
644                .filter(|(_, enabled)| **enabled)
645                .map(|(feature, _)| feature.as_str().into())
646                .collect(),
647        }
648    }
649}
650
651/// The Matrix features supported by Ruma.
652///
653/// Features that are not behind a cargo feature are features that are part of the Matrix
654/// specification and that Ruma still supports, like the unstable version of an endpoint or a stable
655/// feature. Features behind a cargo feature are only supported when this feature is enabled.
656#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
657#[derive(Clone, StringEnum, Hash)]
658#[non_exhaustive]
659pub enum FeatureFlag {
660    /// `fi.mau.msc2246` ([MSC])
661    ///
662    /// Asynchronous media uploads.
663    ///
664    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2246
665    #[ruma_enum(rename = "fi.mau.msc2246")]
666    Msc2246,
667
668    /// `org.matrix.msc2432` ([MSC])
669    ///
670    /// Updated semantics for publishing room aliases.
671    ///
672    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2432
673    #[ruma_enum(rename = "org.matrix.msc2432")]
674    Msc2432,
675
676    /// `fi.mau.msc2659` ([MSC])
677    ///
678    /// Application service ping endpoint.
679    ///
680    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2659
681    #[ruma_enum(rename = "fi.mau.msc2659")]
682    Msc2659,
683
684    /// `fi.mau.msc2659` ([MSC])
685    ///
686    /// Stable version of the application service ping endpoint.
687    ///
688    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2659
689    #[ruma_enum(rename = "fi.mau.msc2659.stable")]
690    Msc2659Stable,
691
692    /// `uk.half-shot.msc2666.query_mutual_rooms` ([MSC])
693    ///
694    /// Get rooms in common with another user.
695    ///
696    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2666
697    #[cfg(feature = "unstable-msc2666")]
698    #[ruma_enum(rename = "uk.half-shot.msc2666.query_mutual_rooms")]
699    Msc2666,
700
701    /// `org.matrix.msc3030` ([MSC])
702    ///
703    /// Jump to date API endpoint.
704    ///
705    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/3030
706    #[ruma_enum(rename = "org.matrix.msc3030")]
707    Msc3030,
708
709    /// `org.matrix.msc3882` ([MSC])
710    ///
711    /// Allow an existing session to sign in a new session.
712    ///
713    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/3882
714    #[ruma_enum(rename = "org.matrix.msc3882")]
715    Msc3882,
716
717    /// `org.matrix.msc3916` ([MSC])
718    ///
719    /// Authentication for media.
720    ///
721    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/3916
722    #[ruma_enum(rename = "org.matrix.msc3916")]
723    Msc3916,
724
725    /// `org.matrix.msc3916.stable` ([MSC])
726    ///
727    /// Stable version of authentication for media.
728    ///
729    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/3916
730    #[ruma_enum(rename = "org.matrix.msc3916.stable")]
731    Msc3916Stable,
732
733    /// `org.matrix.msc4108` ([MSC])
734    ///
735    /// Mechanism to allow OIDC sign in and E2EE set up via QR code.
736    ///
737    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4108
738    #[cfg(feature = "unstable-msc4108")]
739    #[ruma_enum(rename = "org.matrix.msc4108")]
740    Msc4108,
741
742    /// `org.matrix.msc4140` ([MSC])
743    ///
744    /// Delayed events.
745    ///
746    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4140
747    #[cfg(feature = "unstable-msc4140")]
748    #[ruma_enum(rename = "org.matrix.msc4140")]
749    Msc4140,
750
751    /// `org.matrix.simplified_msc3575` ([MSC])
752    ///
753    /// Simplified Sliding Sync.
754    ///
755    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4186
756    #[cfg(feature = "unstable-msc4186")]
757    #[ruma_enum(rename = "org.matrix.simplified_msc3575")]
758    Msc4186,
759
760    /// `org.matrix.msc4380_invite_permission_config` ([MSC])
761    ///
762    /// Invite Blocking.
763    ///
764    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4380
765    #[cfg(feature = "unstable-msc4380")]
766    #[ruma_enum(rename = "org.matrix.msc4380")]
767    Msc4380,
768
769    #[doc(hidden)]
770    _Custom(PrivOwnedStr),
771}