-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathFlatBuffersSession.cs
More file actions
533 lines (451 loc) · 19.5 KB
/
FlatBuffersSession.cs
File metadata and controls
533 lines (451 loc) · 19.5 KB
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
using System.Net.Sockets;
using System.Threading.Channels;
using Microsoft.Extensions.Logging;
using RLBot.Flat;
using RLBotCS.ManagerTools;
using RLBotCS.Model;
using RLBotCS.Server.BridgeMessage;
using RLBotCS.Server.ServerMessage;
using StartMatch = RLBotCS.Server.ServerMessage.StartMatch;
namespace RLBotCS.Server;
/// <summary>
/// A message sent to <see cref="FlatBuffersSession"/> from <see cref="FlatBuffersServer"/>.
/// </summary>
interface SessionMessage
{
public readonly record struct MatchConfig(MatchConfigurationT Config) : SessionMessage;
public readonly record struct FieldInfo(FieldInfoT Info) : SessionMessage;
public readonly record struct PlayerIdPairs(uint Team, List<PlayerIdPair> IdMaps)
: SessionMessage;
public readonly record struct DistributeBallPrediction(BallPredictionT BallPrediction)
: SessionMessage;
public readonly record struct DistributeGameState(GamePacketT GameState) : SessionMessage;
public readonly record struct RendersAllowed(bool Allowed) : SessionMessage;
public readonly record struct StateSettingAllowed(bool Allowed) : SessionMessage;
public readonly record struct MatchComm(MatchCommT Message) : SessionMessage;
public readonly record struct StopMatch(bool Force) : SessionMessage;
public readonly record struct UpdateRendering(RenderingStatus Status) : SessionMessage;
public readonly record struct PingResponse() : SessionMessage;
}
class FlatBuffersSession
{
private static readonly ILogger Logger = Logging.GetLogger("FlatBuffersSession");
private readonly TcpClient _client;
private readonly int _clientId;
private readonly SpecStreamReader _socketSpecReader;
private readonly SpecStreamWriter _socketSpecWriter;
private readonly Channel<SessionMessage> _incomingMessages;
private readonly ChannelWriter<IServerMessage> _rlbotServer;
private readonly ChannelWriter<IBridgeMessage> _bridge;
private readonly Dictionary<uint, bool> _gotInput = new();
/// <summary>Indicates that we received a ConnectionSettings message from the client, and that
/// we now know its agent id (if any) and whether it is interested in ball prediction, match comms,
/// and closing between matches.</summary>
private bool _connectionEstablished;
private bool _wantsBallPredictions;
private bool _wantsComms;
private bool _closeBetweenMatches;
/// <summary>Indicates that the client have responded with InitComplete after we sent a ControllableTeamInfo.
/// I.e. it is ready to receive live data. Match runners (with no agent id) never becomes ready.</summary>
private bool _isReady;
private bool _stateSettingIsEnabled;
private bool _renderingIsEnabled;
private string _agentId = string.Empty;
private uint _team = Team.Other;
private List<PlayerIdPair> _playerIdPairs = new();
private bool _sessionForceClosed;
private bool _closed;
public string ClientName =>
_agentId != ""
? $"client {_clientId} (index {string.Join("+", _playerIdPairs.Select(p => p.Index))}, team {_team}, aid {_agentId})"
: $"client {_clientId} (w/o aid)";
public FlatBuffersSession(
TcpClient client,
int clientId,
Channel<SessionMessage> incomingMessages,
ChannelWriter<IServerMessage> rlbotServer,
ChannelWriter<IBridgeMessage> bridge,
DebugRendering renderingIsEnabled,
bool stateSettingIsEnabled
)
{
_client = client;
_clientId = clientId;
_incomingMessages = incomingMessages;
_rlbotServer = rlbotServer;
_bridge = bridge;
_renderingIsEnabled = renderingIsEnabled switch
{
DebugRendering.OnByDefault => true,
_ => false,
};
_stateSettingIsEnabled = stateSettingIsEnabled;
NetworkStream stream = _client.GetStream();
_socketSpecReader = new SpecStreamReader(stream);
_socketSpecWriter = new SpecStreamWriter(stream);
}
private async Task<bool> ParseClientMessage(InterfacePacket msg)
{
switch (msg.MessageType)
{
case InterfaceMessage.NONE:
Logger.LogError(
$"Received a message with type NONE from {ClientName}. "
+ "Something has gone very wrong. Disconnecting."
);
return false;
case InterfaceMessage.DisconnectSignal:
// The client requested that we close the connection
return false;
case InterfaceMessage.ConnectionSettings when !_connectionEstablished:
var readyMsg = msg.MessageAsConnectionSettings();
_agentId = (readyMsg.AgentId ?? "").Trim();
_wantsBallPredictions = readyMsg.WantsBallPredictions;
_wantsComms = readyMsg.WantsComms;
_closeBetweenMatches = readyMsg.CloseBetweenMatches;
if (_agentId != "" && !_closeBetweenMatches)
{
Logger.LogError(
$"Detected a client with close_between_matches=False AND a non-empty agent id '{_agentId}'. "
+ $"These settings are incompatible. Disconnecting."
);
return false;
}
await _rlbotServer.WriteAsync(
new IntroDataRequest(_clientId, _incomingMessages.Writer, _agentId)
);
_connectionEstablished = true;
break;
case InterfaceMessage.SetLoadout when _connectionEstablished:
if (_isReady && !_stateSettingIsEnabled)
break;
var setLoadout = msg.MessageAsSetLoadout().UnPack();
if (_isReady)
{
// state setting is enabled,
// allow setting the loadout of any bots post-init
await _bridge.WriteAsync(
new StateSetLoadout(setLoadout.Loadout, setLoadout.Index)
);
}
else
{
// ensure the provided index is a bot we control,
// and map the index to the spawn id
PlayerIdPair? maybeIdPair = _playerIdPairs.FirstOrDefault(idPair =>
idPair.Index == setLoadout.Index
);
if (maybeIdPair is { } pair)
{
await _bridge.WriteAsync(
new SetInitLoadout(setLoadout.Loadout, pair.PlayerId)
);
}
else
{
var owned = string.Join(", ", _playerIdPairs.Select(p => p.Index));
Logger.LogWarning(
$"Client tried to set loadout of player it does not own "
+ $"(index(es) owned: {owned},"
+ $" got: {setLoadout.Index})"
);
}
}
break;
case InterfaceMessage.InitComplete when _connectionEstablished && !_isReady:
if (_closeBetweenMatches)
{
await _bridge.WriteAsync(new SessionReady(_clientId));
}
Logger.LogDebug("InitComplete from {}", ClientName);
_isReady = true;
break;
case InterfaceMessage.StopCommand:
var stopCommand = msg.MessageAsStopCommand();
await _rlbotServer.WriteAsync(new StopMatch(stopCommand.ShutdownServer));
break;
case InterfaceMessage.StartCommand:
var startCommand = msg.MessageAsStartCommand();
var parser = new ConfigParser();
if (
parser.TryLoadMatchConfig(startCommand.ConfigPath, out var tomlMatchConfig)
&& ConfigValidator.Validate(tomlMatchConfig)
)
{
await _rlbotServer.WriteAsync(new StartMatch(tomlMatchConfig));
}
break;
case InterfaceMessage.MatchConfiguration:
var matchConfig = msg.MessageAsMatchConfiguration().UnPack();
if (ConfigValidator.Validate(matchConfig))
{
await _rlbotServer.WriteAsync(new StartMatch(matchConfig));
}
break;
case InterfaceMessage.PlayerInput when _connectionEstablished:
var playerInputMsg = msg.MessageAsPlayerInput().UnPack();
// ensure the provided index is a bot we control
if (
!_stateSettingIsEnabled
&& !_playerIdPairs.Any(playerInfo =>
playerInfo.Index == playerInputMsg.PlayerIndex
)
)
{
var owned = string.Join(", ", _playerIdPairs.Select(p => p.Index));
Logger.LogWarning(
$"Client tried to set loadout of player it does not own"
+ $" (index(es) owned: {owned},"
+ $" got: {playerInputMsg.PlayerIndex})"
);
break;
}
_gotInput[playerInputMsg.PlayerIndex] = true;
await _bridge.WriteAsync(new Input(playerInputMsg));
break;
case InterfaceMessage.MatchComm:
var matchComms = msg.MessageAsMatchComm().UnPack();
if (_agentId != "")
{
// ensure the team is correctly set
matchComms.Team = _team;
// ensure the provided index is a bot we control,
// and map the index to the spawn id
PlayerIdPair? playerIdPair = _playerIdPairs.FirstOrDefault(idPair =>
idPair.Index == matchComms.Index
);
if (playerIdPair != null)
{
await _rlbotServer.WriteAsync(
new SendMatchComm(_clientId, matchComms)
);
await _bridge.WriteAsync(new ShowQuickChat(matchComms));
}
}
else if (_agentId == "" && _connectionEstablished)
{
// Client is a match manager.
// We allow these to send match comms to bots/scripts too, e.g. for briefing.
// They will not appear in quick chat.
matchComms.Index = 0;
matchComms.Team = Team.Other;
matchComms.TeamOnly = false;
await _rlbotServer.WriteAsync(new SendMatchComm(_clientId, matchComms));
}
break;
case InterfaceMessage.RenderGroup:
if (!_renderingIsEnabled)
break;
var renderingGroup = msg.MessageAsRenderGroup().UnPack();
await _bridge.WriteAsync(
new AddRenders(_clientId, renderingGroup.Id, renderingGroup.RenderMessages)
);
break;
case InterfaceMessage.RemoveRenderGroup:
if (!_renderingIsEnabled)
break;
var removeRenderGroup = msg.MessageAsRemoveRenderGroup();
await _bridge.WriteAsync(new RemoveRenders(_clientId, removeRenderGroup.Id));
break;
case InterfaceMessage.DesiredGameState:
if (!_stateSettingIsEnabled)
break;
var desiredGameState = msg.MessageAsDesiredGameState().UnPack();
await _bridge.WriteAsync(new SetGameState(desiredGameState));
break;
case InterfaceMessage.RenderingStatus:
var renderingStatus = msg.MessageAsRenderingStatus();
await _rlbotServer.WriteAsync(new UpdateRendering(renderingStatus));
break;
case InterfaceMessage.PingRequest:
_incomingMessages.Writer.TryWrite(new SessionMessage.PingResponse());
break;
}
return true;
}
private void SendPayloadToClient(CoreMessageUnion payload)
{
try
{
_socketSpecWriter.Write(payload);
_socketSpecWriter.Send();
}
catch (ObjectDisposedException)
{
// we disconnected before the message could be sent
return;
}
catch (IOException)
{
// client disconnected before we could send the message
return;
}
}
private async Task HandleInternalMessages()
{
await foreach (SessionMessage message in _incomingMessages.Reader.ReadAllAsync())
switch (message)
{
case SessionMessage.FieldInfo m:
SendPayloadToClient(CoreMessageUnion.FromFieldInfo(m.Info));
break;
case SessionMessage.MatchConfig m:
SendPayloadToClient(CoreMessageUnion.FromMatchConfiguration(m.Config));
break;
case SessionMessage.PlayerIdPairs m:
_team = m.Team;
_playerIdPairs = m.IdMaps;
List<ControllableInfoT> controllables = _playerIdPairs
.Select(playerInfo => new ControllableInfoT()
{
Index = playerInfo.Index,
Identifier = playerInfo.PlayerId,
})
.ToList();
ControllableTeamInfoT playerMappings = new()
{
Team = m.Team,
Controllables = controllables,
};
SendPayloadToClient(
CoreMessageUnion.FromControllableTeamInfo(playerMappings)
);
Logger.LogDebug("Reserved agents for {}", ClientName);
break;
case SessionMessage.DistributeBallPrediction m
when _isReady && _wantsBallPredictions:
SendPayloadToClient(CoreMessageUnion.FromBallPrediction(m.BallPrediction));
break;
case SessionMessage.DistributeGameState m when _isReady:
SendPayloadToClient(CoreMessageUnion.FromGamePacket(m.GameState));
foreach (var (index, gotInput) in _gotInput)
{
await _bridge.WriteAsync(new AddPerfSample(index, gotInput));
_gotInput[index] = false;
}
break;
case SessionMessage.RendersAllowed m:
_renderingIsEnabled = m.Allowed;
break;
case SessionMessage.StateSettingAllowed m:
_stateSettingIsEnabled = m.Allowed;
break;
case SessionMessage.MatchComm m when _wantsComms:
// Do not distribute this match comm to our client in certain cases.
// Match managers with no agent id receive all messages.
if (_agentId != "")
{
if (!_isReady)
{
break;
}
if (m.Message.TeamOnly && m.Message.Team != _team)
{
break;
}
}
SendPayloadToClient(CoreMessageUnion.FromMatchComm(m.Message));
break;
case SessionMessage.StopMatch m
when m.Force || (_connectionEstablished && _closeBetweenMatches):
_sessionForceClosed = m.Force;
return;
case SessionMessage.UpdateRendering m
when (m.Status.IsBot && (_team == Team.Blue || _team == Team.Orange))
|| (!m.Status.IsBot && _team == Team.Scripts):
foreach (var player in _playerIdPairs)
{
if (player.Index == m.Status.Index)
{
_renderingIsEnabled = m.Status.Status;
SendPayloadToClient(
CoreMessageUnion.FromRenderingStatus(
new RenderingStatusT()
{
Index = player.Index,
IsBot = m.Status.IsBot,
Status = m.Status.Status,
}
)
);
break;
}
}
break;
case SessionMessage.PingResponse m:
SendPayloadToClient(
CoreMessageUnion.FromPingResponse(new PingResponseT())
);
break;
}
}
private async Task HandleClientMessages()
{
await foreach (InterfacePacket message in _socketSpecReader.ReadAllAsync())
{
// if the session is closed, ignore any incoming messages
// this should allow the client to close cleanly
if (_closed)
continue;
bool keepRunning = await ParseClientMessage(message);
if (keepRunning)
continue;
return;
}
}
public void BlockingRun()
{
Task incomingMessagesTask = Task.Run(async () =>
{
try
{
await HandleInternalMessages();
}
catch (Exception e)
{
Logger.LogError($"Error while handling incoming messages: {e}");
}
});
Task clientMessagesTask = Task.Run(async () =>
{
try
{
await HandleClientMessages();
}
catch (Exception e)
{
Logger.LogError($"Error while handling client messages: {e}");
}
});
Task.WhenAny(incomingMessagesTask, clientMessagesTask).Wait();
}
public void Cleanup()
{
Logger.LogInformation("Closing session for {}", ClientName);
_connectionEstablished = false;
_isReady = false;
_incomingMessages.Writer.TryComplete();
_bridge.TryWrite(new UnreserveAgents(_clientId));
// try to politely close the connection
try
{
SendPayloadToClient(
CoreMessageUnion.FromDisconnectSignal(new DisconnectSignalT())
);
}
catch (Exception)
{
// if an exception was thrown, the client disconnected first
}
finally
{
// remove this session from the server
_rlbotServer.TryWrite(new SessionClosed(_clientId));
// if we're trying to shut down cleanly,
// let the bot finish sending messages and close the connection itself
_closed = true;
if (!_sessionForceClosed)
_client.Close();
}
}
}