Skip to content

Commit 039a8cc

Browse files
net0wellclaude
andcommitted
feat(hosts): AppHost do Aspire com o ambiente local completo (spec 009)
- hosts/PythonScriptRunner.AppHost com Aspire 13.6.2 (D-171), sobe tudo com um comando: - PostgreSQL 16 com volume e RabbitMQ 3.13 com a interface de gerenciamento; - Mailpit v1.27.0 (D-172); - WorkerHost e DashboardHost (PSR_AUTO_MIGRATE). O DashboardHost tem login fixo com 4 usuários de dev, um por papel, senha psr-dev; o hash fica na configuração do AppHost (D-133, D-177); - o painel Vue em modo dev (AddViteApp), com proxy para o DashboardHost. - Em dev, o psrunner vem do próprio repositório. No `aspire publish`, um ambiente Docker Compose usa os Dockerfiles dos hosts (as mesmas imagens do GHCR). - Testes (Aspire.Hosting.Testing): - AC-1: worker, dashboard, Mailpit e painel sobem, e os hosts recebem o endpoint OTLP do dashboard do Aspire; - AC-2: o autor importa e publica as fixtures pela API e roda o CS-1 e, no Linux, o CS-2, com o e-mail chegando no Mailpit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent e0125a5 commit 039a8cc

9 files changed

Lines changed: 323 additions & 0 deletions

File tree

‎Directory.Packages.props‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
44
</PropertyGroup>
55
<ItemGroup>
6+
<PackageVersion Include="Aspire.Hosting.Docker" Version="13.6.2" />
7+
<PackageVersion Include="Aspire.Hosting.JavaScript" Version="13.6.2" />
8+
<PackageVersion Include="Aspire.Hosting.PostgreSQL" Version="13.6.2" />
9+
<PackageVersion Include="Aspire.Hosting.RabbitMQ" Version="13.6.2" />
10+
<PackageVersion Include="Aspire.Hosting.Testing" Version="13.6.2" />
611
<PackageVersion Include="Cronos" Version="0.13.0" />
712
<PackageVersion Include="Deque.AxeCore.Playwright" Version="4.13.0" />
813
<PackageVersion Include="JsonSchema.Net" Version="9.4.1" />

