Skip to content

Commit f117c48

Browse files
committed
refactoring
1 parent 8d013de commit f117c48

12 files changed

Lines changed: 98 additions & 98 deletions

File tree

Directory.Build.props

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@
5858
<PrivateAssets>all</PrivateAssets>
5959
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
6060
</PackageReference>
61-
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.22.*">
61+
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.24.*">
6262
<PrivateAssets>all</PrivateAssets>
6363
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
6464
</PackageReference>
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
using Backdash.Options;
2+
using Timer = System.Timers.Timer;
3+
4+
namespace Backdash.Network;
5+
6+
sealed class ConnectionTimers(ProtocolOptions options) : IDisposable
7+
{
8+
public readonly Timer QualityReport = new(options.QualityReportInterval);
9+
public readonly Timer NetworkStats = new(options.NetworkPackageStatsInterval);
10+
public readonly Timer KeepAlive = new(options.KeepAliveInterval);
11+
public readonly Timer ResendInputs = new(options.ResendInputInterval);
12+
public readonly Timer ConsistencyCheck = new(options.ConsistencyCheckInterval);
13+
14+
public void Dispose()
15+
{
16+
Stop();
17+
18+
KeepAlive.Dispose();
19+
ResendInputs.Dispose();
20+
QualityReport.Dispose();
21+
NetworkStats.Dispose();
22+
ConsistencyCheck.Dispose();
23+
}
24+
25+
public void Start()
26+
{
27+
KeepAlive.Start();
28+
QualityReport.Start();
29+
ResendInputs.Start();
30+
31+
if (options.IsNetworkPackageStatsEnabled())
32+
NetworkStats.Start();
33+
34+
if (options.IsConsistencyCheckEnabled())
35+
ConsistencyCheck.Start();
36+
}
37+
38+
public void Stop()
39+
{
40+
KeepAlive.Stop();
41+
QualityReport.Stop();
42+
ResendInputs.Stop();
43+
44+
if (options.IsNetworkPackageStatsEnabled())
45+
NetworkStats.Stop();
46+
47+
if (options.IsConsistencyCheckEnabled())
48+
ConsistencyCheck.Stop();
49+
}
50+
}

src/Backdash/Network/PeerConnection.cs

Lines changed: 31 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
using Backdash.Synchronizing;
1111
using Backdash.Synchronizing.Input;
1212
using Backdash.Synchronizing.State;
13-
using Timer = System.Timers.Timer;
1413

1514
namespace Backdash.Network;
1615

@@ -27,11 +26,7 @@ sealed class PeerConnection<TInput> : IDisposable where TInput : unmanaged
2726
readonly ProtocolInputBuffer<TInput> inputBuffer;
2827
readonly ChecksumStore checksumStore;
2928

30-
readonly Timer qualityReportTimer;
31-
readonly Timer networkStatsTimer;
32-
readonly Timer keepAliveTimer;
33-
readonly Timer resendInputsTimer;
34-
readonly Timer consistencyCheckTimer;
29+
readonly ConnectionTimers timers;
3530
readonly bool disconnectCheckEnabled;
3631
long startedAt;
3732

@@ -58,24 +53,16 @@ ChecksumStore checksumStore
5853
this.outbox = outbox;
5954
this.inputBuffer = inputBuffer;
6055
this.checksumStore = checksumStore;
56+
timers = new(options);
6157
disconnectCheckEnabled = options.IsDisconnectTimeoutEnabled();
6258

63-
keepAliveTimer = new(options.KeepAliveInterval);
64-
keepAliveTimer.Elapsed += OnKeepAliveTick;
59+
timers.KeepAlive.Elapsed += OnKeepAliveTick;
60+
timers.ResendInputs.Elapsed += OnResendInputs;
61+
timers.QualityReport.Elapsed += OnQualityReportTick;
62+
timers.NetworkStats.Elapsed += OnNetworkStatsTick;
63+
timers.ConsistencyCheck.Elapsed += OnConsistencyCheck;
6564

66-
resendInputsTimer = new(options.ResendInputInterval);
67-
resendInputsTimer.Elapsed += OnResendInputs;
68-
69-
qualityReportTimer = new(options.QualityReportInterval);
70-
qualityReportTimer.Elapsed += OnQualityReportTick;
71-
72-
networkStatsTimer = new(options.NetworkPackageStatsInterval);
73-
networkStatsTimer.Elapsed += OnNetworkStatsTick;
74-
75-
consistencyCheckTimer = new(options.ConsistencyCheckInterval);
76-
consistencyCheckTimer.Elapsed += OnConsistencyCheck;
77-
78-
state.StoppingToken.Register(StopTimers);
65+
state.StoppingToken.Register(timers.Stop);
7966
}
8067

8168
public void Dispose()
@@ -84,46 +71,14 @@ public void Dispose()
8471
if (!state.StoppingTokenSource.IsCancellationRequested)
8572
state.StoppingTokenSource.Cancel();
8673

