Files
FWS-DiscordBot/src/web/services/status-service.js
T
nocodeandClaude Opus 5 a1e1de7734 feat(web): publish a public status page at /status
Checking whether the service is up required an account, so the answer
lived where the people asking could not reach it.

The page is rendered on the server with no script at all and refreshes
through a meta tag: a status page that needs a working browser is
useless at the moment it is read. Two rules follow from it being public.
A repository the forge does not list as public keeps its environment
visible but loses its name, and the banner always states the worst true
thing — a failed deployment forbids the green headline even while the
bot answers. WEB_PUBLIC_STATUS=false removes page and route together.

/api/status gives the same in JSON, which is what a monitor should watch
rather than /api/health — the latter only says the process is alive.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:46:26 +02:00

134 lines
4.6 KiB
JavaScript

import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { lastDeploymentPerEnvironment } from '../../database/repositories/deploy-repository.js';
import { org, repos, splitRepository } from '../../services/gitea/gitea-admin.js';
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
import { VERSION } from './build-info.js';
/**
* What the public status page and `/api/status` both answer with (M19).
*
* Two rules shape this file. The page is **public**, so nothing here may name
* something the organization has not made public — a private repository leaking
* through a deployment row would be a real disclosure. And it is **unauthenticated**,
* so it may not turn a page load into a forge request: everything from Gitea is
* cached, and a failed refresh serves the previous answer rather than none.
*/
const log = createLogger('web:status');
const CACHE_TTL_MS = 60_000;
let cache = { at: 0, publicRepositories: null, releases: [] };
/** `success` is the only state worth claiming; everything else is spelled out. */
const DEPLOY_TONES = {
success: 'ok',
failed: 'down',
running: 'busy',
pending: 'busy',
};
async function refreshForge() {
if (!isGiteaConfigured()) return;
if (Date.now() - cache.at < CACHE_TTL_MS) return;
const repositories = await org.listRepos({ limit: 50 }).catch((error) => {
log.debug('Could not refresh the public repository list', error);
return null;
});
if (!repositories) return;
const open = repositories.filter((repository) => !repository.private && !repository.archived);
// One release request per repository would grow with the organization; the
// three most recently touched are what a status page is read for anyway.
const recent = open
.slice()
.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
.slice(0, 3);
const releases = (
await Promise.all(
recent.map(async (repository) => {
const parts = splitRepository(repository.full_name);
if (!parts) return null;
const release = await repos.latestRelease(parts.owner, parts.repo).catch(() => null);
if (!release || release.draft) return null;
return {
repository: repository.full_name,
tag: release.tag_name,
name: release.name || release.tag_name,
prerelease: Boolean(release.prerelease),
publishedAt: release.published_at ?? release.created_at ?? null,
htmlUrl: release.html_url ?? null,
};
}),
)
).filter(Boolean);
cache = {
at: Date.now(),
publicRepositories: new Set(open.map((repository) => repository.full_name)),
releases,
};
}
/**
* Deployment rows, stripped of anything the public has no business seeing.
*
* A repository the forge does not list as public is kept as a row — the
* environment is still meaningful — but loses its name.
*/
function environments() {
const guildId = env.discord.guildId;
if (!guildId) return [];
const rows = lastDeploymentPerEnvironment(guildId);
const known = cache.publicRepositories;
return rows.map((row) => ({
environment: row.environment,
repository: !known || known.has(row.repository) ? row.repository : null,
status: row.status,
tone: DEPLOY_TONES[row.status] ?? 'unknown',
releaseTag: row.release_tag ?? null,
finishedAt: row.finished_at ?? null,
}));
}
/** The snapshot behind `/status` and `/api/status`. Never throws. */
export async function statusSnapshot({ client = null, startedAt = Date.now() } = {}) {
await refreshForge().catch((error) => log.debug('Status refresh failed', error));
const online = Boolean(client?.isReady?.());
return {
bot: {
online,
state: online ? 'ok' : 'down',
uptimeMs: Date.now() - startedAt,
startedAt: new Date(startedAt).toISOString(),
version: VERSION,
// Round-trip to Discord: the one number that says the link is healthy
// rather than merely established.
pingMs: typeof client?.ws?.ping === 'number' && client.ws.ping >= 0 ? client.ws.ping : null,
},
environments: environments(),
releases: cache.releases,
links: {
website: env.links.website || null,
docs: env.links.docs || null,
discordInvite: env.links.discordInvite || null,
archRepo: env.links.archRepo || null,
forge: isGiteaConfigured() ? env.gitea.url : null,
},
generatedAt: new Date().toISOString(),
};
}
/** Lets the tests start from a known state. */
export function resetStatusCache() {
cache = { at: 0, publicRepositories: null, releases: [] };
}