Add local-latest endpoint

This commit is contained in:
Austen Adler 2023-10-06 20:58:08 -04:00
parent ccc1a9556c
commit c546432de4
3 changed files with 51 additions and 14 deletions

View File

@ -15,6 +15,6 @@ serde_json = "1.0.107"
tokio = { version = "1.32.0", features = ["net", "rt", "macros", "rt-multi-thread", "process", "io-util"] } tokio = { version = "1.32.0", features = ["net", "rt", "macros", "rt-multi-thread", "process", "io-util"] }
tower = "0.4.13" tower = "0.4.13"
# Use this until https://github.com/tokio-rs/axum/issues/1731 works # Use this until https://github.com/tokio-rs/axum/issues/1731 works
tower-http = { git = "https://github.com/austenadler/tower-http", branch = "serve-dir-mount-point", features = ["fs", "tracing", "trace"] } tower-http = { git = "https://github.com/austenadler/tower-http", branch = "serve-dir-mount-point", features = ["fs", "tracing", "trace", "normalize-path"] }
tracing = "0.1.37" tracing = "0.1.37"
tracing-subscriber = "0.3.17" tracing-subscriber = "0.3.17"

View File

@ -37,10 +37,10 @@
<body> <body>
<div id="links"> <div id="links">
<a href="global/std/" id="std-docs" target="main" onclick="focusFrame()">STD</a> <a href="global/std/" id="std-docs" target="main" onclick="focusFrame()">STD</a>
<a href="local/" id="local-docs" target="main" onclick="focusFrame()">Cargo</a> <a href="local-latest" id="local-docs" target="main" onclick="focusFrame()">Cargo</a>
</div> </div>
<iframe name="main" id="main" src="local/"></iframe> <iframe name="main" id="main" src="local-latest"></iframe>
</body> </body>
<script type="text/javascript"> <script type="text/javascript">

View File

