1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
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))
|