1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
use http::{StatusCode, Uri};

use crate::ProblemType;

#[cfg(feature = "json")]
mod json;

#[cfg(feature = "json")]
pub use json::JsonProblemDetails;

#[cfg(feature = "xml")]
mod xml;

#[cfg(feature = "xml")]
pub use xml::XmlProblemDetails;

#[cfg(test)]
mod tests;

/// A RFC 9457 / RFC 7807 problem details object.
///
/// # Creating problem details
///
/// You can create a new problem details from a given
/// status code using [`ProblemDetails::from_status_code`].
///
/// This will set the [`status`](ProblemDetails::status) field to the given status code,
/// the [`title`](ProblemDetails::title) field to the canonical reason phrase of the status code,
/// and the [`type`](ProblemDetails::type) field to none, which is equivalent to `about:blank`.
///
/// ```rust
/// use http::StatusCode;
/// use problem_details::ProblemDetails;
///
/// let details = ProblemDetails::from_status_code(StatusCode::NOT_FOUND);
///
/// assert_eq!(details.status, Some(StatusCode::NOT_FOUND));
/// assert_eq!(details.title, Some("Not Found".to_string()));
/// assert_eq!(details.r#type.unwrap_or_default(), problem_details::ProblemType::default());
/// ```
///
/// You can then use the builder pattern to add additional fields.
///
/// ```rust
/// use http::{StatusCode, Uri};
/// use problem_details::ProblemDetails;
///
/// let details = ProblemDetails::from_status_code(StatusCode::NOT_FOUND)
///    .with_type(Uri::from_static("example:type"))
///    .with_title("There is something wrong");
///
/// assert_eq!(details.status, Some(StatusCode::NOT_FOUND));
/// assert_eq!(details.title, Some("There is something wrong".to_string()));
/// assert_eq!(details.r#type.unwrap_or_default(), Uri::from_static("example:type").into());
/// ```
///
/// You can also create a new problem details object using [`ProblemDetails::new`].
///
/// ```rust
/// use http::Uri;
/// use problem_details::ProblemDetails;
///
/// let details = ProblemDetails::new()
///   .with_type(Uri::from_static("example:type"))
///   .with_title("There is something wrong");
///
/// assert_eq!(details.status, None);
/// assert_eq!(details.title, Some("There is something wrong".to_string()));
/// assert_eq!(details.r#type.unwrap_or_default(), Uri::from_static("example:type").into());
/// ```
/// # Extensions
///
/// To add extensions, you need to define a struct that holds the extension
/// fields, and use this struct as the generic parameter for [`ProblemDetails<Ext>`].
/// Using [`with_extensions`](ProblemDetails::with_extensions), the type is adjusted
/// automatically for you.
///
/// Extension fields are flattened into the problem details object when serialized.
///
/// ```rust
/// use problem_details::ProblemDetails;
///
/// struct MyExt {
///     foo: String,
///     bar: u32,
/// }
///
/// let details = ProblemDetails::new()
///     .with_extensions(MyExt {
///         foo: "Hello".to_string(),
///         bar: 42,
///     });
///
/// // details is of type ProblemDetails<MyExt>
/// let typecheck: ProblemDetails<MyExt> = details;
/// ```
///
/// If you need dynamic extensions, you can use a [`HashMap`](std::collections::HashMap)
/// as extensions object.
///
/// ```rust
/// use std::collections::HashMap;
/// use problem_details::ProblemDetails;
///
/// let mut extensions = HashMap::<String, serde_json::Value>::new();
/// extensions.insert("foo".to_string(), serde_json::json!("Hello"));
/// extensions.insert("bar".to_string(), serde_json::json!(42));
///
/// let details = ProblemDetails::new()
///    .with_extensions(extensions);
///
/// // details is of type ProblemDetails<HashMap<String, serde_json::Value>>
/// let typecheck: ProblemDetails<HashMap<String, serde_json::Value>> = details;
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ProblemDetails<Ext = ()> {
    /// An optional uri describing the problem type.
    ///
    /// See [https://www.rfc-editor.org/rfc/rfc9457.html#name-type]() for more information.
    #[cfg_attr(feature = "serde", serde(default))]
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub r#type: Option<ProblemType>,

    /// An optional status code for this problem.
    ///
    /// See [https://www.rfc-editor.org/rfc/rfc9457.html#name-status]() for more information.
    #[cfg_attr(feature = "serde", serde(default))]
    #[cfg_attr(feature = "serde", serde(with = "crate::serde::status::opt"))]
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub status: Option<StatusCode>,

    /// An optional human-readable title for this problem.
    ///
    /// See [https://www.rfc-editor.org/rfc/rfc9457.html#name-title]() for more information.
    #[cfg_attr(feature = "serde", serde(default))]
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub title: Option<String>,

    /// An optional human-readable description of this problem.
    ///
    /// See [https://www.rfc-editor.org/rfc/rfc9457.html#name-detail]() for more information.
    #[cfg_attr(feature = "serde", serde(default))]
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub detail: Option<String>,

    /// An optional uri identifying the specific instance of this problem.
    ///
    /// See [https://www.rfc-editor.org/rfc/rfc9457.html#name-instance]() for more information.
    #[cfg_attr(feature = "serde", serde(default))]
    #[cfg_attr(feature = "serde", serde(with = "crate::serde::uri::opt"))]
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub instance: Option<Uri>,

    /// An object containing extensions to this problem details object.
    ///
    /// Note that the extensions will be flattened into the resulting problem details
    /// representation.
    ///
    /// See [https://www.rfc-editor.org/rfc/rfc9457.html#name-extension-members]() for more information.
    #[cfg_attr(feature = "serde", serde(flatten))]
    pub extensions: Ext,
}

