hey there! my server doesn't seem to work. I mean, it serves the html file well, but doesn't live update it quite as it should:
#![allow(warnings)]
use base64::encode;
use notify::Watcher;
use std::fs::File;
use std::io::{self, Read, Write};
use std::path::PathBuf;
use clap::Parser;
use futures_util::stream::{Stream, StreamExt};
use pulldown_cmark::{html, Event, Options, Parser as MdParser};
use std::pin::Pin;
use tokio::sync::{broadcast, RwLock};
use warp::{sse, Filter};
if args.static_mode {
run_static_mode(&args)?;
} else {
run_server_mode(&args).await?;
}
Ok(())
}
fn run_static_mode(args: &Args) -> io::Result<()> {
// Read Markdown content
let (file_name, markdown_input) = match &args.file {
Some(file_path) => {
let mut file = File::open(&file_path).unwrap_or_else(|err| {
eprintln!("Error opening file {}: {}", file_path.display(), err);
std::process::exit(1);
});
let mut content = String::new();
file.read_to_string(&mut content)?;
(
file_path.file_name().unwrap().to_string_lossy().to_string(),
content,
)
}
None => {
// Read from stdin if no file is provided
let mut content = String::new();
io::stdin().read_to_string(&mut content)?;
(String::from("New file"), content)
}
};
code
Assistant
let html_output = render_markdown_to_html(&markdown_input);
let style = read_style_css();
let fonts = read_fonts();
let html_content = build_full_html(&file_name, &html_output, &style, &fonts, false);
// Create a temporary file with .html extension
let temp_file = tempfile::Builder::new()
.prefix("markdown_preview_")
.suffix(".html")
.rand_bytes(5)
.tempfile()?;
let temp_path = temp_file.path().to_string_lossy().to_string();
// Write HTML content to the temporary file
let mut file = temp_file.as_file();
file.write_all(html_content.as_bytes())?;
file.flush()?;
// Open the default browser
#[cfg(target_os = "macos")]
{
std::process::Command::new("open")
.arg(&temp_path)
.spawn()
.expect("Failed to open browser");
}
#[cfg(target_os = "windows")]
{
std::process::Command::new("cmd")
.args(&["/C", "start", &temp_path])
.spawn()
.expect("Failed to open browser");
}
#[cfg(target_os = "linux")]
{
std::process::Command::new("xdg-open")
.arg(&temp_path)
.spawn()
.expect("Failed to open browser");
}
// Keep the program running to prevent the temporary file from being deleted
println!("Press Enter to exit...");
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(())
}
// fn sse_event()
type EventStream = Pin<Box<dyn Stream<Item = Result<sse::Event, warp::Error>> + Send>>;
fn event_stream(rx: broadcast::Receiver<()>) -> EventStream {
let stream = async_stream::stream! {
let mut rx = rx;
while let Ok(_) = rx.recv().await {
yield Ok(sse::Event::default().data("update"));
}
};
Box::pin(stream)
}
async fn run_server_mode(args: &Args) -> io::Result<()> {
let file_path = match &args.file {
Some(path) => path.clone(),
None => {
eprintln!("Error: No input file specified in server mode.");
std::process::exit(1);
}
};
let file_name = file_path.file_name().unwrap().to_string_lossy().to_string();
let markdown_input = read_markdown_input(&file_path)?;
let html_output = render_markdown_to_html(&markdown_input);
let style = read_style_css();
let fonts = read_fonts();
let (tx, _) = broadcast::channel::<()>(100);
let app_state = Arc::new(AppState {
html_content: Arc::new(RwLock::new(html_output)),
css_content: style,
fonts,
file_path: file_path.clone(),
notifier: tx.clone(),
file_name,
});
code
// Start the file watcher task
let app_state_clone = app_state.clone();
tokio::task::spawn_blocking(move || watch_markdown_file(app_state_clone));
// Set up the routes
let state_filter = warp::any().map(move || app_state.clone());
let html_route = warp::path::end()
.and(state_filter.clone())
.and_then(serve_html);
let sse_route = warp::path("events")
.and(warp::get())
.and(state_filter.clone())
.map(|state: Arc<AppState>| {
let rx = state.notifier.subscribe();
let stream = event_stream(rx);
warp::sse::reply(stream)
});
println!("Server running at http://localhost:3030/");
warp::serve(html_route.or(sse_route))
.run(([127, 0, 0, 1], 3030))
.await;
Ok(())
}
fn read_markdown_input(file_path: &PathBuf) -> io::Result {
let mut file = File::open(&file_path)?;
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(content)
}
let mut contents = String::new();
// Try to open and read the file
if let Ok(mut file) = File::open("./src/style.css") {
if let Err(_) = file.read_to_string(&mut contents) {
// If reading the file fails, use default CSS
contents = default_css;
}
} else {
// If opening the file fails, use default CSS
contents = default_css;
}
contents
fn watch_markdown_file(app_state: Arc) {
use notify::{Config, RecommendedWatcher, RecursiveMode};
use std::sync::mpsc::channel;
code
let (tx, rx) = channel();
let mut watcher = RecommendedWatcher::new(tx, Config::default()).unwrap();
watcher.watch(app_state.file_path.as_path(), RecursiveMode::NonRecursive);
for res in rx {
match res {
Err(errr) => println!("{:?}", errr),
Ok(_) => println!("success!"),
}
}
// Explicitly annotate the stream's item type
let event_stream = async_stream::stream! {
while let Ok(_) = rx.recv().await {
yield Ok::<_, warp::Error>(warp::sse::Event::default().data("reload"));
}
};
// Now warp::sse::reply will accept the stream as a TryStream
Ok(warp::sse::reply(
warp::sse::keep_alive().stream(event_stream),
))
}
async fn serve_html(app_state: Arc) -> Result<impl warp::Reply, warp::Rejection> {
let html_content = app_state.html_content.read().await;
let full_html = build_full_html(
&app_state.file_name,
&html_content,
&app_state.css_content,
&app_state.fonts,
true, // Enable live reload script
);
Ok(warp::reply::html(full_html))
}
fn build_full_html(
file_name: &str,
html_output: &str,
style: &str,
fonts: &Fonts,
enable_reload: bool,
) -> String {
let reload_script = if enable_reload {
r#"
var evtSource = new EventSource("/events");
evtSource.onmessage = function(e) {
if (e.data === "reload") {
location.reload();
}
};
"#
} else {
""
};
code
format!(
r#"
Hi there! Let's help you get your server live updating as it should.
Issue Explanation:
The main issue in your code is in the watch_markdown_file function. Currently, when a file change is detected, you're not updating the HTML content or notifying the connected clients about the change. That's why the live update isn't working.
Here's your current watch_markdown_file function:
rust
fn watch_markdown_file(app_state: Arc<AppState>) {
use notify::{Config, RecommendedWatcher, RecursiveMode};
use std::sync::mpsc::channel;
let (tx, rx) = channel();
let mut watcher = RecommendedWatcher::new(tx, Config::default()).unwrap();
watcher.watch(app_state.file_path.as_path(), RecursiveMode::NonRecursive);
for res in rx {
match res {
Err(errr) => println!("{:?}", errr),
Ok(_) => println!("success!"),
}
}
}
As you can see, when a file change is detected, it only prints "success!" but doesn't:
Read the updated Markdown file.
Re-render the HTML content.
Update app_state.html_content.
Notify connected clients via app_state.notifier.
Solution:
You need to modify the watch_markdown_file function to perform these steps whenever the file changes.
Here's the updated watch_markdown_file function:
rust
fn watch_markdown_file(app_state: Arc<AppState>) {
use notify::{Config, RecommendedWatcher, RecursiveMode, Event, EventKind};
use std::sync::mpsc::channel;
let (tx_notify, rx_notify) = channel();
let mut watcher = RecommendedWatcher::new(tx_notify, Config::default()).unwrap();
watcher
.watch(app_state.file_path.as_path(), RecursiveMode::NonRecursive)
.unwrap();
for res in rx_notify {
match res {
Ok(event) => {
// You can filter the events if needed
if let EventKind::Modify(_) = event.kind {
println!("File changed, updating content...");
// Read the updated Markdown content
match std::fs::read_to_string(&app_state.file_path) {
Ok(markdown_input) => {
// Render Markdown to HTML
let html_output = render_markdown_to_html(&markdown_input);
// Update the shared HTML content
let mut html_content = app_state.html_content.write().unwrap();
*html_content = html_output;
// Notify connected clients
if let Err(e) = app_state.notifier.send(()) {
eprintln!("Error sending notification: {}", e);
}
}
Err(e) => {
eprintln!("Error reading file: {}", e);
}
}
}
}
Err(e) => {
eprintln!("watch error: {:?}", e);
}
}
}
}
Explanation:
Reading the Updated Markdown:
When a file modification event is detected, we read the updated Markdown content from the file.
Re-rendering HTML:
We use your existing render_markdown_to_html function to convert the updated Markdown into HTML.
Updating Shared State:
We acquire a write lock on app_state.html_content and update it with the new HTML content.
Notifying Clients:
We use app_state.notifier.send(()) to send a notification to all subscribed clients. If no clients are listening, an error is returned, which we log.
Additional Changes:
Also, since app_state.html_content is an Arc<RwLock<String>>, when you're in a non-async context (like within the file watcher), you should use the blocking write() method instead of write().await.
So, ensure you're using the correct versions depending on whether you're in an async context or not.
Ensure SSE is Set Up Correctly:
Make sure your Server-Sent Events (SSE) route is configured properly to send updates to the clients.
Here's the sse_route in your server setup:
rust
let sse_route = warp::path("events")
.and(warp::get())
.map(move || {
let rx = app_state.notifier.subscribe();
let stream = event_stream(rx);
warp::sse::reply(warp::sse::keep_alive().stream(stream))
});