use super::*;
impl OpenApiOperation {
pub fn new<S>(summary: S) -> Self
where
S: Into<String>,
{
Self {
summary: summary.into(),
description: None,
operation_id: None,
tags: Vec::new(),
parameters: Vec::new(),
responses: BTreeMap::new(),
}
}
pub fn with_tag<S>(mut self, tag: S) -> Self
where
S: Into<String>,
{
self.get_mut_tags().push(tag.into());
self
}
pub fn with_parameter<N, L>(mut self, name: N, location: L, required: bool) -> Self
where
N: Into<String>,
L: Into<String>,
{
self.get_mut_parameters().push(OpenApiParameter {
name: name.into(),
location: location.into(),
required,
description: None,
});
self
}
pub fn with_response<D>(mut self, status: u16, description: D) -> Self
where
D: Into<String>,
{
let _: Option<OpenApiResponse> = self.get_mut_responses().insert(
status.to_string(),
OpenApiResponse {
description: description.into(),
content: BTreeMap::new(),
},
);
self
}
}
impl Default for OpenApiSpec {
fn default() -> Self {
Self::new(DEFAULT_API_TITLE, DEFAULT_API_VERSION)
}
}
impl OpenApiSpec {
pub fn new<T, V>(title: T, version: V) -> Self
where
T: Into<String>,
V: Into<String>,
{
Self {
openapi: OPENAPI_VERSION.to_owned(),
info: OpenApiInfo {
title: title.into(),
version: version.into(),
description: None,
},
servers: Vec::new(),
paths: BTreeMap::new(),
}
}
pub fn with_description<D>(mut self, description: D) -> Self
where
D: Into<String>,
{
self.get_mut_info()
.set_description(Some(description.into()));
self
}
pub fn with_server<U>(mut self, url: U) -> Self
where
U: Into<String>,
{
self.get_mut_servers().push(OpenApiServer {
url: url.into(),
description: None,
});
self
}
pub fn with_operation<P, M>(mut self, path: P, method: M, operation: OpenApiOperation) -> Self
where
P: Into<String>,
M: AsRef<str>,
{
let entry: &mut BTreeMap<String, OpenApiOperation> =
self.get_mut_paths().entry(path.into()).or_default();
let _: Option<OpenApiOperation> =
entry.insert(method.as_ref().trim().to_ascii_lowercase(), operation);
self
}
}
impl Default for OpenApiConfig {
fn default() -> Self {
Self {
spec: OpenApiSpec::default(),
spec_path: DEFAULT_SPEC_PATH.to_owned(),
docs_path: Some(DEFAULT_DOCS_PATH.to_owned()),
cache_control: DEFAULT_OPENAPI_CACHE_CONTROL.to_owned(),
}
}
}
impl OpenApiConfig {
pub fn from_spec(spec: OpenApiSpec) -> Self {
Self {
spec,
..Self::default()
}
}
pub fn with_spec_path<S>(mut self, path: S) -> Self
where
S: Into<String>,
{
self.set_spec_path(path.into());
self
}
pub fn with_docs_path(mut self, path: Option<String>) -> Self {
self.set_docs_path(path);
self
}
}
impl OpenApiPlugin {
pub fn new(config: OpenApiConfig) -> Self {
let spec_json: Vec<u8> = to_vec(config.get_spec()).unwrap_or_default();
let spec_etag: String = compute_strong_etag(&spec_json);
let mut spec_resp: Response = Response::default();
spec_resp
.set_status_code(HttpStatus::Ok.code())
.set_header(CONTENT_TYPE, CONTENT_TYPE_JSON)
.set_header(ETAG, spec_etag.clone())
.set_header(CACHE_CONTROL, config.get_cache_control())
.set_body(spec_json);
let spec_wire: Vec<u8> = spec_resp.build();
let mut not_mod_resp: Response = Response::default();
not_mod_resp
.set_status_code(HttpStatus::NotModified.code())
.set_header(ETAG, spec_etag.clone())
.set_header(CACHE_CONTROL, config.get_cache_control());
let spec_not_modified_wire: Vec<u8> = not_mod_resp.build();
let docs_html: String = render_docs_html(
config.get_spec().get_info().get_title(),
config.get_spec().get_info().get_version(),
config.get_spec_path(),
);
let mut docs_resp: Response = Response::default();
docs_resp
.set_status_code(HttpStatus::Ok.code())
.set_header(CONTENT_TYPE, CONTENT_TYPE_HTML)
.set_header(CACHE_CONTROL, config.get_cache_control())
.set_body(docs_html.into_bytes());
let docs_wire: Vec<u8> = docs_resp.build();
Self {
config,
spec_etag,
spec_wire,
spec_not_modified_wire,
docs_wire,
}
}
pub fn init(config: OpenApiConfig) -> &'static Self {
OPENAPI_PLUGIN.get_or_init(|| Self::new(config))
}
#[inline(always)]
pub fn get() -> Option<&'static Self> {
OPENAPI_PLUGIN.get()
}
#[inline(always)]
pub fn get_spec_etag(&self) -> &str {
let Self { spec_etag, .. } = self;
spec_etag.as_str()
}
#[inline(always)]
pub fn get_spec_wire(&self) -> &[u8] {
let Self { spec_wire, .. } = self;
spec_wire
}
#[inline(always)]
pub fn get_docs_wire(&self) -> &[u8] {
let Self { docs_wire, .. } = self;
docs_wire
}
}
impl ServerHook for OpenapiHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
#[inline(always)]
async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = OpenApiPlugin::get() else {
return Status::Continue;
};
let OpenApiPlugin {
config,
spec_etag,
spec_wire,
spec_not_modified_wire,
docs_wire,
..
} = plugin;
let method: &Method = ctx.get_request().get_method();
if !method.is_get() && !method.is_head() {
return Status::Continue;
}
let path: &str = ctx.get_request().get_path();
if path == config.get_spec_path().as_str() {
let wire: &[u8] = if ctx.get_request().matches_if_none_match(spec_etag) {
spec_not_modified_wire
} else {
spec_wire
};
let _: Result<(), ResponseError> = stream.try_send(wire).await;
return Status::Reject;
}
if let Some(docs_path) = config.try_get_docs_path()
&& path == docs_path.as_str()
{
let _: Result<(), ResponseError> = stream.try_send(docs_wire).await;
return Status::Reject;
}
Status::Continue
}
}