-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectionSupervisor.cs
More file actions
1711 lines (1550 loc) · 67.9 KB
/
Copy pathConnectionSupervisor.cs
File metadata and controls
1711 lines (1550 loc) · 67.9 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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Collections.Concurrent;
using System.Security.Cryptography;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RustPlusBot.Abstractions.Chat;
using RustPlusBot.Abstractions.Connections;
using RustPlusBot.Abstractions.Credentials;
using RustPlusBot.Abstractions.Events;
using RustPlusBot.Abstractions.Time;
using RustPlusBot.Discord.Notifications;
using RustPlusBot.Domain.Connections;
using RustPlusBot.Domain.Credentials;
using RustPlusBot.Features.Connections.Listening;
using RustPlusBot.Persistence.Alarms;
using RustPlusBot.Persistence.Connections;
using RustPlusBot.Persistence.Servers;
using RustPlusBot.Persistence.StorageMonitors;
using RustPlusBot.Persistence.Switches;
namespace RustPlusBot.Features.Connections.Supervisor;
/// <summary>Bundles the security/notification collaborators injected into <see cref="ConnectionSupervisor"/>.</summary>
/// <param name="DmSender">DMs an owner when their credential is rejected.</param>
/// <param name="Protector">Unprotects stored tokens before connecting.</param>
internal sealed record ConnectionSecurity(IUserDmSender DmSender, ICredentialProtector Protector);
/// <summary>Default <see cref="IConnectionSupervisor"/>: one connect->heartbeat->failover loop per (guild, server).</summary>
/// <param name="source">Creates sockets (RustPlusApi in production, a fake in tests).</param>
/// <param name="scopeFactory">Opens scopes for the scoped stores.</param>
/// <param name="security">Bundles the security/notification collaborators.</param>
/// <param name="eventBus">Publishes ConnectionStatusChangedEvent on state changes.</param>
/// <param name="clock">Wall-clock source used for AFK hysteresis timestamps.</param>
/// <param name="options">Timeouts/backoff/heartbeat settings.</param>
/// <param name="logger">The logger.</param>
internal sealed partial class ConnectionSupervisor(
IRustSocketSource source,
IServiceScopeFactory scopeFactory,
ConnectionSecurity security,
IEventBus eventBus,
IClock clock,
IOptions<ConnectionOptions> options,
ILogger<ConnectionSupervisor> logger)
: IConnectionSupervisor, IChatSender, IRustServerQuery, IAfkState, IAsyncDisposable
{
private readonly ConcurrentDictionary<(ulong Guild, Guid Server), Handle> _connections = new();
private readonly SemaphoreSlim _gate = new(1, 1);
private readonly ConcurrentDictionary<(ulong Guild, Guid Server), LiveSocket> _liveSockets = new();
private readonly ConnectionOptions _options = options.Value;
/// <summary>
/// Last status this process REACHED THE PUBLISH STEP WITH per key — the store's persisted status
/// survives restarts and would falsely report Connected at boot. Recorded before bus delivery on
/// purpose: WasConnected must reflect what the supervisor observed, so a failed/cancelled delivery
/// of a Connected event cannot make the next real drop skip its unreachable sweep.
/// </summary>
private readonly ConcurrentDictionary<(ulong Guild, Guid Server), ConnectionStatus> _publishedStatuses = new();
private readonly CancellationTokenSource _shutdown = new();
private bool _disposed;
/// <inheritdoc />
public Task<IReadOnlyList<AfkMember>?> GetAfkMembersAsync(
ulong guildId,
Guid serverId,
CancellationToken cancellationToken)
{
if (_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return Task.FromResult<IReadOnlyList<AfkMember>?>(live.Tracker.CurrentAfk(clock.UtcNow));
}
return Task.FromResult<IReadOnlyList<AfkMember>?>(null);
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
// The supervisor is registered as one singleton backing three service types (IConnectionSupervisor,
// IChatSender, and the concrete type), so the DI container may invoke DisposeAsync more than once.
if (_disposed)
{
return;
}
_disposed = true;
await StopAllAsync().ConfigureAwait(false);
_shutdown.Dispose();
_gate.Dispose();
}
/// <inheritdoc />
public async Task<ChatSendResult> SendAsync(
ChatChannelKind kind,
ulong guildId,
Guid serverId,
string message,
CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return ChatSendResult.NotConnected;
}
try
{
switch (kind)
{
case ChatChannelKind.Team:
await live.Connection.SendTeamMessageAsync(message, cancellationToken).ConfigureAwait(false);
break;
case ChatChannelKind.Clan:
await live.Connection.SendClanMessageAsync(message, cancellationToken).ConfigureAwait(false);
break;
default:
return ChatSendResult.Failed;
}
return ChatSendResult.Sent;
}
catch (OperationCanceledException)
{
throw;
}
#pragma warning disable CA1031 // Broad catch: a failed relay send must not crash the caller; report Failed.
catch (Exception ex)
#pragma warning restore CA1031
{
LogSendFailed(logger, ex, serverId);
return ChatSendResult.Failed;
}
}
/// <inheritdoc />
public async Task StartAllAsync(CancellationToken cancellationToken = default)
{
IReadOnlyList<(ulong GuildId, Guid ServerId)> servers;
var scope = scopeFactory.CreateAsyncScope();
await using (scope.ConfigureAwait(false))
{
var store = scope.ServiceProvider.GetRequiredService<IConnectionStore>();
servers = await store.ListConnectableServersAsync(cancellationToken).ConfigureAwait(false);
}
foreach (var (guildId, serverId) in servers)
{
await EnsureConnectionAsync(guildId, serverId, cancellationToken).ConfigureAwait(false);
}
}
/// <inheritdoc />
public async Task EnsureConnectionAsync(ulong guildId, Guid serverId, CancellationToken cancellationToken = default)
{
var key = (guildId, serverId);
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
await StopConnectionAsync(key).ConfigureAwait(false);
if (_shutdown.IsCancellationRequested)
{
return;
}
var cts = CancellationTokenSource.CreateLinkedTokenSource(_shutdown.Token);
_connections[key] = new Handle(cts, Task.Run(() => RunAsync(key, cts.Token), CancellationToken.None));
}
finally
{
_gate.Release();
}
}
/// <inheritdoc />
public async Task StopAsync(ulong guildId, Guid serverId)
{
// CancellationToken.None, not _shutdown.Token: teardown must still acquire the gate after
// StopAllAsync has already cancelled _shutdown, otherwise the connection is never stopped.
await _gate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
try
{
await StopConnectionAsync((guildId, serverId)).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
/// <inheritdoc />
public async Task StopAllAsync()
{
await _shutdown.CancelAsync().ConfigureAwait(false);
// CancellationToken.None: _shutdown was just cancelled, so waiting on it would abandon shutdown.
await _gate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
try
{
foreach (var key in _connections.Keys.ToList())
{
await StopConnectionAsync(key).ConfigureAwait(false);
}
}
finally
{
_gate.Release();
}
}
/// <inheritdoc />
public async Task<ServerInfoSnapshot?> GetServerInfoAsync(
ulong guildId,
Guid serverId,
CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return null;
}
return await live.Connection.GetServerInfoAsync(_options.HeartbeatTimeout, cancellationToken)
.ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<ServerTimeSnapshot?> GetTimeAsync(ulong guildId,
Guid serverId,
CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return null;
}
return await live.Connection.GetTimeAsync(_options.HeartbeatTimeout, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<TeamInfoSnapshot?> GetTeamInfoAsync(
ulong guildId,
Guid serverId,
CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return null;
}
return await live.Connection.GetTeamInfoAsync(_options.HeartbeatTimeout, cancellationToken)
.ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<bool> PromoteToLeaderAsync(
ulong guildId,
Guid serverId,
ulong steamId,
CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return false;
}
return await live.Connection.PromoteToLeaderAsync(steamId, _options.HeartbeatTimeout, cancellationToken)
.ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<byte[]?> GetMapImageAsync(ulong guildId, Guid serverId, CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return null;
}
return await live.Connection.GetMapImageAsync(_options.HeartbeatTimeout, cancellationToken)
.ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<MapDimensions?> GetMapDimensionsAsync(
ulong guildId,
Guid serverId,
CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return null;
}
return await live.Connection.GetMapDimensionsAsync(_options.HeartbeatTimeout, cancellationToken)
.ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<WorldSnapshot?> GetWorldAsync(ulong guildId, Guid serverId, CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return null;
}
return await live.Connection.GetWorldAsync(_options.HeartbeatTimeout, cancellationToken)
.ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<IReadOnlyList<MonumentSnapshot>> GetMonumentsAsync(
ulong guildId,
Guid serverId,
CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return [];
}
try
{
return await live.Connection.GetMonumentsAsync(_options.HeartbeatTimeout, cancellationToken)
.ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
#pragma warning disable CA1031 // Broad catch: this seam promises degradation, so a failed fetch is "no monuments".
catch (Exception ex)
#pragma warning restore CA1031
{
// The connection-level call throws on a failed/timed-out GetMap (rate limit, no map, slow
// endpoint). Callers here are render paths that must degrade to an icon-less map, never fault:
// an escaping exception tears down the consuming loop for the rest of the process.
LogMonumentsQueryFailed(logger, ex, serverId);
return [];
}
}
/// <inheritdoc />
public async Task<bool?> GetSmartSwitchStateAsync(
ulong guildId,
Guid serverId,
ulong entityId,
CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return null;
}
var reading = await live.Connection
.GetSmartDeviceInfoAsync(entityId, SmartDeviceKind.Switch, _options.HeartbeatTimeout, cancellationToken)
.ConfigureAwait(false);
return reading.IsActive;
}
/// <inheritdoc />
public async Task<DeviceReading> GetSmartAlarmReadingAsync(
ulong guildId,
Guid serverId,
ulong entityId,
CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return new DeviceReading(null, DeviceReachability.NoResponse);
}
return await live.Connection
.GetSmartDeviceInfoAsync(entityId, SmartDeviceKind.Alarm, _options.HeartbeatTimeout, cancellationToken)
.ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<StorageContentsSnapshot?> GetStorageContentsAsync(
ulong guildId,
Guid serverId,
ulong entityId,
CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return null;
}
var reading = await live.Connection
.GetStorageMonitorInfoAsync(entityId, _options.HeartbeatTimeout, cancellationToken)
.ConfigureAwait(false);
return reading.Contents;
}
/// <inheritdoc />
public async Task<DeviceReachability> SetSmartSwitchAsync(
ulong guildId,
Guid serverId,
ulong entityId,
bool value,
CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return DeviceReachability.NoResponse;
}
return await live.Connection
.SetSmartSwitchValueAsync(entityId, value, _options.HeartbeatTimeout, cancellationToken)
.ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<DeviceReachability> StrobeSmartSwitchAsync(
ulong guildId,
Guid serverId,
ulong entityId,
int timeoutMs,
bool value,
CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return DeviceReachability.NoResponse;
}
return await live.Connection
.StrobeSmartSwitchAsync(entityId, timeoutMs, value, _options.HeartbeatTimeout, cancellationToken)
.ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<bool> SetClanMotdAsync(
ulong guildId,
Guid serverId,
string motd,
CancellationToken cancellationToken)
{
if (!_liveSockets.TryGetValue((guildId, serverId), out var live))
{
return false;
}
return await live.Connection
.SetClanMotdAsync(motd, _options.HeartbeatTimeout, cancellationToken)
.ConfigureAwait(false);
}
[LoggerMessage(Level = LogLevel.Error, Message = "Connection loop for server {ServerId} faulted.")]
private static partial void LogLoopFaulted(ILogger logger, Exception exception, Guid serverId);
[LoggerMessage(Level = LogLevel.Error, Message = "Stored token for credential {CredentialId} is unreadable.")]
private static partial void LogUnreadableToken(ILogger logger, Exception exception, Guid credentialId);
private async Task StopConnectionAsync((ulong Guild, Guid Server) key)
{
if (!_connections.TryRemove(key, out var handle))
{
return;
}
await handle.StopAsync().ConfigureAwait(false);
await handle.DisposeAsync().ConfigureAwait(false);
}
private async Task RunAsync((ulong Guild, Guid Server) key, CancellationToken ct)
{
var delay = _options.InitialRetryDelay;
try
{
while (!ct.IsCancellationRequested)
{
var prepared = await PrepareAsync(key, ct).ConfigureAwait(false);
if (prepared is null)
{
await PublishStatusAsync(key, ConnectionStatus.NoCredentials, null, null, ct).ConfigureAwait(false);
return;
}
var p = prepared.Value;
await PublishStatusAsync(key, ConnectionStatus.Connecting, null, p.CredentialId, ct)
.ConfigureAwait(false);
var connection = source.Create(p.Ip, p.Port, p.SteamId, p.PlayerToken);
SocketConnectOutcome outcome;
try
{
outcome = await connection.ConnectAsync(_options.ConnectTimeout, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
await connection.DisposeAsync().ConfigureAwait(false);
throw;
}
if (outcome == SocketConnectOutcome.AuthRejected)
{
await connection.DisposeAsync().ConfigureAwait(false);
// No backoff here: failover should be prompt. The loop is bounded — each rejection permanently
// marks one credential Invalid (never re-selected), so an all-reject pool converges to NoCredentials.
await FailoverAsync(p.CredentialId, p.OwnerUserId, p.ServerName, ct).ConfigureAwait(false);
delay = _options.InitialRetryDelay;
continue;
}
if (outcome == SocketConnectOutcome.Unreachable)
{
await connection.DisposeAsync().ConfigureAwait(false);
await PublishStatusAsync(key, ConnectionStatus.Unreachable, null, p.CredentialId, ct)
.ConfigureAwait(false);
await Task.Delay(delay, ct).ConfigureAwait(false);
delay = NextDelay(delay);
continue;
}
// Connected: run the heartbeat loop until it signals a reason to reconnect.
delay = _options.InitialRetryDelay;
ReconnectReason reason;
try
{
reason = await RunConnectedAsync(key, connection, p.CredentialId, p.SteamId, ct)
.ConfigureAwait(false);
}
finally
{
await connection.DisposeAsync().ConfigureAwait(false);
}
if (reason == ReconnectReason.AuthRejected)
{
// No backoff: failover is prompt; pool exhaustion converges to NoCredentials.
await FailoverAsync(p.CredentialId, p.OwnerUserId, p.ServerName, ct).ConfigureAwait(false);
}
else if (reason == ReconnectReason.Unreachable)
{
await PublishStatusAsync(key, ConnectionStatus.Unreachable, null, p.CredentialId, ct)
.ConfigureAwait(false);
await Task.Delay(delay, ct).ConfigureAwait(false);
delay = NextDelay(delay);
}
}
}
catch (OperationCanceledException)
{
// Stopping.
}
#pragma warning disable CA1031 // Broad catch is intentional: a faulting loop must not crash the host or other servers.
catch (Exception ex)
{
LogLoopFaulted(logger, ex, key.Server);
}
#pragma warning restore CA1031
}
private async Task<ReconnectReason> RunConnectedAsync(
(ulong Guild, Guid Server) key,
IRustServerConnection connection,
Guid credentialId,
ulong activeSteamId,
CancellationToken ct)
{
var first = await connection.GetInfoAsync(_options.HeartbeatTimeout, ct).ConfigureAwait(false);
if (first.Kind == HeartbeatKind.AuthRejected)
{
return ReconnectReason.AuthRejected;
}
if (first.Kind == HeartbeatKind.Unreachable)
{
return ReconnectReason.Unreachable;
}
await PublishStatusAsync(key, ConnectionStatus.Connected, first.PlayerCount, credentialId, ct)
.ConfigureAwait(false);
#pragma warning disable RCS1163 // Unused 'sender': required by the EventHandler<TeamChatLine> delegate shape.
void OnTeamMessage(object? sender, TeamChatLine line)
{
// Fire-and-forget: PublishTeamMessageAsync catches everything internally, so the discarded task
// never surfaces an unobserved exception. Team chat is low-volume, so unbounded concurrency is fine.
_ = PublishTeamMessageAsync(key, activeSteamId, line);
}
#pragma warning restore RCS1163
#pragma warning disable RCS1163 // Unused 'sender': required by the EventHandler<SmartDeviceTrigger> delegate shape.
void OnSmartDevice(object? sender, SmartDeviceTrigger trigger)
{
// Fire-and-forget: PublishDeviceTriggerAsync catches everything internally, so the discarded task never
// surfaces an unobserved exception. Device triggers are low-volume, so unbounded concurrency is fine.
_ = PublishDeviceTriggerAsync(key, trigger);
}
#pragma warning restore RCS1163
#pragma warning disable RCS1163 // Unused 'sender': required by the EventHandler<StorageMonitorTrigger> delegate shape.
void OnStorage(object? sender, StorageMonitorTrigger trigger)
{
_ = PublishStorageTriggerAsync(key, trigger);
}
#pragma warning restore RCS1163
#pragma warning disable RCS1163 // Unused 'sender': required by the EventHandler<ClanChatLine> delegate shape.
void OnClanMessage(object? sender, ClanChatLine line)
{
_ = PublishClanMessageAsync(key, activeSteamId, line);
}
#pragma warning restore RCS1163
#pragma warning disable RCS1163 // Unused 'sender': required by the EventHandler<ClanProbeResult> delegate shape.
void OnClanChanged(object? sender, ClanProbeResult probe)
{
_ = PublishClanStateAsync(key, probe);
}
#pragma warning restore RCS1163
var tracker = new TeamStateTracker();
var dims = new DimensionsHolder();
#pragma warning disable RCS1163 // Unused 'sender': required by the EventHandler<TeamInfoSnapshot> delegate shape.
void OnTeamChanged(object? sender, TeamInfoSnapshot snapshot)
{
// Fire-and-forget: PublishTeamStateAsync catches everything internally.
_ = PublishTeamStateAsync(key, tracker, dims, snapshot);
}
#pragma warning restore RCS1163
connection.TeamMessageReceived += OnTeamMessage;
connection.SmartDeviceTriggered += OnSmartDevice;
connection.StorageMonitorTriggered += OnStorage;
connection.ClanMessageReceived += OnClanMessage;
connection.ClanChanged += OnClanChanged;
connection.TeamChanged += OnTeamChanged;
_liveSockets[key] = new LiveSocket(connection, activeSteamId, tracker);
await PrimeDevicesAsync(key, connection, ct).ConfigureAwait(false);
// Probe once on connect so clan state is correct after a bot restart, not only after the
// next in-game change. An Unavailable result publishes too: the consumer preserves state.
var clanProbe = await connection.GetClanInfoAsync(_options.HeartbeatTimeout, ct).ConfigureAwait(false);
LogClanPrimeProbed(logger, key.Server, clanProbe.Status);
await PublishClanStateAsync(key, clanProbe).ConfigureAwait(false);
using var pollCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
var markerPoll = Task.Run(() => PollMarkersAsync(key, connection, dims, pollCts.Token),
CancellationToken.None);
var reachabilityPoll = Task.Run(() => PollReachabilityAsync(key, connection, pollCts.Token),
CancellationToken.None);
var teamPoll = Task.Run(() => PollTeamAsync(key, connection, tracker, dims, pollCts.Token),
CancellationToken.None);
// Race the heartbeat against a liveness watchdog: the Rust+ library raises no event when the SERVER
// closes the socket, so without the watchdog a silent drop goes unnoticed until the next heartbeat
// (up to a minute). Whichever signals a reason first wins; the finally cancels and joins the rest.
var heartbeat = RunHeartbeatLoopAsync(key, connection, credentialId, pollCts.Token);
var liveness = WatchLivenessAsync(key, connection, pollCts.Token);
try
{
#pragma warning disable VSTHRD003 // Suppress: heartbeat and liveness are owned by this connected window and joined below.
var winner = await Task.WhenAny(heartbeat, liveness).ConfigureAwait(false);
return await winner.ConfigureAwait(false);
#pragma warning restore VSTHRD003
}
finally
{
await pollCts.CancelAsync().ConfigureAwait(false);
try
{
#pragma warning disable VSTHRD003 // Suppress: all five tasks are owned by this connected window and explicitly joined on exit.
await Task.WhenAll(markerPoll, reachabilityPoll, teamPoll, heartbeat, liveness).ConfigureAwait(false);
#pragma warning restore VSTHRD003
}
catch (OperationCanceledException)
{
// Expected on stop.
}
_liveSockets.TryRemove(key, out _);
connection.TeamMessageReceived -= OnTeamMessage;
connection.SmartDeviceTriggered -= OnSmartDevice;
connection.StorageMonitorTriggered -= OnStorage;
connection.ClanMessageReceived -= OnClanMessage;
connection.ClanChanged -= OnClanChanged;
connection.TeamChanged -= OnTeamChanged;
}
}
/// <summary>
/// Polls <see cref="IRustServerConnection.IsConnected"/> while connected and returns
/// <see cref="ReconnectReason.Unreachable"/> as soon as the socket is no longer open. This is the only
/// prompt signal for a server-initiated close, which the Rust+ library does not surface as an event.
/// </summary>
/// <param name="key">The (guild, server) routing key.</param>
/// <param name="connection">The live connection whose liveness is watched.</param>
/// <param name="ct">Cancels when the connected window ends.</param>
/// <returns><see cref="ReconnectReason.Unreachable"/> on a detected drop, else
/// <see cref="ReconnectReason.Stopped"/> when cancelled.</returns>
private async Task<ReconnectReason> WatchLivenessAsync(
(ulong Guild, Guid Server) key,
IRustServerConnection connection,
CancellationToken ct)
{
try
{
while (!ct.IsCancellationRequested)
{
await Task.Delay(_options.LivenessPollInterval, ct).ConfigureAwait(false);
if (!connection.IsConnected)
{
LogSocketDropped(logger, key.Server);
return ReconnectReason.Unreachable;
}
}
}
catch (OperationCanceledException)
{
// The connected window is ending (stop/reconnect): Task.Delay throws on cancellation.
// Return Stopped so the WhenAny winner is a clean reason rather than a faulted task.
}
return ReconnectReason.Stopped;
}
private async Task<ReconnectReason> RunHeartbeatLoopAsync(
(ulong Guild, Guid Server) key,
IRustServerConnection connection,
Guid credentialId,
CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
await Task.Delay(_options.HeartbeatInterval, ct).ConfigureAwait(false);
var beat = await connection.GetInfoAsync(_options.HeartbeatTimeout, ct).ConfigureAwait(false);
switch (beat.Kind)
{
case HeartbeatKind.Ok:
await PublishStatusAsync(key, ConnectionStatus.Connected, beat.PlayerCount, credentialId, ct)
.ConfigureAwait(false);
break;
case HeartbeatKind.AuthRejected:
return ReconnectReason.AuthRejected;
default:
return ReconnectReason.Unreachable;
}
}
return ReconnectReason.Stopped;
}
private async Task PollMarkersAsync(
(ulong Guild, Guid Server) key,
IRustServerConnection connection,
DimensionsHolder dims,
CancellationToken ct)
{
// Fetch map dimensions and oil-rig positions here, off the critical connect path: these are the two
// heavy full-map downloads, and on a degraded map endpoint they can stall for seconds. Doing them in
// this background poll means a slow map no longer delays the connection going live (heartbeat + chat
// relay start immediately); marker/rig detection simply activates once these resolve. Both degrade
// safely on timeout (dims -> null, rigs -> empty) without ending the poll.
var localDims = await connection.GetMapDimensionsAsync(_options.HeartbeatTimeout, ct).ConfigureAwait(false);
dims.Value = localDims;
var rigs = await GetRigPositionsAsync(key.Server, connection, ct).ConfigureAwait(false);
IReadOnlyList<MapMarkerSnapshot>? previous = null;
var rigsInRadius = new HashSet<RigKind>();
while (!ct.IsCancellationRequested)
{
var anyCh47 = false;
try
{
var current = await connection.GetMapMarkersAsync(_options.HeartbeatTimeout, ct).ConfigureAwait(false);
anyCh47 = current.Any(m => m.Kind == MarkerKind.Chinook);
if (previous is null)
{
previous = current; // first poll: silent baseline
}
else
{
await PublishMarkerDeltaAsync(key, localDims, previous, current, ct).ConfigureAwait(false);
previous = current;
}
await DetectRigActivationsAsync(key, current, rigs, localDims, rigsInRadius, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return; // stopping
}
#pragma warning disable CA1031 // Broad catch: a failed poll (incl. a per-request timeout) is logged and skipped; the previous snapshot is retained.
catch (Exception ex)
#pragma warning restore CA1031
{
// A per-request timeout (OperationCanceledException with ct NOT cancelled) must NOT end the
// poll loop — that would silently stop marker/rig/AFK detection for the rest of the connection.
LogMarkerPollFailed(logger, ex, key.Server);
}
var delay = anyCh47 ? _options.MarkerPollFastInterval : _options.MarkerPollInterval;
await Task.Delay(delay, ct).ConfigureAwait(false);
}
}
/// <summary>
/// Low-frequency team poll that runs the same <see cref="TeamStateTracker.Diff"/> as the pushed
/// team_changed handler. Live changes arrive via the push event; this loop exists solely to (a) prime the
/// baseline on connect and (b) guarantee <c>Diff</c> runs periodically so a still player in a
/// broadcast-silent team is still flagged AFK. Its first iteration runs immediately (prime), then it waits
/// <see cref="ConnectionOptions.TeamPollInterval"/> between iterations. Degrades safely: a failed poll is
/// logged and skipped, never ending the loop.
/// </summary>
/// <param name="key">The (guild, server) routing key.</param>
/// <param name="connection">The live connection to poll.</param>
/// <param name="tracker">The shared AFK/online tracker whose baseline this poll also primes/diffs.</param>
/// <param name="dims">The connected window's dimensions holder, read for the published event.</param>
/// <param name="ct">Cancels when the connected window ends.</param>
private async Task PollTeamAsync(
(ulong Guild, Guid Server) key,
IRustServerConnection connection,
TeamStateTracker tracker,
DimensionsHolder dims,
CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
var team = await connection.GetTeamInfoAsync(_options.HeartbeatTimeout, ct).ConfigureAwait(false);
await PublishTeamStateAsync(key, tracker, dims, team).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return; // stopping
}
#pragma warning disable CA1031 // Broad catch: a failed team poll is logged and skipped; the loop survives.
catch (Exception ex)
#pragma warning restore CA1031
{
LogTeamPollFailed(logger, ex, key.Server);
}
await Task.Delay(_options.TeamPollInterval, ct).ConfigureAwait(false);
}
}
private async Task PublishMarkerDeltaAsync(
(ulong Guild, Guid Server) key,
MapDimensions? dims,
IReadOnlyList<MapMarkerSnapshot> previous,
IReadOnlyList<MapMarkerSnapshot> current,
CancellationToken ct)
{
var previousById = previous.ToDictionary(p => p.Id);
var added = new List<MapMarkerSnapshot>();
var moved = new List<MapMarkerSnapshot>();
foreach (var c in current)
{
if (!previousById.TryGetValue(c.Id, out var p))
{
added.Add(c);
}
#pragma warning disable S1244 // Exact float compare is intentional: a stationary marker round-trips identical floats.
else if (c.X != p.X || c.Y != p.Y || !Nullable.Equals(c.Rotation, p.Rotation))
#pragma warning restore S1244
{
moved.Add(c);
}
}
var removed = previous.Where(p => current.All(c => c.Id != p.Id)).ToList();
if (added.Count > 0 || removed.Count > 0 || moved.Count > 0)
{
await eventBus.PublishAsync(
new MapMarkersChangedEvent(key.Guild, key.Server, dims, added, removed, moved), ct)
.ConfigureAwait(false);
}
}
private async Task PollReachabilityAsync(
(ulong Guild, Guid Server) key,
IRustServerConnection connection,
CancellationToken ct)
{
var previous = new Dictionary<ulong, DeviceReachability>();
var seeded = false;
while (!ct.IsCancellationRequested)
{
await Task.Delay(_options.ReachabilityPollInterval, ct).ConfigureAwait(false);
Dictionary<ulong, DeviceReachability> current;
try
{
current = await ReadAllReachabilityAsync(key, connection, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
#pragma warning disable CA1031 // Broad catch: a failed reachability sweep (incl. a per-request timeout) is logged and retried next cycle.
catch (Exception ex)
#pragma warning restore CA1031
{
// A per-request timeout (OperationCanceledException with ct NOT cancelled) must be retried next
// cycle, not rethrown — rethrowing would tear the sweep down for the rest of the connection.
LogReachabilityPollFailed(logger, ex, key.Server);
continue;
}
if (!seeded)
{
foreach (var kvp in current)
{
previous[kvp.Key] = kvp.Value;
}
seeded = true;
continue; // first cycle: silent baseline
}
foreach (var change in ReachabilitySweep.Diff(previous, current))
{
previous[change.Key] = change.Value;
await eventBus.PublishAsync(
new DeviceReachabilityChangedEvent(key.Guild, key.Server, change.Key, change.Value), ct)
.ConfigureAwait(false);
}
}
}
/// <summary>
/// Reads every managed device's reachability for one sweep cycle. Side effect: reachable storage
/// monitors get their just-read contents republished as <see cref="StorageMonitorTriggeredEvent"/>,
/// giving embeds a periodic contents refresh independent of broadcasts.
/// </summary>
/// <param name="key">The (guild, server) routing key.</param>
/// <param name="connection">The live connection used to read device state.</param>
/// <param name="ct">A cancellation token.</param>
/// <returns>The reachability snapshot keyed by entity id.</returns>
private async Task<Dictionary<ulong, DeviceReachability>> ReadAllReachabilityAsync(
(ulong Guild, Guid Server) key,
IRustServerConnection connection,
CancellationToken ct)
{
var result = new Dictionary<ulong, DeviceReachability>();
var scope = scopeFactory.CreateAsyncScope();
await using (scope.ConfigureAwait(false))
{
var switches = await scope.ServiceProvider.GetRequiredService<ISwitchStore>()
.ListByServerAsync(key.Guild, key.Server, ct).ConfigureAwait(false);
var alarms = await scope.ServiceProvider.GetRequiredService<IAlarmStore>()
.ListByServerAsync(key.Guild, key.Server, ct).ConfigureAwait(false);
var monitors = await scope.ServiceProvider.GetRequiredService<IStorageMonitorStore>()
.ListByServerAsync(key.Guild, key.Server, ct).ConfigureAwait(false);
var devices = switches.Select(s => (s.EntityId, SmartDeviceKind.Switch))
.Concat(alarms.Select(a => (a.EntityId, SmartDeviceKind.Alarm)));
foreach (var (entityId, kind) in devices)
{
var reading = await connection
.GetSmartDeviceInfoAsync(entityId, kind, _options.HeartbeatTimeout, ct)
.ConfigureAwait(false);
result[entityId] = reading.Reachability;
// Republish the state the read already carries as an OBSERVED event so drifted alarm
// embeds self-correct (the consumer is silent: no ping/relay, no edit when unchanged).
// Deliberately alarms only: switch embeds sync via actuation replies and broadcasts.
if (kind == SmartDeviceKind.Alarm && reading is { IsActive: { } isActive })
{
await eventBus.PublishAsync(
new SmartDeviceStateObservedEvent(key.Guild, key.Server, entityId, isActive), ct)
.ConfigureAwait(false);
}
}
#pragma warning disable S3267 // Not a projection: each iteration awaits with per-monitor best-effort error handling.
foreach (var monitor in monitors)
#pragma warning restore S3267
{
var reading = await connection
.GetStorageMonitorInfoAsync(monitor.EntityId, _options.HeartbeatTimeout, ct)
.ConfigureAwait(false);
result[monitor.EntityId] = reading.Reachability;
// The read already carries the contents — republish them so embeds keep tracking in-game
// changes even when no EntityChanged broadcast arrives (broadcasts alone are unreliable
// for storage monitors). Storage renders have no ping/relay side effects, so a periodic
// republish is safe; device (switch/alarm) triggers must NOT be republished here — an
// active alarm would re-ping on every sweep.
if (reading is { Reachability: DeviceReachability.Reachable, Contents: { } contents })
{
await eventBus.PublishAsync(
new StorageMonitorTriggeredEvent(key.Guild, key.Server, monitor.EntityId, contents), ct)
.ConfigureAwait(false);
}
}
}
return result;
}
private async Task DetectRigActivationsAsync(
(ulong Guild, Guid Server) key,
IReadOnlyList<MapMarkerSnapshot> current,
IReadOnlyList<RigPosition> rigs,
MapDimensions? dims,
HashSet<RigKind> rigsInRadius,
CancellationToken ct)
{