Debian Codegraph @

src/cmd/serve.rs

raw
1 use super::command_prelude::*;
2 #[cfg(feature = "watch")]
3 use super::watch;
4 use crate::{get_book_dir, open};
5 use anyhow::Result;
6 use axum::Router;
7 use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
8 use axum::routing::get;
9 use clap::builder::NonEmptyStringValueParser;
10 use futures_util::StreamExt;
11 use futures_util::sink::SinkExt;
12 use mdbook_driver::MDBook;
13 use std::net::{SocketAddr, ToSocketAddrs};
14 use std::path::PathBuf;
15 use tokio::sync::broadcast;
16 use tower_http::services::{ServeDir, ServeFile};
17 use tracing::{error, info, trace};
18
19 /// The HTTP endpoint for the websocket used to trigger reloads when a file changes.
20 const LIVE_RELOAD_ENDPOINT: &str = "__livereload";
21
22 // Create clap subcommand arguments
23 pub fn make_subcommand() -> Command {
24 Command::new("serve")
25 .about("Serves a book at http://localhost:3000, and rebuilds it on changes")
26 .arg_dest_dir()
27 .arg_root_dir()
28 .arg(
29 Arg::new("hostname")
30 .short('n')
31 .long("hostname")
32 .num_args(1)
33 .default_value("localhost")
34 .value_parser(NonEmptyStringValueParser::new())
35 .help("Hostname to listen on for HTTP connections"),
36 )
37 .arg(
38 Arg::new("port")
39 .short('p')
40 .long("port")
41 .num_args(1)
42 .default_value("3000")
43 .value_parser(NonEmptyStringValueParser::new())
44 .help("Port to use for HTTP connections"),
45 )
46 .arg_open()
47 .arg_watcher()
48 }
49
50 // Serve command implementation
51 pub fn execute(args: &ArgMatches) -> Result<()> {
52 let book_dir = get_book_dir(args);
53 let mut book = MDBook::load(&book_dir)?;
54
55 let port = args.get_one::<String>("port").unwrap();
56 let hostname = args.get_one::<String>("hostname").unwrap();
57 let open_browser = args.get_flag("open");
58
59 let address = format!("{hostname}:{port}");
60
61 let update_config = |book: &mut MDBook| {
62 book.config
63 .set("output.html.live-reload-endpoint", LIVE_RELOAD_ENDPOINT)
64 .expect("live-reload-endpoint update failed");
65 set_dest_dir(args, book);
66 // Override site-url for local serving of the 404 file
67 book.config.set("output.html.site-url", "/").unwrap();
68 };
69 update_config(&mut book);
70 book.build()?;
71
72 let sockaddr: SocketAddr = address
73 .to_socket_addrs()?
74 .next()
75 .ok_or_else(|| anyhow::anyhow!("no address found for {}", address))?;
76 let build_dir = book.build_dir_for("html");
77 let html_config = book.config.html_config().unwrap_or_default();
78 let file_404 = html_config.get_404_output_file();
79
80 // A channel used to broadcast to any websockets to reload when a file changes.
81 let (tx, _rx) = tokio::sync::broadcast::channel::<Message>(100);
82
83 let reload_tx = tx.clone();
84 let thread_handle = std::thread::spawn(move || {
85 serve(build_dir, sockaddr, reload_tx, &file_404);
86 });
87
88 let serving_url = format!("http://{address}");
89 info!("Serving on: {}", serving_url);
90
91 if open_browser {
92 open(serving_url);
93 }
94
95 #[cfg(feature = "watch")]
96 {
97 let watcher = watch::WatcherKind::from_str(args.get_one::<String>("watcher").unwrap());
98 watch::rebuild_on_change(watcher, &book_dir, &update_config, &move || {
99 let _ = tx.send(Message::text("reload"));
100 });
101 }
102
103 let _ = thread_handle.join();
104
105 Ok(())
106 }
107
108 #[tokio::main]
109 async fn serve(
110 build_dir: PathBuf,
111 address: SocketAddr,
112 reload_tx: broadcast::Sender<Message>,
113 file_404: &str,
114 ) {
115 let reload_tx_clone = reload_tx.clone();
116
117 // WebSocket handler for live reload
118 let websocket_handler = move |ws: WebSocketUpgrade| async move {
119 let reload_tx = reload_tx_clone.clone();
120 ws.on_upgrade(move |socket| websocket_connection(socket, reload_tx))
121 };
122
123 let app = Router::new()
124 .route(&format!("/{LIVE_RELOAD_ENDPOINT}"), get(websocket_handler))
125 .fallback_service(
126 ServeDir::new(&build_dir).not_found_service(ServeFile::new(build_dir.join(file_404))),
127 );
128
129 std::panic::set_hook(Box::new(move |panic_info| {
130 // exit if serve panics
131 error!("Unable to serve: {}", panic_info);
132 std::process::exit(1);
133 }));
134
135 let listener = tokio::net::TcpListener::bind(&address)
136 .await
137 .unwrap_or_else(|e| panic!("Unable to bind to {address}: {e}"));
138
139 axum::serve(listener, app).await.unwrap();
140 }
141
142 async fn websocket_connection(ws: WebSocket, reload_tx: broadcast::Sender<Message>) {
143 let (mut user_ws_tx, _user_ws_rx) = ws.split();
144 let mut rx = reload_tx.subscribe();
145
146 trace!("websocket got connection");
147 if let Ok(m) = rx.recv().await {
148 trace!("notify of reload");
149 let _ = user_ws_tx.send(m).await;
150 }
151 }