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::AppserviceLoginUnsupported => ErrorKind::AppserviceLoginUnsupported,
167 ErrorCode::BadAlias => ErrorKind::BadAlias,
168 ErrorCode::BadJson => ErrorKind::BadJson,
169 ErrorCode::BadState => ErrorKind::BadState,
170 ErrorCode::BadStatus => ErrorKind::BadStatus {
171 status: status
172 .map(|s| {
173 from_json_value::<u16>(s)
174 .map_err(de::Error::custom)?
175 .try_into()
176 .map_err(de::Error::custom)
177 })
178 .transpose()?,
179 body: body.map(from_json_value).transpose().map_err(de::Error::custom)?,
180 },
181 ErrorCode::CannotLeaveServerNoticeRoom => ErrorKind::CannotLeaveServerNoticeRoom,
182 ErrorCode::CannotOverwriteMedia => ErrorKind::CannotOverwriteMedia,
183 ErrorCode::CaptchaInvalid => ErrorKind::CaptchaInvalid,
184 ErrorCode::CaptchaNeeded => ErrorKind::CaptchaNeeded,
185 #[cfg(feature = "unstable-msc4306")]
186 ErrorCode::ConflictingUnsubscription => ErrorKind::ConflictingUnsubscription,
187 ErrorCode::ConnectionFailed => ErrorKind::ConnectionFailed,
188 ErrorCode::ConnectionTimeout => ErrorKind::ConnectionTimeout,
189 ErrorCode::DuplicateAnnotation => ErrorKind::DuplicateAnnotation,
190 ErrorCode::Exclusive => ErrorKind::Exclusive,
191 ErrorCode::Forbidden => ErrorKind::forbidden(),
192 ErrorCode::GuestAccessForbidden => ErrorKind::GuestAccessForbidden,
193 ErrorCode::IncompatibleRoomVersion => ErrorKind::IncompatibleRoomVersion {
194 room_version: from_json_value(
195 room_version.ok_or_else(|| de::Error::missing_field("room_version"))?,
196 )
197 .map_err(de::Error::custom)?,
198 },
199 ErrorCode::InvalidParam => ErrorKind::InvalidParam,
200 ErrorCode::InvalidRoomState => ErrorKind::InvalidRoomState,
201 ErrorCode::InvalidUsername => ErrorKind::InvalidUsername,
202 #[cfg(feature = "unstable-msc4380")]
203 ErrorCode::InviteBlocked => ErrorKind::InviteBlocked,
204 ErrorCode::LimitExceeded => ErrorKind::LimitExceeded {
205 retry_after: retry_after_ms
206 .map(from_json_value::<UInt>)
207 .transpose()
208 .map_err(de::Error::custom)?
209 .map(Into::into)
210 .map(Duration::from_millis)
211 .map(RetryAfter::Delay),
212 },
213 ErrorCode::MissingParam => ErrorKind::MissingParam,
214 ErrorCode::MissingToken => ErrorKind::MissingToken,
215 ErrorCode::NotFound => ErrorKind::NotFound,
216 #[cfg(feature = "unstable-msc4306")]
217 ErrorCode::NotInThread => ErrorKind::NotInThread,
218 ErrorCode::NotJson => ErrorKind::NotJson,
219 ErrorCode::NotYetUploaded => ErrorKind::NotYetUploaded,
220 ErrorCode::ResourceLimitExceeded => ErrorKind::ResourceLimitExceeded {
221 admin_contact: from_json_value(
222 admin_contact.ok_or_else(|| de::Error::missing_field("admin_contact"))?,
223 )
224 .map_err(de::Error::custom)?,
225 },
226 ErrorCode::RoomInUse => ErrorKind::RoomInUse,
227 ErrorCode::ServerNotTrusted => ErrorKind::ServerNotTrusted,
228 ErrorCode::ThreepidAuthFailed => ErrorKind::ThreepidAuthFailed,
229 ErrorCode::ThreepidDenied => ErrorKind::ThreepidDenied,
230 ErrorCode::ThreepidInUse => ErrorKind::ThreepidInUse,
231 ErrorCode::ThreepidMediumNotSupported => ErrorKind::ThreepidMediumNotSupported,
232 ErrorCode::ThreepidNotFound => ErrorKind::ThreepidNotFound,
233 ErrorCode::TooLarge => ErrorKind::TooLarge,
234 ErrorCode::UnableToAuthorizeJoin => ErrorKind::UnableToAuthorizeJoin,
235 ErrorCode::UnableToGrantJoin => ErrorKind::UnableToGrantJoin,
236 #[cfg(feature = "unstable-msc3843")]
237 ErrorCode::Unactionable => ErrorKind::Unactionable,
238 ErrorCode::Unauthorized => ErrorKind::Unauthorized,
239 ErrorCode::Unknown => ErrorKind::Unknown,
240 #[cfg(feature = "unstable-msc4186")]
241 ErrorCode::UnknownPos => ErrorKind::UnknownPos,
242 ErrorCode::UnknownToken => ErrorKind::UnknownToken {
243 soft_logout: soft_logout
244 .map(from_json_value)
245 .transpose()
246 .map_err(de::Error::custom)?
247 .unwrap_or_default(),
248 },
249 ErrorCode::Unrecognized => ErrorKind::Unrecognized,
250 ErrorCode::UnsupportedRoomVersion => ErrorKind::UnsupportedRoomVersion,
251 ErrorCode::UrlNotSet => ErrorKind::UrlNotSet,
252 ErrorCode::UserDeactivated => ErrorKind::UserDeactivated,
253 ErrorCode::UserInUse => ErrorKind::UserInUse,
254 ErrorCode::UserLocked => ErrorKind::UserLocked,
255 ErrorCode::UserSuspended => ErrorKind::UserSuspended,
256 ErrorCode::WeakPassword => ErrorKind::WeakPassword,
257 ErrorCode::WrongRoomKeysVersion => ErrorKind::WrongRoomKeysVersion {
258 current_version: from_json_value(
259 current_version.ok_or_else(|| de::Error::missing_field("current_version"))?,
260 )
261 .map_err(de::Error::custom)?,
262 },
263 ErrorCode::_Custom(errcode) => ErrorKind::_Custom { errcode, extra },
264 })
265 }
266}
267
268impl<'de> Deserialize<'de> for ErrorKind {
269 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
270 where
271 D: Deserializer<'de>,
272 {
273 deserializer.deserialize_map(ErrorKindVisitor)
274 }
275}
276
277impl Serialize for ErrorKind {
278 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
279 where
280 S: Serializer,
281 {
282 let mut st = serializer.serialize_map(None)?;
283 st.serialize_entry("errcode", &self.errcode())?;
284 match self {
285 Self::UnknownToken { soft_logout: true } | Self::UserLocked => {
286 st.serialize_entry("soft_logout", &true)?;
287 }
288 Self::LimitExceeded { retry_after: Some(RetryAfter::Delay(duration)) } => {
289 st.serialize_entry(
290 "retry_after_ms",
291 &UInt::try_from(duration.as_millis()).map_err(ser::Error::custom)?,
292 )?;
293 }
294 Self::IncompatibleRoomVersion { room_version } => {
295 st.serialize_entry("room_version", room_version)?;
296 }
297 Self::ResourceLimitExceeded { admin_contact } => {
298 st.serialize_entry("admin_contact", admin_contact)?;
299 }
300 Self::_Custom { extra, .. } => {
301 for (k, v) in &extra.0 {
302 st.serialize_entry(k, v)?;
303 }
304 }
305 _ => {}
306 }
307 st.end()
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use ruma_common::room_version_id;
314 use serde_json::{from_value as from_json_value, json};
315
316 use super::ErrorKind;
317
318 #[test]
319 fn deserialize_forbidden() {
320 let deserialized: ErrorKind = from_json_value(json!({ "errcode": "M_FORBIDDEN" })).unwrap();
321 assert_eq!(
322 deserialized,
323 ErrorKind::Forbidden {
324 #[cfg(feature = "unstable-msc2967")]
325 authenticate: None
326 }
327 );
328 }
329
330 #[test]
331 fn deserialize_forbidden_with_extra_fields() {
332 let deserialized: ErrorKind = from_json_value(json!({
333 "errcode": "M_FORBIDDEN",
334 "error": "…",
335 }))
336 .unwrap();
337
338 assert_eq!(
339 deserialized,
340 ErrorKind::Forbidden {
341 #[cfg(feature = "unstable-msc2967")]
342 authenticate: None
343 }
344 );
345 }
346
347 #[test]
348 fn deserialize_incompatible_room_version() {
349 let deserialized: ErrorKind = from_json_value(json!({
350 "errcode": "M_INCOMPATIBLE_ROOM_VERSION",
351 "room_version": "7",
352 }))
353 .unwrap();
354
355 assert_eq!(
356 deserialized,
357 ErrorKind::IncompatibleRoomVersion { room_version: room_version_id!("7") }
358 );
359 }
360}