hyperlane_plugin_problem_details/impl.rs
1use super::*;
2
3/// Construction, fluent builders, and response application for [`ProblemDetails`].
4impl ProblemDetails {
5 /// Creates a new [`ProblemDetails`] with `status` and its standard HTTP title.
6 ///
7 /// # Arguments
8 ///
9 /// - `HttpStatus` - HTTP error status.
10 ///
11 /// # Returns
12 ///
13 /// - `Self` - Constructed Problem Details object.
14 pub fn from_status(status: HttpStatus) -> Self {
15 let code: usize = status.code();
16 Self {
17 problem_type: ABOUT_BLANK_TYPE.to_owned(),
18 title: default_title_for_status(code).to_owned(),
19 status: code,
20 detail: None,
21 instance: None,
22 extensions: BTreeMap::new(),
23 }
24 }
25
26 /// Creates a new [`ProblemDetails`] with explicit numeric status code and `title`.
27 ///
28 /// # Arguments
29 ///
30 /// - `usize` - HTTP status code.
31 /// - `T` - Human-readable title.
32 ///
33 /// # Returns
34 ///
35 /// - `Self` - Constructed Problem Details object.
36 pub fn new<T>(status: usize, title: T) -> Self
37 where
38 T: Into<String>,
39 {
40 Self {
41 problem_type: ABOUT_BLANK_TYPE.to_owned(),
42 title: title.into(),
43 status,
44 detail: None,
45 instance: None,
46 extensions: BTreeMap::new(),
47 }
48 }
49
50 /// Sets the RFC 9457 `type` URI reference.
51 ///
52 /// # Arguments
53 ///
54 /// - `S` - Problem type URI.
55 ///
56 /// # Returns
57 ///
58 /// - `Self` - Updated Problem Details.
59 pub fn with_type<S>(mut self, problem_type: S) -> Self
60 where
61 S: Into<String>,
62 {
63 self.set_problem_type(problem_type.into());
64 self
65 }
66
67 /// Sets the `detail` explanation string.
68 ///
69 /// # Arguments
70 ///
71 /// - `S` - Detailed explanation for this error occurrence.
72 ///
73 /// # Returns
74 ///
75 /// - `Self` - Updated Problem Details.
76 pub fn with_detail<S>(mut self, detail: S) -> Self
77 where
78 S: Into<String>,
79 {
80 self.set_detail(Some(detail.into()));
81 self
82 }
83
84 /// Sets the `instance` URI reference.
85 ///
86 /// # Arguments
87 ///
88 /// - `S` - Instance URI (typically the request path or trace URI).
89 ///
90 /// # Returns
91 ///
92 /// - `Self` - Updated Problem Details.
93 pub fn with_instance<S>(mut self, instance: S) -> Self
94 where
95 S: Into<String>,
96 {
97 self.set_instance(Some(instance.into()));
98 self
99 }
100
101 /// Attaches a custom top-level JSON extension member.
102 ///
103 /// # Arguments
104 ///
105 /// - `K` - Extension key name.
106 /// - `Value` - JSON extension value.
107 ///
108 /// # Returns
109 ///
110 /// - `Self` - Updated Problem Details.
111 pub fn with_extension<K>(mut self, key: K, value: Value) -> Self
112 where
113 K: Into<String>,
114 {
115 let _: Option<Value> = self.get_mut_extensions().insert(key.into(), value);
116 self
117 }
118
119 /// Serializes this [`ProblemDetails`] into UTF-8 JSON bytes.
120 ///
121 /// # Returns
122 ///
123 /// - `Vec<u8>` - JSON bytes.
124 pub fn to_json_bytes(&self) -> Vec<u8> {
125 to_vec(self).unwrap_or_default()
126 }
127
128 /// Writes this [`ProblemDetails`] directly into a Hyperlane [`Response`].
129 ///
130 /// # Arguments
131 ///
132 /// - `&mut Response` - Target HTTP response.
133 pub fn write_to_response(&self, response: &mut Response) {
134 response
135 .set_status_code(self.get_status())
136 .set_header(CONTENT_TYPE, PROBLEM_JSON_MEDIA_TYPE)
137 .set_body(self.to_json_bytes());
138 }
139
140 /// Writes this [`ProblemDetails`] into `ctx.get_mut_response()`, automatically filling `instance` from request path if unset.
141 ///
142 /// # Arguments
143 ///
144 /// - `&mut Context` - Active Hyperlane context.
145 pub fn apply(&self, ctx: &mut Context) {
146 let mut owned: Self = self.clone();
147 if owned.try_get_instance().is_none() {
148 owned.set_instance(Some(ctx.get_request().get_path().to_owned()));
149 }
150 owned.write_to_response(ctx.get_mut_response());
151 }
152}
153
154/// Default construction for [`ProblemDetailsConfig`].
155impl Default for ProblemDetailsConfig {
156 /// Builds a default config enabling auto-normalization, request `instance`, and `5xx` detail masking.
157 ///
158 /// # Returns
159 ///
160 /// - `Self` - Default configuration.
161 fn default() -> Self {
162 Self {
163 auto_normalize: true,
164 include_instance: true,
165 type_base_uri: None,
166 mask_server_error_details: true,
167 }
168 }
169}
170
171/// Fluent builders for [`ProblemDetailsConfig`].
172impl ProblemDetailsConfig {
173 /// Sets a base URI used to construct `<base>/<status>` problem type URIs.
174 ///
175 /// # Arguments
176 ///
177 /// - `S` - Base URI prefix.
178 ///
179 /// # Returns
180 ///
181 /// - `Self` - Updated configuration.
182 pub fn with_type_base_uri<S>(mut self, base_uri: S) -> Self
183 where
184 S: Into<String>,
185 {
186 self.set_type_base_uri(Some(base_uri.into()));
187 self
188 }
189
190 /// Configures whether raw `5xx` plain-text bodies are hidden during auto-normalization.
191 ///
192 /// # Arguments
193 ///
194 /// - `bool` - `true` to mask `5xx` details.
195 ///
196 /// # Returns
197 ///
198 /// - `Self` - Updated configuration.
199 pub fn with_mask_server_error_details(mut self, mask: bool) -> Self {
200 self.set_mask_server_error_details(mask);
201 self
202 }
203}
204
205/// Normalization engine for [`ProblemDetailsPlugin`].
206impl ProblemDetailsPlugin {
207 /// Compiles a standalone [`ProblemDetailsPlugin`] from `config`.
208 ///
209 /// # Arguments
210 ///
211 /// - `ProblemDetailsConfig` - Problem Details configuration.
212 ///
213 /// # Returns
214 ///
215 /// - `Self` - Compiled plugin.
216 pub fn new(config: ProblemDetailsConfig) -> Self {
217 let type_base_clean: Option<String> = config
218 .try_get_type_base_uri()
219 .as_ref()
220 .map(|u: &String| u.trim().trim_end_matches('/').to_owned())
221 .filter(|u: &String| !u.is_empty());
222 Self {
223 config,
224 type_base_clean,
225 }
226 }
227
228 /// Initializes the global [`ProblemDetailsPlugin`] singleton once.
229 ///
230 /// # Arguments
231 ///
232 /// - `ProblemDetailsConfig` - Configuration.
233 ///
234 /// # Returns
235 ///
236 /// - `&'static Self` - Reference to the global plugin.
237 pub fn init(config: ProblemDetailsConfig) -> &'static Self {
238 PROBLEM_DETAILS_PLUGIN.get_or_init(|| Self::new(config))
239 }
240
241 /// Returns the initialized global [`ProblemDetailsPlugin`], if configured.
242 ///
243 /// # Returns
244 ///
245 /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
246 #[inline(always)]
247 pub fn get() -> Option<&'static Self> {
248 PROBLEM_DETAILS_PLUGIN.get()
249 }
250
251 /// Normalizes a `4xx`/`5xx` response in `ctx` into `application/problem+json` if eligible.
252 ///
253 /// # Arguments
254 ///
255 /// - `&mut Context` - Active request/response context.
256 ///
257 /// # Returns
258 ///
259 /// - `bool` - `true` if the response was converted to RFC 9457 JSON.
260 #[inline]
261 pub fn normalize_context(&self, ctx: &mut Context) -> bool {
262 let Self {
263 config,
264 type_base_clean,
265 ..
266 } = self;
267 if !config.get_auto_normalize() {
268 return false;
269 }
270 let status: usize = ctx.get_response().get_status_code();
271 if status < 400 {
272 return false;
273 }
274 let existing_ct: Option<&str> = ctx
275 .get_response()
276 .get_headers()
277 .get(CONTENT_TYPE)
278 .and_then(|vals: &VecDeque<String>| vals.back().map(String::as_str));
279 if let Some(ct) = existing_ct {
280 let trimmed: &str = ct.trim();
281 if trimmed.len() >= PROBLEM_JSON_PREFIX.len()
282 && trimmed.as_bytes()[..PROBLEM_JSON_PREFIX.len()]
283 .eq_ignore_ascii_case(PROBLEM_JSON_PREFIX.as_bytes())
284 {
285 return false;
286 }
287 let is_plain: bool = trimmed.len() >= TEXT_PLAIN_PREFIX.len()
288 && trimmed.as_bytes()[..TEXT_PLAIN_PREFIX.len()]
289 .eq_ignore_ascii_case(TEXT_PLAIN_PREFIX.as_bytes());
290 if !is_plain && !ctx.get_response().get_body().is_empty() {
291 return false;
292 }
293 }
294 let problem_type: String = match type_base_clean {
295 Some(base) => format!("{base}/{status}"),
296 None => ABOUT_BLANK_TYPE.to_owned(),
297 };
298 let detail: Option<String> = if status >= 500 && config.get_mask_server_error_details() {
299 None
300 } else {
301 let body: &[u8] = ctx.get_response().get_body();
302 if body.is_empty() {
303 None
304 } else {
305 from_utf8(body)
306 .ok()
307 .map(|s: &str| s.trim().to_owned())
308 .filter(|s: &String| !s.is_empty())
309 }
310 };
311 let instance: Option<String> = if config.get_include_instance() {
312 Some(ctx.get_request().get_path().to_owned())
313 } else {
314 None
315 };
316 let problem: ProblemDetails = ProblemDetails {
317 problem_type,
318 title: default_title_for_status(status).to_owned(),
319 status,
320 detail,
321 instance,
322 extensions: BTreeMap::new(),
323 };
324 problem.write_to_response(ctx.get_mut_response());
325 true
326 }
327}
328
329/// Implements [`ServerHook`] for [`ProblemDetailsHook`].
330impl ServerHook for ProblemDetailsHook {
331 /// Constructs a per-response [`ProblemDetailsHook`].
332 ///
333 /// # Arguments
334 ///
335 /// - `&mut Stream` - Connection stream.
336 /// - `&mut Context` - Request context.
337 ///
338 /// # Returns
339 ///
340 /// - `Self` - Hook instance.
341 #[inline(always)]
342 async fn new(_: &mut Stream, _: &mut Context) -> Self {
343 Self
344 }
345
346 /// Converts bare `4xx`/`5xx` error responses into structured RFC 9457 `application/problem+json`.
347 ///
348 /// # Arguments
349 ///
350 /// - `Self` - Hook instance.
351 /// - `&mut Stream` - Connection stream.
352 /// - `&mut Context` - Request context.
353 ///
354 /// # Returns
355 ///
356 /// - `Status` - Always `Status::Continue`.
357 #[inline(always)]
358 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
359 let Some(plugin) = ProblemDetailsPlugin::get() else {
360 return Status::Continue;
361 };
362 let _: bool = plugin.normalize_context(ctx);
363 Status::Continue
364 }
365}