Skip to main content

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/v1.19/#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::OutgoingRequestExt::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/v1.19/#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    /// Version 1.17 of the Matrix specification, released in Q4 2025.
383    ///
384    /// See <https://spec.matrix.org/v1.17/>.
385    V1_17,
386
387    /// Version 1.18 of the Matrix specification, released in Q1 2026.
388    ///
389    /// See <https://spec.matrix.org/v1.18/>.
390    V1_18,
391
392    /// Version 1.19 of the Matrix specification, released in Q2 2026.
393    ///
394    /// See <https://spec.matrix.org/v1.19/>.
395    V1_19,
396}
397
398impl TryFrom<&str> for MatrixVersion {
399    type Error = UnknownVersionError;
400
401    fn try_from(value: &str) -> Result<MatrixVersion, Self::Error> {
402        use MatrixVersion::*;
403
404        Ok(match value {
405            // Identity service API versions between Matrix 1.0 and 1.1.
406            // They might match older client-server API versions but that should not be a problem in practice.
407            "r0.2.0" | "r0.2.1" | "r0.3.0" |
408            // Client-server API versions between Matrix 1.0 and 1.1.
409            "r0.5.0" | "r0.6.0" | "r0.6.1" => V1_0,
410            "v1.1" => V1_1,
411            "v1.2" => V1_2,
412            "v1.3" => V1_3,
413            "v1.4" => V1_4,
414            "v1.5" => V1_5,
415            "v1.6" => V1_6,
416            "v1.7" => V1_7,
417            "v1.8" => V1_8,
418            "v1.9" => V1_9,
419            "v1.10" => V1_10,
420            "v1.11" => V1_11,
421            "v1.12" => V1_12,
422            "v1.13" => V1_13,
423            "v1.14" => V1_14,
424            "v1.15" => V1_15,
425            "v1.16" => V1_16,
426            "v1.17" => V1_17,
427            "v1.18" => V1_18,
428            "v1.19" => V1_19,
429            _ => return Err(UnknownVersionError),
430        })
431    }
432}
433
434impl FromStr for MatrixVersion {
435    type Err = UnknownVersionError;
436
437    fn from_str(s: &str) -> Result<Self, Self::Err> {
438        Self::try_from(s)
439    }
440}
441
442impl MatrixVersion {
443    /// Checks whether a version is compatible with another.
444    ///
445    /// Currently, all versions of Matrix are considered backwards compatible with all the previous
446    /// versions, so this is equivalent to `self >= other`. This behaviour may change in the future,
447    /// if a new release is considered to be breaking compatibility with the previous ones.
448    ///
449    /// > ⚠ Matrix has a deprecation policy, and Matrix versioning is not as straightforward as this
450    /// > function makes it out to be. This function only exists to prune breaking changes between
451    /// > versions, and versions too new for `self`.
452    pub fn is_superset_of(self, other: Self) -> bool {
453        self >= other
454    }
455
456    /// Get a string representation of this Matrix version.
457    ///
458    /// This is the string that can be found in the response to one of the `GET /versions`
459    /// endpoints. Parsing this string will give the same variant.
460    ///
461    /// Returns `None` for [`MatrixVersion::V1_0`] because it can match several per-API versions.
462    pub const fn as_str(self) -> Option<&'static str> {
463        let string = match self {
464            MatrixVersion::V1_0 => return None,
465            MatrixVersion::V1_1 => "v1.1",
466            MatrixVersion::V1_2 => "v1.2",
467            MatrixVersion::V1_3 => "v1.3",
468            MatrixVersion::V1_4 => "v1.4",
469            MatrixVersion::V1_5 => "v1.5",
470            MatrixVersion::V1_6 => "v1.6",
471            MatrixVersion::V1_7 => "v1.7",
472            MatrixVersion::V1_8 => "v1.8",
473            MatrixVersion::V1_9 => "v1.9",
474            MatrixVersion::V1_10 => "v1.10",
475            MatrixVersion::V1_11 => "v1.11",
476            MatrixVersion::V1_12 => "v1.12",
477            MatrixVersion::V1_13 => "v1.13",
478            MatrixVersion::V1_14 => "v1.14",
479            MatrixVersion::V1_15 => "v1.15",
480            MatrixVersion::V1_16 => "v1.16",
481            MatrixVersion::V1_17 => "v1.17",
482            MatrixVersion::V1_18 => "v1.18",
483            MatrixVersion::V1_19 => "v1.19",
484        };
485
486        Some(string)
487    }
488
489    /// Decompose the Matrix version into its major and minor number.
490    const fn into_parts(self) -> (u8, u8) {
491        match self {
492            MatrixVersion::V1_0 => (1, 0),
493            MatrixVersion::V1_1 => (1, 1),
494            MatrixVersion::V1_2 => (1, 2),
495            MatrixVersion::V1_3 => (1, 3),
496            MatrixVersion::V1_4 => (1, 4),
497            MatrixVersion::V1_5 => (1, 5),
498            MatrixVersion::V1_6 => (1, 6),
499            MatrixVersion::V1_7 => (1, 7),
500            MatrixVersion::V1_8 => (1, 8),
501            MatrixVersion::V1_9 => (1, 9),
502            MatrixVersion::V1_10 => (1, 10),
503            MatrixVersion::V1_11 => (1, 11),
504            MatrixVersion::V1_12 => (1, 12),
505            MatrixVersion::V1_13 => (1, 13),
506            MatrixVersion::V1_14 => (1, 14),
507            MatrixVersion::V1_15 => (1, 15),
508            MatrixVersion::V1_16 => (1, 16),
509            MatrixVersion::V1_17 => (1, 17),
510            MatrixVersion::V1_18 => (1, 18),
511            MatrixVersion::V1_19 => (1, 19),
512        }
513    }
514
515    /// Try to turn a pair of (major, minor) version components back into a `MatrixVersion`.
516    const fn from_parts(major: u8, minor: u8) -> Result<Self, UnknownVersionError> {
517        match (major, minor) {
518            (1, 0) => Ok(MatrixVersion::V1_0),
519            (1, 1) => Ok(MatrixVersion::V1_1),
520            (1, 2) => Ok(MatrixVersion::V1_2),
521            (1, 3) => Ok(MatrixVersion::V1_3),
522            (1, 4) => Ok(MatrixVersion::V1_4),
523            (1, 5) => Ok(MatrixVersion::V1_5),
524            (1, 6) => Ok(MatrixVersion::V1_6),
525            (1, 7) => Ok(MatrixVersion::V1_7),
526            (1, 8) => Ok(MatrixVersion::V1_8),
527            (1, 9) => Ok(MatrixVersion::V1_9),
528            (1, 10) => Ok(MatrixVersion::V1_10),
529            (1, 11) => Ok(MatrixVersion::V1_11),
530            (1, 12) => Ok(MatrixVersion::V1_12),
531            (1, 13) => Ok(MatrixVersion::V1_13),
532            (1, 14) => Ok(MatrixVersion::V1_14),
533            (1, 15) => Ok(MatrixVersion::V1_15),
534            (1, 16) => Ok(MatrixVersion::V1_16),
535            (1, 17) => Ok(MatrixVersion::V1_17),
536            (1, 18) => Ok(MatrixVersion::V1_18),
537            (1, 19) => Ok(MatrixVersion::V1_19),
538            _ => Err(UnknownVersionError),
539        }
540    }
541
542    /// Constructor for use by the `metadata!` macro.
543    ///
544    /// Accepts string literals and parses them.
545    #[doc(hidden)]
546    pub const fn from_lit(lit: &'static str) -> Self {
547        use konst::{result, string};
548
549        let mut lit_parts = string::split(lit, ".");
550
551        let checked_first = lit_parts.next().unwrap(); // First iteration always succeeds
552        let major = result::unwrap_or_else!(u8::from_str_radix(checked_first, 10), |_| panic!(
553            "major version is not a valid number"
554        ));
555
556        let Some(checked_second) = lit_parts.next() else {
557            panic!("could not find dot to denote second number");
558        };
559        let minor = result::unwrap_or_else!(u8::from_str_radix(checked_second, 10), |_| panic!(
560            "minor version is not a valid number"
561        ));
562
563        if lit_parts.next().is_some() {
564            panic!("version literal contains more than one dot")
565        }
566
567        result::unwrap_or_else!(Self::from_parts(major, minor), |_| panic!(
568            "not a valid version literal"
569        ))
570    }
571
572    // Internal function to do ordering in const-fn contexts
573    pub(super) const fn const_ord(&self, other: &Self) -> Ordering {
574        let self_parts = self.into_parts();
575        let other_parts = other.into_parts();
576
577        use konst::primitive::cmp::cmp_u8;
578
579        let major_ord = cmp_u8(self_parts.0, other_parts.0);
580        if major_ord.is_ne() { major_ord } else { cmp_u8(self_parts.1, other_parts.1) }
581    }
582
583    // Internal function to check if this version is the legacy (v1.0) version in const-fn contexts
584    pub(super) const fn is_legacy(&self) -> bool {
585        let self_parts = self.into_parts();
586
587        use konst::primitive::cmp::cmp_u8;
588
589        cmp_u8(self_parts.0, 1).is_eq() && cmp_u8(self_parts.1, 0).is_eq()
590    }
591
592    /// Get the default [`RoomVersionId`] for this `MatrixVersion`.
593    pub fn default_room_version(&self) -> RoomVersionId {
594        match self {
595            // <https://spec.matrix.org/historical/index.html#complete-list-of-room-versions>
596            MatrixVersion::V1_0
597            // <https://spec.matrix.org/v1.1/rooms/#complete-list-of-room-versions>
598            | MatrixVersion::V1_1
599            // <https://spec.matrix.org/v1.2/rooms/#complete-list-of-room-versions>
600            | MatrixVersion::V1_2 => RoomVersionId::V6,
601            // <https://spec.matrix.org/v1.3/rooms/#complete-list-of-room-versions>
602            MatrixVersion::V1_3
603            // <https://spec.matrix.org/v1.4/rooms/#complete-list-of-room-versions>
604            | MatrixVersion::V1_4
605            // <https://spec.matrix.org/v1.5/rooms/#complete-list-of-room-versions>
606            | MatrixVersion::V1_5 => RoomVersionId::V9,
607            // <https://spec.matrix.org/v1.6/rooms/#complete-list-of-room-versions>
608            MatrixVersion::V1_6
609            // <https://spec.matrix.org/v1.7/rooms/#complete-list-of-room-versions>
610            | MatrixVersion::V1_7
611            // <https://spec.matrix.org/v1.8/rooms/#complete-list-of-room-versions>
612            | MatrixVersion::V1_8
613            // <https://spec.matrix.org/v1.9/rooms/#complete-list-of-room-versions>
614            | MatrixVersion::V1_9
615            // <https://spec.matrix.org/v1.10/rooms/#complete-list-of-room-versions>
616            | MatrixVersion::V1_10
617            // <https://spec.matrix.org/v1.11/rooms/#complete-list-of-room-versions>
618            | MatrixVersion::V1_11
619            // <https://spec.matrix.org/v1.12/rooms/#complete-list-of-room-versions>
620            | MatrixVersion::V1_12
621            // <https://spec.matrix.org/v1.13/rooms/#complete-list-of-room-versions>
622            | MatrixVersion::V1_13 => RoomVersionId::V10,
623            // <https://spec.matrix.org/v1.14/rooms/#complete-list-of-room-versions>
624            | MatrixVersion::V1_14
625            // <https://spec.matrix.org/v1.15/rooms/#complete-list-of-room-versions>
626            | MatrixVersion::V1_15 => RoomVersionId::V11,
627            // <https://spec.matrix.org/v1.16/rooms/#complete-list-of-room-versions>
628            MatrixVersion::V1_16
629            // <https://spec.matrix.org/v1.17/rooms/#complete-list-of-room-versions>
630            | MatrixVersion::V1_17
631            // <https://spec.matrix.org/v1.18/rooms/#complete-list-of-room-versions>
632            | MatrixVersion::V1_18
633            // <https://spec.matrix.org/v1.19/rooms/#complete-list-of-room-versions>
634            | MatrixVersion::V1_19 => RoomVersionId::V12,
635        }
636    }
637}
638
639/// The list of Matrix versions and features supported by a homeserver.
640#[derive(Debug, Clone)]
641#[allow(clippy::exhaustive_structs)]
642pub struct SupportedVersions {
643    /// The Matrix versions that are supported by the homeserver.
644    ///
645    /// This set contains only known versions.
646    pub versions: BTreeSet<MatrixVersion>,
647
648    /// The features that are supported by the homeserver.
649    ///
650    /// This matches the `unstable_features` field of the `/versions` endpoint, without the boolean
651    /// value.
652    pub features: BTreeSet<FeatureFlag>,
653}
654
655impl SupportedVersions {
656    /// Construct a `SupportedVersions` from the parts of a `/versions` response.
657    ///
658    /// Matrix versions that can't be parsed to a `MatrixVersion`, and features with the boolean
659    /// value set to `false` are discarded.
660    pub fn from_parts(versions: &[String], unstable_features: &BTreeMap<String, bool>) -> Self {
661        Self {
662            versions: versions.iter().flat_map(|s| s.parse::<MatrixVersion>()).collect(),
663            features: unstable_features
664                .iter()
665                .filter(|(_, enabled)| **enabled)
666                .map(|(feature, _)| feature.as_str().into())
667                .collect(),
668        }
669    }
670}
671
672/// The Matrix features supported by Ruma.
673///
674/// Features that are not behind a cargo feature are features that are part of the Matrix
675/// specification and that Ruma still supports, like the unstable version of an endpoint or a stable
676/// feature. Features behind a cargo feature are only supported when this feature is enabled.
677#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
678#[derive(Clone, StringEnum, Hash)]
679#[non_exhaustive]
680pub enum FeatureFlag {
681    /// `fi.mau.msc2246` ([MSC])
682    ///
683    /// Asynchronous media uploads.
684    ///
685    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2246
686    #[ruma_enum(rename = "fi.mau.msc2246")]
687    Msc2246,
688
689    /// `org.matrix.msc2432` ([MSC])
690    ///
691    /// Updated semantics for publishing room aliases.
692    ///
693    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2432
694    #[ruma_enum(rename = "org.matrix.msc2432")]
695    Msc2432,
696
697    /// `fi.mau.msc2659` ([MSC])
698    ///
699    /// Application service ping endpoint.
700    ///
701    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2659
702    #[ruma_enum(rename = "fi.mau.msc2659")]
703    Msc2659,
704
705    /// `fi.mau.msc2659` ([MSC])
706    ///
707    /// Stable version of the application service ping endpoint.
708    ///
709    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2659
710    #[ruma_enum(rename = "fi.mau.msc2659.stable")]
711    Msc2659Stable,
712
713    /// `uk.half-shot.msc2666.query_mutual_rooms` ([MSC])
714    ///
715    /// Get rooms in common with another user.
716    ///
717    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2666
718    #[cfg(feature = "unstable-msc2666")]
719    #[ruma_enum(rename = "uk.half-shot.msc2666.query_mutual_rooms")]
720    Msc2666,
721
722    /// `org.matrix.msc3030` ([MSC])
723    ///
724    /// Jump to date API endpoint.
725    ///
726    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/3030
727    #[ruma_enum(rename = "org.matrix.msc3030")]
728    Msc3030,
729
730    /// `org.matrix.msc3882` ([MSC])
731    ///
732    /// Allow an existing session to sign in a new session.
733    ///
734    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/3882
735    #[ruma_enum(rename = "org.matrix.msc3882")]
736    Msc3882,
737
738    /// `org.matrix.msc3916` ([MSC])
739    ///
740    /// Authentication for media.
741    ///
742    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/3916
743    #[ruma_enum(rename = "org.matrix.msc3916")]
744    Msc3916,
745
746    /// `org.matrix.msc3916.stable` ([MSC])
747    ///
748    /// Stable version of authentication for media.
749    ///
750    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/3916
751    #[ruma_enum(rename = "org.matrix.msc3916.stable")]
752    Msc3916Stable,
753
754    /// `org.matrix.msc4108` ([MSC])
755    ///
756    /// Mechanism to allow OIDC sign in and E2EE set up via QR code.
757    ///
758    /// This is for the unstable 2024 version of the [MSC].
759    ///
760    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4108
761    #[cfg(feature = "unstable-msc4108")]
762    #[ruma_enum(rename = "org.matrix.msc4108")]
763    Msc4108,
764
765    /// `org.matrix.msc4140` ([MSC])
766    ///
767    /// Delayed events.
768    ///
769    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4140
770    #[cfg(feature = "unstable-msc4140")]
771    #[ruma_enum(rename = "org.matrix.msc4140")]
772    Msc4140,
773
774    /// `org.matrix.simplified_msc3575` ([MSC])
775    ///
776    /// Simplified Sliding Sync.
777    ///
778    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4186
779    #[cfg(feature = "unstable-msc4186")]
780    #[ruma_enum(rename = "org.matrix.simplified_msc3575")]
781    Msc4186,
782
783    /// `uk.timedout.msc4323` ([MSC])
784    ///
785    /// Suspend and lock endpoints.
786    ///
787    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4323
788    #[ruma_enum(rename = "uk.timedout.msc4323")]
789    Msc4323,
790
791    /// `org.matrix.msc4380_invite_permission_config` ([MSC])
792    ///
793    /// Invite Blocking.
794    ///
795    /// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4380
796    #[ruma_enum(rename = "org.matrix.msc4380")]
797    Msc4380,
798
799    #[doc(hidden)]
800    _Custom(PrivOwnedStr),
801}