This repository has been archived on 2026-10-29. You can view files and clone it, but you cannot make any changes to its state, such as pushing and creating new issues, pull requests or comments.
EveUnity/packages/org.gamecult.eve.unity-scene/Tests/Editor/EveUnityCultMeshAssetLookupTests.cs

378 lines
16 KiB
C#

using System;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using GameCult.Eve.Surface;
using GameCult.Eve.UnityScene;
using GameCult.Mesh;
using NUnit.Framework;
using UnityEngine;
namespace GameCult.Eve.UnityScene.Tests
{
public sealed class EveUnityCultMeshAssetLookupTests
{
[Test]
public void ConnectCannotPerformRemoteWorkBeforeAsynchronousPreparation()
{
using var transport = new EveUnityCultMeshLiveProviderTransport(
"test-cache",
"cultnet+tcp://127.0.0.1:1",
"test.verse",
"test.runtime",
"test.provider",
"test.surface");
var elapsed = Stopwatch.StartNew();
var failure = Assert.Throws<InvalidOperationException>(() => transport.Connect());
StringAssert.Contains("Await PrepareAsync", failure!.Message);
Assert.That(elapsed.Elapsed, Is.LessThan(TimeSpan.FromMilliseconds(100)));
}
[Test]
public async Task CommandOutboxCompletesOnlyAfterCanonicalReceipt()
{
var entered = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var sends = 0;
using var outbox = new EveUnityCultMeshCommandOutbox(
async (_, cancellationToken) =>
{
Interlocked.Increment(ref sends);
entered.TrySetResult(true);
await AwaitOrCancel(release.Task, cancellationToken);
},
_ => null,
retryDelay: TimeSpan.FromMilliseconds(250));
var elapsed = Stopwatch.StartNew();
outbox.Enqueue(Request("one-shot", "dock"));
Assert.That(elapsed.Elapsed, Is.LessThan(TimeSpan.FromMilliseconds(100)));
await RequireCompletion(entered.Task);
Assert.That(outbox.PendingCount, Is.EqualTo(1));
release.TrySetResult(true);
await WaitUntilAsync(() => outbox.StateOf("one-shot") ==
EveUnityCultMeshCommandOutbox.DeliveryState.AwaitingCanonicalReceipt);
Assert.That(outbox.PendingCount, Is.EqualTo(1));
Assert.That(sends, Is.EqualTo(1));
Assert.That(outbox.Acknowledge("one-shot"), Is.True);
Assert.That(outbox.Acknowledge("one-shot"), Is.False);
await WaitUntilAsync(() => outbox.PendingCount == 0);
}
[Test]
public async Task CommandOutboxCoalescesBlockedContinuousInputToTheLatestValue()
{
var entered = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var sent = new List<string>();
using var outbox = new EveUnityCultMeshCommandOutbox(
async (request, cancellationToken) =>
{
lock (sent) sent.Add(request.CommandId);
entered.TrySetResult(true);
await AwaitOrCancel(release.Task, cancellationToken);
},
request => request.PayloadFields["commandId"] + "\u001f" + request.PayloadFields["entityId"],
retryDelay: TimeSpan.FromMilliseconds(250));
outbox.Enqueue(Request("move-0", "move"));
await RequireCompletion(entered.Task);
for (var index = 1; index <= 1000; index++)
outbox.Enqueue(Request("move-" + index, "move"));
Assert.That(outbox.PendingCount, Is.LessThanOrEqualTo(2));
release.TrySetResult(true);
await WaitUntilAsync(() => outbox.StateOf("move-1000") ==
EveUnityCultMeshCommandOutbox.DeliveryState.AwaitingCanonicalReceipt);
Assert.That(outbox.Acknowledge("move-1000"), Is.True);
await WaitUntilAsync(() => outbox.PendingCount == 0);
lock (sent)
{
CollectionAssert.AreEqual(new[] { "move-0", "move-1000" }, sent);
}
}
[Test]
public async Task CommandOutboxRetriesSameIdWithoutLettingPoisonCommandStarveLaterWork()
{
var attempts = new List<string>();
using var outbox = new EveUnityCultMeshCommandOutbox(
(request, _) =>
{
lock (attempts) attempts.Add(request.CommandId);
if (request.CommandId == "poison") throw new IOException("route unavailable");
return Task.CompletedTask;
},
_ => null,
retryDelay: TimeSpan.FromMilliseconds(20),
maximumRetryDelay: TimeSpan.FromMilliseconds(40));
outbox.Enqueue(Request("poison", "dock"));
outbox.Enqueue(Request("healthy", "undock"));
await WaitUntilAsync(() => outbox.StateOf("healthy") ==
EveUnityCultMeshCommandOutbox.DeliveryState.AwaitingCanonicalReceipt);
Assert.That(outbox.Acknowledge("healthy"), Is.True);
lock (attempts)
{
Assert.That(attempts.IndexOf("healthy"), Is.GreaterThanOrEqualTo(0));
Assert.That(attempts.FindAll(value => value == "poison"), Is.Not.Empty);
}
Assert.That(outbox.PendingCount, Is.EqualTo(1));
}
[Test]
public async Task CommandOutboxRetransmitsUnacknowledgedCommandWithOriginalId()
{
var attempts = 0;
using var outbox = new EveUnityCultMeshCommandOutbox(
(request, _) =>
{
Assert.That(request.CommandId, Is.EqualTo("retry-me"));
Interlocked.Increment(ref attempts);
return Task.CompletedTask;
},
_ => null,
retryDelay: TimeSpan.FromMilliseconds(20),
maximumRetryDelay: TimeSpan.FromMilliseconds(20));
outbox.Enqueue(Request("retry-me", "dock"));
await WaitUntilAsync(() => Volatile.Read(ref attempts) >= 2);
Assert.That(outbox.PendingCount, Is.EqualTo(1));
Assert.That(outbox.Acknowledge("retry-me"), Is.True);
await WaitUntilAsync(() => outbox.PendingCount == 0);
}
[Test]
public void ProviderSelectionCarriesStableIdentityWithoutExposingAPhysicalRoute()
{
var selection = new EveUnityCultMeshProviderSelection(
"cultnet+tcp://odin.example:3075",
"aetheria.public",
"aetheria.public",
"aetheria.daemon",
"aetheria.pilot",
"interactive-world");
Assert.That(selection.RendezvousEndpoint, Is.EqualTo("cultnet+tcp://odin.example:3075"));
Assert.That(selection.VerseId, Is.EqualTo("aetheria.public"));
Assert.That(selection.AuthorityRuntimeId, Is.EqualTo("aetheria.public"));
Assert.That(typeof(EveUnityCultMeshProviderSelection).GetProperty("Endpoint"), Is.Null);
}
private static EveSurfaceCommandRequest Request(string id, string command) => new EveSurfaceCommandRequest(
"test.provider",
"test.surface",
CultMesh.OperationInvocation("test.command", idempotencyKey: id),
CultMesh.OperationPayload(new Dictionary<string, string>
{
["commandId"] = command,
["entityId"] = "ship"
}),
DateTimeOffset.UtcNow,
"test-client");
private static async Task AwaitOrCancel(Task task, CancellationToken cancellationToken)
{
var cancelled = Task.Delay(Timeout.Infinite, cancellationToken);
if (await Task.WhenAny(task, cancelled) != task)
cancellationToken.ThrowIfCancellationRequested();
await task;
}
private static async Task RequireCompletion(Task task)
{
if (await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(2))) != task)
Assert.Fail("Timed out waiting for asynchronous command delivery.");
await task;
}
private static async Task WaitUntilAsync(Func<bool> predicate)
{
var deadline = DateTimeOffset.UtcNow + TimeSpan.FromSeconds(2);
while (!predicate() && DateTimeOffset.UtcNow < deadline)
await Task.Delay(10);
Assert.That(predicate(), Is.True, "Timed out waiting for the command outbox to drain.");
}
[Test]
public void LiveTransportOwnsOneCultMeshClientAndNoDirectSnapshotReplica()
{
var fields = typeof(EveUnityCultMeshLiveProviderTransport)
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
var names = Array.ConvertAll(fields, field => field.Name);
CollectionAssert.Contains(names, "_meshClient");
CollectionAssert.DoesNotContain(names, "_node");
CollectionAssert.DoesNotContain(names, "_snapshot");
CollectionAssert.DoesNotContain(names, "_networkRegistry");
CollectionAssert.DoesNotContain(names, "_replicaShard");
CollectionAssert.DoesNotContain(names, "_subscriptions");
CollectionAssert.DoesNotContain(names, "_entitySubscriptions");
}
[Test]
public void UnavailableTcpRendezvousIsReportedAsRetryablePreparationFailure()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
var error = Assert.ThrowsAsync<InvalidOperationException>(() =>
new EveUnityCultMeshProviderDiscovery().DiscoverAsync($"cultnet+tcp://127.0.0.1:{port}"));
StringAssert.Contains("Could not query CultMesh rendezvous endpoint", error!.Message);
Assert.That(error.InnerException, Is.TypeOf<SocketException>());
}
[Test]
public void UnpreparedProviderGetterFailsFastWithoutStartingNetworkDiscovery()
{
var gameObject = new GameObject("unprepared-eve-provider");
try
{
var provider = gameObject.AddComponent<EveUnityCultMeshPlayableWorldProvider>();
provider.Configure("rudp://127.0.0.1:1");
var stopwatch = Stopwatch.StartNew();
var error = Assert.Throws<InvalidOperationException>(() => _ = provider.CurrentInputCapability);
stopwatch.Stop();
StringAssert.Contains("Await PrepareAsync", error!.Message);
Assert.That(stopwatch.ElapsedMilliseconds, Is.LessThan(100));
Assert.That(provider.Selection, Is.Null);
}
finally
{
UnityEngine.Object.DestroyImmediate(gameObject);
}
}
[Test]
public void ProviderSubscriptionsDoNotDependOnPreparedTransportLifetime()
{
var gameObject = new GameObject("unprepared-eve-provider-subscriptions");
var provider = gameObject.AddComponent<EveUnityCultMeshPlayableWorldProvider>();
Action<EveUnitySceneProviderSurfaceDocument> documentHandler = _ => { };
Action<EveUnitySceneCommandReceipt> receiptHandler = _ => { };
Assert.DoesNotThrow(() => provider.DocumentAvailable += documentHandler);
Assert.DoesNotThrow(() => provider.ReceiptAvailable += receiptHandler);
Assert.DoesNotThrow(() => provider.DocumentAvailable -= documentHandler);
Assert.DoesNotThrow(() => provider.ReceiptAvailable -= receiptHandler);
Assert.DoesNotThrow(() => UnityEngine.Object.DestroyImmediate(gameObject));
}
[Test]
public void ResolvesUnityNormalizedBundleNamesWithoutChangingLogicalAssetIdentity()
{
var method = typeof(EveUnityCultMeshLiveProviderTransport).GetMethod(
"ResolveBundleAssetName",
BindingFlags.Static | BindingFlags.NonPublic);
Assert.That(method, Is.Not.Null);
var result = method!.Invoke(null, new object[]
{
new[] { "assets/generated/eve/thermal/death.asset" },
"Assets/Generated/Eve/Thermal/Death.asset"
});
Assert.That(result, Is.EqualTo("assets/generated/eve/thermal/death.asset"));
}
[Test]
public void RejectsBundleNamesThatDoNotMatchTheAdvertisedAsset()
{
var method = typeof(EveUnityCultMeshLiveProviderTransport).GetMethod(
"ResolveBundleAssetName",
BindingFlags.Static | BindingFlags.NonPublic);
var result = method!.Invoke(null, new object[]
{
new[] { "assets/generated/eve/thermal/heatstroke.asset" },
"Assets/Generated/Eve/Thermal/Death.asset"
});
Assert.That(result, Is.Null);
}
[Test]
public void SelectedRuntimeVariantOwnsConcreteNativeProgramBindings()
{
var method = typeof(EveUnityCultMeshLiveProviderTransport).GetMethod(
"MergeAssetMetadata",
BindingFlags.Static | BindingFlags.NonPublic);
Assert.That(method, Is.Not.Null);
var result = method!.Invoke(null, new object[]
{
new Dictionary<string, string> { ["presentationRole"] = "environment.volume" },
new Dictionary<string, string>
{
["unity.volume.texturePort.surfaceHeight"] = "_NebulaSurfaceHeight",
["unity.volume.pass.raymarch"] = "0"
}
}) as IReadOnlyDictionary<string, string>;
Assert.That(result, Is.Not.Null);
Assert.That(result!["presentationRole"], Is.EqualTo("environment.volume"));
Assert.That(result["unity.volume.texturePort.surfaceHeight"], Is.EqualTo("_NebulaSurfaceHeight"));
Assert.That(result["unity.volume.pass.raymarch"], Is.EqualTo("0"));
}
[Test]
public void PublishingCatalogRegistersBundlesWithoutMaterializingThem()
{
var platformMethod = typeof(EveUnityCultMeshLiveProviderTransport).GetMethod(
"CurrentBundlePlatform",
BindingFlags.Static | BindingFlags.NonPublic);
var publishMethod = typeof(EveUnityCultMeshLiveProviderTransport).GetMethod(
"PublishAssetCatalog",
BindingFlags.Instance | BindingFlags.NonPublic);
var bundlesField = typeof(EveUnityCultMeshLiveProviderTransport).GetField(
"_assetBundles",
BindingFlags.Instance | BindingFlags.NonPublic);
var selectionsField = typeof(EveUnityCultMeshLiveProviderTransport).GetField(
"_assetSelections",
BindingFlags.Instance | BindingFlags.NonPublic);
Assert.That(platformMethod, Is.Not.Null);
Assert.That(publishMethod, Is.Not.Null);
using var transport = new EveUnityCultMeshLiveProviderTransport(
Path.Combine(Path.GetTempPath(), $"eve-lazy-assets-{Guid.NewGuid():N}.cc"),
"cultnet+tcp://127.0.0.1:1",
"provider",
"provider",
"provider",
"surface");
var variant = new EveAssetVariant(
"unity-scene",
(string)platformMethod!.Invoke(null, Array.Empty<object>())!,
"unity-assetbundle",
"cdn:manifest:lazy",
"sha256:00",
1,
"assets/prefab.prefab");
var catalog = new EveAssetCatalogDocument(
"provider",
"catalog",
1,
DateTimeOffset.UtcNow.ToString("O"),
new[] { new EveAssetCatalogEntry("prefab.entity", "prefab", new[] { variant }) });
publishMethod!.Invoke(transport, new object[] { catalog });
Assert.That(((System.Collections.ICollection)bundlesField!.GetValue(transport)!).Count, Is.Zero);
Assert.That(((System.Collections.IDictionary)selectionsField!.GetValue(transport)!).Count, Is.EqualTo(1));
}
}
}