forge
Explore
Log in

Don't you dare go Hollow

The page recovers on its own when the server restarts

Browse files at this commit

8ae072218ae482e93e056ab2fb888132dd868a43Ahmet Kaan GümüşParent: 8a4b8e7
  • feat
    • the page recovers on its own when the server restarts
Show full message
✨ feat: the page recovers on its own when the server restarts

Every page holds a stream to /-/alive. While it is down a bar says the server is
restarting and the page stays put. Soft navigations are kept and made again when the
server is back; a form post is never sent again and the bar asks for a new submit.
A full load during an outage gets an offline page from the service worker, which
reloads itself once the server answers. Every event stream sends retry: 1000, and
streams closed by a proxy's error are reopened by the page after 1, 2, then 3 s.
crates/forge-web/assets/nav.jsmodified+102 -1
@@ -357,17 +357,22 @@
357 function load(o) {357 function load(o) {
358 var mark = ++latest;358 var mark = ++latest;
359 var user = o.how !== 'live';359 var user = o.how !== 'live';
360- if (user) { userBusy += 1; }360+ if (user) { userBusy += 1; clearNote(); }
361 busyStart();361 busyStart();
362 fetch(o.target.href, o.init).then(function (r) {362 fetch(o.target.href, o.init).then(function (r) {
363+ if (RESTART.indexOf(r.status) >= 0) { return { down: true }; }
363 var final = new URL(r.url || o.target.href);364 var final = new URL(r.url || o.target.href);
364 var html = /^\s*text\/html/i.test(r.headers.get('content-type') || '');365 var html = /^\s*text\/html/i.test(r.headers.get('content-type') || '');
365 if (final.origin !== location.origin || !html) {366 if (final.origin !== location.origin || !html) {
366 return { leave: true, url: final, redirected: r.redirected };367 return { leave: true, url: final, redirected: r.redirected };
367 }368 }
368 return r.text().then(function (text) { return { html: text, url: final, status: r.status }; });369 return r.text().then(function (text) { return { html: text, url: final, status: r.status }; });
370+ }, function () {
371+ // No answer at all: the server is down.
372+ return { down: true };
369 }).then(function (res) {373 }).then(function (res) {
370 if (mark !== latest) { return; }374 if (mark !== latest) { return; }
375+ if (res.down) { if (o.how !== 'live') { outage(o); } return; }
371 if (res.leave) { leave(res, o); return; }376 if (res.leave) { leave(res, o); return; }
372 // A code view keeps its page when a live refresh fails. A 404 means its path is gone at the new ref.377 // A code view keeps its page when a live refresh fails. A 404 means its path is gone at the new ref.
373 if (o.how === 'live' && res.status >= 400 && document.querySelector('[data-live-code]')) {378 if (o.how === 'live' && res.status >= 400 && document.querySelector('[data-live-code]')) {
@@ -390,6 +395,102 @@
390 });395 });
391 }396 }
392 397
398+ // Outage. A soft request that finds the server down (no answer, or a proxy's 502, 503 or 504 while
399+ // forge restarts) never falls back to a full load. The page stays and a bar says the server is
400+ // restarting. A GET is kept and made again once the server is back. A POST is never sent again:
401+ // the form keeps its values and the bar asks the reader to submit it again.
402+ var RESTART = [502, 503, 504];
403+ var link = { down: false, pending: null, post: false };
404+ var linkBarEl = null;
405+ var alive = null; // the /-/alive stream every page holds: its open means the server is back
406+
407+ function linkText(name) {
408+ return (document.body && document.body.getAttribute('data-link-' + name)) || '';
409+ }
410+
411+ function showBar(text) {
412+ if (!linkBarEl) {
413+ linkBarEl = document.createElement('div');
414+ linkBarEl.className = 'link-bar';
415+ linkBarEl.setAttribute('role', 'status');
416+ linkBarEl.setAttribute('aria-live', 'polite');
417+ }
418+ linkBarEl.textContent = text;
419+ linkBarEl.hidden = false;
420+ // A swap replaces the body's children, so the bar is put back when it is needed again.
421+ if (!linkBarEl.isConnected && document.body) { document.body.appendChild(linkBarEl); }
422+ }
423+
424+ function hideBar() {
425+ if (linkBarEl) { linkBarEl.hidden = true; }
426+ }
427+
428+ // The "submit again" note stays until the reader acts again.
429+ function clearNote() {
430+ if (link.post && !link.down) { link.post = false; hideBar(); }
431+ }
432+
433+ function linkDown() {
434+ if (link.down) { return; }
435+ link.down = true;
436+ showBar(linkText('restarting'));
437+ }
438+
439+ function outage(o) {
440+ linkDown();
441+ if (o.post) {
442+ link.post = true;
443+ if (o.form) { queued.delete(o.form); }
444+ } else {
445+ link.pending = o;
446+ }
447+ // A stream that is still open did not notice the outage: reconnect it at once.
448+ if (alive) { alive.restart(); }
449+ }
450+
451+ function linkBack() {
452+ if (!link.down) { return; }
453+ link.down = false;
454+ var o = link.pending;
455+ link.pending = null;
456+ if (o) { hideBar(); load(o); return; }
457+ refreshLive();
458+ if (link.post) { showBar(linkText('back')); } else { hideBar(); }
459+ }
460+
461+ // One EventSource that stays open. The browser reconnects by itself, except when a proxy answers
462+ // with an error: EventSource then closes for good, so it is opened again here after 1, 2, then 3 s.
463+ // `restart()` reconnects at once.
464+ function keepOpen(url, onOpen, onError) {
465+ var es = null, delay = 1000, timer = null;
466+ function connect() {
467+ timer = null;
468+ es = new EventSource(url);
469+ es.onopen = function () { delay = 1000; onOpen(); };
470+ es.onerror = function () {
471+ onError();
472+ if (es.readyState !== EventSource.CLOSED) { return; }
473+ es.close();
474+ timer = setTimeout(connect, delay);
475+ delay = Math.min(delay + 1000, 3000);
476+ };
477+ }
478+ connect();
479+ return {
480+ restart: function () {
481+ if (timer) { clearTimeout(timer); timer = null; }
482+ if (es) { es.close(); }
483+ delay = 1000;
484+ connect();
485+ }
486+ };
487+ }
488+
489+ // Every page holds one stream to /-/alive (no data, no login). Its error means the server, or the
490+ // proxy in front of it, is down; its open means it is back.
491+ if (window.EventSource) { alive = keepOpen('/-/alive', linkBack, linkDown); }
492+ if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(function () {}); }
493+
393 // The form to send a queued change on: the form itself, or after a swap the one with the same action.494 // The form to send a queued change on: the form itself, or after a swap the one with the same action.
394 function resend(form) {495 function resend(form) {
395 var target = form;496 var target = form;
crates/forge-web/assets/offline.htmladded+21 -0
@@ -0,0 +1,21 @@
1+<!doctype html>
2+<html lang="en">
3+<head>
4+<meta charset="utf-8">
5+<meta name="viewport" content="width=device-width, initial-scale=1">
6+<meta name="referrer" content="same-origin">
7+<meta name="robots" content="noindex">
8+<title>Forge</title>
9+<link rel="stylesheet" href="/assets/main.css">
10+<script src="/assets/offline.js" defer="defer"></script>
11+</head>
12+<body>
13+<main class="link-offline" role="status" aria-live="polite">
14+<p class="link-offline-mark">Forge</p>
15+<p class="link-offline-text" lang="en">Server restarting&hellip; your page is kept</p>
16+<p class="link-offline-text" lang="tr">Sunucu yeniden başlıyor&hellip; sayfanız korunuyor</p>
17+<p class="link-offline-sub" lang="en">This page loads again by itself when the server is back.</p>
18+<p class="link-offline-sub" lang="tr">Sunucu geri gelince bu sayfa kendiliğinden yeniden yüklenir.</p>
19+</main>
20+</body>
21+</html>
crates/forge-web/assets/offline.jsadded+28 -0
@@ -0,0 +1,28 @@
1+// Offline page (served by the service worker when a page load finds the server down). Shows the
2+// line in the browser's language, then reloads once the server answers again. Nothing else runs here.
3+(function () {
4+ 'use strict';
5+ var want = /^tr\b/i.test(navigator.language || '') ? 'tr' : 'en';
6+ document.querySelectorAll('.link-offline [lang]').forEach(function (el) {
7+ if (el.getAttribute('lang') !== want) { el.hidden = true; }
8+ });
9+
10+ if (!window.EventSource) { return; }
11+ // Opens the stream again after a drop. The browser retries by itself, except when a proxy answers
12+ // with an error (EventSource then closes for good): that case is retried here, 1, 2, then 3 s.
13+ function keepOpen(url, onOpen) {
14+ var delay = 1000;
15+ function connect() {
16+ var es = new EventSource(url);
17+ es.onopen = function () { delay = 1000; onOpen(); };
18+ es.onerror = function () {
19+ if (es.readyState !== EventSource.CLOSED) { return; }
20+ es.close();
21+ setTimeout(connect, delay);
22+ delay = Math.min(delay + 1000, 3000);
23+ };
24+ }
25+ connect();
26+ }
27+ keepOpen('/-/alive', function () { location.reload(); });
28+})();
crates/forge-web/assets/sw.jsmodified+56 -5
@@ -1,13 +1,64 @@
1 // Forge service worker. Served at /sw.js, so its scope is the whole origin. It shows Web Push1 // Forge service worker. Served at /sw.js, so its scope is the whole origin. It shows Web Push
2-// notifications while no tab is open and opens the link of a clicked one. No inline code, no2+// notifications while no tab is open and opens the link of a clicked one. No inline code. The only
3-// network caching: the page is always fetched fresh.3+// thing it caches is the offline page: app pages are always fetched fresh. A full page load that
4+// finds the server down (or a proxy answering 502, 503 or 504 while forge restarts) gets that page
5+// instead of the browser's error page. Everything else passes straight through to the network.
4 6
5-self.addEventListener('install', function () {7+// Bump the version when the offline page changes, so the new one is precached on install.
6- self.skipWaiting();8+var OFFLINE_CACHE = 'forge-offline-v2';
9+var OFFLINE_URL = '/assets/offline.html';
10+// The offline page and the two files it loads. They are precached: while the server is down the
11+// browser could not fetch them for the offline page otherwise.
12+var OFFLINE_FILES = [OFFLINE_URL, '/assets/offline.js', '/assets/main.css'];
13+var RESTART_STATUS = [502, 503, 504];
14+
15+self.addEventListener('install', function (event) {
16+ event.waitUntil(
17+ caches.open(OFFLINE_CACHE)
18+ .then(function (cache) { return cache.addAll(OFFLINE_FILES.map(function (u) { return new Request(u, { cache: 'reload' }); })); })
19+ .catch(function () { /* the server is down: the page is fetched again on the next install */ })
20+ .then(function () { return self.skipWaiting(); })
21+ );
7 });22 });
8 23
9 self.addEventListener('activate', function (event) {24 self.addEventListener('activate', function (event) {
10- event.waitUntil(self.clients.claim());25+ event.waitUntil((async function () {
26+ var names = await caches.keys();
27+ await Promise.all(names.filter(function (n) { return n.indexOf('forge-offline-') === 0 && n !== OFFLINE_CACHE; })
28+ .map(function (n) { return caches.delete(n); }));
29+ await self.clients.claim();
30+ })());
31+});
32+
33+// Navigations only, and only GET: the response is the network's, unless the network failed or the
34+// server is restarting. Subresources, the event stream and form posts are not touched, except the
35+// three offline-page files above (bare URLs, no query): network first, the precache when it fails.
36+self.addEventListener('fetch', function (event) {
37+ var req = event.request;
38+ var asset = new URL(req.url);
39+ if (req.method === 'GET' && req.mode !== 'navigate' && asset.origin === self.location.origin &&
40+ asset.search === '' && OFFLINE_FILES.indexOf(asset.pathname) >= 0) {
41+ event.respondWith((async function () {
42+ var res = null;
43+ try { res = await fetch(req); } catch (e) { res = null; }
44+ if (res && RESTART_STATUS.indexOf(res.status) < 0) { return res; }
45+ var cached = await caches.match(asset.pathname);
46+ return cached || res || Response.error();
47+ })());
48+ return;
49+ }
50+ if (req.mode !== 'navigate' || req.method !== 'GET') { return; }
51+ event.respondWith((async function () {
52+ var res = null;
53+ try {
54+ res = await fetch(req);
55+ } catch (e) {
56+ res = null;
57+ }
58+ if (res && RESTART_STATUS.indexOf(res.status) < 0) { return res; }
59+ var offline = await caches.match(OFFLINE_URL);
60+ return offline || res || Response.error();
61+ })());
11 });62 });
12 63
13 self.addEventListener('push', function (event) {64 self.addEventListener('push', function (event) {
crates/forge-web/src/i18n/link.rsadded+35 -0
@@ -0,0 +1,35 @@
1+//! Strings for the bar that shows while the server restarts. The shell puts them on `<body>` so
2+//! `nav.js` can show them without its own copy.
3+
4+use super::Lang;
5+
6+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7+pub enum K {
8+ Restarting,
9+ BackSubmit,
10+}
11+
12+/// The phrase for `key`.
13+pub fn t(lang: Lang, key: K) -> &'static str {
14+ use K::*;
15+ match (key, lang) {
16+ (Restarting, Lang::En) => "Server restarting\u{2026} your page is kept",
17+ (Restarting, Lang::Tr) => "Sunucu yeniden başlıyor\u{2026} sayfanız korunuyor",
18+ (BackSubmit, Lang::En) => "Server is back, submit again",
19+ (BackSubmit, Lang::Tr) => "Sunucu geri geldi, tekrar gönderin",
20+ }
21+}
22+
23+#[cfg(test)]
24+mod tests {
25+ use super::*;
26+
27+ #[test]
28+ fn every_string_has_no_em_dash() {
29+ for lang in [Lang::En, Lang::Tr] {
30+ for key in [K::Restarting, K::BackSubmit] {
31+ assert!(!t(lang, key).contains('\u{2014}'));
32+ }
33+ }
34+ }
35+}
crates/forge-web/src/i18n/mod.rsmodified+1 -0
@@ -27,6 +27,7 @@ pub mod code;
27 pub mod community;27 pub mod community;
28 pub mod integrations;28 pub mod integrations;
29 pub mod issues;29 pub mod issues;
30+pub mod link;
30 pub mod migrate;31 pub mod migrate;
31 pub mod misc;32 pub mod misc;
32 pub mod orgs;33 pub mod orgs;
crates/forge-web/src/pages/assets.rsmodified+100 -0
@@ -3,9 +3,14 @@
3 3
4 use std::sync::OnceLock;4 use std::sync::OnceLock;
5 5
6+use futures_util::stream;
6 use topcoat::Result;7 use topcoat::Result;
8+use topcoat::context::Cx;
9+use topcoat::router::content::sse::Event;
10+use topcoat::router::response::Response;
7 use topcoat::router::{HeaderMap, StatusCode, header, route};11 use topcoat::router::{HeaderMap, StatusCode, header, route};
8 12
13+use crate::pages::ci_runs::events_response;
9 use crate::render::highlight::highlight_css;14 use crate::render::highlight::highlight_css;
10 15
11 const CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css"));16 const CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css"));
@@ -79,6 +84,51 @@ async fn highlight_css_route() -> Result<(StatusCode, HeaderMap, &'static str)>
79 Ok((StatusCode::OK, headers, highlight_css_text()))84 Ok((StatusCode::OK, headers, highlight_css_text()))
80 }85 }
81 86
87+// The offline page (shown by the service worker when a page load finds the server down) and its
88+// script. Not hashed and not immutable: the service worker fetches them again on each update.
89+const OFFLINE_HTML: &str = include_str!("../../assets/offline.html");
90+const OFFLINE_JS: &str = include_str!("../../assets/offline.js");
91+
92+#[route(GET "/assets/offline.html")]
93+async fn offline_html() -> Result<(StatusCode, HeaderMap, &'static str)> {
94+ let mut headers = HeaderMap::new();
95+ headers.insert(
96+ header::CONTENT_TYPE,
97+ "text/html; charset=utf-8"
98+ .parse()
99+ .expect("static header value"),
100+ );
101+ headers.insert(
102+ header::CACHE_CONTROL,
103+ "no-cache".parse().expect("static header value"),
104+ );
105+ Ok((StatusCode::OK, headers, OFFLINE_HTML))
106+}
107+
108+#[route(GET "/assets/offline.js")]
109+async fn offline_js() -> Result<(StatusCode, HeaderMap, &'static str)> {
110+ let mut headers = HeaderMap::new();
111+ headers.insert(
112+ header::CONTENT_TYPE,
113+ "text/javascript; charset=utf-8"
114+ .parse()
115+ .expect("static header value"),
116+ );
117+ headers.insert(
118+ header::CACHE_CONTROL,
119+ "no-cache".parse().expect("static header value"),
120+ );
121+ Ok((StatusCode::OK, headers, OFFLINE_JS))
122+}
123+
124+/// The stream every page and the offline page watch to learn that the server is back. It carries
125+/// no data and needs no login: it sends `retry`, then holds the connection open with keep-alive
126+/// comments. A dropped connection (or a proxy's 502 while forge restarts) is what the pages watch for.
127+#[route(GET "/-/alive")]
128+async fn alive(cx: &Cx) -> Result<Response> {
129+ events_response(cx, stream::pending::<Result<Event>>())
130+}
131+
82 // Bundled fonts (style/fonts/). The version is in each file name, so the immutable cache is132 // Bundled fonts (style/fonts/). The version is in each file name, so the immutable cache is
83 // safe: a new font version gets a new URL. Licenses sit beside them under /assets/fonts/.133 // safe: a new font version gets a new URL. Licenses sit beside them under /assets/fonts/.
84 const FIGTREE_LATIN: &[u8] =134 const FIGTREE_LATIN: &[u8] =
@@ -274,6 +324,56 @@ mod tests {
274 assert!(String::from_utf8_lossy(&body).contains("__forgeSoft"));324 assert!(String::from_utf8_lossy(&body).contains("__forgeSoft"));
275 }325 }
276 326
327+ #[tokio::test]
328+ async fn alive_stream_sends_retry_first() {
329+ use http_body_util::BodyExt;
330+ let router: Router = Router::builder().discover().cookies().build();
331+ let req = Request::builder()
332+ .method("GET")
333+ .uri("/-/alive")
334+ .body(Body::empty())
335+ .unwrap();
336+ let res = router.handle(req).await;
337+ assert_eq!(res.status(), 200);
338+ assert!(
339+ res.headers()["content-type"]
340+ .to_str()
341+ .unwrap()
342+ .starts_with("text/event-stream")
343+ );
344+ let mut body = res.into_body();
345+ let frame = body.frame().await.expect("a frame").expect("no error");
346+ let data = frame.into_data().expect("data frame");
347+ assert!(
348+ String::from_utf8_lossy(&data).contains("retry: 1000"),
349+ "the first bytes set the reconnect delay"
350+ );
351+ }
352+
353+ #[tokio::test]
354+ async fn offline_page_and_script_are_served_without_caching() {
355+ let router: Router = Router::builder().discover().cookies().build();
356+ for (uri, kind) in [
357+ ("/assets/offline.html", "text/html"),
358+ ("/assets/offline.js", "text/javascript"),
359+ ] {
360+ let req = Request::builder()
361+ .method("GET")
362+ .uri(uri)
363+ .body(Body::empty())
364+ .unwrap();
365+ let res = router.handle(req).await;
366+ assert_eq!(res.status(), 200, "{uri}");
367+ assert!(
368+ res.headers()["content-type"]
369+ .to_str()
370+ .unwrap()
371+ .starts_with(kind)
372+ );
373+ assert_eq!(res.headers()["cache-control"], "no-cache", "{uri}");
374+ }
375+ }
376+
277 #[tokio::test]377 #[tokio::test]
278 async fn highlight_css_is_served_with_long_cache() {378 async fn highlight_css_is_served_with_long_cache() {
279 let router: Router = Router::builder().discover().cookies().build();379 let router: Router = Router::builder().discover().cookies().build();
crates/forge-web/src/pages/ci_runs.rsmodified+9 -4
@@ -16,7 +16,7 @@ use std::time::Duration;
16 use forge_core::ci::{CiJob, CiRun, JobState, RunState};16 use forge_core::ci::{CiJob, CiRun, JobState, RunState};
17 use forge_core::{Action, Denied, Store, User, authorize};17 use forge_core::{Action, Denied, Store, User, authorize};
18 use forge_git::browse::{RefInfo, RefKind, read_commit};18 use forge_git::browse::{RefInfo, RefKind, read_commit};
19-use futures_util::{Stream, stream};19+use futures_util::{Stream, StreamExt, stream};
20 use serde::Deserialize;20 use serde::Deserialize;
21 use time::OffsetDateTime;21 use time::OffsetDateTime;
22 use time::format_description::well_known::Rfc3339;22 use time::format_description::well_known::Rfc3339;
@@ -2023,13 +2023,18 @@ fn repo_changes(wake: watch::Receiver<u64>) -> impl Stream<Item = Result<Event>>
2023 })2023 })
2024 }2024 }
2025 2025
2026-/// The response of an event stream for a CI page: keep-alive comments while idle, and no buffering2026+/// How long the browser waits before it reconnects a dropped event stream. The browser's default is
2027-/// by a reverse proxy.2027+/// a few seconds; one second makes a page come back as soon as a server restart is done.
2028+pub(crate) const STREAM_RETRY: Duration = Duration::from_secs(1);
2029+
2030+/// The response of an event stream: keep-alive comments while idle, no buffering by a reverse
2031+/// proxy, and a `retry` field first so every stream reconnects after `STREAM_RETRY`.
2028 pub(crate) fn events_response(2032 pub(crate) fn events_response(
2029 cx: &Cx,2033 cx: &Cx,
2030 events: impl Stream<Item = Result<Event>> + Send + 'static,2034 events: impl Stream<Item = Result<Event>> + Send + 'static,
2031 ) -> Result<Response> {2035 ) -> Result<Response> {
2032- let events = Sse::new(events).keep_alive(2036+ let retry = stream::once(std::future::ready(Ok(Event::new().retry(STREAM_RETRY))));
2037+ let events = Sse::new(retry.chain(events)).keep_alive(
2033 KeepAlive::new()2038 KeepAlive::new()
2034 .interval(STREAM_KEEP_ALIVE)2039 .interval(STREAM_KEEP_ALIVE)
2035 .text("keepalive"),2040 .text("keepalive"),
crates/forge-web/src/pages/ci_tests.rsmodified+24 -2
@@ -364,7 +364,7 @@ async fn open(
364 }364 }
365 365
366 /// The next frame of an event stream, or None once the stream has ended. Fails after five seconds.366 /// The next frame of an event stream, or None once the stream has ended. Fails after five seconds.
367-async fn next_event<S, E>(frames: &mut S) -> Option<Vec<u8>>367+async fn next_frame<S, E>(frames: &mut S) -> Option<Vec<u8>>
368 where368 where
369 S: futures_util::Stream<Item = Result<bytes::Bytes, E>> + Unpin,369 S: futures_util::Stream<Item = Result<bytes::Bytes, E>> + Unpin,
370 E: std::fmt::Debug,370 E: std::fmt::Debug,
@@ -373,10 +373,29 @@ where
373 373
374 let frame = tokio::time::timeout(Duration::from_secs(5), frames.next())374 let frame = tokio::time::timeout(Duration::from_secs(5), frames.next())
375 .await375 .await
376- .expect("an event within five seconds")?;376+ .expect("a frame within five seconds")?;
377 Some(frame.expect("data").to_vec())377 Some(frame.expect("data").to_vec())
378 }378 }
379 379
380+async fn next_event<S, E>(frames: &mut S) -> Option<Vec<u8>>
381+where
382+ S: futures_util::Stream<Item = Result<bytes::Bytes, E>> + Unpin,
383+ E: std::fmt::Debug,
384+{
385+ use futures_util::StreamExt;
386+
387+ // Every stream opens with its `retry` field (one frame): skip it, the tests want the events.
388+ loop {
389+ let frame = tokio::time::timeout(Duration::from_secs(5), frames.next())
390+ .await
391+ .expect("an event within five seconds")?;
392+ let bytes = frame.expect("data").to_vec();
393+ if !bytes.starts_with(b"retry: ") {
394+ return Some(bytes);
395+ }
396+ }
397+}
398+
380 #[tokio::test]399 #[tokio::test]
381 async fn live_events_need_the_same_access_as_the_page() {400 async fn live_events_need_the_same_access_as_the_page() {
382 let dir = tempfile::tempdir().expect("tempdir");401 let dir = tempfile::tempdir().expect("tempdir");
@@ -588,6 +607,9 @@ async fn run_list_events_follow_repo_changes() {
588 .into_body()607 .into_body()
589 .into_data_stream();608 .into_data_stream();
590 609
610+ // The retry field comes first; after it nothing is sent until a change.
611+ let retry = next_frame(&mut frames).await.expect("the retry field");
612+ assert!(retry.starts_with(b"retry: "), "{retry:?}");
591 let quiet = tokio::time::timeout(Duration::from_millis(200), frames.next()).await;613 let quiet = tokio::time::timeout(Duration::from_millis(200), frames.next()).await;
592 assert!(quiet.is_err(), "nothing is sent on connect");614 assert!(quiet.is_err(), "nothing is sent on connect");
593 615
crates/forge-web/src/pages/notifications.rsmodified+8 -16
@@ -5,7 +5,6 @@
5 //! The sidebar box and the watch form are shared with the issue, pull and repo header views.5 //! The sidebar box and the watch form are shared with the issue, pull and repo header views.
6 6
7 use std::collections::HashMap;7 use std::collections::HashMap;
8-use std::time::Duration;
9 8
10 use forge_core::authz::{Action, authorize};9 use forge_core::authz::{Action, authorize};
11 use forge_core::discussions::{DiscussionNotification, DiscussionReason};10 use forge_core::discussions::{DiscussionNotification, DiscussionReason};
@@ -18,10 +17,10 @@ use serde::Deserialize;
18 use topcoat::Result;17 use topcoat::Result;
19 use topcoat::context::{Cx, app_context};18 use topcoat::context::{Cx, app_context};
20 use topcoat::router::content::Form;19 use topcoat::router::content::Form;
21-use topcoat::router::content::sse::{Event, KeepAlive, Sse};20+use topcoat::router::content::sse::Event;
22 use topcoat::router::error::{SeeOther, bad_request, not_found, see_other};21 use topcoat::router::error::{SeeOther, bad_request, not_found, see_other};
23-use topcoat::router::response::{IntoResponse, Response};22+use topcoat::router::response::Response;
24-use topcoat::router::{Body, HeaderValue, StatusCode, page, path_param, query_params, route};23+use topcoat::router::{Body, StatusCode, page, path_param, query_params, route};
25 use topcoat::view::{View, component, view};24 use topcoat::view::{View, component, view};
26 25
27 use crate::auth::{current_user, percent_encode, require_csrf, require_user};26 use crate::auth::{current_user, percent_encode, require_csrf, require_user};
@@ -30,6 +29,7 @@ use crate::i18n::misc::{self as g, K};
30 use crate::i18n::{self, Key, Lang};29 use crate::i18n::{self, Key, Lang};
31 use crate::live::{Topic, stream_changes};30 use crate::live::{Topic, stream_changes};
32 use crate::notify_hub::publish_unread;31 use crate::notify_hub::publish_unread;
32+use crate::pages::ci_runs::events_response;
33 use crate::pages::issue_parts::{parse_number, stamp_unix};33 use crate::pages::issue_parts::{parse_number, stamp_unix};
34 use crate::pages::repo_ctx::{RepoCtx, load_repo};34 use crate::pages::repo_ctx::{RepoCtx, load_repo};
35 use crate::pages::repo_transfer::transfer_list_for;35 use crate::pages::repo_transfer::transfer_list_for;
@@ -720,8 +720,6 @@ async fn mark_all_read(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther>
720 720
721 /// How often an idle stream sends a `: keepalive` comment, so a reverse proxy does not drop the721 /// How often an idle stream sends a `: keepalive` comment, so a reverse proxy does not drop the
722 /// connection. This is the only timer in the feature: counts are pushed as they change.722 /// connection. This is the only timer in the feature: counts are pushed as they change.
723-const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30);
724-
725 /// One `unread` event carrying the count.723 /// One `unread` event carrying the count.
726 fn unread_event(count: u64) -> topcoat::Result<Event> {724 fn unread_event(count: u64) -> topcoat::Result<Event> {
727 Ok(Event::new().event("unread").data(count.to_string()))725 Ok(Event::new().event("unread").data(count.to_string()))
@@ -746,16 +744,7 @@ async fn notification_stream(cx: &Cx) -> Result<Response> {
746 let count = sub.next_count().await?;744 let count = sub.next_count().await?;
747 Some((unread_event(count), sub))745 Some((unread_event(count), sub))
748 });746 });
749- let events = Sse::new(first.chain(changes)).keep_alive(747+ events_response(cx, first.chain(changes))
750- KeepAlive::new()
751- .interval(STREAM_KEEP_ALIVE)
752- .text("keepalive"),
753- );
754- let mut res = events.into_response(cx)?;
755- // Nginx buffers a proxied response unless told not to, which would hold the events back.
756- res.headers_mut()
757- .insert("x-accel-buffering", HeaderValue::from_static("no"));
758- Ok(res)
759 }748 }
760 749
761 /// Subscribes or unsubscribes the viewer from an issue.750 /// Subscribes or unsubscribes the viewer from an issue.
@@ -1405,6 +1394,9 @@ mod tests {
1405 assert_eq!(res.headers().get("x-accel-buffering").unwrap(), "no");1394 assert_eq!(res.headers().get("x-accel-buffering").unwrap(), "no");
1406 1395
1407 let mut frames = res.into_body().into_data_stream();1396 let mut frames = res.into_body().into_data_stream();
1397+ // The stream opens with its retry field, then the count.
1398+ let retry = frames.next().await.expect("a frame").expect("data");
1399+ assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
1408 let first = frames.next().await.expect("a frame").expect("data");1400 let first = frames.next().await.expect("a frame").expect("data");
1409 assert_eq!(&first[..], b"event: unread\ndata: 1\n\n");1401 assert_eq!(&first[..], b"event: unread\ndata: 1\n\n");
1410 1402
crates/forge-web/src/pages/push.rsmodified+5 -16
@@ -19,20 +19,18 @@ use tokio::sync::broadcast::error::RecvError;
19 use topcoat::Result;19 use topcoat::Result;
20 use topcoat::context::{Cx, app_context};20 use topcoat::context::{Cx, app_context};
21 use topcoat::router::content::Form;21 use topcoat::router::content::Form;
22-use topcoat::router::content::sse::{Event, KeepAlive, Sse};22+use topcoat::router::content::sse::Event;
23 use topcoat::router::error::{SeeOther, see_other};23 use topcoat::router::error::{SeeOther, see_other};
24 use topcoat::router::request::headers;24 use topcoat::router::request::headers;
25-use topcoat::router::response::{IntoResponse, Response};25+use topcoat::router::response::Response;
26-use topcoat::router::{Body, HeaderMap, HeaderValue, StatusCode, header, route};26+use topcoat::router::{Body, HeaderMap, StatusCode, header, route};
27 27
28 use crate::api::{self, json};28 use crate::api::{self, json};
29 use crate::auth::{current_user, require_csrf, require_user};29 use crate::auth::{current_user, require_csrf, require_user};
30+use crate::pages::ci_runs::events_response;
30 use crate::state::AppState;31 use crate::state::AppState;
31 use crate::web_push::{self, Alert, crypto};32 use crate::web_push::{self, Alert, crypto};
32 33
33-/// How often an idle event stream sends a comment so proxies keep it open.
34-const STREAM_KEEP_ALIVE: std::time::Duration = std::time::Duration::from_secs(30);
35-
36 /// Longest push endpoint accepted, in bytes.34 /// Longest push endpoint accepted, in bytes.
37 const MAX_ENDPOINT: usize = 2048;35 const MAX_ENDPOINT: usize = 2048;
38 36
@@ -220,16 +218,7 @@ async fn push_events(cx: &Cx) -> Result<Response> {
220 }218 }
221 }219 }
222 });220 });
223- let events = Sse::new(changes).keep_alive(221+ events_response(cx, changes)
224- KeepAlive::new()
225- .interval(STREAM_KEEP_ALIVE)
226- .text("keepalive"),
227- );
228- let mut res = events.into_response(cx)?;
229- // Nginx buffers a proxied response unless told not to, which would hold the events back.
230- res.headers_mut()
231- .insert("x-accel-buffering", HeaderValue::from_static("no"));
232- Ok(res)
233 }222 }
234 223
235 fn changed_event() -> Result<Event> {224 fn changed_event() -> Result<Event> {
crates/forge-web/src/views/mod.rsmodified+2 -1
@@ -26,6 +26,7 @@ use topcoat::view::{Child, View, component, view};
26 use crate::i18n::admin::{self as ad, K as AK};26 use crate::i18n::admin::{self as ad, K as AK};
27 use crate::i18n::code::{self as g, K};27 use crate::i18n::code::{self as g, K};
28 use crate::i18n::community::{self as cm, K as CK};28 use crate::i18n::community::{self as cm, K as CK};
29+use crate::i18n::link::{self as lk, K as LinkKey};
29 use crate::i18n::migrate::{self as mg, K as MGK};30 use crate::i18n::migrate::{self as mg, K as MGK};
30 use crate::i18n::misc::{self as mi, K as MK};31 use crate::i18n::misc::{self as mi, K as MK};
31 use crate::i18n::orgs::{self as o, K as OK};32 use crate::i18n::orgs::{self as o, K as OK};
@@ -266,7 +267,7 @@ pub async fn shell(
266 }267 }
267 <script src=(NAV_SCRIPT_HREF) defer="defer"></script>268 <script src=(NAV_SCRIPT_HREF) defer="defer"></script>
268 </head>269 </head>
269- <body>270+ <body data-link-restarting=(lk::t(lang, LinkKey::Restarting)) data-link-back=(lk::t(lang, LinkKey::BackSubmit))>
270 <header class="topbar">271 <header class="topbar">
271 if signed_in {272 if signed_in {
272 <details class="nav-toggle">273 <details class="nav-toggle">
docs/architecture.mdmodified+8 -0
@@ -263,6 +263,14 @@ Pages update without a reload. A write that changes what a page shows calls `Liv
263 263
264 The user topics are keyed by user id, and their streams take the viewer from the session, so no URL names another user's inbox. Repo streams follow the same visibility as the repo page (a private repo answers 404 to a viewer who cannot read it). Explore lists public repos only.264 The user topics are keyed by user id, and their streams take the viewer from the session, so no URL names another user's inbox. Repo streams follow the same visibility as the repo page (a private repo answers 404 to a viewer who cannot read it). Explore lists public repos only.
265 265
266+### 5.8 Restart resilience
267+
268+A page survives a server restart without a reload by hand. Every page holds one stream to `GET /-/alive` (no login, no data). The stream sends `retry: 1000` first, and every event stream sent through `events_response` does the same, so the browser reconnects about once a second. When the stream fails, `nav.js` shows a bar ("Server restarting… your page is kept"). When it opens again, the bar goes and the page refreshes once (`refreshLive`).
269+
270+- A soft navigation that finds the server down (no answer, or a 502, 503 or 504 from the proxy) stays on the page and is made again when the server is back. A form post is never sent again: the form keeps its values and the bar asks the reader to submit it again.
271+- A full load while the server is down gets the offline page. `sw.js` (scope `/`) answers failed or 502/503/504 navigations with `/assets/offline.html`, precached on install with its script and stylesheet. The offline page reloads itself when `/-/alive` opens. The service worker caches nothing else: app pages and API responses always come from the network.
272+- EventSource closes for good when a proxy answers with an error, so `nav.js` and the offline page open the stream again themselves after 1, 2, then 3 seconds.
273+
266 ## 6. Authorization model274 ## 6. Authorization model
267 275
268 One function: `forge_core::authz::authorize(actor: Option<&User>, repo: &Repo, collaborator_role: Option<Role>, action: Action) -> Result<(), Denied>`.276 One function: `forge_core::authz::authorize(actor: Option<&User>, repo: &Repo, collaborator_role: Option<Role>, action: Action) -> Result<(), Denied>`.
style/_link.scssadded+49 -0
@@ -0,0 +1,49 @@
1+// The restart bar (shown while the server is down, nav.js) and the offline page (service worker).
2+// Colours come from the tokens, so light and dark follow the theme.
3+
4+.link-bar {
5+ position: fixed;
6+ top: 0;
7+ left: 0;
8+ right: 0;
9+ z-index: 1000;
10+ box-sizing: border-box;
11+ padding: 8px 16px;
12+ text-align: center;
13+ font-size: 0.875rem;
14+ color: var(--text);
15+ background: var(--accent-soft);
16+ border-bottom: 1px solid var(--accent);
17+ overflow-wrap: anywhere;
18+}
19+
20+.link-offline {
21+ box-sizing: border-box;
22+ min-height: 100vh;
23+ display: flex;
24+ flex-direction: column;
25+ align-items: center;
26+ justify-content: center;
27+ gap: 8px;
28+ padding: 24px 16px;
29+ text-align: center;
30+ color: var(--text);
31+ background: var(--bg);
32+}
33+
34+.link-offline-mark {
35+ margin: 0 0 12px;
36+ font-weight: 600;
37+ color: var(--accent);
38+}
39+
40+.link-offline-text {
41+ margin: 0;
42+ font-size: 1.125rem;
43+}
44+
45+.link-offline-sub {
46+ margin: 0;
47+ font-size: 0.875rem;
48+ color: var(--muted);
49+}
style/main.scssmodified+1 -0
@@ -6720,6 +6720,7 @@ button.ci-job-last {
6720 }6720 }
6721 6721
6722 @import "account_admin";6722 @import "account_admin";
6723+@import "link";
6723 6724
6724 // A monospace value with its Copy button on the right; long values wrap inside the box.6725 // A monospace value with its Copy button on the right; long values wrap inside the box.
6725 .copy-box {6726 .copy-box {