Skip to content

Commit

Permalink
Merge branch 'main' into feat/plans-endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
Mr-Leshiy authored Nov 13, 2023
2 parents 10c1048 + b0e2c4a commit 17c6dcb
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 28 deletions.
23 changes: 20 additions & 3 deletions catalyst-gateway/bin/src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
//! CLI interpreter for the service
use std::sync::Arc;
use std::{io::Write, sync::Arc};

use clap::Parser;

use crate::{logger, service, settings::Settings, state::State};
use crate::{
logger, service,
settings::{DocsSettings, ServiceSettings},
state::State,
};

#[derive(thiserror::Error, Debug)]
/// All service errors
Expand All @@ -21,7 +25,9 @@ pub(crate) enum Error {
/// Simple service CLI options
pub(crate) enum Cli {
/// Run the service
Run(Settings),
Run(ServiceSettings),
/// Build API docs of the service in the JSON format
Docs(DocsSettings),
}

impl Cli {
Expand All @@ -46,6 +52,17 @@ impl Cli {
service::run(&settings.address, state).await?;
Ok(())
},
Self::Docs(settings) => {
let docs = service::get_app_docs();
match settings.output {
Some(path) => {
let mut docs_file = std::fs::File::create(path)?;
docs_file.write_all(docs.as_bytes())?;
},
None => println!("{docs}"),
}
Ok(())
},
}
}
}
17 changes: 8 additions & 9 deletions catalyst-gateway/bin/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,13 @@ impl From<LogLevel> for tracing::Level {
}
}

impl LogLevel {
/// Map [`LogLevel`] to [`tracing::Level`]
pub(crate) fn as_log_level(self) -> tracing::log::LevelFilter {
match self {
LogLevel::Info => tracing::log::LevelFilter::Info,
LogLevel::Debug => tracing::log::LevelFilter::Debug,
LogLevel::Warn => tracing::log::LevelFilter::Warn,
LogLevel::Error => tracing::log::LevelFilter::Error,
impl From<LogLevel> for tracing::log::LevelFilter {
fn from(val: LogLevel) -> Self {
match val {
LogLevel::Debug => Self::Debug,
LogLevel::Info => Self::Info,
LogLevel::Warn => Self::Warn,
LogLevel::Error => Self::Error,
}
}
}
Expand All @@ -63,7 +62,7 @@ pub(crate) fn init(log_level: LogLevel) -> Result<(), SetGlobalDefaultError> {
.finish();

// Logging is globally disabled by default, so globally enable it to the required level.
tracing::log::set_max_level(log_level.as_log_level());
tracing::log::set_max_level(log_level.into());

tracing::subscriber::set_global_default(subscriber)
}
17 changes: 7 additions & 10 deletions catalyst-gateway/bin/src/service/docs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,24 @@ use poem_openapi::{OpenApi, OpenApiService, Webhook};
use rust_embed::RustEmbed;

/// Create the documentation pages where the `OpenAPI` docs can be viewed.
pub(crate) fn docs<T: OpenApi + 'static, W: Webhook + 'static>(
api_service: &OpenApiService<T, W>,
) -> Route {
let spec = api_service.spec();

pub(crate) fn docs<T, W>(api_service: &OpenApiService<T, W>) -> Route
where
T: OpenApi + 'static,
W: Webhook + 'static,
{
let swagger_ui = api_service.swagger_ui();
let rapidoc_ui = api_service.rapidoc();
let redoc_ui = api_service.redoc();
let openapi_explorer = api_service.openapi_explorer();
let stoplight_ui = stoplight_elements::create_endpoint(&spec);
let stoplight_ui = stoplight_elements::create_endpoint(&api_service.spec());

Route::new()
.at("/", get(stoplight_ui))
.nest("/swagger_ui", swagger_ui)
.nest("/redoc", redoc_ui)
.nest("/rapidoc", rapidoc_ui)
.nest("/openapi_explorer", openapi_explorer)
.at(
"/cat-gateway.json",
poem::endpoint::make_sync(move |_| spec.clone()),
)
.at("/cat-gateway.json", api_service.spec_endpoint())
}

/// Embed static files.
Expand Down
2 changes: 2 additions & 0 deletions catalyst-gateway/bin/src/service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ mod common;
mod poem_service;
mod utilities;

pub(crate) use poem_service::get_app_docs;

/// Service level errors
#[derive(thiserror::Error, Debug)]
pub(crate) enum Error {
Expand Down
10 changes: 7 additions & 3 deletions catalyst-gateway/bin/src/service/poem_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ use crate::{
};

/// This exists to allow us to add extra routes to the service for testing purposes.
pub(crate) fn mk_app(
hosts: Vec<String>, base_route: Option<Route>, state: &Arc<State>,
) -> impl Endpoint {
fn mk_app(hosts: Vec<String>, base_route: Option<Route>, state: &Arc<State>) -> impl Endpoint {
// Get the base route if defined, or a new route if not.
let base_route = match base_route {
Some(route) => route,
Expand All @@ -57,6 +55,12 @@ pub(crate) fn mk_app(
.data(state.clone())
}

/// Get the API docs as a string in the JSON format.
pub(crate) fn get_app_docs() -> String {
let api_service = mk_api(vec![]);
api_service.spec()
}

/// Run the Poem Service
///
/// This provides only the primary entrypoint to the service.
Expand Down
14 changes: 11 additions & 3 deletions catalyst-gateway/bin/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
use std::{
env,
net::{IpAddr, SocketAddr},
path::PathBuf,
};

use clap::Args;
Expand Down Expand Up @@ -41,7 +42,7 @@ const API_URL_PREFIX_DEFAULT: &str = "/api";
/// the URL to the `PostgreSQL` event database,
/// and the logging level.
#[derive(Args, Clone)]
pub(crate) struct Settings {
pub(crate) struct ServiceSettings {
/// Server binding address
#[clap(long, default_value = ADDRESS_DEFAULT)]
pub(crate) address: SocketAddr,
Expand All @@ -55,6 +56,13 @@ pub(crate) struct Settings {
pub(crate) log_level: LogLevel,
}

/// Settings specifies `OpenAPI` docs generation.
#[derive(Args, Clone)]
pub(crate) struct DocsSettings {
/// The output path to the generated docs file, if omitted prints to stdout.
pub(crate) output: Option<PathBuf>,
}

/// An environment variable read as a string.
pub(crate) struct StringEnvVar(String);

Expand Down Expand Up @@ -256,10 +264,10 @@ mod tests {
// }

#[test]
fn generate_github_issue_url() {
fn generate_github_issue_url_test() {
let title = "Hello, World! How are you?";
assert_eq!(
super::generate_github_issue_url(title).unwrap().as_str(),
generate_github_issue_url(title).unwrap().as_str(),
"https://github.com/input-output-hk/catalyst-core/issues/new?template=bug_report.md&title=Hello%2C+World%21+How+are+you%3F"
);
}
Expand Down

0 comments on commit 17c6dcb

Please sign in to comment.