|
| 1 | +using System.Net; |
| 2 | +using System.Net.Http.Json; |
| 3 | +using Microsoft.AspNetCore.Hosting; |
| 4 | +using Microsoft.EntityFrameworkCore; |
| 5 | +using Microsoft.Extensions.DependencyInjection; |
| 6 | +using OpenShock.API.Models.Response; |
| 7 | +using OpenShock.Common.OpenShockDb; |
| 8 | +using OpenShock.Common.Redis; |
| 9 | +using OpenShock.Common.Services.Geo; |
| 10 | +using OpenShock.Common.Utils; |
| 11 | +using OpenShock.Internal.Common.Utils; |
| 12 | +using Redis.OM.Contracts; |
| 13 | + |
| 14 | +namespace OpenShock.API.IntegrationTests.Tests; |
| 15 | + |
| 16 | +public sealed class LcgCoordinateAssignmentTests |
| 17 | +{ |
| 18 | + [ClassDataSource<GeoLocatedWebApplicationFactory>(Shared = SharedType.PerTestSession)] |
| 19 | + public required GeoLocatedWebApplicationFactory WebApplicationFactory { get; init; } |
| 20 | + |
| 21 | + // Shares the key with LcgAssignmentTests: both suites wipe the same Redis node collection. |
| 22 | + private const string ParalellGateway = "gateway_assignment"; |
| 23 | + |
| 24 | + private static readonly GeoPoint Seattle = new(47.61, -122.33); |
| 25 | + private static readonly GeoPoint NewYork = new(40.71, -74.01); |
| 26 | + private static readonly GeoPoint Oregon = new(45.60, -121.18); |
| 27 | + private static readonly GeoPoint Virginia = new(39.04, -77.49); |
| 28 | + private static readonly GeoPoint Frankfurt = new(50.11, 8.68); |
| 29 | + private static readonly GeoPoint Munich = new(48.14, 11.58); |
| 30 | + private static readonly GeoPoint Hamburg = new(53.55, 9.99); |
| 31 | + private static readonly GeoPoint Vienna = new(48.21, 16.37); |
| 32 | + |
| 33 | + private Guid _userId; |
| 34 | + private Guid _hubId; |
| 35 | + private string _hubToken = string.Empty; |
| 36 | + |
| 37 | + [Before(Test)] |
| 38 | + public async Task Setup() |
| 39 | + { |
| 40 | + await using var context = WebApplicationFactory.Services.CreateAsyncScope(); |
| 41 | + var db = context.ServiceProvider.GetRequiredService<OpenShockContext>(); |
| 42 | + |
| 43 | + _userId = Guid.CreateVersion7(); |
| 44 | + _hubId = Guid.CreateVersion7(); |
| 45 | + _hubToken = CryptoUtils.RandomString(256); |
| 46 | + |
| 47 | + db.Users.Add(new User |
| 48 | + { |
| 49 | + Id = _userId, |
| 50 | + Name = _userId.ToString("N"), |
| 51 | + Email = $"{_userId}@test.org", |
| 52 | + PasswordHash = HashingUtils.HashPassword("password") |
| 53 | + }); |
| 54 | + db.Devices.Add(new Device |
| 55 | + { |
| 56 | + Id = _hubId, |
| 57 | + Name = "TestHub", |
| 58 | + OwnerId = _userId, |
| 59 | + Token = _hubToken, |
| 60 | + CreatedAt = DateTime.UtcNow |
| 61 | + }); |
| 62 | + await db.SaveChangesAsync(); |
| 63 | + } |
| 64 | + |
| 65 | + [After(Test)] |
| 66 | + public async Task Teardown() |
| 67 | + { |
| 68 | + WebApplicationFactory.ClientLocation = null; |
| 69 | + |
| 70 | + await using var context = WebApplicationFactory.Services.CreateAsyncScope(); |
| 71 | + var db = context.ServiceProvider.GetRequiredService<OpenShockContext>(); |
| 72 | + var lcgNodesCollection = context.ServiceProvider.GetRequiredService<IRedisConnectionProvider>().RedisCollection<LcgNode>(false); |
| 73 | + |
| 74 | + await db.Devices.Where(x => x.Id == _hubId).ExecuteDeleteAsync(); |
| 75 | + await db.Users.Where(x => x.Id == _userId).ExecuteDeleteAsync(); |
| 76 | + |
| 77 | + var allLcg = await lcgNodesCollection.ToListAsync(); |
| 78 | + await lcgNodesCollection.DeleteAsync(allLcg); |
| 79 | + } |
| 80 | + |
| 81 | + [Test] |
| 82 | + [NotInParallel(ParalellGateway)] |
| 83 | + public async Task PicksClosestGatewayWithinSameCountry() |
| 84 | + { |
| 85 | + // Both gateways are "US", so the country table alone ties them; coordinates break the tie. |
| 86 | + await AddGateway("us-west.example.com", "US", Oregon); |
| 87 | + await AddGateway("us-east.example.com", "US", Virginia); |
| 88 | + |
| 89 | + WebApplicationFactory.ClientLocation = Seattle; |
| 90 | + await Assert.That(await AssignHost("US")).IsEqualTo("us-west.example.com"); |
| 91 | + |
| 92 | + WebApplicationFactory.ClientLocation = NewYork; |
| 93 | + await Assert.That(await AssignHost("US")).IsEqualTo("us-east.example.com"); |
| 94 | + } |
| 95 | + |
| 96 | + [Test] |
| 97 | + [NotInParallel(ParalellGateway)] |
| 98 | + public async Task UsesCoordinatesWithoutCountryHeader() |
| 99 | + { |
| 100 | + await AddGateway("us-west.example.com", "US", Oregon); |
| 101 | + await AddGateway("de1.example.com", "DE", Frankfurt); |
| 102 | + |
| 103 | + WebApplicationFactory.ClientLocation = Seattle; |
| 104 | + await Assert.That(await AssignHost(null)).IsEqualTo("us-west.example.com"); |
| 105 | + } |
| 106 | + |
| 107 | + [Test] |
| 108 | + [NotInParallel(ParalellGateway)] |
| 109 | + public async Task FallsBackToCountryWhenClientHasNoLocation() |
| 110 | + { |
| 111 | + await AddGateway("us-west.example.com", "US", Oregon); |
| 112 | + await AddGateway("de1.example.com", "DE", Frankfurt); |
| 113 | + |
| 114 | + WebApplicationFactory.ClientLocation = null; |
| 115 | + await Assert.That(await AssignHost("DE")).IsEqualTo("de1.example.com"); |
| 116 | + } |
| 117 | + |
| 118 | + [Test] |
| 119 | + [NotInParallel(ParalellGateway)] |
| 120 | + public async Task FallsBackToCountryForGatewayWithoutLocation() |
| 121 | + { |
| 122 | + // A gateway that has not configured coordinates must still be assignable by country. |
| 123 | + await AddGateway("us-west.example.com", "US", Oregon); |
| 124 | + await AddGateway("de1.example.com", "DE", null); |
| 125 | + |
| 126 | + WebApplicationFactory.ClientLocation = Frankfurt; |
| 127 | + await Assert.That(await AssignHost("DE")).IsEqualTo("de1.example.com"); |
| 128 | + } |
| 129 | + |
| 130 | + [Test] |
| 131 | + [NotInParallel(ParalellGateway)] |
| 132 | + public async Task CoordinatesOverrideLoadWithinRegion() |
| 133 | + { |
| 134 | + // Baseline for MixedCoordinatesLeaveRegionUntouched: with full coordinates, distance wins over load. |
| 135 | + await AddGateway("us-west.example.com", "US", Oregon, load: 5); |
| 136 | + await AddGateway("us-east.example.com", "US", Virginia, load: 0); |
| 137 | + |
| 138 | + WebApplicationFactory.ClientLocation = Seattle; |
| 139 | + await Assert.That(await AssignHost("US")).IsEqualTo("us-west.example.com"); |
| 140 | + } |
| 141 | + |
| 142 | + [Test] |
| 143 | + [NotInParallel(ParalellGateway)] |
| 144 | + public async Task MixedCoordinatesLeaveRegionUntouched() |
| 145 | + { |
| 146 | + // us-east has no coordinates, so the US region can't be ranked fairly and must fall back to |
| 147 | + // pure load balancing, rather than us-east winning on a 0 km same-country score. |
| 148 | + await AddGateway("us-west.example.com", "US", Oregon, load: 0); |
| 149 | + await AddGateway("us-east.example.com", "US", null, load: 5); |
| 150 | + |
| 151 | + WebApplicationFactory.ClientLocation = NewYork; |
| 152 | + await Assert.That(await AssignHost("US")).IsEqualTo("us-west.example.com"); |
| 153 | + } |
| 154 | + |
| 155 | + [Test] |
| 156 | + [NotInParallel(ParalellGateway)] |
| 157 | + public async Task CoordinatesDoNotCrossCountryPick() |
| 158 | + { |
| 159 | + // Munich is nearer Vienna than Hamburg, but coordinates only refine the country pick. |
| 160 | + await AddGateway("de1.example.com", "DE", Hamburg); |
| 161 | + await AddGateway("at1.example.com", "AT", Vienna); |
| 162 | + |
| 163 | + WebApplicationFactory.ClientLocation = Munich; |
| 164 | + await Assert.That(await AssignHost("DE")).IsEqualTo("de1.example.com"); |
| 165 | + } |
| 166 | + |
| 167 | + private async Task AddGateway(string host, string country, GeoPoint? location, byte load = 0) |
| 168 | + { |
| 169 | + await using var context = WebApplicationFactory.Services.CreateAsyncScope(); |
| 170 | + var environment = context.ServiceProvider.GetRequiredService<IWebHostEnvironment>(); |
| 171 | + var lcgNodesCollection = context.ServiceProvider.GetRequiredService<IRedisConnectionProvider>().RedisCollection<LcgNode>(false); |
| 172 | + |
| 173 | + await lcgNodesCollection.InsertAsync(new LcgNode |
| 174 | + { |
| 175 | + Id = host, |
| 176 | + Host = host, |
| 177 | + Port = 443, |
| 178 | + Country = country, |
| 179 | + Latitude = location?.Latitude, |
| 180 | + Longitude = location?.Longitude, |
| 181 | + Load = load, |
| 182 | + Environment = environment.EnvironmentName |
| 183 | + }); |
| 184 | + } |
| 185 | + |
| 186 | + private async Task<string> AssignHost(string? requesterCountry) |
| 187 | + { |
| 188 | + var httpRequest = new HttpRequestMessage(HttpMethod.Get, "/2/device/assignLCG?version=2"); |
| 189 | + httpRequest.Headers.Add("Device-Token", _hubToken); |
| 190 | + if (!string.IsNullOrEmpty(requesterCountry)) httpRequest.Headers.Add("CF-IPCountry", requesterCountry); |
| 191 | + |
| 192 | + using var client = WebApplicationFactory.CreateClient(); |
| 193 | + using var response = await client.SendAsync(httpRequest); |
| 194 | + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); |
| 195 | + |
| 196 | + var data = await response.Content.ReadFromJsonAsync<LcgNodeResponseV2>(); |
| 197 | + await Assert.That(data).IsNotNull(); |
| 198 | + return data!.Host; |
| 199 | + } |
| 200 | +} |
0 commit comments