‎PythonScriptRunner.slnx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<Solution>
22
<Folder Name="/hosts/">
3+
<Project Path="hosts/PythonScriptRunner.AppHost/PythonScriptRunner.AppHost.csproj" />
34
<Project Path="hosts/PythonScriptRunner.DashboardHost/PythonScriptRunner.DashboardHost.csproj" />
45
<Project Path="hosts/PythonScriptRunner.ServiceDefaults/PythonScriptRunner.ServiceDefaults.csproj" />
56
<Project Path="hosts/PythonScriptRunner.WorkerHost/PythonScriptRunner.WorkerHost.csproj" />
@@ -14,6 +15,7 @@
1415
<Project Path="src/PythonScriptRunner.Worker/PythonScriptRunner.Worker.csproj" />
1516
</Folder>
1617
<Folder Name="/tests/">
18+
<Project Path="tests/PythonScriptRunner.AppHost.Tests/PythonScriptRunner.AppHost.Tests.csproj" />
1719
<Project Path="tests/PythonScriptRunner.Containers.Tests/PythonScriptRunner.Containers.Tests.csproj" />
1820
<Project Path="tests/PythonScriptRunner.Core.Tests/PythonScriptRunner.Core.Tests.csproj" />
1921
<Project Path="tests/PythonScriptRunner.Dashboard.Tests/PythonScriptRunner.Dashboard.Tests.csproj" />
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// Ambiente local completo (spec 009; ADR-0019): PostgreSQL, RabbitMQ, SMTP de teste (Mailpit), worker, painel e o
2+
// painel Vue em modo dev. `aspire publish` gera o docker-compose com os Dockerfiles dos hosts (as mesmas imagens do GHCR).
3+
var builder = DistributedApplication.CreateBuilder(args);
4+
5+
builder.AddDockerComposeEnvironment("compose");
6+
7+
var postgres = builder.AddPostgres("postgres").WithImageTag("16-alpine").WithDataVolume("psr-postgres");
8+
var database = postgres.AddDatabase("psr");
9+
var rabbitmq = builder.AddRabbitMQ("rabbitmq").WithImageTag("3.13-management-alpine").WithManagementPlugin();
10+
11+
// SMTP de teste do CS-2: aceita qualquer usuário, sem TLS (D-172).
12+
builder.AddContainer("mailpit", "axllent/mailpit", "v1.27.0")
13+
.WithEnvironment("MP_SMTP_AUTH_ACCEPT_ANY", "1")
14+
.WithEnvironment("MP_SMTP_AUTH_ALLOW_INSECURE", "1")
15+
.WithHttpEndpoint(targetPort: 8025, name: "http")
16+
.WithEndpoint(targetPort: 1025, name: "smtp", scheme: "tcp");
17+
18+
// Em desenvolvimento o psrunner vem do próprio repositório; nas imagens, do wheel embutido (D-169).
19+
var psrunner = Path.GetFullPath(Path.Combine(builder.AppHostDirectory, "..", "..", "python", "psrunner"));
20+
21+
var worker = builder.AddProject<Projects.PythonScriptRunner_WorkerHost>("worker")
22+
.WithHttpEndpoint(name: "http")
23+
.WithHttpHealthCheck("/health/ready")
24+
.WithReference(database).WaitFor(database)
25+
.WithReference(rabbitmq).WaitFor(rabbitmq)
26+
.WithEnvironment("PSR_AUTO_MIGRATE", "true")
27+
.WithEnvironment("PythonScriptRunner__Secrets__SMTP_USUARIO", "psr")
28+
.WithEnvironment("PythonScriptRunner__Secrets__SMTP_SENHA", "psr-dev")
29+
.PublishAsDockerFile(c => c.WithDockerfile("../..", "hosts/PythonScriptRunner.WorkerHost/Dockerfile"));
30+
31+
// Login fixo com 4 usuários de desenvolvimento, um por papel, todos com a senha psr-dev (D-133, D-177).
32+
var passwordHash = builder.Configuration["PythonScriptRunner:DevPasswordHash"]
33+
?? throw new InvalidOperationException("PythonScriptRunner:DevPasswordHash is missing from the AppHost configuration.");
34+
(string Name, string Role)[] users = [("leitor", "Reader"), ("executor", "Executor"), ("autor", "Author"), ("admin", "Admin")];
35+
var dashboard = builder.AddProject<Projects.PythonScriptRunner_DashboardHost>("dashboard")
36+
.WithHttpEndpoint(name: "http")
37+
.WithExternalHttpEndpoints()
38+
.WithUrlForEndpoint("http", url =>
39+
{
40+
url.Url = "/psr/";
41+
url.DisplayText = "Painel";
42+
})
43+
.WithHttpHealthCheck("/health/ready")
44+
.WithReference(database).WaitFor(database)
45+
.WithReference(rabbitmq).WaitFor(rabbitmq)
46+
.WithEnvironment("PSR_AUTO_MIGRATE", "true")
47+
.PublishAsDockerFile(c => c.WithDockerfile("../..", "hosts/PythonScriptRunner.DashboardHost/Dockerfile"));
48+
for (var i = 0; i < users.Length; i++)
49+
{
50+
dashboard
51+
.WithEnvironment($"PythonScriptRunner__Dashboard__Login__Users__{i}__Name", users[i].Name)
52+
.WithEnvironment($"PythonScriptRunner__Dashboard__Login__Users__{i}__Role", users[i].Role)
53+
.WithEnvironment($"PythonScriptRunner__Dashboard__Login__Users__{i}__PasswordHash", passwordHash);
54+
}
55+
56+
if (builder.ExecutionContext.IsRunMode)
57+
{
58+
worker.WithEnvironment("PythonScriptRunner__PsrunnerRequirement", psrunner);
59+
dashboard.WithEnvironment("PythonScriptRunner__PsrunnerRequirement", psrunner);
60+
61+
// Painel Vue com hot reload, com proxy da API para o DashboardHost (no compose o painel vem embutido na imagem).
62+
builder.AddViteApp("panel", "../../panel")
63+
.WithNpm()
64+
.WithEnvironment("PSR_DASHBOARD_URL", dashboard.GetEndpoint("http"))
65+
.WaitFor(dashboard);
66+
}
67+
68+
builder.Build().Run();
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"$schema": "https://json.schemastore.org/launchsettings.json",
3+
"profiles": {
4+
"http": {
5+
"commandName": "Project",
6+
"dotnetRunMessages": true,
7+
"launchBrowser": true,
8+
"applicationUrl": "http://localhost:15000",
9+
"environmentVariables": {
10+
"ASPNETCORE_ENVIRONMENT": "Development",
11+
"DOTNET_ENVIRONMENT": "Development",
12+
"ASPIRE_DASHBOARD_OTLP_HTTP_ENDPOINT_URL": "http://localhost:19000",
13+
"ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20000",
14+
"ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true"
15+
}
16+
}
17+
}
18+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<Project Sdk="Aspire.AppHost.Sdk/13.6.2">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<AspireUseCliBundle>true</AspireUseCliBundle>
6+
<UserSecretsId>psr-apphost-6f1c2a4e</UserSecretsId>
7+
</PropertyGroup>
8+
9+
<ItemGroup>
10+
<ProjectReference Include="..\PythonScriptRunner.WorkerHost\PythonScriptRunner.WorkerHost.csproj" />
11+
<ProjectReference Include="..\PythonScriptRunner.DashboardHost\PythonScriptRunner.DashboardHost.csproj" />
12+
</ItemGroup>
13+
14+
<ItemGroup>
15+
<PackageReference Include="Aspire.Hosting.Docker" />
16+
<PackageReference Include="Aspire.Hosting.JavaScript" />
17+
<PackageReference Include="Aspire.Hosting.PostgreSQL" />
18+
<PackageReference Include="Aspire.Hosting.RabbitMQ" />
19+
</ItemGroup>
20+
21+
</Project>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning",
6+
"Aspire.Hosting.Dcp": "Warning"
7+
}
8+
},
9+
"PythonScriptRunner": {
10+
"DevPasswordHash": "AQAAAAIAAYagAAAAEOzP04xls5e0roG3bww80/+u+X1d75u5LMZkVxmb/UCA9st4tKCh8ccvJgNTM4os5A=="
11+
}
12+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"appHost": {
3+
"path": "PythonScriptRunner.AppHost.csproj"
4+
}
5+
}
Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
using System.IO.Compression;
2+
using System.Net;
3+
using System.Net.Http.Headers;
4+
using System.Net.Http.Json;
5+
using System.Text;
6+
using System.Text.Json.Nodes;
7+
8+
namespace PythonScriptRunner.AppHost.Tests;
9+
10+
/// <summary>
11+
/// Spec 009, AC-1 and AC-2: the Aspire AppHost brings the whole environment up, and the fixed user <c>autor</c> imports the
12+
/// fixtures and runs CS-1 and CS-2 through the dashboard API, with the e-mail arriving in Mailpit.
13+
/// </summary>
14+
public sealed class AppHostTests
15+
{
16+
private const string DevPassword = "psr-dev";
17+
18+
private static readonly TimeSpan StartTimeout = TimeSpan.FromMinutes(5);
19+
20+
private static CancellationToken Ct => TestContext.Current.CancellationToken;
21+
22+
[Fact]
23+
public async Task Spec009_AC01_AC02_TheAppHostBringsEverythingUp_AndTheAuthorRunsCs1AndCs2()
24+
{
25+
var appHost = await DistributedApplicationTestingBuilder.CreateAsync<Projects.PythonScriptRunner_AppHost>(
26+
[], (options, _) => options.DisableDashboard = false, Ct);
27+
28+
// A fresh database each run: the persistent volume is for developers, not for tests.
29+
foreach (var container in appHost.Resources.OfType<ContainerResource>())
30+
{
31+
foreach (var volume in container.Annotations.OfType<ContainerMountAnnotation>().Where(m => m.Type == ContainerMountType.Volume).ToList())
32+
{
33+
container.Annotations.Remove(volume);
34+
}
35+
}
36+
37+
await using var app = await appHost.BuildAsync(Ct);
38+
await app.StartAsync(Ct);
39+
40+
// AC-1: every resource is up, and the hosts send their telemetry to the Aspire dashboard.
41+
using (var start = CancellationTokenSource.CreateLinkedTokenSource(Ct))
42+
{
43+
start.CancelAfter(StartTimeout);
44+
await Task.WhenAll(
45+
app.ResourceNotifications.WaitForResourceHealthyAsync("worker", start.Token),
46+
app.ResourceNotifications.WaitForResourceHealthyAsync("dashboard", start.Token),
47+
app.ResourceNotifications.WaitForResourceAsync("mailpit", KnownResourceStates.Running, start.Token),
48+
app.ResourceNotifications.WaitForResourceAsync("panel", KnownResourceStates.Running, start.Token));
49+
}
50+
51+
foreach (var name in new[] { "worker", "dashboard" })
52+
{
53+
var running = await app.ResourceNotifications.WaitForResourceAsync(name, e => !e.Snapshot.EnvironmentVariables.IsDefaultOrEmpty, Ct);
54+
running.Snapshot.EnvironmentVariables.Select(v => v.Name).ShouldContain("OTEL_EXPORTER_OTLP_ENDPOINT", $"{name} sends telemetry to the dashboard");
55+
}
56+
57+
// AC-2: the fixed user autor imports the fixtures, publishes them and runs CS-1 and CS-2.
58+
var dashboard = app.GetEndpoint("dashboard", "http");
59+
using var http = new HttpClient(new HttpClientHandler { CookieContainer = new CookieContainer() }) { BaseAddress = dashboard };
60+
http.DefaultRequestHeaders.Add("X-PSR-Request", "1");
61+
(await http.PostAsJsonAsync("/psr/api/auth/login", new { name = "autor", password = DevPassword }, Ct)).StatusCode
62+
.ShouldBe(HttpStatusCode.NoContent);
63+
64+
var smtp = app.GetEndpoint("mailpit", "smtp");
65+
await ImportAndPublishAsync(http, "calculo-progressao", static (_, content) => content);
66+
var runsCs2 = !OperatingSystem.IsWindows();
67+
if (runsCs2)
68+
{
69+
await ImportAndPublishAsync(http, "html-para-email", (path, content) => path.EndsWith(".pipeline.json", StringComparison.Ordinal)
70+
? content.Replace("smtp.exemplo.com", smtp.Host, StringComparison.Ordinal)
71+
.Replace("\"const\": 465", $"\"const\": {smtp.Port}", StringComparison.Ordinal)
72+
: content);
73+
}
74+
75+
var cs1 = await RunAsync(http, "calculo-progressao", JsonContent.Create(new
76+
{
77+
inputs = new { a1 = 1, razao = 2, n = 3, coeficientes = new[] { 0, 1 } },
78+
}));
79+
(await WaitForRunAsync(http, cs1))["outputs"]!["soma"]!.GetValue<double>().ShouldBe(9);
80+
81+
// CS-2 needs weasyprint (GTK/pango), which runs on Linux only (D-106).
82+
if (runsCs2)
83+
{
84+
using var form = new MultipartFormDataContent();
85+
form.Add(new StringContent("""{"destinatarios": ["financeiro@exemplo.com"], "assunto": "Relatório do Aspire"}"""), "inputs");
86+
var html = new ByteArrayContent(Encoding.UTF8.GetBytes("<html><body><h1>Relatório</h1></body></html>"));
87+
html.Headers.ContentType = new MediaTypeHeaderValue("text/html");
88+
form.Add(html, "html", "pagina.html");
89+
var cs2 = await RunAsync(http, "html-para-email", form);
90+
await WaitForRunAsync(http, cs2);
91+
92+
using var mailpit = app.CreateHttpClient("mailpit", "http");
93+
var messages = (await mailpit.GetFromJsonAsync<JsonObject>("/api/v1/messages", Ct))!["messages"]!.AsArray();
94+
messages.Select(m => m!["Subject"]!.GetValue<string>()).ShouldContain("Relatório do Aspire");
95+
}
96+
}
97+
98+
/// <summary>Imports a fixture as a zip (drafts), then publishes its stages and pipelines with their ETags.</summary>
99+
private static async Task ImportAndPublishAsync(HttpClient http, string fixture, Func<string, string, string> transform)
100+
{
101+
var root = Path.Combine(RepositoryRoot(), "tests", "fixtures", fixture);
102+
using var zip = new MemoryStream();
103+
using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true))
104+
{
105+
foreach (var file in Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories).Where(f => !f.Contains("__pycache__", StringComparison.Ordinal)))
106+
{
107+
var relative = Path.GetRelativePath(root, file).Replace('\\', '/');
108+
await using var writer = new StreamWriter(archive.CreateEntry(relative).Open());
109+
await writer.WriteAsync(transform(relative, await File.ReadAllTextAsync(file, Ct)));
110+
}
111+
}
112+
113+
using var form = new MultipartFormDataContent();
114+
var archiveContent = new ByteArrayContent(zip.ToArray());
115+
archiveContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
116+
form.Add(archiveContent, "archive", $"{fixture}.zip");
117+
var import = await http.PostAsync("/psr/api/import", form, Ct);
118+
import.StatusCode.ShouldBe(HttpStatusCode.OK, await import.Content.ReadAsStringAsync(Ct));
119+
var items = (await import.Content.ReadFromJsonAsync<JsonObject>(Ct))!["items"]!.AsArray();
120+
121+
// Stages first: the pipeline references their published versions.
122+
foreach (var item in items.OrderBy(i => i!["kind"]!.GetValue<string>() == "Stage" ? 0 : 1))
123+
{
124+
var kind = item!["kind"]!.GetValue<string>() == "Stage" ? "stages" : "pipelines";
125+
var key = item["key"]!.GetValue<string>();
126+
var draft = await http.GetAsync($"/psr/api/{kind}/{key}/draft", Ct);
127+
using var publish = new HttpRequestMessage(HttpMethod.Post, $"/psr/api/{kind}/{key}/draft/publish");
128+
publish.Headers.IfMatch.Add(draft.Headers.ETag!);
129+
var published = await http.SendAsync(publish, Ct);
130+
published.StatusCode.ShouldBe(HttpStatusCode.OK, await published.Content.ReadAsStringAsync(Ct));
131+
}
132+
}
133+
134+
private static async Task<string> RunAsync(HttpClient http, string pipeline, HttpContent body)
135+
{
136+
var response = await http.PostAsync($"/psr/api/pipelines/{pipeline}/runs", body, Ct);
137+
response.IsSuccessStatusCode.ShouldBeTrue(await response.Content.ReadAsStringAsync(Ct));
138+
return (await response.Content.ReadFromJsonAsync<JsonObject>(Ct))!["runId"]!.GetValue<string>();
139+
}
140+
141+
private static async Task<JsonObject> WaitForRunAsync(HttpClient http, string runId)
142+
{
143+
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(Ct);
144+
timeout.CancelAfter(TimeSpan.FromMinutes(5));
145+
while (true)
146+
{
147+
var run = (await http.GetFromJsonAsync<JsonObject>($"/psr/api/runs/{runId}", timeout.Token))!;
148+
var status = run["status"]!.GetValue<string>();
149+
if (status is "Succeeded" or "Failed" or "Cancelled" or "TimedOut")
150+
{
151+
status.ShouldBe("Succeeded", run["error"]?.ToJsonString());
152+
return run;
153+
}
154+
155+
await Task.Delay(TimeSpan.FromSeconds(1), timeout.Token);
156+
}
157+
}
158+
159+
private static string RepositoryRoot()
160+
{
161+
for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory is not null; directory = directory.Parent)
162+
{
163+
if (File.Exists(Path.Combine(directory.FullName, "PythonScriptRunner.slnx")))
164+
{
165+
return directory.FullName;
166+
}
167+
}
168+
169+
throw new InvalidOperationException("The repository root (PythonScriptRunner.slnx) was not found.");
170+
}
171+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<ItemGroup>
4+
<ProjectReference Include="..\..\hosts\PythonScriptRunner.AppHost\PythonScriptRunner.AppHost.csproj" />
5+
</ItemGroup>
6+
7+
<ItemGroup>
8+
<Using Include="Aspire.Hosting" />
9+
<Using Include="Aspire.Hosting.ApplicationModel" />
10+
<Using Include="Aspire.Hosting.Testing" />
11+
<Using Include="Shouldly" />
12+
<Using Include="Xunit" />
13+
</ItemGroup>
14+
15+
<ItemGroup>
16+
<PackageReference Include="Aspire.Hosting.Testing" />
17+
<PackageReference Include="Shouldly" />
18+
<PackageReference Include="xunit.v3" />
19+
</ItemGroup>
20+
21+
</Project>

0 commit comments

Comments
 (0)