about summary refs log tree commit diff
path: root/src/lib.rs
diff options
context:
space:
mode:
authorAlexander_Kabui <alexanderkabua@gmail.com>2026-10-03 20:25:37 +0300
committerAlexander_Kabui <alexanderkabua@gmail.com>2026-10-03 20:25:37 +0300
commitfd0d45b98ec1136aeb84fc28fa647df9023abf75 (patch)
tree05748707d319deb9668a194a90c3724a69c4f328 /src/lib.rs
parent5ecc6b70e8a6ce2ba91f7808295a7d7672481d58 (diff)
downloadgenenetwork4-fd0d45b98ec1136aeb84fc28fa647df9023abf75.tar.gz
Add foundation structure: config layering, response envelope, routes modules.
* src/config.rs: New module. Layered configuration,
  defaults -> GN4_CONF -> GN4_SECRETS -> environment, mirroring
  GeneNetwork3's SQL_URI convention so the two services can share
  configuration. Missing config files are ignored.
* src/response.rs: New module. The descriptive success envelope
  (data + next actions) from the foundation design note
  (topics/gn4/gn4-api-foundation.gmi). Not yet adopted by existing
  endpoints; that is a deliberate wire-format change to agree on
  before it ships.
* src/routes/mod.rs, species.rs, groups.rs: Move the species and
  groups handlers out of lib.rs into one module per domain, per the
  foundation structure. Handlers are pub; lib.rs just registers them.
* src/lib.rs (app): Register the moved routes. hello_world and
  version predate the domain split and stay as top-level utility
  routes.
* src/db.rs (sql_uri): Resolve through config::Config instead of
  reading the environment directly.
* src/main.rs: Bind the port from config::Config.
Diffstat (limited to 'src/lib.rs')
-rw-r--r--src/lib.rs251
1 files changed, 15 insertions, 236 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 8a9142e..39ac601 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,14 +1,15 @@
-use axum::extract::{Extension, Path, Query};
-use axum::http::StatusCode;
-use axum::{Json, Router};
-use serde::Serialize;
+use axum::Json;
+use axum::Router;
 use tower_http::request_id::{MakeRequestUuid, PropagateRequestIdLayer, RequestId, SetRequestIdLayer};
 use utoipa::OpenApi;
 use utoipa_axum::router::OpenApiRouter;
 use utoipa_axum::routes;
 
+pub mod config;
 mod db;
 mod error;
+pub mod response;
+mod routes;
 
 use error::ApiError;
 
@@ -26,17 +27,17 @@ pub fn app() -> Router {
     let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi())
         .routes(routes!(hello_world))
         .routes(routes!(version))
-        .routes(routes!(species))
-        .routes(routes!(species_by_name))
-        .routes(routes!(groups))
-        .routes(routes!(group_by_name))
-        .routes(routes!(group_strains))
+        .routes(routes!(routes::species::species))
+        .routes(routes!(routes::species::species_by_name))
+        .routes(routes!(routes::groups::groups))
+        .routes(routes!(routes::groups::group_by_name))
+        .routes(routes!(routes::groups::group_strains))
         .split_for_parts();
     router
         .route("/openapi.json", axum::routing::get(|| async { Json(api) }))
         // Assigns each request an x-request-id (if the client didn't
-        // already send one) and copies it onto the response, so it can
-        // be included in ApiError bodies (see error.rs) and correlated
+        // already send one) and copies it onto the response, so it can be
+        // included in ApiError bodies (see error.rs) and correlated
         // with logs.
         .layer(PropagateRequestIdLayer::x_request_id())
         .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid))
@@ -46,6 +47,8 @@ fn request_id_string(request_id: &RequestId) -> Option<String> {
     request_id.header_value().to_str().ok().map(str::to_string)
 }
 
+// hello_world and version predate the domain-module split and don't
+// belong to a data domain; kept here as top-level utility routes.
 #[utoipa::path(get, path = "/", responses(
     (status = 200, description = "Greeting", body = String),
     (status = 500, description = "Internal error", body = ApiError)
