OPC # 0001: Extract OPC into standalone repo
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
using ControlPlane.Api.Services;
|
||||
using ControlPlane.Core.Services;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ControlPlane.Api.Endpoints;
|
||||
|
||||
public static class ProjectBuildEndpoints
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOpts = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() },
|
||||
};
|
||||
|
||||
public static IEndpointRouteBuilder MapProjectBuildEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var group = app.MapGroup("/api/builds").WithTags("Builds");
|
||||
group.MapGet("/projects", GetProjects);
|
||||
group.MapGet("/history", GetHistory);
|
||||
group.MapPost("/{projectName}", TriggerProjectBuild);
|
||||
return app;
|
||||
}
|
||||
|
||||
/// <summary>Returns the list of known projects the build monitor can track.</summary>
|
||||
private static IResult GetProjects(ProjectBuildService svc) =>
|
||||
Results.Ok(svc.GetProjects());
|
||||
|
||||
private static async Task<IResult> GetHistory(BuildHistoryService history) =>
|
||||
Results.Ok(await history.GetBuildsAsync());
|
||||
|
||||
/// <summary>
|
||||
/// Triggers a build for a named project and streams SSE output.
|
||||
/// projectName must match one of the names returned by GET /api/builds/projects.
|
||||
/// </summary>
|
||||
private static async Task TriggerProjectBuild(
|
||||
string projectName,
|
||||
HttpContext ctx,
|
||||
ProjectBuildService svc,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(svc.RepoRoot))
|
||||
{
|
||||
ctx.Response.StatusCode = 503;
|
||||
await ctx.Response.WriteAsJsonAsync(
|
||||
new { error = "Docker:RepoRoot is not configured on the server." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.Response.Headers.ContentType = "text/event-stream";
|
||||
ctx.Response.Headers.CacheControl = "no-cache";
|
||||
ctx.Response.Headers.Connection = "keep-alive";
|
||||
|
||||
async Task Send(object payload)
|
||||
{
|
||||
var json = JsonSerializer.Serialize(payload, JsonOpts);
|
||||
await ctx.Response.WriteAsync($"data: {json}\n\n", ct);
|
||||
await ctx.Response.Body.FlushAsync(ct);
|
||||
}
|
||||
|
||||
void OnLine(string line) => Send(new { line }).GetAwaiter().GetResult();
|
||||
|
||||
var record = await svc.BuildProjectAsync(projectName, OnLine, ct);
|
||||
|
||||
await Send(new { done = true, build = record });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user