@ -3,11 +3,13 @@
use anyhow::bail; use anyhow::bail;
use anyhow::Context; use anyhow::Context;
use anyhow::Result; use anyhow::Result;
use axum::extract::State;
use axum::http::header::CONTENT_SECURITY_POLICY; use axum::http::header::CONTENT_SECURITY_POLICY;
use axum::http::header::X_FRAME_OPTIONS; use axum::http::header::X_FRAME_OPTIONS;
use axum::http::HeaderMap; use axum::http::HeaderMap;
use axum::http::Uri; use axum::http::Uri;
use axum::response::Html; use axum::response::Html;
use axum::response::IntoResponse;
use axum::response::Redirect; use axum::response::Redirect;
use axum::routing::get; use axum::routing::get;
use clap::Parser; use clap::Parser;
@ -18,11 +20,13 @@ use std::ffi::OsString;
use std::os::unix::prelude::OsStringExt; use std::os::unix::prelude::OsStringExt;
use std::path::PathBuf; use std::path::PathBuf;
use std::process::Stdio; use std::process::Stdio;
use std::sync::Arc;
use std::{net::SocketAddr, str::FromStr}; use std::{net::SocketAddr, str::FromStr};
use tokio::io::AsyncBufReadExt; use tokio::io::AsyncBufReadExt;
use tokio::io::BufReader; use tokio::io::BufReader;
use tokio::process::Command; use tokio::process::Command;
use tokio::task::JoinHandle; use tokio::task::JoinHandle;
use tower_http::normalize_path::NormalizePathLayer;
use tower_http::trace::DefaultOnResponse; use tower_http::trace::DefaultOnResponse;
use tower_http::trace::TraceLayer; use tower_http::trace::TraceLayer;
use tracing::Level; use tracing::Level;
@ -48,29 +52,39 @@ async fn main() -> Result<()> {
let std_docs_path = get_std_docs_path().await?; let std_docs_path = get_std_docs_path().await?;
info!("Found: {std_docs_path:?}"); info!("Found: {std_docs_path:?}");
info!("Building docs..."); info!("Building docs...");
let build_docs_path = build_docs().await?; let LocalDocsPath {
info!("Done: {build_docs_path:?}"); root_path,
latest_built_crate_name,
} = build_docs().await?;
info!("Done: {root_path:?}");
start_http(std_docs_path, build_docs_path).await
}
async fn start_http(std_docs_path: PathBuf, build_docs_path: PathBuf) -> Result<()> {
let app = Router::new() let app = Router::new()
.route("/", get(get_index)) .route("/", get(get_index))
.route(
"/local-latest",
get(
move |State(latest_built_crate_redirect): State<Arc<String>>| async move {
Redirect::temporary(&latest_built_crate_redirect).into_response()
},
),
)
.layer(NormalizePathLayer::trim_trailing_slash())
.nest_service( .nest_service(
"/global/", "/global/",
ServeDir::new(std_docs_path).with_mount_point("/global"), ServeDir::new(std_docs_path).with_mount_point("/global"),
) )
.nest_service( .nest_service(
"/local/", "/local/",
ServeDir::new(build_docs_path).with_mount_point("/local"), ServeDir::new(root_path).with_mount_point("/local"),
) )
.with_state(Arc::new(format!("/local/{latest_built_crate_name}/")))
.route("/global", get(add_slash)) .route("/global", get(add_slash))
.route("/local", get(add_slash)) .route("/local", get(add_slash))
.layer(TraceLayer::new_for_http().on_response(DefaultOnResponse::new().level(Level::INFO))); .layer(TraceLayer::new_for_http().on_response(DefaultOnResponse::new().level(Level::INFO)));
let addr = SocketAddr::from_str("127.0.0.1:8888").unwrap(); let addr = SocketAddr::from_str("127.0.0.1:8888").unwrap();
info!("Listening on address http://{}", addr); info!("Listening on address http://{}", addr);
axum::Server::bind(&addr) axum::Server::bind(&addr)
.serve(app.into_make_service()) .serve(app.into_make_service())
.await .await
@ -92,7 +106,7 @@ async fn get_index() -> (HeaderMap, Html<&'static [u8]>) {
(headers, Html(include_bytes!("../index.html"))) (headers, Html(include_bytes!("../index.html")))
} }
async fn build_docs() -> Result<PathBuf> { async fn build_docs() -> Result<LocalDocsPath> {
let mut child = Command::new("cargo") let mut child = Command::new("cargo")
.args(["doc", "--keep-going", "--message-format=json"]) .args(["doc", "--keep-going", "--message-format=json"])
.stdout(Stdio::piped()) .stdout(Stdio::piped())
@ -156,17 +170,40 @@ async fn build_docs() -> Result<PathBuf> {
info!("Last successful artifact: {output_path:?}"); info!("Last successful artifact: {output_path:?}");
let output_path = output_path let root_path = output_path
.parent() .parent()
.map(|p| p.parent()) .map(|p| p.parent())
.flatten() .flatten()
.context("Crate docs directory is invalid")?; .context("Crate docs directory is invalid")?;
if !output_path.is_dir() { if !root_path.is_dir() {
bail!("Crate docs directory does not exist"); bail!("Crate docs directory does not exist");
} }
Ok(output_path.to_owned()) // We can unwrap because we know this has a parent
let latest_built_crate_name = output_path
.parent()
.unwrap()
.file_name()
.context("No latest crate built")?
.to_str()
.context("Latest crate name is not utf8")?
.to_string();
if latest_built_crate_name.is_empty() {
bail!("Latest built crate name not valid (path: {output_path:?})");
}
Ok(LocalDocsPath {
root_path: root_path.to_path_buf(),
latest_built_crate_name,
})
}
#[derive(Debug)]
struct LocalDocsPath {
root_path: PathBuf,
latest_built_crate_name: String,
} }
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]