업데이트 알림(joke-app과 같게): 웹 빌드 id를 index.html meta(mq-build)에 넣고 서버가 /api/version·welcome으로 알려 줌, 다르면 위쪽에 '업데이트 내용이 있습니다 · 지금 새로고침하기 · ✕' 카드(소켓 다시 연결될 때·5분마다·탭으로 돌아올 때 확인)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-19 22:28:38 +09:00
parent 127513db63
commit 6ed669d5b4
11 changed files with 185 additions and 8 deletions

View File

@@ -29,6 +29,8 @@ export interface HttpDeps {
discordExchange?: (code: string, redirectUri: string) => Promise<DiscordUser>;
ipOf: (req: Request) => string;
health: () => { ok: boolean; [k: string]: unknown };
/** The web build being served (업데이트 알림), null without one. */
build?: () => string | null;
admin: Omit<AdminDeps, 'users' | 'sessions' | 'roles' | 'settings'>;
/** Deletes a guest account everywhere (sockets, DB). */
removeGuest: (userId: string) => void;
@@ -79,6 +81,11 @@ export function createHttpApp(d: HttpDeps) {
return c.json(h, h.ok ? 200 : 503);
});
app.get('/api/version', (c) => {
c.header('Cache-Control', 'no-store');
return c.json({ build: d.build?.() ?? null });
});
app.get('/api/config', (c) => {
const site = d.settings.getSite();
return c.json({ discord: d.config.discord !== null, siteName: site.siteName, announcement: site.announcement, maintenance: site.maintenance });

View File

@@ -1,5 +1,5 @@
/** Wires DB, auth, admin, HTTP and WebSocket into one Bun server (docs/01). Structure follows joke-app. */
import { existsSync } from 'node:fs';
import { existsSync, readFileSync } from 'node:fs';
import { join, normalize } from 'node:path';
import type { Server } from 'bun';
import type { Config } from './config';
@@ -68,7 +68,11 @@ export function startServer(opts: StartOptions) {
roomPolicy: () => ({ defaults: settings.getSite().roomDefaults, locks: settings.getSite().roomLocks }),
});
const collect = opts.collect ?? collectorControl(db, log);
const staticDir = opts.staticDir === undefined ? join(import.meta.dir, '../../web/dist') : opts.staticDir;
const serveStatic = !!staticDir && existsSync(staticDir);
const build = serveStatic ? webBuildId(staticDir!) : null;
const gateway = new Gateway({
build: () => build,
log,
onClose: (id) => users.touch(id),
rooms,
@@ -93,8 +97,6 @@ export function startServer(opts: StartOptions) {
const ipOf = (req: Request) =>
(config.trustProxy ? req.headers.get('x-forwarded-for')?.split(',').pop()?.trim() : undefined) || server?.requestIP(req)?.address || 'unknown';
const staticDir = opts.staticDir === undefined ? join(import.meta.dir, '../../web/dist') : opts.staticDir;
const serveStatic = !!staticDir && existsSync(staticDir);
const app = createHttpApp({
config,
users,
@@ -105,6 +107,7 @@ export function startServer(opts: StartOptions) {
db,
ipOf,
discordExchange: opts.discordExchange,
build: () => build,
health: () => ({ ok: ready, connections: gateway.connectionCount, rooms: rooms.rooms.size }),
removeGuest,
admin: {
@@ -204,3 +207,12 @@ async function serveFile(root: string, pathname: string): Promise<Response> {
// SPA fallback.
return new Response(Bun.file(join(root, 'index.html')), { headers: { 'Cache-Control': 'no-cache', 'Content-Type': 'text/html; charset=utf-8' } });
}
/** The build id the web build wrote into its index.html (`<meta name="mq-build">`, vite.config.ts), or null. */
export function webBuildId(root: string): string | null {
try {
return /<meta name="mq-build" content="([0-9a-f]+)"/.exec(readFileSync(join(root, 'index.html'), 'utf8'))?.[1] ?? null;
} catch {
return null;
}
}

View File

@@ -0,0 +1,44 @@
/** 업데이트 알림 (same as joke-app): the server tells which web build it serves. */
import { afterEach, expect, test } from 'bun:test';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { webBuildId } from './server';
import { Client, api, boot, guest } from './test-utils';
const running: ReturnType<typeof boot>[] = [];
const clients: Client[] = [];
afterEach(async () => {
for (const c of clients.splice(0)) c.close();
for (const s of running.splice(0)) await s.stop();
});
function webDir(html: string): string {
const dir = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), 'mq-web-'));
writeFileSync(join(dir, 'index.html'), html);
return dir;
}
test('the build id comes from the meta tag of the served index.html', () => {
expect(webBuildId(webDir('<html><head><meta name="mq-build" content="abc123def456"></head></html>'))).toBe('abc123def456');
expect(webBuildId(webDir('<html><head></head></html>'))).toBeNull();
expect(webBuildId('/nonexistent/dir')).toBeNull();
});
test('/api/version and the socket welcome carry the build', async () => {
const s = boot({ staticDir: webDir('<html><head><meta name="mq-build" content="0123456789ab"></head></html>') });
running.push(s);
const r = await api(s.base, '/api/version');
expect(r.res.headers.get('cache-control')).toBe('no-store');
expect(r.body).toEqual({ build: '0123456789ab' });
const g = await guest(s.base, '버전확인');
const c = await new Client(s.base, g.cookie).connect();
clients.push(c);
expect(c.messages.find((m) => m.t === 'welcome')).toMatchObject({ build: '0123456789ab' });
});
test('without a web build (dev, tests) there is nothing to compare', async () => {
const s = boot();
running.push(s);
expect((await api(s.base, '/api/version')).body).toEqual({ build: null });
});

View File

@@ -21,6 +21,8 @@ export interface GatewayDeps {
rooms: RoomManager;
/** Chat flood guard (docs/12 채팅): off by default, the admin turns it on in site settings. */
chatGuard?: () => { on: boolean; ratePerSec: number; burst: number };
/** The web build being served (업데이트 알림). */
build?: () => string | null;
}
export class Gateway {
@@ -63,7 +65,7 @@ export class Gateway {
const set = this.conns.get(ws.data.userId) ?? new Set();
set.add(ws);
this.conns.set(ws.data.userId, set);
this.send(ws, { t: 'welcome', protocol: PROTOCOL, userId: ws.data.userId, serverNow: Date.now() });
this.send(ws, { t: 'welcome', protocol: PROTOCOL, userId: ws.data.userId, serverNow: Date.now(), build: this.d.build?.() ?? null });
},
message: (ws: ServerWebSocket<WsData>, raw: string | Buffer): void => {
const text = typeof raw === 'string' ? raw : raw.toString();