use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::Notify;
pub type SharedMessage = Arc<Mutex<String>>;
pub fn initial_message() -> SharedMessage {
Arc::new(Mutex::new(
"Building your app for the first time…".to_string(),
))
}
pub fn set_message(message: &SharedMessage, text: impl Into<String>) {
let mut guard = message
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
*guard = text.into();
}
pub async fn serve(
listener: TcpListener,
app_name: String,
message: SharedMessage,
stop: Arc<Notify>,
) {
let app_name = Arc::new(app_name);
loop {
tokio::select! {
() = stop.notified() => return,
accepted = listener.accept() => {
let Ok((stream, _addr)) = accepted else { continue };
let message = Arc::clone(&message);
let app_name = Arc::clone(&app_name);
tokio::spawn(async move {
let _ = respond(stream, &app_name, &message).await;
});
}
}
}
}
async fn respond(
mut stream: TcpStream,
app_name: &str,
message: &SharedMessage,
) -> std::io::Result<()> {
let mut discard = [0u8; 1024];
let _ = tokio::time::timeout(Duration::from_millis(200), stream.read(&mut discard)).await;
let text = message
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clone();
let body = render_page(app_name, &text);
let response = format!(
"HTTP/1.1 503 Service Unavailable\r\n\
Content-Type: text/html; charset=utf-8\r\n\
Content-Length: {}\r\n\
Connection: close\r\n\
\r\n\
{}",
body.len(),
body
);
stream.write_all(response.as_bytes()).await
}
const LIVE_RELOAD_SCRIPT: &str = r#"<script>
(function () {
var es = null;
function connect() {
if (es) { es.close(); }
es = new EventSource('/__larust_dev');
es.onopen = function () {
// `location.replace`, not `location.reload` - see
// `larust_view::runtime`'s own copy of this comment for why: a page
// that's the direct render of a POST would otherwise silently
// resubmit that POST on reload, landing on a bare, unstyled CSRF
// rejection with no way back. Low-risk here specifically (this
// placeholder is never itself the result of a form submission), but
// consistent with every other dev-reload script for the same reason.
location.replace(location.href);
};
es.onerror = function () {
es.close();
setTimeout(connect, 1000);
};
}
connect();
// Fallback for a backgrounded tab: browsers throttle a hidden tab's own
// `setTimeout` chain (often to once a minute or worse), so the 1s retry
// above can silently stretch out indefinitely while this tab isn't
// focused - a real build that finished during that window would only
// ever get picked up whenever the throttled timer next happens to fire,
// which can look indistinguishable from "never reloads" even though the
// mechanism above is working correctly. Forcing a fresh connection
// attempt the instant the tab regains visibility sidesteps the
// throttling entirely, the same way manually refreshing already does.
//
// Only when `es` is actually `CLOSED`, though - visibilitychange can
// fire more than once in ordinary use (alt-tabbing, a DevTools focus
// change), and forcing a reconnect while a connection is already
// `CONNECTING`/`OPEN` would tear down a perfectly healthy one for no
// reason, adding extra churn on top of whatever's already retrying.
document.addEventListener('visibilitychange', function () {
if (document.visibilityState === 'visible' && (!es || es.readyState === EventSource.CLOSED)) {
connect();
}
});
})();
</script>"#;
fn render_page(app_name: &str, message: &str) -> String {
let app_name = html_escape(app_name);
format!(
r##"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#f4513d">
{live_reload_script}
<title>{app_name} · Larust development</title>
<style>
:root {{ color-scheme: dark; font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }}
* {{ box-sizing: border-box; }}
body {{
min-height: 100vh; margin: 0; display: grid; place-items: center;
color: #f8f3eb; background: #171513;
}}
main {{ width: min(100% - 32px, 42rem); position: relative; }}
.card {{ padding: clamp(1.5rem, 6vw, 3.5rem); }}
.brand {{ display: inline-flex; align-items: center; gap: .75rem; color: #fff; font-size: 1.15rem; font-weight: 800; letter-spacing: -.04em; }}
.brand-mark {{ width: 2.5rem; height: 2.5rem; flex: none; }}
.eyebrow {{ display: flex; align-items: center; gap: .55rem; margin: 3rem 0 .85rem; color: #ff9a89; font-size: .74rem; font-weight: 800; letter-spacing: .11em; text-transform: uppercase; }}
h1 {{ margin: 0; max-width: 13ch; font-size: clamp(2.15rem, 7vw, 3.6rem); line-height: .98; letter-spacing: -.07em; }}
p {{ margin: 1rem 0 0; color: #c7bdb1; font-size: 1rem; line-height: 1.6; }}
.app-name {{ color: #fff; font-weight: 700; }}
.status {{
margin-top: 0.2rem; padding: 1rem 1.1rem; color: #f3ece2; background: #272522;
border: 1px solid #4c453d; border-radius: .8rem;
max-height: min(55vh, 28rem); overflow-y: auto;
scrollbar-color: #5c544a #272522; scrollbar-width: thin;
}}
.status-label {{ display: block; margin-top: 2rem; margin-bottom: .15rem; color: #a99d90; font-size: .7rem; font-weight: 800; letter-spacing: .1em; text-transform: uppercase; }}
pre {{ margin: 0; overflow-wrap: anywhere; white-space: pre-wrap; font: .82rem/1.55 ui-monospace, SFMono-Regular, Consolas, monospace; }}
.refresh {{ display: flex; align-items: center; gap: .55rem; margin-top: 1.3rem; color: #a99d90; font-size: .83rem; }}
.refresh svg {{ width: 1rem; height: 1rem; color: #ff735f; }}
@keyframes pulse {{ 70% {{ box-shadow: 0 0 0 .55rem transparent; }} 100% {{ box-shadow: 0 0 0 0 transparent; }} }}
@media (prefers-reduced-motion: reduce) {{ .pulse {{ animation: none; }} }}
</style>
</head>
<body>
<main>
<section class="card" aria-labelledby="status-heading">
<div class="brand" aria-label="Larust">
<svg class="brand-mark" viewBox="0 0 48 48" role="img" aria-hidden="true"><path fill="#ff735f" d="M12 0h24c6.63 0 12 5.37 12 12v24c0 6.63-5.37 12-12 12H0V12C0 5.37 5.37 0 12 0Z"/><path fill="#fff" d="M13.25 30.59a1 1 0 0 1-.76-1.64l4.7-5.59-4.69-5.42a1 1 0 1 1 1.51-1.31l5.25 6.07a1 1 0 0 1 0 1.3l-5.25 6.24a1 1 0 0 1-.76.35Z"/><path fill="#fff" d="M32.75 34.73h-12a1 1 0 1 1 0-2h12a1 1 0 1 1 0 2Z"/></svg>
<span>larust</span>
</div>
<h1 id="status-heading">Your app is on its way.</h1>
<p>We’re waiting for <span class="app-name">{app_name}</span> to finish building. This page will disappear as soon as your app is ready.</p>
<span class="status-label">Build status</span>
<div class="status"><pre>{escaped}</pre></div>
<div class="refresh"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M20 11a8.1 8.1 0 0 0-15.5-2M4 5v4h4M4 13a8.1 8.1 0 0 0 15.5 2M20 19v-4h-4"/></svg>This page will reload itself the instant your app is ready</div>
</section>
</main>
</body>
</html>"##,
escaped = html_escape(message),
live_reload_script = LIVE_RELOAD_SCRIPT,
)
}
fn html_escape(text: &str) -> String {
text.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn render_page_includes_the_given_message() {
let page = render_page("xr dev", "build failed: missing semicolon");
assert!(page.contains("build failed: missing semicolon"));
}
#[test]
fn render_page_includes_the_live_reload_script_instead_of_a_polling_meta_refresh() {
let page = render_page("xr dev", "building");
assert!(page.contains("EventSource('/__larust_dev')"));
assert!(page.contains("location.replace(location.href)"));
assert!(!page.contains("http-equiv=\"refresh\""));
}
#[test]
fn render_page_manually_retries_the_event_source_instead_of_relying_on_its_built_in_reconnect()
{
let page = render_page("xr dev", "building");
assert!(page.contains("es.onerror"));
assert!(page.contains("setTimeout(connect"));
}
#[test]
fn render_page_reconnects_immediately_when_the_tab_regains_visibility() {
let page = render_page("xr dev", "building");
assert!(page.contains("visibilitychange"));
assert!(page.contains("document.visibilityState === 'visible'"));
}
#[test]
fn render_page_includes_the_given_app_name_in_the_title_and_heading() {
let page = render_page("demo", "building");
assert!(page.contains("<title>demo · Larust development</title>"));
assert!(page.contains("waiting for <span class=\"app-name\">demo</span>"));
assert!(page.contains("<span>larust</span>"));
}
#[test]
fn render_page_escapes_html_in_the_message() {
let page = render_page("xr dev", "<script>alert(1)</script>");
assert!(!page.contains("<script>alert(1)</script>"));
assert!(page.contains("<script>alert(1)</script>"));
}
#[test]
fn render_page_makes_long_build_output_scrollable_instead_of_clipping_it() {
let page = render_page("xr dev", "a very long build failure message");
assert!(
page.contains(".status {") && page.contains("overflow-y: auto"),
"the build-status box must be independently scrollable"
);
assert!(
!page.contains("overflow: hidden"),
"the page itself must never clip overflow outright - a real build error overflowed \
this exact page before this fix, with no way to scroll to the rest of it"
);
}
#[test]
fn set_message_replaces_the_shared_text() {
let message = initial_message();
set_message(&message, "build failed: syntax error");
assert_eq!(
*message.lock().unwrap(),
"build failed: syntax error".to_string()
);
}
}