use super::*;
impl ProblemDetails {
pub fn from_status(status: HttpStatus) -> Self {
let code: usize = status.code();
Self {
problem_type: ABOUT_BLANK_TYPE.to_owned(),
title: default_title_for_status(code).to_owned(),
status: code,
detail: None,
instance: None,
extensions: BTreeMap::new(),
}
}
pub fn new<T>(status: usize, title: T) -> Self
where
T: Into<String>,
{
Self {
problem_type: ABOUT_BLANK_TYPE.to_owned(),
title: title.into(),
status,
detail: None,
instance: None,
extensions: BTreeMap::new(),
}
}
pub fn with_type<S>(mut self, problem_type: S) -> Self
where
S: Into<String>,
{
self.set_problem_type(problem_type.into());
self
}
pub fn with_detail<S>(mut self, detail: S) -> Self
where
S: Into<String>,
{
self.set_detail(Some(detail.into()));
self
}
pub fn with_instance<S>(mut self, instance: S) -> Self
where
S: Into<String>,
{
self.set_instance(Some(instance.into()));
self
}
pub fn with_extension<K>(mut self, key: K, value: Value) -> Self
where
K: Into<String>,
{
let _: Option<Value> = self.get_mut_extensions().insert(key.into(), value);
self
}
pub fn to_json_bytes(&self) -> Vec<u8> {
to_vec(self).unwrap_or_default()
}
pub fn write_to_response(&self, response: &mut Response) {
response
.set_status_code(self.get_status())
.set_header(CONTENT_TYPE, PROBLEM_JSON_MEDIA_TYPE)
.set_body(self.to_json_bytes());
}
pub fn apply(&self, ctx: &mut Context) {
let mut owned: Self = self.clone();
if owned.try_get_instance().is_none() {
owned.set_instance(Some(ctx.get_request().get_path().to_owned()));
}
owned.write_to_response(ctx.get_mut_response());
}
}
impl Default for ProblemDetailsConfig {
fn default() -> Self {
Self {
auto_normalize: true,
include_instance: true,
type_base_uri: None,
mask_server_error_details: true,
}
}
}
impl ProblemDetailsConfig {
pub fn with_type_base_uri<S>(mut self, base_uri: S) -> Self
where
S: Into<String>,
{
self.set_type_base_uri(Some(base_uri.into()));
self
}
pub fn with_mask_server_error_details(mut self, mask: bool) -> Self {
self.set_mask_server_error_details(mask);
self
}
}
impl ProblemDetailsPlugin {
pub fn new(config: ProblemDetailsConfig) -> Self {
let type_base_clean: Option<String> = config
.try_get_type_base_uri()
.as_ref()
.map(|u: &String| u.trim().trim_end_matches('/').to_owned())
.filter(|u: &String| !u.is_empty());
Self {
config,
type_base_clean,
}
}
pub fn init(config: ProblemDetailsConfig) -> &'static Self {
PROBLEM_DETAILS_PLUGIN.get_or_init(|| Self::new(config))
}
#[inline(always)]
pub fn get() -> Option<&'static Self> {
PROBLEM_DETAILS_PLUGIN.get()
}
#[inline]
pub fn normalize_context(&self, ctx: &mut Context) -> bool {
let Self {
config,
type_base_clean,
..
} = self;
if !config.get_auto_normalize() {
return false;
}
let status: usize = ctx.get_response().get_status_code();
if status < 400 {
return false;
}
let existing_ct: Option<&str> = ctx
.get_response()
.get_headers()
.get(CONTENT_TYPE)
.and_then(|vals: &VecDeque<String>| vals.back().map(String::as_str));
if let Some(ct) = existing_ct {
let trimmed: &str = ct.trim();
if trimmed.len() >= PROBLEM_JSON_PREFIX.len()
&& trimmed.as_bytes()[..PROBLEM_JSON_PREFIX.len()]
.eq_ignore_ascii_case(PROBLEM_JSON_PREFIX.as_bytes())
{
return false;
}
let is_plain: bool = trimmed.len() >= TEXT_PLAIN_PREFIX.len()
&& trimmed.as_bytes()[..TEXT_PLAIN_PREFIX.len()]
.eq_ignore_ascii_case(TEXT_PLAIN_PREFIX.as_bytes());
if !is_plain && !ctx.get_response().get_body().is_empty() {
return false;
}
}
let problem_type: String = match type_base_clean {
Some(base) => format!("{base}/{status}"),
None => ABOUT_BLANK_TYPE.to_owned(),
};
let detail: Option<String> = if status >= 500 && config.get_mask_server_error_details() {
None
} else {
let body: &[u8] = ctx.get_response().get_body();
if body.is_empty() {
None
} else {
from_utf8(body)
.ok()
.map(|s: &str| s.trim().to_owned())
.filter(|s: &String| !s.is_empty())
}
};
let instance: Option<String> = if config.get_include_instance() {
Some(ctx.get_request().get_path().to_owned())
} else {
None
};
let problem: ProblemDetails = ProblemDetails {
problem_type,
title: default_title_for_status(status).to_owned(),
status,
detail,
instance,
extensions: BTreeMap::new(),
};
problem.write_to_response(ctx.get_mut_response());
true
}
}
impl ServerHook for ProblemDetailsHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
#[inline(always)]
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = ProblemDetailsPlugin::get() else {
return Status::Continue;
};
let _: bool = plugin.normalize_context(ctx);
Status::Continue
}
}