87-
StopTimers();
74+
timers.Stop();
8875
DispatchDisconnectEvent();
89-
90-
keepAliveTimer.Elapsed -= OnKeepAliveTick;
91-
resendInputsTimer.Elapsed -= OnKeepAliveTick;
92-
qualityReportTimer.Elapsed -= OnQualityReportTick;
93-
networkStatsTimer.Elapsed -= OnNetworkStatsTick;
94-
consistencyCheckTimer.Elapsed -= OnConsistencyCheck;
95-
96-
keepAliveTimer.Dispose();
97-
resendInputsTimer.Dispose();
98-
qualityReportTimer.Dispose();
99-
networkStatsTimer.Dispose();
100-
consistencyCheckTimer.Dispose();
101-
}
102-
103-
void StartTimers()
104-
{
105-
keepAliveTimer.Start();
106-
qualityReportTimer.Start();
107-
resendInputsTimer.Start();
108-
109-
if (options.IsNetworkPackageStatsEnabled())
110-
networkStatsTimer.Start();
111-
112-
if (options.IsConsistencyCheckEnabled())
113-
consistencyCheckTimer.Start();
114-
}
115-
116-
void StopTimers()
117-
{
118-
keepAliveTimer.Stop();
119-
qualityReportTimer.Stop();
120-
resendInputsTimer.Stop();
121-
122-
if (options.IsNetworkPackageStatsEnabled())
123-
networkStatsTimer.Stop();
124-
125-
if (options.IsConsistencyCheckEnabled())
126-
consistencyCheckTimer.Stop();
76+
timers.KeepAlive.Elapsed -= OnKeepAliveTick;
77+
timers.ResendInputs.Elapsed -= OnKeepAliveTick;
78+
timers.QualityReport.Elapsed -= OnQualityReportTick;
79+
timers.NetworkStats.Elapsed -= OnNetworkStatsTick;
80+
timers.ConsistencyCheck.Elapsed -= OnConsistencyCheck;
81+
timers.Dispose();
12782
}
12883

12984
public void Disconnect()
@@ -149,7 +104,7 @@ public void Disconnect()
149104
public void Start()
150105
{
151106
if (startedAt is 0)
152-
StartTimers();
107+
timers.Start();
153108

154109
startedAt = Stopwatch.GetTimestamp();
155110
}
@@ -260,41 +215,34 @@ void CheckDisconnection()
260215
}
261216
}
262217

263-
readonly object eventLocker = new();
264218

265219
bool DispatchInterruptedEvent(TimeSpan timeout)
266220
{
267-
lock (eventLocker)
268-
{
269-
if (state.Connection is not { DisconnectNotifySent: false, DisconnectEventSent: false })
270-
return false;
221+
if (state.Connection is not { DisconnectNotifySent: false, DisconnectEventSent: false })
222+
return false;
271223

272-
networkEventHandler.OnNetworkEvent(state.Player, new(PeerEvent.ConnectionInterrupted)
224+
networkEventHandler.OnNetworkEvent(state.Player, new(PeerEvent.ConnectionInterrupted)
225+
{
226+
ConnectionInterrupted = new()
273227
{
274-
ConnectionInterrupted = new()
275-
{
276-
DisconnectTimeout = timeout,
277-
},
278-
});
228+
DisconnectTimeout = timeout,
229+
},
230+
});
279231

280-
state.Connection.DisconnectNotifySent = true;
232+
state.Connection.DisconnectNotifySent = true;
281233

282-
return true;
283-
}
234+
return true;
284235
}
285236

286237
bool DispatchDisconnectEvent()
287238
{
288-
lock (eventLocker)
289-
{
290-
if (state.Connection.DisconnectEventSent)
291-
return false;
239+
if (state.Connection.DisconnectEventSent)
240+
return false;
292241

293-
state.Connection.DisconnectEventSent = true;
294-
networkEventHandler.OnNetworkEvent(PeerEvent.Disconnected, state.Player);
242+
state.Connection.DisconnectEventSent = true;
243+
networkEventHandler.OnNetworkEvent(PeerEvent.Disconnected, state.Player);
295244

296-
return true;
297-
}
245+
return true;
298246
}
299247

300248
void OnKeepAliveTick(object? sender, ElapsedEventArgs e)

