summaryrefslogtreecommitdiff
path: root/server/lib/net/app.dart
blob: db501e4dd30e651aea9202b7a05a552e652dfb96 (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
/// The X-Haven web server: static file serving for the built SPA plus the
/// game WebSocket endpoint at `/ws`.
///
/// Phase 0 scope: serve the SPA (or a stub page), answer the `hello`
/// handshake with `welcome`, ping/pong, and error responses for malformed
/// input. Game state, sessions, seats and secret gating land in later phases
/// (see PLAN.md).
library;

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';

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 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

import 'protocol.dart';

final _log = Logger('server');

/// Builds the HTTP handler for the game server.
Handler createHandler({required String staticDir}) {
  final router = Router();
  router.get('/ws', webSocketHandler(_handleConnection));
  router.get(
    '/healthz',
    (Request request) => Response.ok(
      jsonEncode({'status': 'ok'}),
      headers: {'content-type': 'application/json; charset=utf-8'},
    ),
  );
  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}) {
  return shelf_io.serve(createHandler(staticDir: staticDir), '0.0.0.0', port);
}

void _handleConnection(WebSocketChannel channel, Object? encodable) {
  final session = _newSessionId();
  channel.stream.listen((Object? raw) {
    final String? text = _coerceText(raw);
    if (text == null) {
      _send(channel,
          Protocol.errorMessage(Protocol.errBadRequest, 'expected a UTF-8 JSON message'));
      return;
    }
    final Map<String, dynamic>? message = _decodeMessage(text);
    if (message == null) {
      _send(channel,
          Protocol.errorMessage(Protocol.errBadRequest, 'malformed JSON'));
      return;
    }
    final type = message['t'];
    if (type == Protocol.hello) {
      _send(channel, Protocol.welcomeMessage(
        session: session,
        role: Protocol.roleSpectator,
        index: 0,
        state: const {},
        seats: const {},
      ));
    } else if (type == Protocol.ping) {
      _send(channel, Protocol.pongMessage());
    } else {
      _send(channel, Protocol.errorMessage(
          Protocol.errUnknownMessage, 'unknown message type: $type'));
    }
  }, onDone: () {
    _log.info('session $session closed');
  }, onError: (Object error) {
    _log.warning('session $session connection error: $error');
  });
}

String? _coerceText(Object? raw) {
  if (raw is String) return raw;
  if (raw is List<int>) return utf8.decode(raw, allowMalformed: true);
  return null;
}

Map<String, dynamic>? _decodeMessage(String text) {
  try {
    final dynamic decoded = jsonDecode(text);
    return decoded is Map<String, dynamic> ? decoded : null;
  } catch (_) {
    return null;
  }
}

void _send(WebSocketChannel channel, Map<String, dynamic> message) {
  channel.sink.add(jsonEncode(message));
}

String _newSessionId() {
  final random = Random.secure();
  return List.generate(16, (_) => random.nextInt(16).toRadixString(16)).join();
}

Handler _createStaticHandler(String staticDir) {
  final directory = Directory(staticDir);
  if (!directory.existsSync()) {
    _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>');
  }
  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.
      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'});
      }
    }
    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;
    };
  };
}