Show the community server's status on the homepage

This commit is contained in:
ancsemi committed 2026-10-17 12:35:02 -04:00
1 parent 73a7a79ece
commit 90aabb428c
4 files changed
+309

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
name: Community server status
# Checks the community server every ten minutes and keeps the result in
# status.json on the site-status branch, which the homepage's status line
# reads (docs/index.html). The branch holds that one file in a single
# commit, replaced each run, so main's history stays clean and nothing that
# builds or publishes runs on it. scripts/community-status.js does the check.
on:
schedule:
- cron: '*/10 * * * *'
workflow_dispatch:
permissions:
contents: write
concurrency:
group: community-status
cancel-in-progress: false
jobs:
check:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Get the checker
uses: actions/checkout@v4
with:
sparse-checkout: scripts/community-status.js
sparse-checkout-cone-mode: false
- name: Get the last result
run: |
if git fetch --depth=1 origin site-status 2>/dev/null; then
git show FETCH_HEAD:status.json > previous.json 2>/dev/null || true
fi
- name: Check the community server
run: node scripts/community-status.js status.json "$( [ -s previous.json ] && echo previous.json )"
- name: Publish the result
run: |
mkdir publish
cp status.json publish/status.json
cd publish
git init -q -b site-status
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add status.json
git commit -q -m "Community server status"
git push -q --force "https://x-access-token:${{ github.token }}@github.com/${{ github.repository }}.git" site-status
+70
View File
@@ -149,6 +149,17 @@
.btn-secondary:hover { border-color: var(--ink); text-decoration: none; }
.btn .ver { font-family: var(--mono); font-weight: 500; font-size: 14px; opacity: 0.85; }
.actions .plain { font-size: 15px; }
/* The community server's status, under the join button. */
.server-status { display: grid; grid-template-columns: 9px 1fr; column-gap: 10px; row-gap: 2px; margin: 16px 0 0; font-size: 14px; color: var(--muted); }
.server-status .dot { align-self: start; margin-top: 6px; width: 9px; height: 9px; border-radius: 50%; background: var(--rule-strong); }
.server-status .status-when { grid-column: 2; }
.server-status .status-when:empty { display: none; }
.server-status[data-state="ok"] .dot { background: #2E9E5B; box-shadow: 0 0 0 3px rgba(46, 158, 91, 0.18); }
.server-status[data-state="warn"] .dot { background: #D19A1C; box-shadow: 0 0 0 3px rgba(209, 154, 28, 0.2); }
.server-status[data-state="down"] .dot { background: #D2463C; box-shadow: 0 0 0 3px rgba(210, 70, 60, 0.2); }
.server-status[data-state="down"] .status-text,
.server-status[data-state="warn"] .status-text { color: var(--ink); }
.server-status .status-when { font-size: 13px; }
.term { background: var(--term-bg); color: var(--term-ink); border-radius: 6px; padding: 18px 20px; font-family: var(--mono); font-size: 13.5px; line-height: 1.5; overflow-x: auto; border: 1px solid var(--rule-strong); }
.term pre { margin: 0; white-space: pre-wrap; }
@@ -298,6 +309,7 @@
<a class="btn btn-secondary" id="try-server" href="https://haven.moviethingy.xyz/?invite=da0b9be7">Join the community server</a>
<a class="plain" href="https://github.com/ancsemi/Haven">Source on GitHub</a>
</div>
<p class="server-status" id="server-status" data-state="unknown" role="status" aria-live="polite"><span class="dot" aria-hidden="true"></span><span class="status-text">Checking the community server…</span><span class="status-when"></span></p>
</div>
<div>
<div class="term" role="img" aria-label="Haven's start-up message in a terminal: HAVEN is running, with the local and network addresses">
@@ -618,6 +630,64 @@
})();
</script>
<script>
// The community server's status line. A job checks the server every ten
// minutes (scripts/community-status.js) and keeps the result on the repo's
// site-status branch; this reads it when the page opens and every two
// minutes after. A result older than 40 minutes means the checks stopped,
// so it says so rather than showing an old answer.
(() => {
const line = document.getElementById('server-status');
if (!line) return;
const text = line.querySelector('.status-text');
const when = line.querySelector('.status-when');
const SOURCE = 'https://raw.githubusercontent.com/ancsemi/Haven/site-status/status.json';
const STALE_MS = 40 * 60 * 1000;
const ago = (iso) => {
const min = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 60000));
if (min < 1) return 'just now';
if (min < 60) return min === 1 ? '1 minute ago' : `${min} minutes ago`;
const h = Math.round(min / 60);
return h === 1 ? '1 hour ago' : `${h} hours ago`;
};
const at = (isoTime) => new Date(isoTime).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
// Certificate dates in the visitor's own time; anything else as the
// checker wrote it.
const say = (s) => {
if (s.code === 'cert-expired' && s.certificateExpires) {
return `The community server's security certificate expired ${at(s.certificateExpires)}, so browsers won't connect until it's renewed.`;
}
if (s.code === 'cert-expiring' && s.certificateExpires) {
return `The community server is online. Its security certificate runs out ${at(s.certificateExpires)}.`;
}
return s.message || 'The community server is online.';
};
const show = (state, message, detail) => {
line.dataset.state = state;
text.textContent = message;
when.textContent = detail || '';
};
const check = async () => {
try {
const res = await fetch(`${SOURCE}?t=${Date.now()}`, { cache: 'no-store' });
if (!res.ok) throw new Error(`status ${res.status}`);
const s = await res.json();
if (!s || !s.checkedAt || Date.now() - Date.parse(s.checkedAt) > STALE_MS) {
show('unknown', "The community server's status hasn't been checked lately.");
return;
}
const state = ['ok', 'warn', 'down'].includes(s.state) ? s.state : 'unknown';
const since = state === 'down' && s.code !== 'cert-expired' && s.since ? `Since ${at(s.since)}. ` : '';
show(state, say(s), `${since}Checked ${ago(s.checkedAt)}.`);
} catch (err) {
show('unknown', "Couldn't load the community server's status.");
}
};
check();
setInterval(check, 2 * 60 * 1000);
})();
</script>
<script>
// "Try it now" in the bar: back to the top, then light up the community server button.
(() => {
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env node
'use strict';
// Checks the community server and writes what the homepage's status line
// shows (docs/index.html, "Community server" under the join button).
//
// Run every ten minutes by .github/workflows/community-status.yml, which
// keeps the result on the site-status branch. A visitor's browser cannot
// read a certificate, so it could only tell "reachable" from "not"; this
// says why: the certificate expired, it is not valid, the server does not
// answer, or it cannot be reached at all.
//
// node scripts/community-status.js [out.json] [previous.json]
//
// HOST overrides the server (default haven.moviethingy.xyz).
const fs = require('fs');
const https = require('https');
const tls = require('tls');
const HOST = process.env.HOST || 'haven.moviethingy.xyz';
const OUT = process.argv[2] || 'status.json';
const PREV = process.argv[3] || null;
const TIMEOUT_MS = 15000;
// A certificate this close to its end gets a warning while still working.
const SOON_MS = 3 * 24 * 60 * 60 * 1000;
// The certificate as the server presents it, valid or not.
function readCertificate() {
return new Promise((resolve) => {
const sock = tls.connect({ host: HOST, port: 443, servername: HOST, rejectUnauthorized: false, timeout: TIMEOUT_MS }, () => {
const cert = sock.getPeerCertificate();
resolve({
reached: true,
authorized: sock.authorized,
error: sock.authorizationError ? String(sock.authorizationError) : null,
validTo: cert && cert.valid_to ? new Date(cert.valid_to).toISOString() : null,
issuer: cert && cert.issuer ? (cert.issuer.O || cert.issuer.CN || null) : null,
});
sock.end();
});
sock.on('timeout', () => { sock.destroy(); resolve({ reached: false, error: 'timeout' }); });
sock.on('error', (err) => resolve({ reached: false, error: err.code || err.message }));
});
}
// Haven's own health check, read even through a bad certificate, so an
// expired one can still say whether the server behind it is running.
function readHealth() {
return new Promise((resolve) => {
const req = https.get({ host: HOST, path: '/api/health', servername: HOST, rejectUnauthorized: false, timeout: TIMEOUT_MS }, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (c) => { if (body.length < 4096) body += c; });
res.on('end', () => {
let json = null;
try { json = JSON.parse(body); } catch { /* not JSON: judged by the status code alone */ }
resolve({ status: res.statusCode, online: !!(json && json.status === 'online'), name: json && typeof json.name === 'string' ? json.name.slice(0, 80) : null });
});
});
req.on('timeout', () => { req.destroy(); resolve({ status: 0, online: false }); });
req.on('error', () => resolve({ status: 0, online: false }));
});
}
const day = (iso) => new Date(iso).toUTCString().replace(/:\d\d GMT$/, ' UTC');
function judge(cert, health, now) {
if (!cert.reached) {
return { state: 'down', code: 'unreachable', message: "The community server can't be reached right now." };
}
if (!cert.authorized) {
if (cert.error === 'CERT_HAS_EXPIRED') {
return { state: 'down', code: 'cert-expired', message: `The community server's security certificate expired ${day(cert.validTo)}, so browsers won't connect until it's renewed.` };
}
return { state: 'down', code: 'cert-invalid', message: `The community server's security certificate isn't valid (${cert.error}), so browsers won't connect.` };
}
if (!health.online) {
return { state: 'down', code: 'not-answering', message: "The community server isn't answering right now." };
}
if (cert.validTo && new Date(cert.validTo).getTime() - now < SOON_MS) {
return { state: 'warn', code: 'cert-expiring', message: `The community server is online. Its security certificate runs out ${day(cert.validTo)}.` };
}
return { state: 'ok', code: 'online', message: 'The community server is online.' };
}
async function main() {
const now = Date.now();
const cert = await readCertificate();
const health = cert.reached ? await readHealth() : { status: 0, online: false };
const verdict = judge(cert, health, now);
// "Since" carries over while the verdict stays the same. An expired
// certificate has been down since the moment it ran out.
let since = verdict.code === 'cert-expired' && cert.validTo ? cert.validTo : new Date(now).toISOString();
if (PREV && verdict.code !== 'cert-expired') {
try {
const prev = JSON.parse(fs.readFileSync(PREV, 'utf8'));
if (prev && prev.code === verdict.code && typeof prev.since === 'string') since = prev.since;
} catch { /* no earlier result yet: this one starts the clock */ }
}
const out = {
host: HOST,
...verdict,
since,
checkedAt: new Date(now).toISOString(),
certificateExpires: cert.validTo || null,
certificateIssuer: cert.issuer || null,
};
fs.writeFileSync(OUT, JSON.stringify(out, null, 2) + '\n');
console.log(`${out.state}: ${out.message}`);
}
main().catch((err) => {
console.error('[community-status]', err);
process.exit(1);
});
+70
View File
@@ -149,6 +149,17 @@
.btn-secondary:hover { border-color: var(--ink); text-decoration: none; }
.btn .ver { font-family: var(--mono); font-weight: 500; font-size: 14px; opacity: 0.85; }
.actions .plain { font-size: 15px; }
/* The community server's status, under the join button. */
.server-status { display: grid; grid-template-columns: 9px 1fr; column-gap: 10px; row-gap: 2px; margin: 16px 0 0; font-size: 14px; color: var(--muted); }
.server-status .dot { align-self: start; margin-top: 6px; width: 9px; height: 9px; border-radius: 50%; background: var(--rule-strong); }
.server-status .status-when { grid-column: 2; }
.server-status .status-when:empty { display: none; }
.server-status[data-state="ok"] .dot { background: #2E9E5B; box-shadow: 0 0 0 3px rgba(46, 158, 91, 0.18); }
.server-status[data-state="warn"] .dot { background: #D19A1C; box-shadow: 0 0 0 3px rgba(209, 154, 28, 0.2); }
.server-status[data-state="down"] .dot { background: #D2463C; box-shadow: 0 0 0 3px rgba(210, 70, 60, 0.2); }
.server-status[data-state="down"] .status-text,
.server-status[data-state="warn"] .status-text { color: var(--ink); }
.server-status .status-when { font-size: 13px; }
.term { background: var(--term-bg); color: var(--term-ink); border-radius: 6px; padding: 18px 20px; font-family: var(--mono); font-size: 13.5px; line-height: 1.5; overflow-x: auto; border: 1px solid var(--rule-strong); }
.term pre { margin: 0; white-space: pre-wrap; }
@@ -298,6 +309,7 @@
<a class="btn btn-secondary" id="try-server" href="https://haven.moviethingy.xyz/?invite=da0b9be7">Join the community server</a>
<a class="plain" href="https://github.com/ancsemi/Haven">Source on GitHub</a>
</div>
<p class="server-status" id="server-status" data-state="unknown" role="status" aria-live="polite"><span class="dot" aria-hidden="true"></span><span class="status-text">Checking the community server…</span><span class="status-when"></span></p>
</div>
<div>
<div class="term" role="img" aria-label="Haven's start-up message in a terminal: HAVEN is running, with the local and network addresses">
@@ -618,6 +630,64 @@
})();
</script>
<script>
// The community server's status line. A job checks the server every ten
// minutes (scripts/community-status.js) and keeps the result on the repo's
// site-status branch; this reads it when the page opens and every two
// minutes after. A result older than 40 minutes means the checks stopped,
// so it says so rather than showing an old answer.
(() => {
const line = document.getElementById('server-status');
if (!line) return;
const text = line.querySelector('.status-text');
const when = line.querySelector('.status-when');
const SOURCE = 'https://raw.githubusercontent.com/ancsemi/Haven/site-status/status.json';
const STALE_MS = 40 * 60 * 1000;
const ago = (iso) => {
const min = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 60000));
if (min < 1) return 'just now';
if (min < 60) return min === 1 ? '1 minute ago' : `${min} minutes ago`;
const h = Math.round(min / 60);
return h === 1 ? '1 hour ago' : `${h} hours ago`;
};
const at = (isoTime) => new Date(isoTime).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
// Certificate dates in the visitor's own time; anything else as the
// checker wrote it.
const say = (s) => {
if (s.code === 'cert-expired' && s.certificateExpires) {
return `The community server's security certificate expired ${at(s.certificateExpires)}, so browsers won't connect until it's renewed.`;
}
if (s.code === 'cert-expiring' && s.certificateExpires) {
return `The community server is online. Its security certificate runs out ${at(s.certificateExpires)}.`;
}
return s.message || 'The community server is online.';
};
const show = (state, message, detail) => {
line.dataset.state = state;
text.textContent = message;
when.textContent = detail || '';
};
const check = async () => {
try {
const res = await fetch(`${SOURCE}?t=${Date.now()}`, { cache: 'no-store' });
if (!res.ok) throw new Error(`status ${res.status}`);
const s = await res.json();
if (!s || !s.checkedAt || Date.now() - Date.parse(s.checkedAt) > STALE_MS) {
show('unknown', "The community server's status hasn't been checked lately.");
return;
}
const state = ['ok', 'warn', 'down'].includes(s.state) ? s.state : 'unknown';
const since = state === 'down' && s.code !== 'cert-expired' && s.since ? `Since ${at(s.since)}. ` : '';
show(state, say(s), `${since}Checked ${ago(s.checkedAt)}.`);
} catch (err) {
show('unknown', "Couldn't load the community server's status.");
}
};
check();
setInterval(check, 2 * 60 * 1000);
})();
</script>
<script>
// "Try it now" in the bar: back to the top, then light up the community server button.
(() => {