@@ -54,7 +57,7 @@ async fn hello_world() -> &'static str {
     "Hello, world!"
 }
 
-#[derive(Serialize, utoipa::ToSchema)]
+#[derive(serde::Serialize, utoipa::ToSchema)]
 struct VersionInfo {
     name: &'static str,
     short_name: &'static str,
@@ -78,227 +81,3 @@ async fn version() -> Json<VersionInfo> {
         git: env!("GN4_GIT_HASH"),
     })
 }
-
-#[utoipa::path(get, path = "/species", responses(
-    (status = 200, description = "All species in the database", body = Vec<db::Species>),
-    (status = 500, description = "Database error", body = ApiError)
-))]
-async fn species(Extension(request_id): Extension<RequestId>) -> Result<Json<Vec<db::Species>>, ApiError> {
-    let rid = request_id_string(&request_id);
-    // mysql's Conn is blocking; run it on a blocking thread so it doesn't
-    // stall the async runtime.
-    tokio::task::spawn_blocking(db::get_all_species)
-        .await
-        .map_err(|e| {
-            ApiError::new(
-                StatusCode::INTERNAL_SERVER_ERROR,
-                "internal_error",
-                "Internal error",
-                e.to_string(),
-                "species",
-            )
-            .with_request_id(rid.clone())
-        })?
-        .map(Json)
-        .map_err(|e| {
-            ApiError::new(
-                StatusCode::INTERNAL_SERVER_ERROR,
-                "database_error",
-                "Database error",
-                e.to_string(),
-                "species",
-            )
-            .with_request_id(rid)
-        })
-}
-
-#[utoipa::path(get, path = "/species/{species}", params(
-    ("species" = String, Path, description = "Species Name, FullName or SpeciesName")
-), responses(
-    (status = 200, description = "The matching row of the Species table", body = db::SpeciesDetail),
-    (status = 404, description = "No matching species", body = ApiError),
-    (status = 500, description = "Database error", body = ApiError)
-))]
-async fn species_by_name(
-    Extension(request_id): Extension<RequestId>,
-    Path(species): Path<String>,
-) -> Result<Json<db::SpeciesDetail>, ApiError> {
-    let rid = request_id_string(&request_id);
-    let not_found_name = species.clone();
-    tokio::task::spawn_blocking(move || db::get_species_by_name(&species))
-        .await
-        .map_err(|e| {
-            ApiError::new(
-                StatusCode::INTERNAL_SERVER_ERROR,
-                "internal_error",
-                "Internal error",
-                e.to_string(),
-                "species_by_name",
-            )
-            .with_request_id(rid.clone())
-        })?
-        .map_err(|e| {
-            ApiError::new(
-                StatusCode::INTERNAL_SERVER_ERROR,
-                "database_error",
-                "Database error",
-                e.to_string(),
-                "species_by_name",
-            )
-            .with_request_id(rid.clone())
-        })?
-        .map(Json)
-        .ok_or_else(|| {
-            ApiError::new(
-                StatusCode::NOT_FOUND,
-                "species_not_found",
-                "Species not found",
-                format!("No species matching '{not_found_name}'."),
-                "species_by_name",
-            )
-            .with_request_id(rid)
-            .with_next("/species")
-        })
-}
-
-#[utoipa::path(get, path = "/groups", responses(
-    (status = 200, description = "All groups (InbredSet rows) in the database", body = Vec<db::Group>),
-    (status = 500, description = "Database error", body = ApiError)
-))]
-async fn groups(Extension(request_id): Extension<RequestId>) -> Result<Json<Vec<db::Group>>, ApiError> {
-    let rid = request_id_string(&request_id);
-    tokio::task::spawn_blocking(db::get_all_groups)
-        .await
-        .map_err(|e| {
-            ApiError::new(
-                StatusCode::INTERNAL_SERVER_ERROR,
-                "internal_error",
-                "Internal error",
-                e.to_string(),
-                "groups",
-            )
-            .with_request_id(rid.clone())
-        })?
-        .map(Json)
-        .map_err(|e| {
-            ApiError::new(
-                StatusCode::INTERNAL_SERVER_ERROR,
-                "database_error",
-                "Database error",
-                e.to_string(),
-                "groups",
-            )
-            .with_request_id(rid)
-        })
-}
-
-#[utoipa::path(get, path = "/groups/{group}", params(
-    ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id")
-), responses(
-    (status = 200, description = "The matching row of the InbredSet table", body = db::GroupDetail),
-    (status = 404, description = "No matching group", body = ApiError),
-    (status = 500, description = "Database error", body = ApiError)
-))]
-async fn group_by_name(
-    Extension(request_id): Extension<RequestId>,
-    Path(group): Path<String>,
-) -> Result<Json<db::GroupDetail>, ApiError> {
-    let rid = request_id_string(&request_id);
-    let not_found_name = group.clone();
-    tokio::task::spawn_blocking(move || db::get_group_by_name(&group))
-        .await
-        .map_err(|e| {
-            ApiError::new(
-                StatusCode::INTERNAL_SERVER_ERROR,
-                "internal_error",
-                "Internal error",
-                e.to_string(),
-                "group_by_name",
-            )
-            .with_request_id(rid.clone())
-        })?
-        .map_err(|e| {
-            ApiError::new(
-                StatusCode::INTERNAL_SERVER_ERROR,
-                "database_error",
-                "Database error",
-                e.to_string(),
-                "group_by_name",
-            )
-            .with_request_id(rid.clone())
-        })?
-        .map(Json)
-        .ok_or_else(|| {
-            ApiError::new(
-                StatusCode::NOT_FOUND,
-                "group_not_found",
-                "Group not found",
-                format!("No group matching '{not_found_name}'."),
-                "group_by_name",
-            )
-            .with_request_id(rid)
-            .with_next("/groups")
-        })
-}
-
-#[derive(serde::Deserialize)]
-struct GroupStrainsParams {
-    used_for_mapping: Option<bool>,
-}
-
-#[utoipa::path(get, path = "/groups/{group}/strains", params(
-    ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"),
-    ("used_for_mapping" = Option<bool>, Query, description = "Only strains/samples used for mapping")
-), responses(
-    (status = 200, description = "The strains/samples belonging to the group", body = Vec<db::Strain>),
-    (status = 404, description = "No matching group", body = ApiError),
-    (status = 500, description = "Database error", body = ApiError)
-))]
-async fn group_strains(
-    Extension(request_id): Extension<RequestId>,
-    Path(group): Path<String>,
-    Query(params): Query<GroupStrainsParams>,
-) -> Result<Json<Vec<db::Strain>>, ApiError> {
-    let rid = request_id_string(&request_id);
-    let not_found_name = group.clone();
-    let used_for_mapping = params.used_for_mapping;
-    tokio::task::spawn_blocking(move || {
-        db::get_group_by_name(&group).and_then(|group| match group {
-            Some(group) => db::get_group_strains(group.id, used_for_mapping).map(Some),
-            None => Ok(None),
-        })
-    })
-    .await
-    .map_err(|e| {
-        ApiError::new(
-            StatusCode::INTERNAL_SERVER_ERROR,
-            "internal_error",
-            "Internal error",
-            e.to_string(),
-            "group_strains",
-        )
-        .with_request_id(rid.clone())
-    })?
-    .map_err(|e| {
-        ApiError::new(
-            StatusCode::INTERNAL_SERVER_ERROR,
-            "database_error",
-            "Database error",
-            e.to_string(),
-            "group_strains",
-        )
-        .with_request_id(rid.clone())
-    })?
-    .map(Json)
-    .ok_or_else(|| {
-        ApiError::new(
-            StatusCode::NOT_FOUND,
-            "group_not_found",
-            "Group not found",
-            format!("No group matching '{not_found_name}'."),
-            "group_strains",
-        )
-        .with_request_id(rid)
-        .with_next("/groups")
-    })
-}