1use std::{
2 borrow::Cow,
3 collections::btree_map::{BTreeMap, Entry},
4 fmt,
5 time::Duration,
6};
7
8use js_int::UInt;
9use serde::{
10 de::{self, Deserialize, Deserializer, MapAccess, Visitor},
11 ser::{self, Serialize, SerializeMap, Serializer},
12};
13use serde_json::from_value as from_json_value;
14
15use super::{ErrorCode, ErrorKind, Extra, RetryAfter};
16
17enum Field<'de> {
18 ErrorCode,
19 SoftLogout,
20 RetryAfterMs,
21 RoomVersion,
22 AdminContact,
23 Status,
24 Body,
25 CurrentVersion,
26 Other(Cow<'de, str>),
27}
28
29impl<'de> Field<'de> {
30 fn new(s: Cow<'de, str>) -> Field<'de> {
31 match s.as_ref() {
32 "errcode" => Self::ErrorCode,
33 "soft_logout" => Self::SoftLogout,
34 "retry_after_ms" => Self::RetryAfterMs,
35 "room_version" => Self::RoomVersion,
36 "admin_contact" => Self::AdminContact,
37 "status" => Self::Status,
38 "body" => Self::Body,
39 "current_version" => Self::CurrentVersion,
40 _ => Self::Other(s),
41 }
42 }
43}
44
45impl<'de> Deserialize<'de> for Field<'de> {
46 fn deserialize<D>(deserializer: D) -> Result<Field<'de>, D::Error>
47 where
48 D: Deserializer<'de>,
49 {
50 struct FieldVisitor;
51
52 impl<'de> Visitor<'de> for FieldVisitor {
53 type Value = Field<'de>;
54
55 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
56 formatter.write_str("any struct field")
57 }
58
59 fn visit_str<E>(self, value: &str) -> Result<Field<'de>, E>
60 where
61 E: de::Error,
62 {
63 Ok(Field::new(Cow::Owned(value.to_owned())))
64 }
65
66 fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Field<'de>, E>
67 where
68 E: de::Error,
69 {
70 Ok(Field::new(Cow::Borrowed(value)))
71 }
72
73 fn visit_string<E>(self, value: String) -> Result<Field<'de>, E>
74 where
75 E: de::Error,
76 {
77 Ok(Field::new(Cow::Owned(value)))
78 }
79 }
80
81 deserializer.deserialize_identifier(FieldVisitor)
82 }
83}
84
85struct ErrorKindVisitor;
86
87impl<'de> Visitor<'de> for ErrorKindVisitor {
88 type Value = ErrorKind;
89
90 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
91 formatter.write_str("enum ErrorKind")
92 }
93
94 fn visit_map<V>(self, mut map: V) -> Result<ErrorKind, V::Error>
95 where
96 V: MapAccess<'de>,
97 {
98 let mut errcode = None;
99 let mut soft_logout = None;
100 let mut retry_after_ms = None;
101 let mut room_version = None;
102 let mut admin_contact = None;
103 let mut status = None;
104 let mut body = None;
105 let mut current_version = None;
106 let mut extra = BTreeMap::new();
107
108 macro_rules! set_field {
109 (errcode) => {
110 set_field!(@inner errcode)
111 };
112 ($field:ident) => {
113 match errcode {
114 Some(set_field!(@variant_containing $field)) | None => {
115 set_field!(@inner $field)
116 }
117 Some(_) => {
120 let _ = map.next_value::<de::IgnoredAny>()?;
121 },
122 }
123 };
124 (@variant_containing soft_logout) => { ErrorCode::UnknownToken };
125 (@variant_containing retry_after_ms) => { ErrorCode::LimitExceeded };
126 (@variant_containing room_version) => { ErrorCode::IncompatibleRoomVersion };
127 (@variant_containing admin_contact) => { ErrorCode::ResourceLimitExceeded };
128 (@variant_containing status) => { ErrorCode::BadStatus };
129 (@variant_containing body) => { ErrorCode::BadStatus };
130 (@variant_containing current_version) => { ErrorCode::WrongRoomKeysVersion };
131 (@inner $field:ident) => {
132 {
133 if $field.is_some() {
134 return Err(de::Error::duplicate_field(stringify!($field)));
135 }
136 $field = Some(map.next_value()?);
137 }
138 };
139 }
140
141 while let Some(key) = map.next_key()? {
142 match key {
143 Field::ErrorCode => set_field!(errcode),
144 Field::SoftLogout => set_field!(soft_logout),
145 Field::RetryAfterMs => set_field!(retry_after_ms),
146 Field::RoomVersion => set_field!(room_version),
147 Field::AdminContact => set_field!(admin_contact),
148 Field::Status => set_field!(status),
149 Field::Body => set_field!(body),
150 Field::CurrentVersion => set_field!(current_version),
151 Field::Other(other) => match extra.entry(other.into_owned()) {
152 Entry::Vacant(v) => {
153 v.insert(map.next_value()?);
154 }
155 Entry::Occupied(o) => {
156 return Err(de::Error::custom(format!("duplicate field `{}`", o.key())));
157 }
158 },
159 }
160 }
161
162 let errcode = errcode.ok_or_else(|| de::Error::missing_field("errcode"))?;
163 let extra = Extra(extra);
164
165 Ok(match errcode {
166 ErrorCode::BadAlias => ErrorKind::BadAlias,
167 ErrorCode::BadJson => ErrorKind::BadJson,
168 ErrorCode::BadState => ErrorKind::BadState,
169 ErrorCode::BadStatus => ErrorKind::BadStatus {
170 status: status
171 .map(|s| {
172 from_json_value::<u16>(s)
173 .map_err(de::Error::custom)?
174 .try_into()
175 .map_err(de::Error::custom)
176 })
177 .transpose()?,
178 body: body.map(from_json_value).transpose().map_err(de::Error::custom)?,
179 },
180 ErrorCode::CannotLeaveServerNoticeRoom => ErrorKind::CannotLeaveServerNoticeRoom,
181 ErrorCode::CannotOverwriteMedia => ErrorKind::CannotOverwriteMedia,
182 ErrorCode::CaptchaInvalid => ErrorKind::CaptchaInvalid,
183 ErrorCode::CaptchaNeeded => ErrorKind::CaptchaNeeded,
184 ErrorCode::ConnectionFailed => ErrorKind::ConnectionFailed,
185 ErrorCode::ConnectionTimeout => ErrorKind::ConnectionTimeout,
186 ErrorCode::DuplicateAnnotation => ErrorKind::DuplicateAnnotation,
187 ErrorCode::Exclusive => ErrorKind::Exclusive,
188 ErrorCode::Forbidden => ErrorKind::forbidden(),
189 ErrorCode::GuestAccessForbidden => ErrorKind::GuestAccessForbidden,
190 ErrorCode::IncompatibleRoomVersion => ErrorKind::IncompatibleRoomVersion {
191 room_version: from_json_value(
192 room_version.ok_or_else(|| de::Error::missing_field("room_version"))?,
193 )
194 .map_err(de::Error::custom)?,
195 },
196 ErrorCode::InvalidParam => ErrorKind::InvalidParam,
197 ErrorCode::InvalidRoomState => ErrorKind::InvalidRoomState,
198 ErrorCode::InvalidUsername => ErrorKind::InvalidUsername,
199 ErrorCode::LimitExceeded => ErrorKind::LimitExceeded {
200 retry_after: retry_after_ms
201 .map(from_json_value::<UInt>)
202 .transpose()
203 .map_err(de::Error::custom)?
204 .map(Into::into)
205 .map(Duration::from_millis)
206 .map(RetryAfter::Delay),
207 },
208 ErrorCode::MissingParam => ErrorKind::MissingParam,
209 ErrorCode::MissingToken => ErrorKind::MissingToken,
210 ErrorCode::NotFound => ErrorKind::NotFound,
211 ErrorCode::NotJson => ErrorKind::NotJson,
212 ErrorCode::NotYetUploaded => ErrorKind::NotYetUploaded,
213 ErrorCode::ResourceLimitExceeded => ErrorKind::ResourceLimitExceeded {
214 admin_contact: from_json_value(
215 admin_contact.ok_or_else(|| de::Error::missing_field("admin_contact"))?,
216 )
217 .map_err(de::Error::custom)?,
218 },
219 ErrorCode::RoomInUse => ErrorKind::RoomInUse,
220 ErrorCode::ServerNotTrusted => ErrorKind::ServerNotTrusted,
221 ErrorCode::ThreepidAuthFailed => ErrorKind::ThreepidAuthFailed,
222 ErrorCode::ThreepidDenied => ErrorKind::ThreepidDenied,
223 ErrorCode::ThreepidInUse => ErrorKind::ThreepidInUse,
224 ErrorCode::ThreepidMediumNotSupported => ErrorKind::ThreepidMediumNotSupported,
225 ErrorCode::ThreepidNotFound => ErrorKind::ThreepidNotFound,
226 ErrorCode::TooLarge => ErrorKind::TooLarge,
227 ErrorCode::UnableToAuthorizeJoin => ErrorKind::UnableToAuthorizeJoin,
228 ErrorCode::UnableToGrantJoin => ErrorKind::UnableToGrantJoin,
229 #[cfg(feature = "unstable-msc3843")]
230 ErrorCode::Unactionable => ErrorKind::Unactionable,
231 ErrorCode::Unauthorized => ErrorKind::Unauthorized,
232 ErrorCode::Unknown => ErrorKind::Unknown,
233 #[cfg(feature = "unstable-msc4186")]
234 ErrorCode::UnknownPos => ErrorKind::UnknownPos,
235 ErrorCode::UnknownToken => ErrorKind::UnknownToken {
236 soft_logout: soft_logout
237 .map(from_json_value)
238 .transpose()
239 .map_err(de::Error::custom)?
240 .unwrap_or_default(),
241 },
242 ErrorCode::Unrecognized => ErrorKind::Unrecognized,
243 ErrorCode::UnsupportedRoomVersion => ErrorKind::UnsupportedRoomVersion,
244 ErrorCode::UrlNotSet => ErrorKind::UrlNotSet,
245 ErrorCode::UserDeactivated => ErrorKind::UserDeactivated,
246 ErrorCode::UserInUse => ErrorKind::UserInUse,
247 ErrorCode::UserLocked => ErrorKind::UserLocked,
248 ErrorCode::UserSuspended => ErrorKind::UserSuspended,
249 ErrorCode::WeakPassword => ErrorKind::WeakPassword,
250 ErrorCode::WrongRoomKeysVersion => ErrorKind::WrongRoomKeysVersion {
251 current_version: from_json_value(
252 current_version.ok_or_else(|| de::Error::missing_field("current_version"))?,
253 )
254 .map_err(de::Error::custom)?,
255 },
256 ErrorCode::_Custom(errcode) => ErrorKind::_Custom { errcode, extra },
257 })
258 }
259}
260
261impl<'de> Deserialize<'de> for ErrorKind {
262 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
263 where
264 D: Deserializer<'de>,
265 {
266 deserializer.deserialize_map(ErrorKindVisitor)
267 }
268}
269
270impl Serialize for ErrorKind {
271 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
272 where
273 S: Serializer,
274 {
275 let mut st = serializer.serialize_map(None)?;
276 st.serialize_entry("errcode", &self.errcode())?;
277 match self {
278 Self::UnknownToken { soft_logout: true } | Self::UserLocked => {
279 st.serialize_entry("soft_logout", &true)?;
280 }
281 Self::LimitExceeded { retry_after: Some(RetryAfter::Delay(duration)) } => {
282 st.serialize_entry(
283 "retry_after_ms",
284 &UInt::try_from(duration.as_millis()).map_err(ser::Error::custom)?,
285 )?;
286 }
287 Self::IncompatibleRoomVersion { room_version } => {
288 st.serialize_entry("room_version", room_version)?;
289 }
290 Self::ResourceLimitExceeded { admin_contact } => {
291 st.serialize_entry("admin_contact", admin_contact)?;
292 }
293 Self::_Custom { extra, .. } => {
294 for (k, v) in &extra.0 {
295 st.serialize_entry(k, v)?;
296 }
297 }
298 _ => {}
299 }
300 st.end()
301 }
302}
303
304#[cfg(test)]
305mod tests {
306 use ruma_common::room_version_id;
307 use serde_json::{from_value as from_json_value, json};
308
309 use super::ErrorKind;
310
311 #[test]
312 fn deserialize_forbidden() {
313 let deserialized: ErrorKind = from_json_value(json!({ "errcode": "M_FORBIDDEN" })).unwrap();
314 assert_eq!(
315 deserialized,
316 ErrorKind::Forbidden {
317 #[cfg(feature = "unstable-msc2967")]
318 authenticate: None
319 }
320 );
321 }
322
323 #[test]
324 fn deserialize_forbidden_with_extra_fields() {
325 let deserialized: ErrorKind = from_json_value(json!({
326 "errcode": "M_FORBIDDEN",
327 "error": "…",
328 }))
329 .unwrap();
330
331 assert_eq!(
332 deserialized,
333 ErrorKind::Forbidden {
334 #[cfg(feature = "unstable-msc2967")]
335 authenticate: None
336 }
337 );
338 }
339
340 #[test]
341 fn deserialize_incompatible_room_version() {
342 let deserialized: ErrorKind = from_json_value(json!({
343 "errcode": "M_INCOMPATIBLE_ROOM_VERSION",
344 "room_version": "7",
345 }))
346 .unwrap();
347
348 assert_eq!(
349 deserialized,
350 ErrorKind::IncompatibleRoomVersion { room_version: room_version_id!("7") }
351 );
352 }
353}