impl ProblemDetails<()> {
    /// Creates a new empty problem details object.
    #[must_use]
    pub fn new() -> Self {
        Self {
            r#type: None,
            status: None,
            title: None,
            detail: None,
            instance: None,
            extensions: Default::default(),
        }
    }

    /// Creates a new problem details object from a given status code.
    ///
    /// This will set the `status` field to the given status code,
    /// the `title` field to the canonical reason phrase of the status code,
    /// and the `type` field to none, which is equivalent to `about:blank`.
    #[must_use]
    pub fn from_status_code(status: StatusCode) -> Self {
        Self {
            r#type: None,
            status: Some(status),
            title: status.canonical_reason().map(ToOwned::to_owned),
            detail: None,
            instance: None,
            extensions: Default::default(),
        }
    }
}

impl<Ext> ProblemDetails<Ext> {
    /// Builder-style method that sets the `type` field of this problem details object.
    #[must_use]
    pub fn with_type(mut self, r#type: impl Into<ProblemType>) -> Self {
        self.r#type = Some(r#type.into());
        self
    }

    /// Builder-style method that sets the `status` field of this problem details object.
    #[must_use]
    pub fn with_status(mut self, status: impl Into<StatusCode>) -> Self {
        self.status = Some(status.into());
        self
    }

    /// Builder-style method that sets the `title` field of this problem details object.
    #[must_use]
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Builder-style method that sets the `detail` field of this problem details object.
    #[must_use]
    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
        self.detail = Some(detail.into());
        self
    }

    /// Builder-style method that sets the `instance` field of this problem details object.
    #[must_use]
    pub fn with_instance(mut self, instance: impl Into<Uri>) -> Self {
        self.instance = Some(instance.into());
        self
    }

    /// Builder style method that sets the `extensions` field of this probelm details object.
    #[must_use]
    pub fn with_extensions<NewExt>(self, extensions: NewExt) -> ProblemDetails<NewExt> {
        ProblemDetails::<NewExt> {
            r#type: self.r#type,
            status: self.status,
            title: self.title,
            detail: self.detail,
            instance: self.instance,
            extensions,
        }
    }
}

impl<Ext> std::fmt::Display for ProblemDetails<Ext> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let default_type = ProblemType::default();
        let r#type = self.r#type.as_ref().unwrap_or(&default_type);
        write!(f, "[{type}")?;

        if let Some(status) = self.status {
            write!(f, " {}]", status.as_u16())?;
        } else {
            write!(f, "]")?;
        }

        let title = self
            .title
            .as_deref()
            .or(self.status.as_ref().and_then(StatusCode::canonical_reason));

        if let Some(title) = title {
            write!(f, " {title}")?;
        }

        if let Some(detail) = self.detail.as_ref() {
            if title.is_some() {
                write!(f, ":")?;
            }

            write!(f, " {detail}")?;
        }

        // if let Some()
        Ok(())
    }
}

impl<Ext> std::error::Error for ProblemDetails<Ext> where Ext: std::fmt::Debug {}