836 lines
36 KiB
C#
836 lines
36 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Json;
|
|
using System.Net.Sockets;
|
|
using System.Numerics;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using GameCult.Networking;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using RustToDust.Core;
|
|
using RustToDust.DirectoryService;
|
|
using RustToDust.Net;
|
|
using RustToDust.Ymir;
|
|
using Xunit;
|
|
|
|
namespace RustToDust.Tests
|
|
{
|
|
public sealed class LobbyAndDirectoryTests
|
|
{
|
|
private static async Task<(WebApplication App, string BaseUrl)> StartDirectoryServerAsync(DirectoryRegistryOptions? options = null)
|
|
{
|
|
var opts = options ?? new DirectoryRegistryOptions();
|
|
var app = DirectoryApp.Build(Array.Empty<string>(), opts);
|
|
app.Urls.Clear();
|
|
app.Urls.Add("http://127.0.0.1:0");
|
|
await app.StartAsync();
|
|
string baseUrl = app.Urls.First();
|
|
return (app, baseUrl);
|
|
}
|
|
|
|
private static void PumpHostAndClients(ServerMatchHost host, params RemoteArenaSession[] clients)
|
|
{
|
|
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
|
host.StepOnce(nowMs);
|
|
for (int i = 0; i < clients.Length; i++)
|
|
{
|
|
clients[i].PumpNetwork(nowMs);
|
|
}
|
|
}
|
|
|
|
private static void PumpListenHostAndClient(ListenHostArenaSession listenHost, RemoteArenaSession client, int ticks = 1)
|
|
{
|
|
for (int i = 0; i < ticks; i++)
|
|
{
|
|
listenHost.SubmitLocalInput(default, isPhysicsTick: true);
|
|
client.PumpNetwork();
|
|
Thread.Sleep(2);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Directory_Heartbeat_LeaseTokenSecrecy_AuthRejection_LoopbackSpoof_And_TtlExpiry()
|
|
{
|
|
var now = DateTimeOffset.UtcNow;
|
|
var opts = new DirectoryRegistryOptions
|
|
{
|
|
EntryTtl = TimeSpan.FromMilliseconds(350),
|
|
ReaperInterval = TimeSpan.FromMilliseconds(60),
|
|
UtcNow = () => now
|
|
};
|
|
|
|
var (app, baseUrl) = await StartDirectoryServerAsync(opts);
|
|
try
|
|
{
|
|
using var http = new HttpClient { BaseAddress = new Uri(baseUrl) };
|
|
|
|
// 1. Register with empty publicHost behind simulated nginx X-Real-IP -> auto-resolves to caller IP
|
|
using var regReq = new HttpRequestMessage(HttpMethod.Post, "/api/v1/servers/heartbeat")
|
|
{
|
|
Content = JsonContent.Create(new DirectoryHeartbeatRequest
|
|
{
|
|
Name = "Yggdrasil Ring",
|
|
PublicHost = "",
|
|
UdpPort = 3076,
|
|
Map = "sion",
|
|
Seed = 77,
|
|
Humans = 2,
|
|
MaxHumans = 12,
|
|
Phase = "Lobby",
|
|
Wave = 0
|
|
})
|
|
};
|
|
regReq.Headers.TryAddWithoutValidation("X-Real-IP", "203.0.113.42");
|
|
using var regResp = await http.SendAsync(regReq);
|
|
Assert.Equal(HttpStatusCode.OK, regResp.StatusCode);
|
|
|
|
var ack = await regResp.Content.ReadFromJsonAsync<DirectoryHeartbeatResponse>();
|
|
Assert.NotNull(ack);
|
|
Assert.NotEqual(Guid.Empty, ack!.ServerId);
|
|
Assert.False(string.IsNullOrWhiteSpace(ack.LeaseToken));
|
|
Assert.True(ack.TtlSeconds >= 1);
|
|
|
|
// 2. GET /api/v1/servers returns resolved publicHost and NEVER exposes leaseToken
|
|
string rawListJson = await http.GetStringAsync("/api/v1/servers");
|
|
Assert.DoesNotContain(ack.LeaseToken, rawListJson, StringComparison.Ordinal);
|
|
|
|
var list = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http);
|
|
Assert.Single(list);
|
|
Assert.Equal(ack.ServerId, list[0].ServerId);
|
|
Assert.Equal("203.0.113.42", list[0].PublicHost);
|
|
Assert.Equal("sion", list[0].Map);
|
|
Assert.Equal("Lobby", list[0].Phase);
|
|
|
|
// 3. Non-loopback X-Real-IP attempting to spoof loopback publicHost is rejected (400)
|
|
foreach (string spoofHost in new[] { "127.0.0.1", "localhost", "::1" })
|
|
{
|
|
using var spoofReq = new HttpRequestMessage(HttpMethod.Post, "/api/v1/servers/heartbeat")
|
|
{
|
|
Content = JsonContent.Create(new DirectoryHeartbeatRequest
|
|
{
|
|
Name = "Spoofed",
|
|
PublicHost = spoofHost,
|
|
UdpPort = 3076
|
|
})
|
|
};
|
|
spoofReq.Headers.TryAddWithoutValidation("X-Real-IP", "203.0.113.42");
|
|
using var spoofResp = await http.SendAsync(spoofReq);
|
|
Assert.Equal(HttpStatusCode.BadRequest, spoofResp.StatusCode);
|
|
}
|
|
|
|
// 4. Wrong leaseToken on refresh -> 403, entry stays intact
|
|
using var badRefresh = await http.PostAsJsonAsync("/api/v1/servers/heartbeat", new DirectoryHeartbeatRequest
|
|
{
|
|
ServerId = ack.ServerId,
|
|
LeaseToken = "wrong-token-value",
|
|
Name = "Hijacked",
|
|
PublicHost = "203.0.113.42",
|
|
UdpPort = 3076
|
|
});
|
|
Assert.Equal(HttpStatusCode.Forbidden, badRefresh.StatusCode);
|
|
|
|
// 5. Wrong leaseToken on DELETE -> 403, entry stays intact
|
|
using var badDeleteReq = new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/servers/{ack.ServerId}");
|
|
badDeleteReq.Headers.TryAddWithoutValidation("X-Lease-Token", "wrong-token-value");
|
|
using var badDeleteResp = await http.SendAsync(badDeleteReq);
|
|
Assert.Equal(HttpStatusCode.Forbidden, badDeleteResp.StatusCode);
|
|
|
|
var stillPresent = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http);
|
|
Assert.Single(stillPresent);
|
|
Assert.Equal("Yggdrasil Ring", stillPresent[0].Name);
|
|
|
|
// 6. Valid leaseToken refresh succeeds and keeps entry alive
|
|
using var goodRefresh = await http.PostAsJsonAsync("/api/v1/servers/heartbeat", new DirectoryHeartbeatRequest
|
|
{
|
|
ServerId = ack.ServerId,
|
|
LeaseToken = ack.LeaseToken,
|
|
Name = "Yggdrasil Ring Updated",
|
|
PublicHost = "203.0.113.42",
|
|
UdpPort = 3076,
|
|
Humans = 5,
|
|
Phase = "Active",
|
|
Wave = 1
|
|
});
|
|
Assert.Equal(HttpStatusCode.OK, goodRefresh.StatusCode);
|
|
|
|
// 7. Advance clock past TTL -> entry expires cleanly and disappears
|
|
now = now + TimeSpan.FromMilliseconds(500);
|
|
await Task.Delay(150);
|
|
var afterExpiry = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http);
|
|
Assert.Empty(afterExpiry);
|
|
}
|
|
finally
|
|
{
|
|
await app.StopAsync();
|
|
await app.DisposeAsync();
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task DirectoryReporter_Registers_Updates_And_DeregistersOnDispose()
|
|
{
|
|
var (app, baseUrl) = await StartDirectoryServerAsync();
|
|
try
|
|
{
|
|
int humans = 1;
|
|
string phase = "Lobby";
|
|
|
|
var reporter = new DirectoryReporter(
|
|
baseUrl,
|
|
() => new DirectoryHeartbeatSnapshot(
|
|
"Reporter Test Ring",
|
|
"127.0.0.1",
|
|
3079,
|
|
"desert",
|
|
42,
|
|
humans,
|
|
12,
|
|
phase,
|
|
0),
|
|
heartbeatInterval: TimeSpan.FromSeconds(30));
|
|
|
|
try
|
|
{
|
|
var deadline = DateTime.UtcNow.AddSeconds(15);
|
|
IReadOnlyList<DirectoryServerInfo> servers = Array.Empty<DirectoryServerInfo>();
|
|
while (DateTime.UtcNow < deadline)
|
|
{
|
|
servers = await DirectoryBrowserClient.FetchServersAsync(baseUrl);
|
|
if (servers.Count > 0) break;
|
|
await Task.Delay(25);
|
|
}
|
|
|
|
Assert.Single(servers);
|
|
Assert.Equal("Reporter Test Ring", servers[0].Name);
|
|
Assert.Equal(1, servers[0].Humans);
|
|
|
|
humans = 4;
|
|
phase = "Active";
|
|
reporter.NotifyChanged();
|
|
|
|
deadline = DateTime.UtcNow.AddSeconds(15);
|
|
while (DateTime.UtcNow < deadline)
|
|
{
|
|
servers = await DirectoryBrowserClient.FetchServersAsync(baseUrl);
|
|
if (servers.Count == 1 && servers[0].Humans == 4 && servers[0].Phase == "Active") break;
|
|
await Task.Delay(25);
|
|
}
|
|
Assert.Equal(4, servers[0].Humans);
|
|
Assert.Equal("Active", servers[0].Phase);
|
|
}
|
|
finally
|
|
{
|
|
await reporter.DisposeAsync();
|
|
}
|
|
|
|
var afterDispose = await DirectoryBrowserClient.FetchServersAsync(baseUrl);
|
|
Assert.Empty(afterDispose);
|
|
}
|
|
finally
|
|
{
|
|
await app.StopAsync();
|
|
await app.DisposeAsync();
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task StatelessUdpPing_CoexistsWithActiveRemoteSession_AndHandlesMalformedPingsSafely()
|
|
{
|
|
using var host = new ServerMatchHost(
|
|
IPAddress.Loopback,
|
|
0,
|
|
seed: 77,
|
|
mapKind: ArenaMapKind.Desert,
|
|
serverName: "Ping Coexistence Arena",
|
|
startInLobby: false);
|
|
using var client = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "ProbePilot");
|
|
|
|
var joinDeadline = DateTime.UtcNow.AddSeconds(3);
|
|
while (!client.IsJoined && DateTime.UtcNow < joinDeadline)
|
|
{
|
|
PumpHostAndClients(host, client);
|
|
await Task.Delay(5);
|
|
}
|
|
Assert.True(client.IsJoined);
|
|
|
|
// Drive and fire concurrently on the active RUDP session while probing RTDP pings
|
|
for (int i = 0; i < 15; i++)
|
|
{
|
|
client.SubmitLocalInput(new PlayerInput(1f, 0.25f, 30f, 40f, Fire: true, InteractPickup: false, Brake: false), isPhysicsTick: true);
|
|
PumpHostAndClients(host, client);
|
|
}
|
|
|
|
var target = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
|
|
var pingTask = Task.Run(async () =>
|
|
{
|
|
var results = new List<ServerPingResult>(4);
|
|
for (int i = 0; i < 4; i++)
|
|
{
|
|
results.Add(await ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2)));
|
|
}
|
|
return results;
|
|
});
|
|
|
|
while (!pingTask.IsCompleted)
|
|
{
|
|
client.SubmitLocalInput(new PlayerInput(0.8f, -0.1f, 25f, 35f, Fire: true, InteractPickup: false, Brake: false), isPhysicsTick: true);
|
|
PumpHostAndClients(host, client);
|
|
await Task.Delay(3);
|
|
}
|
|
|
|
var pingResults = await pingTask;
|
|
Assert.Equal(4, pingResults.Count);
|
|
foreach (var r in pingResults)
|
|
{
|
|
Assert.True(r.Success, "Expected stateless RTDP ping to succeed alongside active RUDP session");
|
|
Assert.True(r.Summary.HasValue);
|
|
Assert.Equal("Ping Coexistence Arena", r.Summary!.Value.ServerName);
|
|
Assert.Equal(1, r.Summary.Value.Humans);
|
|
Assert.Equal(12, r.Summary.Value.MaxHumans);
|
|
Assert.Equal(MatchPhase.Active, r.Summary.Value.Phase);
|
|
Assert.Equal(ArenaMapKind.Desert, r.Summary.Value.MapKind);
|
|
Assert.Equal(77, r.Summary.Value.Seed);
|
|
Assert.True(r.Summary.Value.AcceptingJoin);
|
|
Assert.True(SnapshotCodec.EncodePong(r.Summary.Value).Length < 110);
|
|
}
|
|
|
|
Assert.Equal(0, host.TransportPacketsDropped);
|
|
Assert.True(client.ConnectionStatus.Connected);
|
|
|
|
// Send truncated "RTDP" packet (< 16B) and bogus magic packet; host must not crash or drop RUDP peer
|
|
using (var rawSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
|
|
{
|
|
byte[] truncatedPing = Encoding.ASCII.GetBytes("RTDP\x01\x01short"); // 11 bytes
|
|
rawSock.SendTo(truncatedPing, target);
|
|
for (int i = 0; i < 4; i++)
|
|
{
|
|
PumpHostAndClients(host, client);
|
|
await Task.Delay(2);
|
|
}
|
|
Assert.Equal(0, host.TransportPacketsDropped);
|
|
|
|
byte[] bogusMagic = Encoding.ASCII.GetBytes("JUNK_NOT_RTDP_OR_CNR0_PAYLOAD_DATA");
|
|
rawSock.SendTo(bogusMagic, target);
|
|
for (int i = 0; i < 4; i++)
|
|
{
|
|
PumpHostAndClients(host, client);
|
|
await Task.Delay(2);
|
|
}
|
|
}
|
|
|
|
Assert.True(client.IsJoined);
|
|
Assert.True(client.ConnectionStatus.Connected);
|
|
|
|
// Valid ping still succeeds after malformed datagrams
|
|
var finalPingTask = ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2));
|
|
while (!finalPingTask.IsCompleted)
|
|
{
|
|
PumpHostAndClients(host, client);
|
|
await Task.Delay(2);
|
|
}
|
|
var finalPing = await finalPingTask;
|
|
Assert.True(finalPing.Success);
|
|
}
|
|
|
|
[Fact]
|
|
public void Lobby_NonHostConfigAndStartRejected_AndLocalOutcomeIsActive()
|
|
{
|
|
using var listenHost = new ListenHostArenaSession(
|
|
IPAddress.Loopback,
|
|
0,
|
|
seed: 42,
|
|
mapKind: ArenaMapKind.Desert,
|
|
startInLobby: true,
|
|
serverName: "Host Authority Lobby");
|
|
using var client = new RemoteArenaSession(
|
|
new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort),
|
|
"Guest");
|
|
|
|
var joinDeadline = DateTime.UtcNow.AddSeconds(3);
|
|
while (!client.IsJoined && DateTime.UtcNow < joinDeadline)
|
|
{
|
|
PumpListenHostAndClient(listenHost, client);
|
|
}
|
|
Assert.True(client.IsJoined);
|
|
|
|
Assert.Equal(MatchPhase.Lobby, listenHost.ViewState.Phase);
|
|
Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase);
|
|
Assert.Equal(ClientMatchOutcome.Active, listenHost.LocalOutcome);
|
|
Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome);
|
|
|
|
// Guest attempts unauthorized config change and launch
|
|
Assert.True(client.RequestLobbyConfig(999, ArenaMapKind.Sion));
|
|
Assert.True(client.RequestLobbyStart());
|
|
PumpListenHostAndClient(listenHost, client, ticks: 15);
|
|
|
|
Assert.Equal(MatchPhase.Lobby, listenHost.ViewState.Phase);
|
|
Assert.Equal(ArenaMapKind.Desert, listenHost.ViewState.MapKind);
|
|
Assert.Equal(42, listenHost.ViewState.Seed);
|
|
Assert.Null(listenHost.LobbyState?.CountdownSeconds);
|
|
Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase);
|
|
Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome);
|
|
}
|
|
|
|
[Fact]
|
|
public void Lobby_CountdownStartsWhenAllReady_CancelsOnUnready_AndResetsOnMapSwitch()
|
|
{
|
|
using var host = new ServerMatchHost(
|
|
IPAddress.Loopback,
|
|
0,
|
|
seed: 42,
|
|
mapKind: ArenaMapKind.Desert,
|
|
allowClientReset: true,
|
|
startInLobby: true,
|
|
minHumansToStart: 2);
|
|
using var peerA = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "Alpha");
|
|
using var peerB = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "Bravo");
|
|
|
|
var deadline = DateTime.UtcNow.AddSeconds(3);
|
|
while ((!peerA.IsJoined || !peerB.IsJoined) && DateTime.UtcNow < deadline)
|
|
{
|
|
PumpHostAndClients(host, peerA, peerB);
|
|
Thread.Sleep(3);
|
|
}
|
|
Assert.True(peerA.IsJoined);
|
|
Assert.True(peerB.IsJoined);
|
|
|
|
// Peer A readies up; Peer B not ready -> no countdown yet
|
|
Assert.True(peerA.SetLobbyReady(true));
|
|
for (int i = 0; i < 10; i++)
|
|
{
|
|
PumpHostAndClients(host, peerA, peerB);
|
|
Thread.Sleep(2);
|
|
}
|
|
Assert.Null(host.Lobby?.CountdownSeconds);
|
|
|
|
// Peer B readies up -> countdown starts
|
|
Assert.True(peerB.SetLobbyReady(true));
|
|
for (int i = 0; i < 15; i++)
|
|
{
|
|
PumpHostAndClients(host, peerA, peerB);
|
|
Thread.Sleep(2);
|
|
}
|
|
Assert.NotNull(host.Lobby?.CountdownSeconds);
|
|
Assert.True(host.Lobby!.CountdownSeconds!.Value > 0f && host.Lobby.CountdownSeconds.Value < 5.0f);
|
|
Assert.NotNull(peerA.LobbyState?.CountdownSeconds);
|
|
|
|
// Peer B un-readies -> countdown cancels and Wave 0 does NOT launch
|
|
Assert.True(peerB.SetLobbyReady(false));
|
|
for (int i = 0; i < 15; i++)
|
|
{
|
|
PumpHostAndClients(host, peerA, peerB);
|
|
Thread.Sleep(2);
|
|
}
|
|
Assert.Null(host.Lobby?.CountdownSeconds);
|
|
Assert.Null(peerA.LobbyState?.CountdownSeconds);
|
|
Assert.Equal(MatchPhase.Lobby, host.Session.State.Phase);
|
|
Assert.Empty(host.Session.State.OrbitalDrop.ActivePods);
|
|
|
|
// Authorized config switch in Lobby resets ready flags and syncs all peers
|
|
Assert.True(peerA.SetLobbyReady(true));
|
|
for (int i = 0; i < 6; i++)
|
|
{
|
|
PumpHostAndClients(host, peerA, peerB);
|
|
Thread.Sleep(2);
|
|
}
|
|
|
|
Assert.True(host.ConfigureLobby(peerA.LocalContenderId, 99, ArenaMapKind.Sion));
|
|
for (int i = 0; i < 15; i++)
|
|
{
|
|
PumpHostAndClients(host, peerA, peerB);
|
|
Thread.Sleep(2);
|
|
}
|
|
|
|
Assert.Equal(MatchPhase.Lobby, host.Session.State.Phase);
|
|
Assert.Equal(ArenaMapKind.Sion, host.Session.State.MapKind);
|
|
Assert.Equal(99, host.Session.State.Seed);
|
|
Assert.Equal(ArenaMapKind.Sion, peerA.ViewState.MapKind);
|
|
Assert.Equal(99, peerA.ViewState.Seed);
|
|
Assert.Equal(ArenaMapKind.Sion, peerB.ViewState.MapKind);
|
|
Assert.Equal(99, peerB.ViewState.Seed);
|
|
Assert.All(host.Lobby!.Slots.Where(s => s.IsHuman), s => Assert.False(s.IsReady));
|
|
Assert.Equal(ClientMatchOutcome.Active, peerA.LocalOutcome);
|
|
Assert.Equal(ClientMatchOutcome.Active, peerB.LocalOutcome);
|
|
}
|
|
|
|
[Fact]
|
|
public void Lobby_IdleClientKeptAlivePastIdleTimeout_WithActiveOutcome()
|
|
{
|
|
using var host = new ServerMatchHost(
|
|
IPAddress.Loopback,
|
|
0,
|
|
seed: 42,
|
|
mapKind: ArenaMapKind.Desert,
|
|
startInLobby: true);
|
|
using var client = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "IdlePilot");
|
|
|
|
long simNowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
|
for (int i = 0; i < 100 && !client.IsJoined; i++)
|
|
{
|
|
simNowMs += 20;
|
|
host.StepOnce(simNowMs);
|
|
client.PumpNetwork(simNowMs);
|
|
Thread.Sleep(2);
|
|
}
|
|
Assert.True(client.IsJoined);
|
|
|
|
// Advance 8.5 seconds (> IdleTimeoutMs 5000ms and > ClientDisconnectTimeoutMs 6000ms) with ZERO SubmitLocalInput
|
|
for (int step = 0; step < 170; step++)
|
|
{
|
|
simNowMs += 50;
|
|
host.StepOnce(simNowMs);
|
|
client.PumpNetwork(simNowMs);
|
|
}
|
|
|
|
Assert.True(client.IsJoined);
|
|
Assert.True(client.ConnectionStatus.Connected);
|
|
Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome);
|
|
Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase);
|
|
Assert.Equal(1, host.ConnectedHumanCount);
|
|
}
|
|
|
|
[Fact]
|
|
public void Lobby_SynchronizedLaunch_TransitionsToActiveAndDropsWave0AcrossHostAndRemote()
|
|
{
|
|
using var listenHost = new ListenHostArenaSession(
|
|
IPAddress.Loopback,
|
|
0,
|
|
seed: 42,
|
|
mapKind: ArenaMapKind.Desert,
|
|
startInLobby: true,
|
|
minHumansToStart: 2);
|
|
using var remote = new RemoteArenaSession(
|
|
new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort),
|
|
"DropMate");
|
|
|
|
var deadline = DateTime.UtcNow.AddSeconds(3);
|
|
while (!remote.IsJoined && DateTime.UtcNow < deadline)
|
|
{
|
|
PumpListenHostAndClient(listenHost, remote);
|
|
}
|
|
Assert.True(remote.IsJoined);
|
|
|
|
Assert.True(listenHost.SetLobbyReady(true));
|
|
Assert.True(remote.SetLobbyReady(true));
|
|
|
|
// Step 320 ticks (~5.33s at 60Hz) so the 5.0s countdown completes cleanly
|
|
for (int tick = 0; tick < 330; tick++)
|
|
{
|
|
listenHost.SubmitLocalInput(default, isPhysicsTick: true);
|
|
remote.PumpNetwork();
|
|
if (listenHost.ViewState.Phase == MatchPhase.Active &&
|
|
remote.ViewState.Phase == MatchPhase.Active &&
|
|
remote.ActivePods.Count > 0)
|
|
{
|
|
break;
|
|
}
|
|
Thread.Sleep(1);
|
|
}
|
|
|
|
// Pump a few extra frames to ensure all Wave 0 reliable events arrive on remote
|
|
PumpListenHostAndClient(listenHost, remote, ticks: 10);
|
|
|
|
Assert.Equal(MatchPhase.Active, listenHost.ViewState.Phase);
|
|
Assert.Equal(MatchPhase.Active, remote.ViewState.Phase);
|
|
Assert.Equal(ClientMatchOutcome.Active, listenHost.LocalOutcome);
|
|
Assert.Equal(ClientMatchOutcome.Active, remote.LocalOutcome);
|
|
|
|
Assert.True(listenHost.ActivePods.Count >= MatchState.ContenderCount);
|
|
Assert.Equal(ContenderLifecycle.Deploying, listenHost.LocalContender.Lifecycle);
|
|
Assert.Equal(ContenderLifecycle.Deploying, remote.LocalContender.Lifecycle);
|
|
Assert.Contains(remote.ActivePods, p => p.PodKind == OrbitalPodKind.Contender && p.ContenderId == remote.LocalContenderId);
|
|
|
|
var remoteEvents = new List<ISimEvent>();
|
|
remote.DrainSimEvents(remoteEvents);
|
|
Assert.Contains(remoteEvents, e => e is MatchStartedEvent);
|
|
}
|
|
|
|
[Fact]
|
|
public void CorePvs_RoundTripsMatchPhaseLobby_Within1152Bytes()
|
|
{
|
|
var state = new MatchState(seed: 42, ArenaMapKind.Desert, startInLobby: true);
|
|
var local = state.Contenders[0];
|
|
local.Grid.SwapChassis(Catalog.Bastion);
|
|
|
|
var contenders = new List<NetContenderState>(12);
|
|
var walkers = new List<NetWalkerEntry>(12);
|
|
var specs = new List<NetSpectatorState>(10);
|
|
|
|
for (int i = 0; i < 12; i++)
|
|
{
|
|
contenders.Add(new NetContenderState
|
|
{
|
|
SlotId = (byte)i,
|
|
Alive = true,
|
|
IsHuman = i < 2,
|
|
Lifecycle = ContenderLifecycle.Deploying,
|
|
Pos = new Vector3(i * 10f, 3f, -i * 5f),
|
|
Rot = Quaternion.Identity,
|
|
Vel = Vector3.Zero,
|
|
CoreHpRatio = 1f
|
|
});
|
|
var ws = new WalkerVisualSnapshot { LegCount = 4 };
|
|
walkers.Add(new NetWalkerEntry { IsContender = true, EntityId = (byte)i, Snapshot = ws });
|
|
}
|
|
|
|
byte[] payload = SnapshotCodec.EncodeCorePvs(
|
|
1, 5, 10, 0f, 0, 0, 772f, MatchPhase.Lobby, null, 0, 0xFFF,
|
|
local, Vector3.Zero, contenders, walkers, specs);
|
|
byte[] wireFrame = SnapshotCodec.WrapLatest(payload, 1, 5);
|
|
byte[] rudpDatagram = CultNetRudpPacketCodec.Encode(new CultNetRudpPacket
|
|
{
|
|
ConnectionId = 0x52544431,
|
|
PacketType = CultNetRudpPacketType.Data,
|
|
ChannelId = SnapshotCodec.ChannelLatest,
|
|
Sequence = 5,
|
|
Sequenced = true,
|
|
Payload = wireFrame
|
|
});
|
|
|
|
Assert.True(rudpDatagram.Length <= SnapshotCodec.MaxLatestDatagramBytes,
|
|
$"Lobby CorePvs UDP datagram {rudpDatagram.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B");
|
|
|
|
Assert.True(SnapshotCodec.TryDecodeCorePvs(payload, out var decoded));
|
|
Assert.Equal(MatchPhase.Lobby, decoded.Phase);
|
|
Assert.Null(decoded.WinnerContenderId);
|
|
|
|
// Also verify Completed + WinnerContenderId still round-trips via bit 2 (0x04)
|
|
byte[] completedPayload = SnapshotCodec.EncodeCorePvs(
|
|
1, 6, 12, 100f, 0, 0, 120f, MatchPhase.Completed, 3, 0, 0xFFF,
|
|
local, Vector3.Zero, contenders, walkers, specs);
|
|
Assert.True(SnapshotCodec.TryDecodeCorePvs(completedPayload, out var decodedCompleted));
|
|
Assert.Equal(MatchPhase.Completed, decodedCompleted.Phase);
|
|
Assert.Equal(3, decodedCompleted.WinnerContenderId);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task StatelessUdpPing_HandlesMultiByteUtf8ServerName_WithoutOverflow()
|
|
{
|
|
string multiByteName = new string('\u2022', 24);
|
|
using var host = new ServerMatchHost(
|
|
IPAddress.Loopback,
|
|
0,
|
|
seed: 77,
|
|
mapKind: ArenaMapKind.Desert,
|
|
serverName: multiByteName,
|
|
startInLobby: true);
|
|
|
|
var target = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
|
|
var pingTask = ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2));
|
|
while (!pingTask.IsCompleted)
|
|
{
|
|
host.PollStatelessPings();
|
|
await Task.Delay(5);
|
|
}
|
|
|
|
var res = await pingTask;
|
|
Assert.True(res.Success);
|
|
Assert.NotNull(res.Summary);
|
|
Assert.Equal(new string('\u2022', 16), res.Summary!.Value.ServerName);
|
|
}
|
|
|
|
[Fact]
|
|
public void LobbySquadSwap_ReliableRoundTrip()
|
|
{
|
|
using var listenHost = new ListenHostArenaSession(
|
|
IPAddress.Loopback,
|
|
0,
|
|
seed: 42,
|
|
mapKind: ArenaMapKind.Desert,
|
|
startInLobby: true,
|
|
minHumansToStart: 2,
|
|
squadSize: 3);
|
|
using var remote = new RemoteArenaSession(
|
|
new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort),
|
|
"WingBuddy");
|
|
|
|
var deadline = DateTime.UtcNow.AddSeconds(3);
|
|
while (!remote.IsJoined && DateTime.UtcNow < deadline)
|
|
{
|
|
PumpListenHostAndClient(listenHost, remote);
|
|
}
|
|
Assert.True(remote.IsJoined);
|
|
int remoteId = remote.LocalContenderId;
|
|
|
|
Assert.Equal((byte)3, listenHost.LobbyState?.SquadSize);
|
|
Assert.Equal((byte)3, remote.LobbyState?.SquadSize);
|
|
Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId);
|
|
|
|
// 1. Remote client swaps to Squad 2 -> swaps cleanly with an AI in Squad 2
|
|
Assert.True(remote.RequestLobbySquad(2));
|
|
PumpListenHostAndClient(listenHost, remote, ticks: 15);
|
|
Assert.Equal((byte)2, listenHost.LobbyState!.Slots[remoteId].SquadId);
|
|
Assert.Equal((byte)2, remote.LobbyState!.Slots[remoteId].SquadId);
|
|
|
|
// 2. Host switches SquadMode to Duos (2) -> slots regroup cleanly to 2-player squads
|
|
Assert.True(listenHost.RequestLobbyConfig(77, ArenaMapKind.Desert, 2));
|
|
PumpListenHostAndClient(listenHost, remote, ticks: 15);
|
|
Assert.Equal((byte)2, listenHost.LobbyState!.SquadSize);
|
|
Assert.Equal((byte)2, remote.LobbyState!.SquadSize);
|
|
Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId);
|
|
|
|
// 3. Remote swaps to Squad 3, then back to Squad 0 (Host's Duo), both ready up & launch!
|
|
Assert.True(remote.RequestLobbySquad(3));
|
|
PumpListenHostAndClient(listenHost, remote, ticks: 15);
|
|
Assert.Equal((byte)3, remote.LobbyState!.Slots[remoteId].SquadId);
|
|
|
|
Assert.True(remote.RequestLobbySquad(0));
|
|
PumpListenHostAndClient(listenHost, remote, ticks: 15);
|
|
Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId);
|
|
|
|
Assert.True(listenHost.SetLobbyReady(true));
|
|
Assert.True(remote.SetLobbyReady(true));
|
|
for (int tick = 0; tick < 340; tick++)
|
|
{
|
|
listenHost.SubmitLocalInput(default, isPhysicsTick: true);
|
|
remote.PumpNetwork();
|
|
if (listenHost.ViewState.Phase == MatchPhase.Active &&
|
|
remote.ViewState.Phase == MatchPhase.Active &&
|
|
remote.ActivePods.Count > 0)
|
|
{
|
|
break;
|
|
}
|
|
Thread.Sleep(1);
|
|
}
|
|
PumpListenHostAndClient(listenHost, remote, ticks: 10);
|
|
|
|
Assert.Equal(MatchPhase.Active, listenHost.ViewState.Phase);
|
|
Assert.Equal(MatchPhase.Active, remote.ViewState.Phase);
|
|
Assert.Equal((byte)2, listenHost.ViewState.SquadSize);
|
|
Assert.Equal((byte)2, remote.ViewState.SquadSize);
|
|
Assert.Equal(0, listenHost.ViewState.Contenders[remoteId].SquadId);
|
|
Assert.Equal(0, remote.ViewState.Contenders[remoteId].SquadId);
|
|
Assert.True(listenHost.ViewState.AreAllies(0, remoteId));
|
|
Assert.True(remote.ViewState.AreAllies(0, remoteId));
|
|
}
|
|
|
|
[Fact]
|
|
public void LobbySquadSwap_MidMatchReconnectAndLateJoin_PreservesAll12SquadIdsOutsidePvs()
|
|
{
|
|
using var host = new ServerMatchHost(
|
|
IPAddress.Loopback,
|
|
0,
|
|
seed: 42,
|
|
mapKind: ArenaMapKind.Desert,
|
|
startInLobby: true,
|
|
minHumansToStart: 1,
|
|
squadSize: 3);
|
|
var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
|
|
|
|
using var clientA = new RemoteArenaSession(ep, "LeaderSwap");
|
|
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
|
var deadline = DateTime.UtcNow.AddSeconds(3);
|
|
while (!clientA.IsJoined && DateTime.UtcNow < deadline)
|
|
{
|
|
nowMs += 16;
|
|
host.StepOnce(nowMs);
|
|
clientA.PumpNetwork();
|
|
Thread.Sleep(2);
|
|
}
|
|
Assert.True(clientA.IsJoined);
|
|
int slotA = clientA.LocalContenderId;
|
|
Assert.Equal(0, slotA);
|
|
|
|
// Polish check: out-of-range TargetSquadId >= maxSquads (4 for SquadSize=3) must be rejected, not clamped
|
|
Assert.False(host.MovePeerToSquad(slotA, 4));
|
|
Assert.Equal((byte)0, host.Session.State.Contenders[slotA].SquadId);
|
|
|
|
// Swap Slot 0 (0 -> 2) and Slot 6 (2 -> 0) in Lobby (SquadSize = 3)
|
|
Assert.True(clientA.RequestLobbySquad(2));
|
|
for (int t = 0; t < 20; t++)
|
|
{
|
|
nowMs += 16;
|
|
host.StepOnce(nowMs);
|
|
clientA.PumpNetwork();
|
|
Thread.Sleep(2);
|
|
}
|
|
Assert.Equal((byte)2, host.Session.State.Contenders[0].SquadId);
|
|
Assert.Equal((byte)0, host.Session.State.Contenders[6].SquadId);
|
|
|
|
// Launch to MatchPhase.Active
|
|
Assert.True(host.SetLobbyReady(slotA, true));
|
|
for (int tick = 0; tick < 340; tick++)
|
|
{
|
|
nowMs += 16;
|
|
host.StepOnce(nowMs);
|
|
clientA.PumpNetwork();
|
|
if (host.Session.State.Phase == MatchPhase.Active && clientA.ViewState.Phase == MatchPhase.Active)
|
|
{
|
|
break;
|
|
}
|
|
Thread.Sleep(1);
|
|
}
|
|
Assert.Equal(MatchPhase.Active, host.Session.State.Phase);
|
|
|
|
// Position contenders far apart across Desert so non-allies (including Slot 6) are outside PVS
|
|
host.Session.SetContenderPose(0, -320f, -320f, 0f);
|
|
for (int i = 1; i < MatchState.ContenderCount; i++)
|
|
{
|
|
if (host.Session.State.AreAllies(0, i))
|
|
{
|
|
host.Session.SetContenderPose(i, -310f + i * 3f, -320f, 0f);
|
|
}
|
|
else
|
|
{
|
|
host.Session.SetContenderPose(i, 320f, 320f - i * 8f, MathF.PI);
|
|
}
|
|
}
|
|
nowMs += 16;
|
|
host.StepOnce(nowMs);
|
|
Assert.False(host.Session.IsEntityInPeerPvs(0, true, 6));
|
|
|
|
// 1. Reconnect clientA mid-match and assert ALL 12 SquadIds and AreAllies match server 12/12
|
|
Guid tokenA = clientA.ReconnectToken;
|
|
clientA.DisconnectGracefully("ReconnectSquadTest");
|
|
clientA.Dispose();
|
|
for (int t = 0; t < 20; t++)
|
|
{
|
|
nowMs += 16;
|
|
host.StepOnce(nowMs);
|
|
Thread.Sleep(1);
|
|
}
|
|
|
|
using var clientARejoin = new RemoteArenaSession(ep, "LeaderSwap", tokenA);
|
|
deadline = DateTime.UtcNow.AddSeconds(3);
|
|
while (!clientARejoin.IsJoined && DateTime.UtcNow < deadline)
|
|
{
|
|
nowMs += 16;
|
|
host.StepOnce(nowMs);
|
|
clientARejoin.PumpNetwork();
|
|
Thread.Sleep(2);
|
|
}
|
|
Assert.True(clientARejoin.IsJoined);
|
|
Assert.Equal(0, clientARejoin.LocalContenderId);
|
|
|
|
// 2. Late-join a fresh clientB mid-match while non-allies are outside PVS
|
|
using var clientB = new RemoteArenaSession(ep, "LateJoiner");
|
|
deadline = DateTime.UtcNow.AddSeconds(3);
|
|
while (!clientB.IsJoined && DateTime.UtcNow < deadline)
|
|
{
|
|
nowMs += 16;
|
|
host.StepOnce(nowMs);
|
|
clientARejoin.PumpNetwork();
|
|
clientB.PumpNetwork();
|
|
Thread.Sleep(2);
|
|
}
|
|
Assert.True(clientB.IsJoined);
|
|
|
|
var serverState = host.Session.State;
|
|
for (int i = 0; i < MatchState.ContenderCount; i++)
|
|
{
|
|
Assert.Equal(serverState.Contenders[i].SquadId, clientARejoin.ViewState.Contenders[i].SquadId);
|
|
Assert.Equal(serverState.Contenders[i].SquadId, clientB.ViewState.Contenders[i].SquadId);
|
|
for (int j = 0; j < MatchState.ContenderCount; j++)
|
|
{
|
|
Assert.Equal(serverState.AreAllies(i, j), clientARejoin.ViewState.AreAllies(i, j));
|
|
Assert.Equal(serverState.AreAllies(i, j), clientB.ViewState.AreAllies(i, j));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|