src/Backdash/Network/Protocol/Comm/ProtocolInbox.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,8 @@ bool OnConsistencyCheckReply(ref readonly ProtocolMessage message, ref ProtocolM
319319

320320
if (state.Consistency.AskedFrame != checkFrame || localChecksum.IsEmpty || checksum.IsEmpty)
321321
{
322-
logger.Write(LogLevel.Warning, $"Unable to find reply local checksum #{checksum} for {checkFrame}");
322+
logger.Write(LogLevel.Warning,
323+
$"Unable to find reply local checksum #{checksum} for {checkFrame} [last: {checksumStore.LastFrame()}]");
323324
return false;
324325
}
325326

src/Backdash/Network/Protocol/ProtocolClientFactory.cs renamed to src/Backdash/Network/Protocol/PeerClientFactory.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
namespace Backdash.Network.Protocol;
88

9-
sealed class ProtocolClientFactory(
9+
sealed class PeerClientFactory(
1010
NetcodeOptions options,
1111
IPeerSocketFactory socketFactory,
1212
Logger logger,

src/Backdash/Options/ProtocolOptions.cs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -177,15 +177,15 @@ internal bool IsNetworkPackageStatsEnabled() =>
177177
/// On each interval one peer requests a frame to other peer which must respond
178178
/// with the state checksum of that frame.
179179
/// </summary>
180-
/// <value>Defaults to <c>3_000</c> milliseconds</value>
180+
/// <value>Defaults to <c>1</c> second</value>
181181
/// <seealso cref="ConsistencyCheckDistance" />
182182
/// <seealso cref="ConsistencyCheckTimeout" />
183-
public TimeSpan ConsistencyCheckInterval { get; set; } = TimeSpan.FromSeconds(3);
183+
public TimeSpan ConsistencyCheckInterval { get; set; } = TimeSpan.FromSeconds(1);
184184

185185
/// <summary>
186186
/// The number of checksum frames that will be keep for consistency checks.
187187
/// </summary>
188-
/// <value>Defaults to <c>180</c></value>
188+
/// <value>Defaults to <c>250</c></value>
189189
/// <seealso cref="ConsistencyCheckTimeout" />
190190
/// <seealso cref="ConsistencyCheckInterval" />
191191
public int ConsistencyCheckStoreSize { get; set; } = 250;
@@ -203,11 +203,10 @@ internal bool IsConsistencyCheckEnabled() =>
203203
/// <summary>
204204
/// Max wait time for non-success consistency checks (0 to disable).
205205
/// </summary>
206-
/// <value>Defaults to <c>10_000</c> milliseconds</value>
206+
/// <value>Defaults to <c>10</c> seconds</value>
207207
/// <seealso cref="ConsistencyCheckDistance" />
208208
/// <seealso cref="ConsistencyCheckInterval" />
209-
public TimeSpan ConsistencyCheckTimeout { get; set; } =
210-
TimeSpan.FromMilliseconds(10_000);
209+
public TimeSpan ConsistencyCheckTimeout { get; set; } = TimeSpan.FromSeconds(10);
211210

212211
/// <summary>
213212
/// Custom receive socket address size

src/Backdash/Session/Backends/RemoteSession.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ SessionServices<TInput> services
100100
inputListener = new MemoryInputListener<TInput>(inputListener);
101101

102102

103-
udp = services.ProtocolClientFactory.CreateClient(options.LocalPort, peerObservers);
103+
udp = services.PeerClientFactory.CreateClient(options.LocalPort, peerObservers);
104104

105105
peerConnectionFactory = new(
106106
networkEventQueue,

src/Backdash/Session/Backends/SpectatorSession.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ SessionServices<TInput> services
7676
inputs = new GameInput<ConfirmedInputs<TInput>>[options.SpectatorInputBufferLength];
7777
callbacks = services.SessionHandler;
7878
endianness = options.GetEndiannessNumberStateSerializer();
79-
udp = services.ProtocolClientFactory.CreateClient(options.LocalPort, peerObservers);
79+
udp = services.PeerClientFactory.CreateClient(options.LocalPort, peerObservers);
8080
ConfigureJobs(services);
8181

8282
var magicNumber = services.Random.SyncNumber();

src/Backdash/Session/SessionServices.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ sealed class SessionServices<TInput> where TInput : unmanaged
1616
public IChecksumProvider ChecksumProvider { get; }
1717
public Logger Logger { get; }
1818
public NetcodeJobManager JobManager { get; }
19-
public ProtocolClientFactory ProtocolClientFactory { get; }
19+
public PeerClientFactory PeerClientFactory { get; }
2020
public IStateStore StateStore { get; }
2121
public ChecksumStore ChecksumStore { get; }
2222
public IRandomNumberGenerator Random { get; }
@@ -60,7 +60,7 @@ public SessionServices(
6060
SessionHandler = services?.SessionHandler ?? new EmptySessionHandler(Logger);
6161

6262
var socketFactory = services?.PeerSocketFactory ?? new PeerSocketFactory();
63-
ProtocolClientFactory = new(options, socketFactory, Logger, LatencyStrategy);
63+
PeerClientFactory = new(options, socketFactory, Logger, LatencyStrategy);
6464
Jobs = services?.Jobs.ToArray() ?? [];
6565
PluginManager = new(Logger, services?.Plugin);
6666
}

0 commit comments

Comments
 (0)