G: G3 Serving and CLI serve the spec behind auth and print it offline
This commit is contained in:
1 parent
7078ed15b1
commit
869b6818e9
7 files changed
+192
-12
No files matched your search
+26
-3
@@ -17,17 +17,19 @@ use std::convert::Infallible;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::rejection::QueryRejection;
|
||||
use axum::extract::Query;
|
||||
use axum::extract::{Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::sse::{Event, KeepAlive, Sse};
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use futures::Stream;
|
||||
use serde::de::DeserializeOwned;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use utoipa::openapi::OpenApi;
|
||||
|
||||
use crate::error::{error_response, AppError};
|
||||
use crate::openapi::Health;
|
||||
use crate::openapi::{self, ErrorBody, Health};
|
||||
use crate::state::AppState;
|
||||
|
||||
/// Routes under `/api/v1`, already bound to `state`.
|
||||
@@ -36,7 +38,8 @@ pub fn router(state: AppState) -> Router {
|
||||
.merge(systemd::routes())
|
||||
.merge(journal::routes())
|
||||
.merge(docker::routes())
|
||||
.merge(ping::routes());
|
||||
.merge(ping::routes())
|
||||
.route("/openapi.json", get(openapi_json));
|
||||
// Peer routes are absent entirely when the feature is off.
|
||||
let router = if state.peers.is_some() {
|
||||
router.merge(peers::routes())
|
||||
@@ -68,6 +71,26 @@ pub async fn healthz() -> Json<serde_json::Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
/// The generated description of this instance, behind the normal auth: it
|
||||
/// names every route, so it is not public like `/healthz`.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/openapi.json",
|
||||
operation_id = "get_openapi",
|
||||
tag = "meta",
|
||||
summary = "This OpenAPI document",
|
||||
description = "The description of this instance as served. Peer routes and the peer MCP \
|
||||
tools appear only when `[peers] enabled = true`; `slinuxm openapi` prints \
|
||||
the same document offline.",
|
||||
responses(
|
||||
(status = 200, body = serde_json::Value, content_type = "application/json", description = "The OpenAPI 3.1 document"),
|
||||
(status = 401, body = ErrorBody, description = "Missing or unknown bearer token"),
|
||||
)
|
||||
)]
|
||||
pub(crate) async fn openapi_json(State(st): State<AppState>) -> Json<std::sync::Arc<OpenApi>> {
|
||||
Json(openapi::document(st.peers.is_some()))
|
||||
}
|
||||
|
||||
/// Route-level 404 in the common error shape.
|
||||
pub async fn not_found() -> AppError {
|
||||
AppError::NotFound("no such route".into())
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
//! `slinuxm openapi`: print the generated REST and MCP description.
|
||||
//!
|
||||
//! Offline by construction: the document is generated from the code, so this
|
||||
//! reads no config file, no token file and no socket, and starts no server.
|
||||
//! The bytes match what `GET /api/v1/openapi.json` serves for the same mode.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
use crate::openapi;
|
||||
|
||||
/// Pretty-printed description, with a trailing newline.
|
||||
pub fn render(peers: bool) -> Result<String> {
|
||||
let json = openapi::to_pretty_json(peers).context("serializing the OpenAPI document")?;
|
||||
Ok(format!("{json}\n"))
|
||||
}
|
||||
|
||||
/// Print the description of a peer-less or a consolidator instance.
|
||||
pub fn print_openapi(peers: bool) -> Result<()> {
|
||||
print!("{}", render(peers)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::Value;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn render_is_valid_json_for_both_modes() {
|
||||
for peers in [false, true] {
|
||||
let text = render(peers).unwrap();
|
||||
assert!(text.ends_with("}\n"));
|
||||
let spec: Value = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(spec["openapi"], "3.1.0");
|
||||
assert_eq!(
|
||||
spec["paths"].get("/api/v1/peers").is_some(),
|
||||
peers,
|
||||
"peer routes follow the mode"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
pub mod api;
|
||||
pub mod auth;
|
||||
pub mod cli;
|
||||
pub mod config;
|
||||
pub mod db;
|
||||
pub mod error;
|
||||
|
||||
+18
-4
@@ -11,11 +11,11 @@ use tokio_util::sync::CancellationToken;
|
||||
|
||||
use skyg_linux_tracker::auth::tokens::{self, TokenCmd};
|
||||
use skyg_linux_tracker::config::{CliOverrides, Config};
|
||||
use skyg_linux_tracker::peers::cli::{self, PeerCmd};
|
||||
use skyg_linux_tracker::peers::cli::{self as peer_cli, PeerCmd};
|
||||
use skyg_linux_tracker::peers::registry::PeersReloader;
|
||||
use skyg_linux_tracker::peers::PeerRegistry;
|
||||
use skyg_linux_tracker::state::AppState;
|
||||
use skyg_linux_tracker::{db, server, telemetry, tls};
|
||||
use skyg_linux_tracker::{cli, db, server, telemetry, tls};
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(name = "slinuxm", version, about = "Read-only Linux system monitor")]
|
||||
@@ -71,6 +71,12 @@ enum Command {
|
||||
#[command(subcommand)]
|
||||
cmd: PeerCmd,
|
||||
},
|
||||
/// Print the generated OpenAPI description (REST and MCP) and exit.
|
||||
Openapi {
|
||||
/// Describe a consolidator: includes the peer routes and peer tools.
|
||||
#[arg(long)]
|
||||
peers: bool,
|
||||
},
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
@@ -91,9 +97,9 @@ impl Cli {
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
let config = Config::load(cli.config.as_deref(), &cli.overrides())?;
|
||||
|
||||
if cli.print_config {
|
||||
let config = Config::load(cli.config.as_deref(), &cli.overrides())?;
|
||||
print!(
|
||||
"{}",
|
||||
config.to_toml_redacted().context("serializing config")?
|
||||
@@ -101,12 +107,20 @@ async fn main() -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// The spec is generated from the code, so this runs without a config
|
||||
// file, a token file or any socket.
|
||||
if let Some(Command::Openapi { peers }) = &cli.command {
|
||||
return cli::print_openapi(*peers);
|
||||
}
|
||||
|
||||
let config = Config::load(cli.config.as_deref(), &cli.overrides())?;
|
||||
let overrides = cli.overrides();
|
||||
let config_path = cli.config.clone();
|
||||
match cli.command.unwrap_or(Command::Serve) {
|
||||
Command::Serve => serve(config, config_path, overrides).await,
|
||||
Command::Token { cmd } => tokens::run(cmd, &config).await,
|
||||
Command::Peer { cmd } => cli::run(cmd, &config).await,
|
||||
Command::Peer { cmd } => peer_cli::run(cmd, &config).await,
|
||||
Command::Openapi { peers } => cli::print_openapi(peers),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+25
-5
@@ -15,6 +15,7 @@
|
||||
//! produces, so a field cannot go missing quietly.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use schemars::generate::SchemaSettings;
|
||||
use schemars::{JsonSchema, SchemaGenerator};
|
||||
@@ -60,6 +61,7 @@ pub const BEARER_SCHEME: &str = "bearer_auth";
|
||||
crate::api::peers::list,
|
||||
crate::api::peers::one,
|
||||
crate::api::peers::pass,
|
||||
crate::api::openapi_json,
|
||||
mcp_endpoint,
|
||||
),
|
||||
components(schemas(
|
||||
@@ -81,11 +83,26 @@ pub const BEARER_SCHEME: &str = "bearer_auth";
|
||||
)]
|
||||
struct ApiDoc;
|
||||
|
||||
/// The description of one instance.
|
||||
/// The description of one instance, built once per peer mode.
|
||||
///
|
||||
/// `peers` is `state.peers.is_some()`, the flag that also decides whether the
|
||||
/// router merges the peer routes and whether MCP advertises the peer tools.
|
||||
pub fn document(peers: bool) -> OpenApi {
|
||||
/// Building it walks every DTO and the whole tool router, and the result
|
||||
/// cannot change while the process runs, so both modes are cached.
|
||||
pub fn document(peers: bool) -> Arc<OpenApi> {
|
||||
static OFF: OnceLock<Arc<OpenApi>> = OnceLock::new();
|
||||
static ON: OnceLock<Arc<OpenApi>> = OnceLock::new();
|
||||
let cache = if peers { &ON } else { &OFF };
|
||||
cache.get_or_init(|| Arc::new(build(peers))).clone()
|
||||
}
|
||||
|
||||
/// The document as JSON text, the form the committed `docs/openapi.json` and
|
||||
/// `slinuxm openapi` use.
|
||||
pub fn to_pretty_json(peers: bool) -> serde_json::Result<String> {
|
||||
serde_json::to_string_pretty(&*document(peers))
|
||||
}
|
||||
|
||||
fn build(peers: bool) -> OpenApi {
|
||||
let mut doc = ApiDoc::openapi();
|
||||
doc.info = info();
|
||||
doc.servers = Some(vec![ServerBuilder::new()
|
||||
@@ -905,10 +922,13 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_is_deterministic() {
|
||||
fn generation_is_deterministic() {
|
||||
// The committed `docs/openapi.json` is compared with this output, so
|
||||
// two builds must produce the same bytes.
|
||||
assert_eq!(
|
||||
serde_json::to_value(document(true)).unwrap(),
|
||||
serde_json::to_value(document(true)).unwrap()
|
||||
serde_json::to_value(build(true)).unwrap(),
|
||||
serde_json::to_value(build(true)).unwrap()
|
||||
);
|
||||
assert_eq!(to_pretty_json(true).unwrap(), to_pretty_json(true).unwrap());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user