diff options
Diffstat (limited to 'tests/SomhairlesDream.Server.Tests')
4 files changed, 579 insertions, 0 deletions
diff --git a/tests/SomhairlesDream.Server.Tests/ApiTests.fs b/tests/SomhairlesDream.Server.Tests/ApiTests.fs new file mode 100644 index 0000000..cc8a3da --- /dev/null +++ b/tests/SomhairlesDream.Server.Tests/ApiTests.fs @@ -0,0 +1,235 @@ +module SomhairlesDream.Server.Tests.ApiTests + +open System +open System.IO +open System.Net +open System.Net.Http +open System.Text +open System.Text.Json +open System.Threading +open Microsoft.AspNetCore.Builder +open Microsoft.AspNetCore.Hosting +open Microsoft.AspNetCore.TestHost +open Xunit +open SomhairlesDream.Modeling +open SomhairlesDream.Server +open SomhairlesDream.Shared + +let private ids : RunIds = + { ProjectId = "heritage-001" + RunId = "run-api-001" + BaseId = "base-000" + TargetId = "target-003" } + +let private withTempDirectory action = + let path = Path.Combine(Path.GetTempPath(), "somhairles-dream-api-" + Guid.NewGuid().ToString("N")) + Directory.CreateDirectory(path) |> ignore + + try + action path + finally + if Directory.Exists(path) then + Directory.Delete(path, true) + +type private TestBridge() = + interface IArtifactBridge with + member _.Export(request, _) = + File.WriteAllBytes(request.GlbPath, [| 0x67uy; 0x6Cuy; 0x54uy; byte request.Step.Index |]) + Directory.CreateDirectory(Path.GetDirectoryName(request.LogPath)) |> ignore + File.WriteAllText(request.LogPath, $"bridge log for {request.Step.StepId}") + + Ok + { BlenderVersion = "5.0.1" + ExportedAt = DateTimeOffset.Parse("2026-09-20T12:00:05Z") + ObjectIds = request.Step.ObjectIds + VerifiedObjectIds = request.Step.ObjectIds + GlbBytes = 4L + RenderPath = None + RenderedAt = None } + +type private BlockingBridge(gate: ManualResetEventSlim) = + interface IArtifactBridge with + member _.Export(request, _) = + gate.Wait() + (TestBridge() :> IArtifactBridge).Export(request, fun () -> ()) + +let private requestBody runId = + $"{{\"projectId\":\"{ids.ProjectId}\",\"runId\":\"{runId}\",\"baseId\":\"{ids.BaseId}\",\"targetId\":\"{ids.TargetId}\"}}" + +let private withAppUsing (bridgeFactory: unit -> IArtifactBridge) action = + withTempDirectory (fun root -> + let clock () = DateTimeOffset.Parse("2026-09-20T12:00:00Z") + let coordinator = + ArtifactRunCoordinator( + root, + bridgeFactory, + clock, + TimeSpan.FromSeconds 15. + ) + + let builder = WebApplication.CreateBuilder([||]) + builder.WebHost.UseTestServer() |> ignore + let app = builder.Build() + + ArtifactRunApi.register + app + { Coordinator = coordinator + Clock = clock + JsonOptions = JsonSerializerOptions(JsonSerializerDefaults.Web) } + + app.StartAsync().GetAwaiter().GetResult() + + try + action (app.GetTestClient()) coordinator + finally + app.StopAsync().GetAwaiter().GetResult() + app.DisposeAsync().AsTask().GetAwaiter().GetResult()) + +let private withApp action = withAppUsing (fun () -> TestBridge() :> IArtifactBridge) action + +let private waitFor predicate = + let deadline = DateTime.UtcNow.AddSeconds(5.) + let mutable matched = predicate () + + while not matched && DateTime.UtcNow < deadline do + Thread.Sleep(10) + matched <- predicate () + + matched + +[<Fact>] +let ``start endpoint accepts a run and conflicts on its second start`` () = + withApp (fun client _ -> + let first = + use content = new StringContent(requestBody ids.RunId, Encoding.UTF8, "application/json") + client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult() + + Assert.Equal(HttpStatusCode.Accepted, first.StatusCode) + + let firstSnapshot = + first.Content.ReadAsStringAsync().GetAwaiter().GetResult() + |> fun body -> JsonSerializer.Deserialize<RunSnapshot>(body, JsonSerializerOptions(JsonSerializerDefaults.Web)) + + Assert.Equal(ids.ProjectId, firstSnapshot.ProjectId) + Assert.Equal(ids.RunId, firstSnapshot.RunId) + + use duplicateContent = new StringContent(requestBody ids.RunId, Encoding.UTF8, "application/json") + let duplicate = client.PostAsync("/api/runs/start", duplicateContent).GetAwaiter().GetResult() + + Assert.Equal(HttpStatusCode.Conflict, duplicate.StatusCode)) + +[<Fact>] +let ``start endpoint rejects invalid resource ids before creating a run`` () = + withApp (fun client coordinator -> + let body = requestBody "../outside" + use content = new StringContent(body, Encoding.UTF8, "application/json") + let response = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult() + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode) + Assert.True(coordinator.TryFind(ids.ProjectId, "../outside").IsNone)) + +[<Fact>] +let ``manifest and artifact endpoints expose a completed run and reject traversal`` () = + withApp (fun client coordinator -> + let runId = "run-api-complete" + + use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json") + let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult() + Assert.Equal(HttpStatusCode.Accepted, start.StatusCode) + + let completed = + waitFor (fun () -> + coordinator.TryFind(ids.ProjectId, runId) + |> Option.exists (fun store -> store.Snapshot().Status = "complete")) + + Assert.True(completed) + + let manifest = + client + .GetAsync($"/api/artifacts/manifest?projectId={ids.ProjectId}&runId={runId}") + .GetAwaiter() + .GetResult() + + Assert.Equal(HttpStatusCode.OK, manifest.StatusCode) + let manifestBody = manifest.Content.ReadAsStringAsync().GetAwaiter().GetResult() + Assert.Contains("\"schemaVersion\":1", manifestBody) + + let glbPath = Uri.EscapeDataString("steps/01-foundation.glb") + let artifact = + client + .GetAsync($"/api/artifacts/file?projectId={ids.ProjectId}&runId={runId}&path={glbPath}") + .GetAwaiter() + .GetResult() + + Assert.Equal(HttpStatusCode.OK, artifact.StatusCode) + + let traversalPath = Uri.EscapeDataString("../manifest.json") + let traversal = + client + .GetAsync($"/api/artifacts/file?projectId={ids.ProjectId}&runId={runId}&path={traversalPath}") + .GetAwaiter() + .GetResult() + + Assert.Equal(HttpStatusCode.BadRequest, traversal.StatusCode)) + +[<Fact>] +let ``manifest endpoint reports active runs as conflicts`` () = + let gate = new ManualResetEventSlim(false) + + try + withAppUsing + (fun () -> BlockingBridge(gate) :> IArtifactBridge) + (fun client coordinator -> + let runId = "run-api-active" + use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json") + let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult() + Assert.Equal(HttpStatusCode.Accepted, start.StatusCode) + + let manifest = + client + .GetAsync($"/api/artifacts/manifest?projectId={ids.ProjectId}&runId={runId}") + .GetAwaiter() + .GetResult() + + Assert.Equal(HttpStatusCode.Conflict, manifest.StatusCode) + gate.Set() + + Assert.True( + waitFor (fun () -> + coordinator.TryFind(ids.ProjectId, runId) + |> Option.exists (fun store -> store.Snapshot().Status = "complete"))) + ) + finally + gate.Set() + gate.Dispose() + +[<Fact>] +let ``events endpoint streams only the selected run`` () = + withApp (fun client _ -> + let runId = "run-api-events" + use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json") + let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult() + Assert.Equal(HttpStatusCode.Accepted, start.StatusCode) + + use response = + client + .GetAsync( + $"/api/runs/events?projectId={ids.ProjectId}&runId={runId}", + HttpCompletionOption.ResponseHeadersRead + ) + .GetAwaiter() + .GetResult() + + Assert.Equal(HttpStatusCode.OK, response.StatusCode) + use reader = new StreamReader(response.Content.ReadAsStream()) + let line = reader.ReadLine() + Assert.StartsWith("data: ", line) + Assert.Contains(runId, line) + + let unknown = + client + .GetAsync($"/api/runs/events?projectId={ids.ProjectId}&runId=run-api-missing") + .GetAwaiter() + .GetResult() + + Assert.Equal(HttpStatusCode.NotFound, unknown.StatusCode)) diff --git a/tests/SomhairlesDream.Server.Tests/CoordinatorTests.fs b/tests/SomhairlesDream.Server.Tests/CoordinatorTests.fs new file mode 100644 index 0000000..e9689bb --- /dev/null +++ b/tests/SomhairlesDream.Server.Tests/CoordinatorTests.fs @@ -0,0 +1,83 @@ +module SomhairlesDream.Server.Tests.CoordinatorTests + +open System +open System.IO +open System.Threading +open Xunit +open SomhairlesDream.Modeling +open SomhairlesDream.Server +open SomhairlesDream.Shared + +let private ids : RunIds = + { ProjectId = "heritage-001" + RunId = "run-20260920-001" + BaseId = "heritage" + TargetId = "heritage-001" } + +let private withTempDirectory action = + let path = Path.Combine(Path.GetTempPath(), "somhairles-dream-server-" + Guid.NewGuid().ToString("N")) + Directory.CreateDirectory(path) |> ignore + + try + action path + finally + if Directory.Exists(path) then + Directory.Delete(path, true) + +type private TestBridge() = + interface IArtifactBridge with + member _.Export(request, _) = + File.WriteAllBytes(request.GlbPath, [| 0x67uy; 0x6Cuy; 0x54uy; byte request.Step.Index |]) + Directory.CreateDirectory(Path.GetDirectoryName(request.LogPath)) |> ignore + File.WriteAllText(request.LogPath, $"bridge log for {request.Step.StepId}") + + Ok + { BlenderVersion = "5.0.1" + ExportedAt = DateTimeOffset.Parse("2026-09-20T12:00:05Z") + ObjectIds = request.Step.ObjectIds + VerifiedObjectIds = request.Step.ObjectIds + GlbBytes = 4L + RenderPath = None + RenderedAt = None } + +let private waitFor predicate = + let deadline = DateTime.UtcNow.AddSeconds(5.) + let mutable matched = predicate () + + while not matched && DateTime.UtcNow < deadline do + Thread.Sleep(10) + matched <- predicate () + + matched + +[<Fact>] +let ``coordinator starts one shared pipeline and publishes its manifest`` () = + withTempDirectory (fun root -> + let clock () = DateTimeOffset.Parse("2026-09-20T12:00:00Z") + let coordinator = + ArtifactRunCoordinator( + root, + (fun () -> TestBridge() :> IArtifactBridge), + clock, + TimeSpan.FromSeconds 15. + ) + + match coordinator.Start(ids, false) with + | Error message -> failwith message + | Ok(Accepted snapshot) -> + Assert.Equal(ids.ProjectId, snapshot.ProjectId) + Assert.Equal(ids.RunId, snapshot.RunId) + | Ok(Conflict _) -> failwith "expected the first start to be accepted" + + let completed = + waitFor (fun () -> + coordinator.TryFind(ids.ProjectId, ids.RunId) + |> Option.exists (fun store -> store.Snapshot().Status = "complete")) + + Assert.True(completed) + + match coordinator.Manifest(ids.ProjectId, ids.RunId) with + | Error failure -> failwith $"manifest lookup failed: {failure}" + | Ok manifest -> + Assert.Equal("complete", manifest.Status) + Assert.Equal(3, manifest.Steps.Length)) diff --git a/tests/SomhairlesDream.Server.Tests/SomhairlesDream.Server.Tests.fsproj b/tests/SomhairlesDream.Server.Tests/SomhairlesDream.Server.Tests.fsproj new file mode 100644 index 0000000..88e85f0 --- /dev/null +++ b/tests/SomhairlesDream.Server.Tests/SomhairlesDream.Server.Tests.fsproj @@ -0,0 +1,25 @@ +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <TargetFramework>net8.0</TargetFramework> + <IsPackable>false</IsPackable> + <IsTestProject>true</IsTestProject> + </PropertyGroup> + <ItemGroup> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" /> + <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="8.0.12" /> + <PackageReference Include="xunit" Version="2.9.2" /> + <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2"> + <PrivateAssets>all</PrivateAssets> + <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> + </PackageReference> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="../../src/SomhairlesDream.Server/SomhairlesDream.Server.fsproj" /> + <ProjectReference Include="../../src/SomhairlesDream.Modeling/SomhairlesDream.Modeling.fsproj" /> + </ItemGroup> + <ItemGroup> + <Compile Include="StoreTests.fs" /> + <Compile Include="CoordinatorTests.fs" /> + <Compile Include="ApiTests.fs" /> + </ItemGroup> +</Project> diff --git a/tests/SomhairlesDream.Server.Tests/StoreTests.fs b/tests/SomhairlesDream.Server.Tests/StoreTests.fs new file mode 100644 index 0000000..4aec16f --- /dev/null +++ b/tests/SomhairlesDream.Server.Tests/StoreTests.fs @@ -0,0 +1,236 @@ +namespace SomhairlesDream.Server.Tests + +open System +open Xunit +open SomhairlesDream.Shared +open SomhairlesDream.Server + +module StoreTests = + let private at hour = DateTimeOffset(2026, 9, 20, hour, 0, 0, 0, TimeSpan.Zero) + + let private artifactIds : RunIds = + { ProjectId = "heritage-001" + RunId = "run-20260920-001" + BaseId = "base-000" + TargetId = "target-003" } + + let private mesh version label = + { Version = version + Label = label + Vertices = + [| { X = 0.; Y = 0.; Z = 0. } + { X = float version; Y = 1.; Z = 0. } |] + Faces = [||] } + + [<Fact>] + let ``store publishes the latest state atomically`` () = + let store = RunStore("heritage-001", "run-001", TimeSpan.FromMinutes 2.) + + let running = store.Start(at 9) + let published = store.Publish(at 9, mesh running.TargetVersion "主承力骨架") + + Assert.Equal(RunStatus.Succeeded, published.Status) + Assert.Equal(published, store.Snapshot()) + Assert.Equal(1, published.CurrentVersion) + + [<Fact>] + let ``store marks an unresponsive run stale when observed`` () = + let store = RunStore("heritage-001", "run-001", TimeSpan.FromMinutes 2.) + store.Start(at 9) |> ignore + + let observed = store.Observe(at 10) + + Assert.Equal(RunStatus.Stale, observed.Status) + Assert.Equal("心跳超时,等待重连", observed.Message) + + [<Fact>] + let ``store sends an initial snapshot and every transition to subscribers`` () = + let store = RunStore("heritage-001", "run-001", TimeSpan.FromMinutes 2.) + let reader = store.Subscribe() + + let initial = reader.ReadAsync().AsTask().GetAwaiter().GetResult() + let running = store.Start(at 9) + let update = reader.ReadAsync().AsTask().GetAwaiter().GetResult() + + Assert.Equal(RunStatus.Idle, initial.Status) + Assert.Equal(running, update) + + [<Fact>] + let ``artifact store applies lifecycle events to a run snapshot`` () = + let store = ArtifactRunStore(artifactIds, TimeSpan.FromSeconds 15., at 9) + + let start = + RunEvent.Start + { Ids = artifactIds + At = at 9 + TotalSteps = 3 } + + let checkpoint = + RunEvent.Checkpoint + { Ids = artifactIds + At = at 9 + StepId = "01-foundation" + StepIndex = 0 + TotalSteps = 3 + Message = "artifact verified" + ArtifactPath = "steps/01-foundation.glb" } + + Assert.True(store.Apply(start) |> Result.isOk) + Assert.True(store.Apply(checkpoint) |> Result.isOk) + + let snapshot = store.Snapshot() + + Assert.Equal("running", snapshot.Status) + Assert.Equal(artifactIds.BaseId, snapshot.BaseId) + Assert.Equal(artifactIds.TargetId, snapshot.TargetId) + Assert.Equal(Some "01-foundation", snapshot.CurrentStepId) + Assert.Equal(0, snapshot.CurrentStepIndex) + Assert.Equal(3, snapshot.TotalSteps) + Assert.True(snapshot.ManifestPath.IsNone) + Assert.False(snapshot.IsStale) + + [<Fact>] + let ``artifact store derives staleness without changing lifecycle status`` () = + let store = ArtifactRunStore(artifactIds, TimeSpan.FromSeconds 15., at 9) + + store.Apply( + RunEvent.Start + { Ids = artifactIds + At = at 9 + TotalSteps = 3 } + ) + |> ignore + + let snapshot = store.Observe(at 10) + + Assert.Equal("running", snapshot.Status) + Assert.True(snapshot.IsStale) + + [<Fact>] + let ``artifact store rejects lifecycle events after completion`` () = + let store = ArtifactRunStore(artifactIds, TimeSpan.FromSeconds 15., at 9) + + store.Apply( + RunEvent.Start + { Ids = artifactIds + At = at 9 + TotalSteps = 3 } + ) + |> ignore + + for index, stepId in [| 0, "01-foundation"; 1, "02-frame"; 2, "03-cabin" |] do + store.Apply( + RunEvent.Checkpoint + { Ids = artifactIds + At = at 9 + StepId = stepId + StepIndex = index + TotalSteps = 3 + Message = "artifact verified" + ArtifactPath = $"steps/{stepId}.glb" } + ) + |> ignore + + store.Apply( + RunEvent.Complete + { Ids = artifactIds + At = at 9 + ManifestPath = "manifest.json" } + ) + |> ignore + + let result = + store.Apply( + RunEvent.Heartbeat + { Ids = artifactIds + At = at 9 + Message = "late heartbeat" } + ) + + Assert.True(result |> Result.isError) + + [<Fact>] + let ``artifact store rejects completion before every checkpoint`` () = + let store = ArtifactRunStore(artifactIds, TimeSpan.FromSeconds 15., at 9) + + store.Apply( + RunEvent.Start + { Ids = artifactIds + At = at 9 + TotalSteps = 3 } + ) + |> ignore + + let result = + store.Apply( + RunEvent.Complete + { Ids = artifactIds + At = at 9 + ManifestPath = "manifest.json" } + ) + + Assert.True(result |> Result.isError) + Assert.Equal("running", store.Snapshot().Status) + + [<Fact>] + let ``artifact store records a pipeline failure before start`` () = + let store = ArtifactRunStore(artifactIds, TimeSpan.FromSeconds 15., at 9) + + let result = + store.Apply( + RunEvent.Fail + { Ids = artifactIds + At = at 9 + StepId = None + Message = "run directory already exists" } + ) + + Assert.True(result |> Result.isOk) + Assert.Equal("failed", store.Snapshot().Status) + Assert.Equal(Some "run directory already exists", store.Snapshot().Error) + + [<Fact>] + let ``artifact store accepts completion after ordered checkpoints`` () = + let store = ArtifactRunStore(artifactIds, TimeSpan.FromSeconds 15., at 9) + + store.Apply( + RunEvent.Start + { Ids = artifactIds + At = at 9 + TotalSteps = 3 } + ) + |> ignore + + for index, stepId in [| 0, "01-foundation"; 1, "02-frame"; 2, "03-cabin" |] do + store.Apply( + RunEvent.Checkpoint + { Ids = artifactIds + At = at 9 + StepId = stepId + StepIndex = index + TotalSteps = 3 + Message = "artifact verified" + ArtifactPath = $"steps/{stepId}.glb" } + ) + |> ignore + + let result = + store.Apply( + RunEvent.Complete + { Ids = artifactIds + At = at 9 + ManifestPath = "manifest.json" } + ) + + Assert.True(result |> Result.isOk) + Assert.Equal("complete", store.Snapshot().Status) + + [<Fact>] + let ``artifact registry atomically creates only one store for a run key`` () = + let registry = ArtifactRunRegistry(TimeSpan.FromSeconds 15., fun () -> at 9) + + let first = registry.TryCreate(artifactIds) + let duplicate = registry.TryCreate(artifactIds) + + Assert.True(first.IsSome) + Assert.True(duplicate.IsNone) |
