diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js
index c9b7d02..59959bd 100644
--- a/crates/forge-web/assets/nav.js
+++ b/crates/forge-web/assets/nav.js
@@ -357,17 +357,22 @@
function load(o) {
var mark = ++latest;
var user = o.how !== 'live';
- if (user) { userBusy += 1; }
+ if (user) { userBusy += 1; clearNote(); }
busyStart();
fetch(o.target.href, o.init).then(function (r) {
+ if (RESTART.indexOf(r.status) >= 0) { return { down: true }; }
var final = new URL(r.url || o.target.href);
var html = /^\s*text\/html/i.test(r.headers.get('content-type') || '');
if (final.origin !== location.origin || !html) {
return { leave: true, url: final, redirected: r.redirected };
}
return r.text().then(function (text) { return { html: text, url: final, status: r.status }; });
+ }, function () {
+ // No answer at all: the server is down.
+ return { down: true };
}).then(function (res) {
if (mark !== latest) { return; }
+ if (res.down) { if (o.how !== 'live') { outage(o); } return; }
if (res.leave) { leave(res, o); return; }
// A code view keeps its page when a live refresh fails. A 404 means its path is gone at the new ref.
if (o.how === 'live' && res.status >= 400 && document.querySelector('[data-live-code]')) {
@@ -390,6 +395,102 @@
});
}
+ // Outage. A soft request that finds the server down (no answer, or a proxy's 502, 503 or 504 while
+ // forge restarts) never falls back to a full load. The page stays and a bar says the server is
+ // restarting. A GET is kept and made again once the server is back. A POST is never sent again:
+ // the form keeps its values and the bar asks the reader to submit it again.
+ var RESTART = [502, 503, 504];
+ var link = { down: false, pending: null, post: false };
+ var linkBarEl = null;
+ var alive = null; // the /-/alive stream every page holds: its open means the server is back
+
+ function linkText(name) {
+ return (document.body && document.body.getAttribute('data-link-' + name)) || '';
+ }
+
+ function showBar(text) {
+ if (!linkBarEl) {
+ linkBarEl = document.createElement('div');
+ linkBarEl.className = 'link-bar';
+ linkBarEl.setAttribute('role', 'status');
+ linkBarEl.setAttribute('aria-live', 'polite');
+ }
+ linkBarEl.textContent = text;
+ linkBarEl.hidden = false;
+ // A swap replaces the body's children, so the bar is put back when it is needed again.
+ if (!linkBarEl.isConnected && document.body) { document.body.appendChild(linkBarEl); }
+ }
+
+ function hideBar() {
+ if (linkBarEl) { linkBarEl.hidden = true; }
+ }
+
+ // The "submit again" note stays until the reader acts again.
+ function clearNote() {
+ if (link.post && !link.down) { link.post = false; hideBar(); }
+ }
+
+ function linkDown() {
+ if (link.down) { return; }
+ link.down = true;
+ showBar(linkText('restarting'));
+ }
+
+ function outage(o) {
+ linkDown();
+ if (o.post) {
+ link.post = true;
+ if (o.form) { queued.delete(o.form); }
+ } else {
+ link.pending = o;
+ }
+ // A stream that is still open did not notice the outage: reconnect it at once.
+ if (alive) { alive.restart(); }
+ }
+
+ function linkBack() {
+ if (!link.down) { return; }
+ link.down = false;
+ var o = link.pending;
+ link.pending = null;
+ if (o) { hideBar(); load(o); return; }
+ refreshLive();
+ if (link.post) { showBar(linkText('back')); } else { hideBar(); }
+ }
+
+ // One EventSource that stays open. The browser reconnects by itself, except when a proxy answers
+ // with an error: EventSource then closes for good, so it is opened again here after 1, 2, then 3 s.
+ // `restart()` reconnects at once.
+ function keepOpen(url, onOpen, onError) {
+ var es = null, delay = 1000, timer = null;
+ function connect() {
+ timer = null;
+ es = new EventSource(url);
+ es.onopen = function () { delay = 1000; onOpen(); };
+ es.onerror = function () {
+ onError();
+ if (es.readyState !== EventSource.CLOSED) { return; }
+ es.close();
+ timer = setTimeout(connect, delay);
+ delay = Math.min(delay + 1000, 3000);
+ };
+ }
+ connect();
+ return {
+ restart: function () {
+ if (timer) { clearTimeout(timer); timer = null; }
+ if (es) { es.close(); }
+ delay = 1000;
+ connect();
+ }
+ };
+ }
+
+ // Every page holds one stream to /-/alive (no data, no login). Its error means the server, or the
+ // proxy in front of it, is down; its open means it is back.
+ if (window.EventSource) { alive = keepOpen('/-/alive', linkBack, linkDown); }
+ if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(function () {}); }
+
// The form to send a queued change on: the form itself, or after a swap the one with the same action.
function resend(form) {
var target = form;
diff --git a/crates/forge-web/assets/offline.html b/crates/forge-web/assets/offline.html
new file mode 100644
index 0000000..9089a5d
--- /dev/null
+++ b/crates/forge-web/assets/offline.html
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+Forge
+
+
+
+
+
+
Forge
+
Server restarting… your page is kept
+
Sunucu yeniden başlıyor… sayfanız korunuyor
+
This page loads again by itself when the server is back.
+
Sunucu geri gelince bu sayfa kendiliğinden yeniden yüklenir.
+
+
+
diff --git a/crates/forge-web/assets/offline.js b/crates/forge-web/assets/offline.js
new file mode 100644
index 0000000..81f523c
--- /dev/null
+++ b/crates/forge-web/assets/offline.js
@@ -0,0 +1,28 @@
+// Offline page (served by the service worker when a page load finds the server down). Shows the
+// line in the browser's language, then reloads once the server answers again. Nothing else runs here.
+(function () {
+ 'use strict';
+ var want = /^tr\b/i.test(navigator.language || '') ? 'tr' : 'en';
+ document.querySelectorAll('.link-offline [lang]').forEach(function (el) {
+ if (el.getAttribute('lang') !== want) { el.hidden = true; }
+ });
+
+ if (!window.EventSource) { return; }
+ // Opens the stream again after a drop. The browser retries by itself, except when a proxy answers
+ // with an error (EventSource then closes for good): that case is retried here, 1, 2, then 3 s.
+ function keepOpen(url, onOpen) {
+ var delay = 1000;
+ function connect() {
+ var es = new EventSource(url);
+ es.onopen = function () { delay = 1000; onOpen(); };
+ es.onerror = function () {
+ if (es.readyState !== EventSource.CLOSED) { return; }
+ es.close();
+ setTimeout(connect, delay);
+ delay = Math.min(delay + 1000, 3000);
+ };
+ }
+ connect();
+ }
+ keepOpen('/-/alive', function () { location.reload(); });
+})();
diff --git a/crates/forge-web/assets/sw.js b/crates/forge-web/assets/sw.js
index 38ea13b..9dbcb14 100644
--- a/crates/forge-web/assets/sw.js
+++ b/crates/forge-web/assets/sw.js
@@ -1,13 +1,64 @@
// Forge service worker. Served at /sw.js, so its scope is the whole origin. It shows Web Push
-// notifications while no tab is open and opens the link of a clicked one. No inline code, no
-// network caching: the page is always fetched fresh.
+// notifications while no tab is open and opens the link of a clicked one. No inline code. The only
+// thing it caches is the offline page: app pages are always fetched fresh. A full page load that
+// finds the server down (or a proxy answering 502, 503 or 504 while forge restarts) gets that page
+// instead of the browser's error page. Everything else passes straight through to the network.
-self.addEventListener('install', function () {
- self.skipWaiting();
+// Bump the version when the offline page changes, so the new one is precached on install.
+var OFFLINE_CACHE = 'forge-offline-v2';
+var OFFLINE_URL = '/assets/offline.html';
+// The offline page and the two files it loads. They are precached: while the server is down the
+// browser could not fetch them for the offline page otherwise.
+var OFFLINE_FILES = [OFFLINE_URL, '/assets/offline.js', '/assets/main.css'];
+var RESTART_STATUS = [502, 503, 504];
+
+self.addEventListener('install', function (event) {
+ event.waitUntil(
+ caches.open(OFFLINE_CACHE)
+ .then(function (cache) { return cache.addAll(OFFLINE_FILES.map(function (u) { return new Request(u, { cache: 'reload' }); })); })
+ .catch(function () { /* the server is down: the page is fetched again on the next install */ })
+ .then(function () { return self.skipWaiting(); })
+ );
});
self.addEventListener('activate', function (event) {
- event.waitUntil(self.clients.claim());
+ event.waitUntil((async function () {
+ var names = await caches.keys();
+ await Promise.all(names.filter(function (n) { return n.indexOf('forge-offline-') === 0 && n !== OFFLINE_CACHE; })
+ .map(function (n) { return caches.delete(n); }));
+ await self.clients.claim();
+ })());
+});
+
+// Navigations only, and only GET: the response is the network's, unless the network failed or the
+// server is restarting. Subresources, the event stream and form posts are not touched, except the
+// three offline-page files above (bare URLs, no query): network first, the precache when it fails.
+self.addEventListener('fetch', function (event) {
+ var req = event.request;
+ var asset = new URL(req.url);
+ if (req.method === 'GET' && req.mode !== 'navigate' && asset.origin === self.location.origin &&
+ asset.search === '' && OFFLINE_FILES.indexOf(asset.pathname) >= 0) {
+ event.respondWith((async function () {
+ var res = null;
+ try { res = await fetch(req); } catch (e) { res = null; }
+ if (res && RESTART_STATUS.indexOf(res.status) < 0) { return res; }
+ var cached = await caches.match(asset.pathname);
+ return cached || res || Response.error();
+ })());
+ return;
+ }
+ if (req.mode !== 'navigate' || req.method !== 'GET') { return; }
+ event.respondWith((async function () {
+ var res = null;
+ try {
+ res = await fetch(req);
+ } catch (e) {
+ res = null;
+ }
+ if (res && RESTART_STATUS.indexOf(res.status) < 0) { return res; }
+ var offline = await caches.match(OFFLINE_URL);
+ return offline || res || Response.error();
+ })());
});
self.addEventListener('push', function (event) {
diff --git a/crates/forge-web/src/i18n/link.rs b/crates/forge-web/src/i18n/link.rs
new file mode 100644
index 0000000..9ac8491
--- /dev/null
+++ b/crates/forge-web/src/i18n/link.rs
@@ -0,0 +1,35 @@
+//! Strings for the bar that shows while the server restarts. The shell puts them on `` so
+//! `nav.js` can show them without its own copy.
+
+use super::Lang;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum K {
+ Restarting,
+ BackSubmit,
+}
+
+/// The phrase for `key`.
+pub fn t(lang: Lang, key: K) -> &'static str {
+ use K::*;
+ match (key, lang) {
+ (Restarting, Lang::En) => "Server restarting\u{2026} your page is kept",
+ (Restarting, Lang::Tr) => "Sunucu yeniden başlıyor\u{2026} sayfanız korunuyor",
+ (BackSubmit, Lang::En) => "Server is back, submit again",
+ (BackSubmit, Lang::Tr) => "Sunucu geri geldi, tekrar gönderin",
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn every_string_has_no_em_dash() {
+ for lang in [Lang::En, Lang::Tr] {
+ for key in [K::Restarting, K::BackSubmit] {
+ assert!(!t(lang, key).contains('\u{2014}'));
+ }
+ }
+ }
+}
diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs
index d7835b9..b61427e 100644
--- a/crates/forge-web/src/i18n/mod.rs
+++ b/crates/forge-web/src/i18n/mod.rs
@@ -27,6 +27,7 @@ pub mod code;
pub mod community;
pub mod integrations;
pub mod issues;
+pub mod link;
pub mod migrate;
pub mod misc;
pub mod orgs;
diff --git a/crates/forge-web/src/pages/assets.rs b/crates/forge-web/src/pages/assets.rs
index aad4afb..d6d213f 100644
--- a/crates/forge-web/src/pages/assets.rs
+++ b/crates/forge-web/src/pages/assets.rs
@@ -3,9 +3,14 @@
use std::sync::OnceLock;
+use futures_util::stream;
use topcoat::Result;
+use topcoat::context::Cx;
+use topcoat::router::content::sse::Event;
+use topcoat::router::response::Response;
use topcoat::router::{HeaderMap, StatusCode, header, route};
+use crate::pages::ci_runs::events_response;
use crate::render::highlight::highlight_css;
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)>
Ok((StatusCode::OK, headers, highlight_css_text()))
}
+// The offline page (shown by the service worker when a page load finds the server down) and its
+// script. Not hashed and not immutable: the service worker fetches them again on each update.
+const OFFLINE_HTML: &str = include_str!("../../assets/offline.html");
+const OFFLINE_JS: &str = include_str!("../../assets/offline.js");
+
+#[route(GET "/assets/offline.html")]
+async fn offline_html() -> Result<(StatusCode, HeaderMap, &'static str)> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ header::CONTENT_TYPE,
+ "text/html; charset=utf-8"
+ .parse()
+ .expect("static header value"),
+ );
+ headers.insert(
+ header::CACHE_CONTROL,
+ "no-cache".parse().expect("static header value"),
+ );
+ Ok((StatusCode::OK, headers, OFFLINE_HTML))
+}
+
+#[route(GET "/assets/offline.js")]
+async fn offline_js() -> Result<(StatusCode, HeaderMap, &'static str)> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ header::CONTENT_TYPE,
+ "text/javascript; charset=utf-8"
+ .parse()
+ .expect("static header value"),
+ );
+ headers.insert(
+ header::CACHE_CONTROL,
+ "no-cache".parse().expect("static header value"),
+ );
+ Ok((StatusCode::OK, headers, OFFLINE_JS))
+}
+
+/// The stream every page and the offline page watch to learn that the server is back. It carries
+/// no data and needs no login: it sends `retry`, then holds the connection open with keep-alive
+/// comments. A dropped connection (or a proxy's 502 while forge restarts) is what the pages watch for.
+#[route(GET "/-/alive")]
+async fn alive(cx: &Cx) -> Result {
+ events_response(cx, stream::pending::>())
+}
+
// Bundled fonts (style/fonts/). The version is in each file name, so the immutable cache is
// safe: a new font version gets a new URL. Licenses sit beside them under /assets/fonts/.
const FIGTREE_LATIN: &[u8] =
@@ -274,6 +324,56 @@ mod tests {
assert!(String::from_utf8_lossy(&body).contains("__forgeSoft"));
}
+ #[tokio::test]
+ async fn alive_stream_sends_retry_first() {
+ use http_body_util::BodyExt;
+ let router: Router = Router::builder().discover().cookies().build();
+ let req = Request::builder()
+ .method("GET")
+ .uri("/-/alive")
+ .body(Body::empty())
+ .unwrap();
+ let res = router.handle(req).await;
+ assert_eq!(res.status(), 200);
+ assert!(
+ res.headers()["content-type"]
+ .to_str()
+ .unwrap()
+ .starts_with("text/event-stream")
+ );
+ let mut body = res.into_body();
+ let frame = body.frame().await.expect("a frame").expect("no error");
+ let data = frame.into_data().expect("data frame");
+ assert!(
+ String::from_utf8_lossy(&data).contains("retry: 1000"),
+ "the first bytes set the reconnect delay"
+ );
+ }
+
+ #[tokio::test]
+ async fn offline_page_and_script_are_served_without_caching() {
+ let router: Router = Router::builder().discover().cookies().build();
+ for (uri, kind) in [
+ ("/assets/offline.html", "text/html"),
+ ("/assets/offline.js", "text/javascript"),
+ ] {
+ let req = Request::builder()
+ .method("GET")
+ .uri(uri)
+ .body(Body::empty())
+ .unwrap();
+ let res = router.handle(req).await;
+ assert_eq!(res.status(), 200, "{uri}");
+ assert!(
+ res.headers()["content-type"]
+ .to_str()
+ .unwrap()
+ .starts_with(kind)
+ );
+ assert_eq!(res.headers()["cache-control"], "no-cache", "{uri}");
+ }
+ }
+
#[tokio::test]
async fn highlight_css_is_served_with_long_cache() {
let router: Router = Router::builder().discover().cookies().build();
diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs
index f79d89b..8030a49 100644
--- a/crates/forge-web/src/pages/ci_runs.rs
+++ b/crates/forge-web/src/pages/ci_runs.rs
@@ -16,7 +16,7 @@ use std::time::Duration;
use forge_core::ci::{CiJob, CiRun, JobState, RunState};
use forge_core::{Action, Denied, Store, User, authorize};
use forge_git::browse::{RefInfo, RefKind, read_commit};
-use futures_util::{Stream, stream};
+use futures_util::{Stream, StreamExt, stream};
use serde::Deserialize;
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
@@ -2023,13 +2023,18 @@ fn repo_changes(wake: watch::Receiver) -> impl Stream>
})
}
-/// The response of an event stream for a CI page: keep-alive comments while idle, and no buffering
-/// by a reverse proxy.
+/// How long the browser waits before it reconnects a dropped event stream. The browser's default is
+/// a few seconds; one second makes a page come back as soon as a server restart is done.
+pub(crate) const STREAM_RETRY: Duration = Duration::from_secs(1);
+
+/// The response of an event stream: keep-alive comments while idle, no buffering by a reverse
+/// proxy, and a `retry` field first so every stream reconnects after `STREAM_RETRY`.
pub(crate) fn events_response(
cx: &Cx,
events: impl Stream> + Send + 'static,
) -> Result {
- let events = Sse::new(events).keep_alive(
+ let retry = stream::once(std::future::ready(Ok(Event::new().retry(STREAM_RETRY))));
+ let events = Sse::new(retry.chain(events)).keep_alive(
KeepAlive::new()
.interval(STREAM_KEEP_ALIVE)
.text("keepalive"),
diff --git a/crates/forge-web/src/pages/ci_tests.rs b/crates/forge-web/src/pages/ci_tests.rs
index fdaeec1..66f6d3a 100644
--- a/crates/forge-web/src/pages/ci_tests.rs
+++ b/crates/forge-web/src/pages/ci_tests.rs
@@ -364,7 +364,7 @@ async fn open(
}
/// The next frame of an event stream, or None once the stream has ended. Fails after five seconds.
-async fn next_event(frames: &mut S) -> Option>
+async fn next_frame(frames: &mut S) -> Option>
where
S: futures_util::Stream> + Unpin,
E: std::fmt::Debug,
@@ -373,10 +373,29 @@ where
let frame = tokio::time::timeout(Duration::from_secs(5), frames.next())
.await
- .expect("an event within five seconds")?;
+ .expect("a frame within five seconds")?;
Some(frame.expect("data").to_vec())
}
+async fn next_event(frames: &mut S) -> Option>
+where
+ S: futures_util::Stream> + Unpin,
+ E: std::fmt::Debug,
+{
+ use futures_util::StreamExt;
+
+ // Every stream opens with its `retry` field (one frame): skip it, the tests want the events.
+ loop {
+ let frame = tokio::time::timeout(Duration::from_secs(5), frames.next())
+ .await
+ .expect("an event within five seconds")?;
+ let bytes = frame.expect("data").to_vec();
+ if !bytes.starts_with(b"retry: ") {
+ return Some(bytes);
+ }
+ }
+}
+
#[tokio::test]
async fn live_events_need_the_same_access_as_the_page() {
let dir = tempfile::tempdir().expect("tempdir");
@@ -588,6 +607,9 @@ async fn run_list_events_follow_repo_changes() {
.into_body()
.into_data_stream();
+ // The retry field comes first; after it nothing is sent until a change.
+ let retry = next_frame(&mut frames).await.expect("the retry field");
+ assert!(retry.starts_with(b"retry: "), "{retry:?}");
let quiet = tokio::time::timeout(Duration::from_millis(200), frames.next()).await;
assert!(quiet.is_err(), "nothing is sent on connect");
diff --git a/crates/forge-web/src/pages/notifications.rs b/crates/forge-web/src/pages/notifications.rs
index 07329db..ec23464 100644
--- a/crates/forge-web/src/pages/notifications.rs
+++ b/crates/forge-web/src/pages/notifications.rs
@@ -5,7 +5,6 @@
//! The sidebar box and the watch form are shared with the issue, pull and repo header views.
use std::collections::HashMap;
-use std::time::Duration;
use forge_core::authz::{Action, authorize};
use forge_core::discussions::{DiscussionNotification, DiscussionReason};
@@ -18,10 +17,10 @@ use serde::Deserialize;
use topcoat::Result;
use topcoat::context::{Cx, app_context};
use topcoat::router::content::Form;
-use topcoat::router::content::sse::{Event, KeepAlive, Sse};
+use topcoat::router::content::sse::Event;
use topcoat::router::error::{SeeOther, bad_request, not_found, see_other};
-use topcoat::router::response::{IntoResponse, Response};
-use topcoat::router::{Body, HeaderValue, StatusCode, page, path_param, query_params, route};
+use topcoat::router::response::Response;
+use topcoat::router::{Body, StatusCode, page, path_param, query_params, route};
use topcoat::view::{View, component, view};
use crate::auth::{current_user, percent_encode, require_csrf, require_user};
@@ -30,6 +29,7 @@ use crate::i18n::misc::{self as g, K};
use crate::i18n::{self, Key, Lang};
use crate::live::{Topic, stream_changes};
use crate::notify_hub::publish_unread;
+use crate::pages::ci_runs::events_response;
use crate::pages::issue_parts::{parse_number, stamp_unix};
use crate::pages::repo_ctx::{RepoCtx, load_repo};
use crate::pages::repo_transfer::transfer_list_for;
@@ -720,8 +720,6 @@ async fn mark_all_read(cx: &Cx, Form(form): Form) -> Result
/// How often an idle stream sends a `: keepalive` comment, so a reverse proxy does not drop the
/// connection. This is the only timer in the feature: counts are pushed as they change.
-const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30);
-
/// One `unread` event carrying the count.
fn unread_event(count: u64) -> topcoat::Result {
Ok(Event::new().event("unread").data(count.to_string()))
@@ -746,16 +744,7 @@ async fn notification_stream(cx: &Cx) -> Result {
let count = sub.next_count().await?;
Some((unread_event(count), sub))
});
- let events = Sse::new(first.chain(changes)).keep_alive(
- KeepAlive::new()
- .interval(STREAM_KEEP_ALIVE)
- .text("keepalive"),
- );
- let mut res = events.into_response(cx)?;
- // Nginx buffers a proxied response unless told not to, which would hold the events back.
- res.headers_mut()
- .insert("x-accel-buffering", HeaderValue::from_static("no"));
- Ok(res)
+ events_response(cx, first.chain(changes))
}
/// Subscribes or unsubscribes the viewer from an issue.
@@ -1405,6 +1394,9 @@ mod tests {
assert_eq!(res.headers().get("x-accel-buffering").unwrap(), "no");
let mut frames = res.into_body().into_data_stream();
+ // The stream opens with its retry field, then the count.
+ let retry = frames.next().await.expect("a frame").expect("data");
+ assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
let first = frames.next().await.expect("a frame").expect("data");
assert_eq!(&first[..], b"event: unread\ndata: 1\n\n");
diff --git a/crates/forge-web/src/pages/push.rs b/crates/forge-web/src/pages/push.rs
index 22c77d2..aee3aea 100644
--- a/crates/forge-web/src/pages/push.rs
+++ b/crates/forge-web/src/pages/push.rs
@@ -19,20 +19,18 @@ use tokio::sync::broadcast::error::RecvError;
use topcoat::Result;
use topcoat::context::{Cx, app_context};
use topcoat::router::content::Form;
-use topcoat::router::content::sse::{Event, KeepAlive, Sse};
+use topcoat::router::content::sse::Event;
use topcoat::router::error::{SeeOther, see_other};
use topcoat::router::request::headers;
-use topcoat::router::response::{IntoResponse, Response};
-use topcoat::router::{Body, HeaderMap, HeaderValue, StatusCode, header, route};
+use topcoat::router::response::Response;
+use topcoat::router::{Body, HeaderMap, StatusCode, header, route};
use crate::api::{self, json};
use crate::auth::{current_user, require_csrf, require_user};
+use crate::pages::ci_runs::events_response;
use crate::state::AppState;
use crate::web_push::{self, Alert, crypto};
-/// How often an idle event stream sends a comment so proxies keep it open.
-const STREAM_KEEP_ALIVE: std::time::Duration = std::time::Duration::from_secs(30);
-
/// Longest push endpoint accepted, in bytes.
const MAX_ENDPOINT: usize = 2048;
@@ -220,16 +218,7 @@ async fn push_events(cx: &Cx) -> Result {
}
}
});
- let events = Sse::new(changes).keep_alive(
- KeepAlive::new()
- .interval(STREAM_KEEP_ALIVE)
- .text("keepalive"),
- );
- let mut res = events.into_response(cx)?;
- // Nginx buffers a proxied response unless told not to, which would hold the events back.
- res.headers_mut()
- .insert("x-accel-buffering", HeaderValue::from_static("no"));
- Ok(res)
+ events_response(cx, changes)
}
fn changed_event() -> Result {
diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs
index 546c329..e2f736d 100644
--- a/crates/forge-web/src/views/mod.rs
+++ b/crates/forge-web/src/views/mod.rs
@@ -26,6 +26,7 @@ use topcoat::view::{Child, View, component, view};
use crate::i18n::admin::{self as ad, K as AK};
use crate::i18n::code::{self as g, K};
use crate::i18n::community::{self as cm, K as CK};
+use crate::i18n::link::{self as lk, K as LinkKey};
use crate::i18n::migrate::{self as mg, K as MGK};
use crate::i18n::misc::{self as mi, K as MK};
use crate::i18n::orgs::{self as o, K as OK};
@@ -266,7 +267,7 @@ pub async fn shell(
}
-
+
if signed_in {
diff --git a/docs/architecture.md b/docs/architecture.md
index 4dc3cf4..bbbac39 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -263,6 +263,14 @@ Pages update without a reload. A write that changes what a page shows calls `Liv
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.
+### 5.8 Restart resilience
+
+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`).
+
+- 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.
+- 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.
+- 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.
+
## 6. Authorization model
One function: `forge_core::authz::authorize(actor: Option<&User>, repo: &Repo, collaborator_role: Option, action: Action) -> Result<(), Denied>`.
diff --git a/style/_link.scss b/style/_link.scss
new file mode 100644
index 0000000..c527b06
--- /dev/null
+++ b/style/_link.scss
@@ -0,0 +1,49 @@
+// The restart bar (shown while the server is down, nav.js) and the offline page (service worker).
+// Colours come from the tokens, so light and dark follow the theme.
+
+.link-bar {
+ position: fixed;
+ top: 0;
+ left: 0;
+ right: 0;
+ z-index: 1000;
+ box-sizing: border-box;
+ padding: 8px 16px;
+ text-align: center;
+ font-size: 0.875rem;
+ color: var(--text);
+ background: var(--accent-soft);
+ border-bottom: 1px solid var(--accent);
+ overflow-wrap: anywhere;
+}
+
+.link-offline {
+ box-sizing: border-box;
+ min-height: 100vh;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ padding: 24px 16px;
+ text-align: center;
+ color: var(--text);
+ background: var(--bg);
+}
+
+.link-offline-mark {
+ margin: 0 0 12px;
+ font-weight: 600;
+ color: var(--accent);
+}
+
+.link-offline-text {
+ margin: 0;
+ font-size: 1.125rem;
+}
+
+.link-offline-sub {
+ margin: 0;
+ font-size: 0.875rem;
+ color: var(--muted);
+}
diff --git a/style/main.scss b/style/main.scss
index 933e425..75aaca6 100644
--- a/style/main.scss
+++ b/style/main.scss
@@ -6720,6 +6720,7 @@ button.ci-job-last {
}
@import "account_admin";
+@import "link";
// A monospace value with its Copy button on the right; long values wrap inside the box.
.copy-box {