diff --git a/apps/server/src/http/app.ts b/apps/server/src/http/app.ts index 9fde0f1..754c6cb 100644 --- a/apps/server/src/http/app.ts +++ b/apps/server/src/http/app.ts @@ -29,6 +29,8 @@ export interface HttpDeps { discordExchange?: (code: string, redirectUri: string) => Promise; ipOf: (req: Request) => string; health: () => { ok: boolean; [k: string]: unknown }; + /** The web build being served (업데이트 알림), null without one. */ + build?: () => string | null; admin: Omit; /** 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 }); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 9f23d75..df6b701 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -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 { // 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 (``, vite.config.ts), or null. */ +export function webBuildId(root: string): string | null { + try { + return /[] = []; +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(''))).toBe('abc123def456'); + expect(webBuildId(webDir(''))).toBeNull(); + expect(webBuildId('/nonexistent/dir')).toBeNull(); +}); + +test('/api/version and the socket welcome carry the build', async () => { + const s = boot({ staticDir: webDir('') }); + 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 }); +}); diff --git a/apps/server/src/ws/gateway.ts b/apps/server/src/ws/gateway.ts index 7661a96..7e490d8 100644 --- a/apps/server/src/ws/gateway.ts +++ b/apps/server/src/ws/gateway.ts @@ -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, raw: string | Buffer): void => { const text = typeof raw === 'string' ? raw : raw.toString(); diff --git a/apps/web/src/components/ui.tsx b/apps/web/src/components/ui.tsx index c48b97a..56d1226 100644 --- a/apps/web/src/components/ui.tsx +++ b/apps/web/src/components/ui.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef, type ReactNode } from 'react'; import type { PublicUser } from '@mq/shared/lite'; import { useToasts } from '../store/toast'; +import { dismissUpdate, useUpdateAvailable } from '../net/update'; /** Per-user fixed colour; skips the 60°~160° green band so names never look like the 정답 green (docs/03). */ export function userHue(id: string): number { @@ -99,3 +100,20 @@ export function DiscordMark() { ); } + +/** The site was updated while this page was open (same as joke-app): refresh, or ✕ to close until the next update. */ +export function UpdateBanner() { + const show = useUpdateAvailable(); + if (!show) return null; + return ( +
+ 업데이트 내용이 있습니다. + + +
+ ); +} diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index f4dba0d..abb4f3e 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -3,7 +3,8 @@ import { createRoot } from 'react-dom/client'; import { BrowserRouter, Route, Routes, useLocation, useNavigate } from 'react-router'; import 'pretendard/dist/web/variable/pretendardvariable-dynamic-subset.css'; import './styles/global.css'; -import { Toasts } from './components/ui'; +import { Toasts, UpdateBanner } from './components/ui'; +import { initUpdateCheck } from './net/update'; import { SiteHeader } from './components/SiteHeader'; import { useSession } from './store/session'; import { toast } from './store/toast'; @@ -50,6 +51,7 @@ function Shell() { + 불러오는 중…}> } /> @@ -63,6 +65,8 @@ function Shell() { ); } +initUpdateCheck(); + createRoot(document.getElementById('root')!).render( diff --git a/apps/web/src/net/socket.ts b/apps/web/src/net/socket.ts index 963a0d6..42faed0 100644 --- a/apps/web/src/net/socket.ts +++ b/apps/web/src/net/socket.ts @@ -5,6 +5,7 @@ import { create } from 'zustand'; import type { ChatLine, GameView, RoomView, ServerMessage } from '@mq/shared/lite'; import { toast } from '../store/toast'; import { player } from './player'; +import { noteServerBuild } from './update'; type Status = 'idle' | 'connecting' | 'open' | 'reconnecting'; @@ -79,6 +80,7 @@ function onMessage(m: ServerMessage): void { switch (m.t) { case 'welcome': { myId = m.userId; + noteServerBuild(m.build); useRoom.setState({ status: 'open', offset: m.serverNow - Date.now() }); retry = 0; syncClock(); diff --git a/apps/web/src/net/update.ts b/apps/web/src/net/update.ts new file mode 100644 index 0000000..717bb10 --- /dev/null +++ b/apps/web/src/net/update.ts @@ -0,0 +1,54 @@ +/** + * "업데이트 내용이 있습니다" (same as joke-app). The page knows its own build (``, written by + * vite.config.ts); the server tells its build in `welcome` and at `/api/version`. When they differ the page offers a + * refresh at the top; ✕ hides it until the next update. Dev builds have no meta and never ask. + */ +import { useSyncExternalStore } from 'react'; + +const POLL_MS = 5 * 60_000; + +const mine = typeof document === 'undefined' ? null : (document.querySelector('meta[name="mq-build"]')?.content ?? null); +/** Build the server has that this page doesn't. */ +let latest: string | null = null; +let dismissed: string | null = null; +const listeners = new Set<() => void>(); +const emit = () => listeners.forEach((l) => l()); + +/** The server's build (welcome message, `/api/version`). */ +export function noteServerBuild(build: string | null | undefined): void { + if (!mine || !build || build === mine || build === latest) return; + latest = build; + emit(); +} + +export function dismissUpdate(): void { + dismissed = latest; + emit(); +} + +async function check(): Promise { + try { + const res = await fetch('/api/version', { cache: 'no-store' }); + if (res.ok) noteServerBuild(((await res.json()) as { build?: string | null }).build); + } catch { + // Offline or restarting: the next check (or the socket's welcome) will tell. + } +} + +/** Call once at startup: checks now and then, and whenever the tab comes back into view. */ +export function initUpdateCheck(): void { + if (!mine) return; + setInterval(() => void check(), POLL_MS); + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible') void check(); + }); +} + +const subscribe = (l: () => void) => { + listeners.add(l); + return () => void listeners.delete(l); +}; + +export function useUpdateAvailable(): boolean { + return useSyncExternalStore(subscribe, () => latest !== null && latest !== dismissed, () => false); +} diff --git a/apps/web/src/styles/global.css b/apps/web/src/styles/global.css index 39bfb84..f51ccbf 100644 --- a/apps/web/src/styles/global.css +++ b/apps/web/src/styles/global.css @@ -170,6 +170,18 @@ textarea.input { padding: 10px 14px; min-height: 90px; resize: vertical; } .avatar img { width: 100%; height: 100%; object-fit: cover; } .announcement { background: var(--primary-soft); padding: 8px 16px; text-align: center; font-weight: 700; border-bottom: 1.5px solid var(--line); } .announcement.maintenance { background: var(--warning-soft); } +/* 업데이트 알림 (same as joke-app): a card at the top, never reloads by itself */ +.update-banner { + position: fixed; top: calc(8px + env(safe-area-inset-top)); left: 50%; transform: translateX(-50%); z-index: 70; + width: min(94vw, 480px); display: flex; align-items: center; gap: 10px; + background: var(--surface); color: var(--text); border: 2px solid var(--primary); border-radius: var(--radius); + box-shadow: 4px 4px 0 var(--ink); padding: 10px 8px 10px 16px; animation: update-in 0.2s ease; +} +@keyframes update-in { from { opacity: 0; transform: translate(-50%, -8px); } } +.update-banner .update-text { flex: 1; min-width: 0; font-weight: 700; } +.update-banner .btn { white-space: nowrap; } +.update-close { flex: none; width: 40px; height: 40px; border: 0; background: transparent; color: var(--text-sub); font-size: 1.2rem; cursor: pointer; border-radius: var(--radius-sm); } +.update-close:hover { background: var(--surface-2); } /* ---------------------------------------------------------------- pages */ .page { max-width: 1440px; margin: 0 auto; padding: 28px 40px; } diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 38897cd..1473013 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -1,8 +1,29 @@ -import { defineConfig } from 'vite'; +import { createHash } from 'node:crypto'; +import { defineConfig, type Plugin } from 'vite'; import react from '@vitejs/plugin-react'; +/** + * Writes `` into index.html: a hash of the built file names, so it changes whenever + * any script or style changes. The server reads it from dist/index.html; an open page compares its own with the + * server's and offers to refresh (업데이트 알림, same as joke-app). + */ +function buildId(): Plugin { + return { + name: 'mq-build-id', + apply: 'build', + transformIndexHtml: { + order: 'post', + handler(_html, ctx) { + const files = Object.keys(ctx.bundle ?? {}).filter((f) => !f.endsWith('.html')).sort().join('\n'); + const build = createHash('sha256').update(files).digest('hex').slice(0, 12); + return [{ tag: 'meta', attrs: { name: 'mq-build', content: build }, injectTo: 'head' }]; + }, + }, + }; +} + export default defineConfig({ - plugins: [react()], + plugins: [react(), buildId()], server: { port: 5173, proxy: { diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts index ee700ff..6a23521 100644 --- a/packages/shared/src/protocol.ts +++ b/packages/shared/src/protocol.ts @@ -141,7 +141,8 @@ export interface GameView { } export type ServerMessage = - | { t: 'welcome'; protocol: number; userId: string; serverNow: number } + /** `build`: the web build the server serves (``), null without one — a different build means "새로고침". */ + | { t: 'welcome'; protocol: number; userId: string; serverNow: number; build: string | null } | { t: 'room'; room: RoomView } | { t: 'left'; code: string; reason: 'leave' | 'kicked' | 'closed' | 'elsewhere' | 'admin' } | { t: 'chat'; code: string; line: ChatLine }