summaryrefslogtreecommitdiff
path: root/server/lib/net/app.dart
blob: 1d66c4948bf830fb8ca53443105f283d49cb53f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/// The X-Haven web server: static file serving for the built SPA, the
/// session endpoint, and the game WebSocket endpoint at `/ws`.
library;

import 'dart:convert';
import 'dart:io';

import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf_static/shelf_static.dart';

import 'game_server.dart';
import 'sessions.dart';
import 'ws_upgrade.dart';

final _log = Logger('server');

/// One year, in seconds — the cache lifetime for immutable assets
/// (PLAN.md Phase 7 "Performance").
const int _kCacheYearSeconds = 60 * 60 * 24 * 365;

/// `Cache-Control` for assets that are never mutated in place: the game
/// data, images, in-game translations, and the content-hashed build
/// outputs. Browsers keep them for a year and never revalidate.
const String _kImmutableCacheControl =
    'public, max-age=$_kCacheYearSeconds, immutable';

/// `Cache-Control` for the SPA entry point: always revalidate, so a
/// rebuilt app reaches open tabs on the next navigation.
const String _kNoCacheControl = 'no-cache';

/// Builds the HTTP handler for the game server.
///
/// [dataDir] (e.g. `assets/data/`) is served read-only at `/data/` when
/// non-null: the client's menus read the campaign/scenario/character/section
/// JSON from it (the same files the engine loads). [imageDir] (e.g.
/// `assets/images/`) is served at `/images/` when non-null — character and
/// monster artwork for the main list. [i18nDir] (e.g. `assets/i18n/`) is
/// served at `/i18n/` when non-null — the in-game ability-text translations
/// the client's card renderer resolves (the reference app's
/// `TranslationService`, PLAN.md Phase 4).
Handler createHandler({
  required String staticDir,
  required GameServer gameServer,
  String? dataDir,
  String? imageDir,
  String? i18nDir,
}) {
  final router = Router();
  router.get('/ws', createWebSocketUpgradeHandler(gameServer));
  router.get('/healthz', (Request request) => Response.ok(
    jsonEncode({'status': 'ok'}),
    headers: {'content-type': 'application/json; charset=utf-8'},
  ));
  if (dataDir != null) {
    router.mount('/data/', _createStaticHandler(dataDir, plain: true));
  }
  if (imageDir != null) {
    router.mount('/images/', _createStaticHandler(imageDir, plain: true));
  }
  if (i18nDir != null) {
    router.mount('/i18n/', _createStaticHandler(i18nDir, plain: true));
  }
  // Session endpoint (PLAN.md section 3.3): returns the caller's persistent
  // session id, setting the `x-haven-session` cookie when the caller has
  // none yet. Browsers then carry the cookie on every same-origin request,
  // including the `/ws` upgrade — so a player keeps their seat across page
  // refreshes.
  router.get('/session', (Request request) {
    final existing = _validSessionIdFrom(request);
    final Map<String, String> headers = {
      'content-type': 'application/json; charset=utf-8',
    };
    if (existing != null) {
      return Response.ok(jsonEncode({'session': existing}), headers: headers);
    }
    final id = SessionManager.newSessionId();
    headers['set-cookie'] =
        '$sessionCookieName=$id; Path=/; HttpOnly; SameSite=Lax';
    return Response.ok(jsonEncode({'session': id}), headers: headers);
  });
  router.mount('/', _createStaticHandler(staticDir));
  return const Pipeline().addMiddleware(_logRequests()).addHandler(router);
}

/// Starts the server on [port] (0 for an ephemeral port).
Future<HttpServer> startServer({
  required int port,
  required String staticDir,
  required GameServer gameServer,
  String? dataDir,
  String? imageDir,
  String? i18nDir,
}) {
  return shelf_io.serve(
    createHandler(
      staticDir: staticDir,
      gameServer: gameServer,
      dataDir: dataDir,
      imageDir: imageDir,
      i18nDir: i18nDir,
    ),
    '0.0.0.0',
    port,
  );
}

/// The session id from [request]'s cookie, when well-formed.
String? _validSessionIdFrom(Request request) {
  final cookie = request.headers['Cookie'];
  if (cookie == null) return null;
  for (final part in cookie.split(';')) {
    final trimmed = part.trim();
    if (trimmed.startsWith('$sessionCookieName=')) {
      final value = trimmed.substring(sessionCookieName.length + 1).trim();
      if (SessionManager.isKnownFormat(value)) return value;
    }
  }
  return null;
}

/// Serves [staticDir] as static files. When [plain] is true (data/image
/// directories) it is plain static serving with a cache header and a plain
/// 404; otherwise (the SPA build) a 404 on an extensionless path falls back
/// to `index.html` so client-side routes resolve.
Handler _createStaticHandler(String staticDir, {bool plain = false}) {
  final directory = Directory(staticDir);
  if (!directory.existsSync()) {
    if (plain) {
      _log.info('data dir $staticDir not found; serving 404');
      return (Request request) => Response.notFound('not found');
    }
    _log.info('static dir $staticDir not found; serving stub page');
    return (Request request) => Response.ok(
      '<!doctype html><meta charset="utf-8">'
      '<title>X-Haven</title>'
      '<body style="font-family:system-ui;background:#15181d;color:#e6e8ee">'
      '<h1>X-Haven server</h1>'
      '<p>Running, but the web app is not built yet. '
      'Run <code>npm run build</code> in <code>web/</code> and restart '
      'with <code>--static-dir ../web/dist</code>.</p>',
    );
  }
  if (plain) {
    // Plain static serving (no SPA fallback) for the game data, images, and
    // in-game translations — immutable build inputs: cached for a year
    // without revalidation (the 66 MB image set is the big win here).
    final inner = createStaticHandler(directory.path);
    return (Request request) async {
      final response = await inner(request);
      if (response.statusCode == 200) {
        return response
            .change(headers: {'cache-control': _kImmutableCacheControl});
      }
      return response;
    };
  }
  final staticHandler = createStaticHandler(
    directory.path,
    defaultDocument: 'index.html',
  );
  return (Request request) async {
    final response = await staticHandler(request);
    if (response.statusCode == 404 &&
        request.method == 'GET' &&
        !request.url.path.contains('.')) {
      // SPA fallback: routes without a file extension get index.html —
      // no-cache, like the real file, so deploys reach open tabs.
      final indexFile = File(p.join(directory.path, 'index.html'));
      if (await indexFile.exists()) {
        return Response.ok(
          await indexFile.readAsString(),
          headers: {
            'content-type': 'text/html; charset=utf-8',
            'cache-control': _kNoCacheControl,
          },
        );
      }
      return response;
    }
    if (response.statusCode == 200) {
      // index.html is revalidated every navigation; everything else in the
      // build is content-hashed (or a stable font) and immutable.
      // (shelf_router strips the `/` mount prefix, so the handler sees
      // `index.html` / `` rather than `/index.html` / `/`.)
      final path = request.url.path;
      final isIndex =
          path.isEmpty || path == '/' || path.endsWith('index.html');
      return response.change(
        headers: {
          'cache-control': isIndex ? _kNoCacheControl : _kImmutableCacheControl,
        },
      );
    }
    return response;
  };
}

Middleware _logRequests() {
  return (Handler inner) {
    return (Request request) async {
      final stopwatch = Stopwatch()..start();
      final response = await inner(request);
      stopwatch.stop();
      _log.info(
        '${request.method} ${request.requestedUri.path} -> '
        '${response.statusCode} (${stopwatch.elapsedMilliseconds}ms)',
      );
      return response;
    };
  };
}