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
|
// ignore_for_file: avoid-late-keyword, avoid-top-level-members-in-tests
/// Shared helpers for the Phase 2 network tests: a [TestGameServer] that
/// boots the real engine + real HTTP/WebSocket stack on an ephemeral port,
/// and a [TestClient] that drives a real WebSocket connection with a
/// message queue.
library;
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'package:collection/collection.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:x_haven_server/core/game_data.dart';
import 'package:x_haven_server/core/save_store.dart';
import 'package:x_haven_server/core/service_locator.dart';
import 'package:x_haven_server/core/state/game_state.dart';
import 'package:x_haven_server/net/app.dart';
import 'package:x_haven_server/net/game_server.dart';
import 'package:x_haven_server/net/protocol.dart';
import 'package:x_haven_server/net/seat_store.dart';
import 'package:x_haven_server/net/sessions.dart';
/// Boots the engine (test data) and a [GameServer] on an ephemeral port.
class TestGameServer {
TestGameServer._();
/// The Dart [HttpServer] on an ephemeral port (port 0).
late HttpServer server;
late GameServer gameServer;
late GameState gameState;
late SessionManager sessions;
late SeatStore seatStore;
static Future<TestGameServer> boot({
SaveStore? saveStore,
SeatStore? seatStore,
Duration heartbeatInterval = const Duration(seconds: 20),
Duration deadTimeout = const Duration(seconds: 90),
String dataDir = 'assets/testData/',
}) async {
// Same bootstrap as test/command/test_helpers.dart's setUpGame(), but
// with the caller's [saveStore] (persistence tests pass a FileSaveStore).
setupCore(saveStore: saveStore ?? InMemorySaveStore());
final gs = getIt<GameState>();
gs.init();
await getIt<GameData>().loadData(dataDir);
gs.load();
final instance = TestGameServer._();
instance.gameState = gs;
instance.sessions = SessionManager();
instance.seatStore = seatStore ?? InMemorySeatStore();
instance.gameServer = GameServer(
gameState: gs,
sessions: instance.sessions,
seatStore: instance.seatStore,
heartbeatInterval: heartbeatInterval,
deadTimeout: deadTimeout,
);
instance.server = await startServer(
port: 0,
staticDir: 'nonexistent-static-dir',
gameServer: instance.gameServer,
dataDir: dataDir,
);
return instance;
}
/// The `ws://` base url for [TestClient.connect].
Uri get wsUrl => Uri.parse('ws://localhost:${server.port}/ws');
/// The `http://` base url for HTTP helpers.
Uri get httpUrl => Uri.parse('http://localhost:${server.port}');
/// Stops the heartbeat, closes the HTTP server, and resets the DI
/// container so the next test can boot a fresh engine.
Future<void> shutdown() async {
gameServer.dispose();
await server.close(force: true);
await getIt.reset();
}
}
/// A fake WS client: a real [WebSocketChannel] with a message queue and
/// typed send helpers.
class TestClient {
TestClient._(this.channel);
final WebSocketChannel channel;
final Queue<Map<String, dynamic>> _queue = Queue();
final List<Completer<Map<String, dynamic>>> _waiters = [];
Completer<void>? _closedCompleter;
bool closed = false;
static Future<TestClient> connect(Uri url, {String? session}) async {
final uri =
session == null
? url
: url.replace(queryParameters: {'session': session});
final channel = WebSocketChannel.connect(uri);
final client = TestClient._(channel);
channel.stream.listen(
(Object? raw) {
final dynamic decoded = jsonDecode(raw as String);
if (decoded is Map<String, dynamic>) client._deliver(decoded);
},
onDone: client._markClosed,
onError: (Object _) => client._markClosed(),
);
await channel.ready;
return client;
}
void _deliver(Map<String, dynamic> message) {
final waiter = _waiters.isNotEmpty ? _waiters.removeAt(0) : null;
if (waiter != null) {
waiter.complete(message);
} else {
_queue.add(message);
}
}
void _markClosed() {
if (closed) return;
closed = true;
_closedCompleter?.complete();
for (final waiter in _waiters) {
waiter.completeError(StateError('connection closed'));
}
_waiters.clear();
}
// --- sending -------------------------------------------------------------
void send(Map<String, dynamic> message) =>
channel.sink.add(jsonEncode(message));
void sendHello({int version = Protocol.version}) =>
send(Protocol.helloMessage());
void sendCmd(String name, [Map<String, dynamic> args = const {}]) =>
send(Protocol.commandMessage(name, args));
void sendClaim(String characterId) => send(Protocol.claimMessage(characterId));
void sendRaw(String raw) => channel.sink.add(raw);
/// Closes the socket from the client side.
Future<void> close() => channel.sink.close();
/// Completes when the connection is closed (by either side).
Future<void> get closedFuture => (_closedCompleter ??= Completer<void>()).future;
// --- receiving -----------------------------------------------------------
/// The next message, with a timeout.
Future<Map<String, dynamic>> next({
Duration timeout = const Duration(seconds: 10),
}) async {
if (_queue.isNotEmpty) return _queue.removeFirst();
final completer = Completer<Map<String, dynamic>>();
_waiters.add(completer);
return completer.future.timeout(
timeout,
onTimeout: () =>
throw TimeoutException('waiting for a message', timeout),
);
}
/// The next message satisfying [test]; earlier non-matching messages are
/// kept (in order) for later [next] calls.
Future<Map<String, dynamic>> nextWhere(
bool Function(Map<String, dynamic>) test, {
Duration timeout = const Duration(seconds: 10),
String why = '',
}) async {
final skipped = <Map<String, dynamic>>[];
while (true) {
final Map<String, dynamic> message;
if (_queue.isNotEmpty) {
message = _queue.removeFirst();
} else {
final completer = Completer<Map<String, dynamic>>();
_waiters.add(completer);
try {
message = await completer.future.timeout(
timeout,
onTimeout: () =>
throw TimeoutException('nextWhere($why)', timeout),
);
} catch (_) {
_waiters.remove(completer);
rethrow;
}
}
if (test(message)) {
_queue.addAll(skipped);
return message;
}
skipped.add(message);
}
}
/// The next message of type [type] (e.g. `'update'`, `'seats'`).
Future<Map<String, dynamic>> nextOf(
String type, {
Duration timeout = const Duration(seconds: 10),
}) =>
nextWhere((m) => m['t'] == type, timeout: timeout, why: type);
/// Drains and returns all messages currently buffered.
List<Map<String, dynamic>> flush() {
final result = _queue.toList();
_queue.clear();
return result;
}
// --- convenience -----------------------------------------------------------
/// The character entry of [characterId] in a state payload.
static Map<String, dynamic>? characterIn(
Map<String, dynamic> state,
String characterId,
) {
final list = state['currentList'];
if (list is! List) return null;
return list.firstWhereOrNull(
(item) => item is Map && item['id'] == characterId,
) as Map<String, dynamic>?;
}
/// The initiative value as delivered on the wire for [characterId]
/// (null = masked or absent).
static int? initiativeIn(Map<String, dynamic> state, String characterId) {
final character = characterIn(state, characterId);
final characterState = character?['characterState'];
if (characterState is! Map) return null;
final initiative = characterState['initiative'];
return initiative is int ? initiative : null;
}
/// The seats payload of a `seats` (or `welcome`) message.
static Map<String, dynamic> seatsOf(Map<String, dynamic> message) =>
Map<String, dynamic>.from(message['seats'] as Map);
}
|