summaryrefslogtreecommitdiff
path: root/server/tool/perf_measure.dart
blob: 98c5adbf1d8e9f0d9e34e0e6dfee7517324d5fc8 (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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// Performance probe (PLAN.md Phase 7 "Performance").
//
// Boots the real server on a free port with a temp saves dir, connects N
// WebSocket clients (a full table, each a distinct session), plays a
// realistic round, and reports:
//
//   * the state payload size at full-table scale (the largest
//     `update`/`welcome` frame, and the raw `state` JSON inside it)
//   * WS fan-out: bytes delivered to ALL connections per executed action
//   * total traffic per connection over the whole round
//
// Run from `server/`:
//
// ```sh
// dart run tool/perf_measure.dart            # 6 clients
// dart run tool/perf_measure.dart --clients 8
// ```
//
// This is a measurement tool, not part of the product or the test suite.

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

Future<void> main(List<String> args) async {
  var clients = 6;
  for (var i = 0; i < args.length; i++) {
    if (args[i] == '--clients' && i + 1 < args.length) {
      clients = int.parse(args[i + 1]);
    }
  }

  final port = await _freePort();
  final savesDir = Directory.systemTemp.createTempSync('xhaven-perf-').path;
  final server = await Process.start(
    'dart',
    ['run', 'bin/main.dart', '--port=$port', '--saves-dir=$savesDir'],
  );
  server.stdout
      .transform(utf8.decoder)
      .transform(const LineSplitter())
      .listen(stdout.write);
  server.stderr
      .transform(utf8.decoder)
      .transform(const LineSplitter())
      .listen((l) => stderr.writeln('[server] $l'));

  try {
    await _waitForHttp('http://127.0.0.1:$port/healthz', 90_000);
    await _run(port, clients);
  } finally {
    server.kill(ProcessSignal.sigkill);
    unawaited(server.exitCode
        .timeout(const Duration(seconds: 3), onTimeout: () => -1));
    Directory(savesDir).deleteSync(recursive: true);
  }
  // The measurement is printed; exit regardless of lingering sockets.
  exit(0);
}

Future<void> _run(int port, int clients) async {
  // Jaws of the Lion has exactly these four classes, and the reference app
  // (and ours) forbids duplicate regular classes, so a JoL table has at most
  // four player characters. Extra connections are spectators — which is
  // exactly the fan-out we want to measure.
  final names = ['Hatchet', 'Demolitionist', 'Red Guard', 'Voidwarden'];
  final players = min(clients, names.length);

  final all = <_Client>[];
  for (var i = 0; i < clients; i++) {
    final c = _Client(i);
    await c.connect('ws://127.0.0.1:$port/ws');
    all.add(c);
  }
  await Future<void>.delayed(const Duration(milliseconds: 200));

  // --- setup ----------------------------------------------------------------
  // Every client adds its own character (the onboarding path; each session
  // becomes a player).
  await _action(
      all,
      'setup: $players players add characters',
      (i) => i < players
          ? all[i].cmd('addCharacter', {
                'id': names[i],
                'edition': 'Jaws of the Lion',
                'level': 1
              })
          : null);

  await _action(all, 'set scenario',
      (i) => i == 0
          ? all[0].cmd('setScenario', {
                'scenario': '#1 Roadside Ambush',
                'section': false
              })
          : null);

  final monsters = [
    'Zealot',
    'Vermling Raider',
    'Black Sludge',
    'Rat Monstrosity',
    'Blood Imp',
    'Blood Monstrosity',
    'Chaos Demon',
    'Blood Tumor',
    'Blood Horror',
    'First of the Order'
  ];
  for (var m = 0; m < monsters.length; m++) {
    await _action(
        all,
        'add monster ${m + 1}/${monsters.length}',
        (i) => i == 0
            ? all[0].cmd('addMonster', {'name': monsters[m], 'isAlly': false})
            : null);
  }

  // --- three full rounds -------------------------------------------------------
  for (var round = 1; round <= 3; round++) {
    for (var i = 0; i < players; i++) {
      await _action(
          all,
          'round $round: player $i sets initiative',
          (j) => j == i
              ? all[j]
                  .cmd('setInit', {'characterId': all[j].myCharacterId!, 'init': i + 1})
              : null);
    }
    await _action(all, 'round $round: draw',
        (i) => i == 0 ? all[0].cmd('draw', {}) : null);
    for (var i = 0; i < players; i++) {
      await _action(
          all,
          'round $round: player $i ends turn',
          (j) =>
              j == i ? all[j].cmd('turnDone', {'id': all[j].myCharacterId!}) : null);
    }
    if (round < 3) {
      await _action(all, 'round $round: next round',
          (i) => i == 0 ? all[0].cmd('nextRound', {}) : null);
    }
  }

  await Future<void>.delayed(const Duration(milliseconds: 300));

  // --- summary -----------------------------------------------------------------
  var maxFrame = 0;
  var maxState = 0;
  for (final c in all) {
    maxFrame = max(maxFrame, c.largestFrameBytes);
    maxState = max(maxState, c.lastStateBytes);
  }
  stdout
    ..writeln('')
    ..writeln('--- summary ($clients connected clients) ---')
    ..writeln('');
  for (final c in all) {
    stdout.writeln(
        'client ${c.id}: ${_kb(c.totalReceived)} total '
        'over ${c.frames} frames '
        '(largest frame ${(c.largestFrameBytes / 1024).toStringAsFixed(1)} kB)');
  }
  stdout
    ..writeln('')
    ..writeln('state JSON at full-table scale: ${_kb(maxState)}')
    ..writeln('largest update frame (envelope + state): ${_kb(maxFrame)}')
    ..writeln('')
    ..writeln('fan-out per executed action: '
        '${_kb(maxFrame)} x $clients = ${_kb(maxFrame * clients)}')
    ..writeln('')
    ..writeln(
        'note: the full-snapshot protocol trades bandwidth for simplicity — '
        'every action re-sends the whole state to every connection, so the '
        'per-action cost is O(state size x connections).');
  // Best-effort teardown; a slow close must not wedge the probe.
  for (final c in all) {
    unawaited(c.close().timeout(const Duration(seconds: 2), onTimeout: () {}));
  }
}

/// Runs [fn(i)] (one client's command, or null) and resolves when every
/// client has observed the resulting update. Waiters are registered BEFORE
/// the command is sent, so no update can be missed.
Future<void> _action(
  List<_Client> all,
  String label,
  Future<void>? Function(int i) fn,
) async {
  final waits = all.map((c) => c.nextUpdate()).toList();
  for (var i = 0; i < all.length; i++) {
    await fn(i); // null for the non-senders
  }
  final sw = Stopwatch()..start();
  await Future.wait(waits).timeout(
      const Duration(seconds: 20),
      onTimeout: () =>
          throw TimeoutException('$label: the update never arrived — the '
              'command was probably rejected (see error output above)'));
  stdout.writeln(
      '${label.padRight(42)} '
      '${(sw.elapsedMilliseconds / 1000).toStringAsFixed(2)} s wall clock');
}

/// One WS client that counts every frame it receives.
class _Client {
  final int id;
  WebSocket? _ws;
  var totalReceived = 0;
  var frames = 0;
  var largestFrameBytes = 0;
  var lastStateBytes = 0;
  String? myCharacterId;
  final List<Completer<void>> _frameWaiters = [];

  _Client(this.id);

  Future<void> connect(String url) async {
    final socket = await WebSocket.connect(url);
    _ws = socket;
    socket.listen(_onData, onError: (Object e) => stderr.writeln('[c$id] $e'));
    await _send({'t': 'hello', 'v': 1});
    await nextUpdate().timeout(const Duration(seconds: 20)); // the welcome
  }

  void _onData(Object? data) {
    final text = data is String ? data : utf8.decode(data as List<int>);
    totalReceived += text.length;
    frames++;
    largestFrameBytes = max(largestFrameBytes, text.length);
    final Map<String, dynamic> msg;
    try {
      msg = jsonDecode(text) as Map<String, dynamic>;
    } catch (_) {
      return; // ignore non-JSON frames
    }
    if (msg['t'] == 'error') {
      stderr.writeln('[c$id] error: ${msg['message']}');
    }
    if (msg['t'] == 'welcome' || msg['t'] == 'update') {
      // The full state travels as a JSON object under `state`.
      final state = msg['state'];
      if (state is Map) {
        lastStateBytes = jsonEncode(state).length;
        myCharacterId ??= _firstCharacterId(state);
      }
      if (_frameWaiters.isNotEmpty) {
        _frameWaiters.removeAt(0).complete();
      }
    }
  }

  /// Resolves on the next state-carrying frame (welcome/update).
  Future<void> nextUpdate() {
    final completer = Completer<void>();
    _frameWaiters.add(completer);
    return completer.future;
  }

  Future<void> _send(Map<String, Object?> message) async {
    final s = _ws;
    if (s == null) throw StateError('not connected');
    s.add(jsonEncode(message));
  }

  Future<void> cmd(String name, Map<String, Object?> args) async {
    await _send({'t': 'cmd', 'name': name, 'args': args});
  }

  Future<void> close() async {
    await _ws?.close();
  }
}

String? _firstCharacterId(Map state) {
  final list = state['currentList'] as List?;
  for (final e in list ?? <dynamic>[]) {
    final item = e as Map<String, dynamic>?;
    if (item != null && item['characterClass'] != null) {
      return item['id'] as String?;
    }
  }
  return null;
}

String _kb(int bytes) => '${(bytes / 1024).toStringAsFixed(1)} kB';

Future<int> _freePort() async {
  final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  final port = s.port;
  await s.close();
  return port;
}

Future<void> _waitForHttp(String url, int timeoutMs) async {
  final deadline = DateTime.now().add(Duration(milliseconds: timeoutMs));
  while (DateTime.now().isBefore(deadline)) {
    try {
      final client = HttpClient();
      final req = await client.getUrl(Uri.parse(url))
          .timeout(const Duration(seconds: 2));
      final resp = await req.close();
      final code = resp.statusCode;
      client.close();
      if (code == 200) return;
    } catch (_) {}
    await Future<void>.delayed(const Duration(milliseconds: 250));
  }
  throw TimeoutException('server did not start: $url');
}