Skip to content

Commit

Permalink
Merge pull request #2433 from HTGAzureX1212/nightly
Browse files Browse the repository at this point in the history
Change to `GET` Method for Retrieving Uptime
  • Loading branch information
HTGAzureX1212 authored Nov 2, 2024
2 parents f2d3480 + db48fef commit e2bedc4
Show file tree
Hide file tree
Showing 17 changed files with 193 additions and 128 deletions.
80 changes: 65 additions & 15 deletions api-backend/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api-backend/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[workspace]
members = [
"hartex-backend-driver",
"hartex-backend-layers",
"hartex-backend-extractors",
"hartex-backend-models",
"hartex-backend-routes",
]
Expand Down
5 changes: 4 additions & 1 deletion api-backend/hartex-backend-driver/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,12 @@ miette = { version = "7.2.0", features = ["fancy"] }
serde = "1.0.210"
serde_json = "1.0.128"
tokio = { version = "1.40.0", features = ["full"] }
tower = "0.4.13"
tower = "0.5.1"
tower-http = { version = "0.6.1", features = ["timeout", "trace"] }
tower-service = "0.3.3"
tracing = { version = "0.1.40", features = ["log-always"] }
utoipa = "5.1.3"
utoipa-axum = "0.1.2"
utoipa-scalar = { version = "0.2.0", features = ["axum"] }

[features]
29 changes: 17 additions & 12 deletions api-backend/hartex-backend-driver/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ use std::env;
use std::future;
use std::time::Duration;

use axum::routing::post;
use axum::Router;
use bb8_postgres::bb8::Pool;
use bb8_postgres::tokio_postgres::NoTls;
use bb8_postgres::PostgresConnectionManager;
Expand All @@ -49,6 +47,11 @@ use tokio::net::TcpListener;
use tokio::signal;
use tower_http::timeout::TimeoutLayer;
use tower_http::trace::TraceLayer;
use utoipa::openapi::Info;
use utoipa_axum::router::OpenApiRouter;
use utoipa_axum::routes;
use utoipa_scalar::Scalar;
use utoipa_scalar::Servable;

/// # Entry Point
///
Expand Down Expand Up @@ -78,21 +81,23 @@ pub async fn main() -> miette::Result<()> {
let pool = Pool::builder().build(manager).await.into_diagnostic()?;

log::debug!("starting axum server");
let app = Router::new()
let (app, mut openapi) = OpenApiRouter::new()
.layer(TraceLayer::new_for_http())
.layer(TimeoutLayer::new(Duration::from_secs(30)))
.route(
"/api/:version/stats/uptime",
post(hartex_backend_routes::uptime::post_uptime)
.patch(hartex_backend_routes::uptime::patch_uptime),
)
.with_state(pool);
.routes(routes!(
hartex_backend_routes::uptime::get_uptime
))
.with_state(pool)
.split_for_parts();

let domain = env::var("API_DOMAIN").into_diagnostic()?;
let listener = TcpListener::bind(&domain).await.into_diagnostic()?;
log::debug!("listening on {domain}");
log::debug!("listening on {}", &domain);

axum::serve(listener, app)
openapi.info = Info::new("HarTex API", env!("CARGO_PKG_VERSION"));
let router = app.merge(Scalar::with_url("/openapi", openapi));

axum::serve(listener, router)
.with_graceful_shutdown(shutdown())
.await
.into_diagnostic()?;
Expand All @@ -118,7 +123,7 @@ async fn shutdown() {
.recv()
.await;
};

#[cfg(not(unix))]
let terminate = future::pending::<()>();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
[package]
name = "hartex_backend_layers"
name = "hartex_backend_extractors"
version = "0.13.0"
edition = "2021"
description = """
Backend middleware
Backend extractors
"""
license = "AGPL-3.0-or-later"
rust-version = "1.83.0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@
* with HarTex. If not, see <https://www.gnu.org/licenses/>.
*/

//! # Backend Layers
//! # Backend Extractors
//!
//! This crate defines certain middleware layers for use with the Axum HTTP server.
//! This crate defines certain extractors for use with the Axum HTTP server.

#![deny(clippy::pedantic)]
#![deny(unsafe_code)]
Expand Down
2 changes: 2 additions & 0 deletions api-backend/hartex-backend-models/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,7 @@ hartex_discord_configuration_models = { path = "../../discord-frontend/hartex-di

axum = "0.7.7"
serde = { version = "1.0.210", features = ["derive"] }
utoipa = "5.1.3"
utoipa-axum = "0.1.2"

[features]
39 changes: 0 additions & 39 deletions api-backend/hartex-backend-models/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,52 +28,13 @@
#![deny(unsafe_code)]
#![deny(warnings)]

use std::collections::HashMap;

use axum::async_trait;
use axum::extract::FromRequestParts;
use axum::extract::Path;
use axum::http::request::Parts;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::response::Response as AxumResponse;
use axum::Json;
use axum::RequestPartsExt;
use serde::Deserialize;
use serde::Serialize;

pub use hartex_discord_configuration_models as config;
pub mod uptime;

/// Specifies the API version to be used for a given API request.
#[derive(Copy, Clone, Debug)]
pub enum APIVersion {
/// Version 0.11.0 of the backend API.
V0_11_0,
}

#[async_trait]
impl<S> FromRequestParts<S> for APIVersion
where
S: Send + Sync,
{
type Rejection = AxumResponse;

async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
let parameters: Path<HashMap<String, String>> =
parts.extract().await.map_err(IntoResponse::into_response)?;

let version = parameters
.get("version")
.ok_or_else(|| (StatusCode::NOT_FOUND, "version not specified").into_response())?;

match version.as_str() {
"v0110" | "v1" => Ok(APIVersion::V0_11_0),
_ => Err((StatusCode::NOT_FOUND, "unknown version specified").into_response()),
}
}
}

/// An API response object.
///
/// This is the object returned by a certain API endpoint.
Expand Down
14 changes: 8 additions & 6 deletions api-backend/hartex-backend-models/src/uptime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,33 +26,35 @@

use serde::Deserialize;
use serde::Serialize;
use utoipa::IntoParams;
use utoipa::ToSchema;

/// An uptime query.
#[allow(clippy::module_name_repetitions)]
#[derive(Deserialize, Serialize)]
#[derive(Deserialize, IntoParams, Serialize)]
pub struct UptimeQuery {
component_name: String,
component: String,
}

impl UptimeQuery {
/// Create a new uptime query with the component name to search for.
#[must_use]
pub fn new(component_name: &str) -> Self {
pub fn new(component: &str) -> Self {
Self {
component_name: component_name.to_string(),
component: component.to_string(),
}
}

/// The component name to search for in this uptime query.
#[must_use]
pub fn component_name(&self) -> &str {
self.component_name.as_str()
self.component.as_str()
}
}

/// A response to an uptime query.
#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Deserialize, Serialize)]
#[derive(Clone, Deserialize, Serialize, ToSchema)]
pub struct UptimeResponse {
start_timestamp: u128,
}
Expand Down
1 change: 1 addition & 0 deletions api-backend/hartex-backend-routes/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ axum = { version = "0.7.7", features = ["json", "macros"] }
bb8-postgres = "0.8.1"
serde_json = "1.0.128"
time = "0.3.36"
utoipa = "5.1.3"

[features]
Loading

0 comments on commit e2bedc4

Please sign in to comment.