Compare commits
6 Commits
uat
..
f046db7fc2
| Author | SHA1 | Date | |
|---|---|---|---|
| f046db7fc2 | |||
| 66ef611761 | |||
| c7da1eb017 | |||
| c78bcf3360 | |||
| ff7fa8e812 | |||
| 13ff5eb926 |
@@ -19,13 +19,19 @@ public static class GitEndpoints
|
|||||||
// All responses include a repoKey field so the caller knows which repo each commit came from.
|
// All responses include a repoKey field so the caller knows which repo each commit came from.
|
||||||
// GET /api/git/log?grep=...&limit=25&page=1&repo=all
|
// GET /api/git/log?grep=...&limit=25&page=1&repo=all
|
||||||
// page is 1-based. Each repo contributes up to limit*page commits before merge-sort+skip/take.
|
// page is 1-based. Each repo contributes up to limit*page commits before merge-sort+skip/take.
|
||||||
|
// branch filters to commits reachable from the named local branch; requires a specific repo (not "all").
|
||||||
|
// Each result includes a branches[] array listing local branches that contain that commit.
|
||||||
private static IResult GetLog(
|
private static IResult GetLog(
|
||||||
IConfiguration config,
|
IConfiguration config,
|
||||||
string? grep = null,
|
string? grep = null,
|
||||||
int limit = 25,
|
int limit = 25,
|
||||||
int page = 1,
|
int page = 1,
|
||||||
string repo = "all")
|
string repo = "all",
|
||||||
|
string? branch = null)
|
||||||
{
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(branch) && repo == "all")
|
||||||
|
return Results.BadRequest("'branch' filter requires a specific 'repo' parameter.");
|
||||||
|
|
||||||
var repos = repo == "all"
|
var repos = repo == "all"
|
||||||
? ResolveAllRepos(config)
|
? ResolveAllRepos(config)
|
||||||
: ResolveNamedRepo(config, repo) is { } p
|
: ResolveNamedRepo(config, repo) is { } p
|
||||||
@@ -43,16 +49,30 @@ public static class GitEndpoints
|
|||||||
|
|
||||||
using var r = new Repository(repoPath);
|
using var r = new Repository(repoPath);
|
||||||
|
|
||||||
var tips = r.Branches
|
CommitFilter filter;
|
||||||
.Where(b => b.Tip != null)
|
if (!string.IsNullOrWhiteSpace(branch))
|
||||||
.Select(b => (GitObject)b.Tip)
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
var filter = new CommitFilter
|
|
||||||
{
|
{
|
||||||
SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time,
|
var branchRef = r.Branches[branch];
|
||||||
IncludeReachableFrom = tips.Count > 0 ? tips : (object)r.Head,
|
if (branchRef?.Tip is null)
|
||||||
};
|
return Results.BadRequest($"Branch '{branch}' not found in repo '{repoKey}'.");
|
||||||
|
filter = new CommitFilter
|
||||||
|
{
|
||||||
|
SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time,
|
||||||
|
IncludeReachableFrom = branchRef.Tip,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var tips = r.Branches
|
||||||
|
.Where(b => b.Tip != null)
|
||||||
|
.Select(b => (GitObject)b.Tip)
|
||||||
|
.ToList();
|
||||||
|
filter = new CommitFilter
|
||||||
|
{
|
||||||
|
SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time,
|
||||||
|
IncludeReachableFrom = tips.Count > 0 ? tips : (object)r.Head,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
IEnumerable<Commit> query = r.Commits.QueryBy(filter);
|
IEnumerable<Commit> query = r.Commits.QueryBy(filter);
|
||||||
|
|
||||||
@@ -63,22 +83,42 @@ public static class GitEndpoints
|
|||||||
bucket.Add((c.Author.When, repoKey, ToGitCommit(r, c)));
|
bucket.Add((c.Author.When, repoKey, ToGitCommit(r, c)));
|
||||||
}
|
}
|
||||||
|
|
||||||
var commits = bucket
|
var pageEntries = bucket
|
||||||
.OrderByDescending(x => x.When)
|
.OrderByDescending(x => x.When)
|
||||||
.Skip((page - 1) * limit)
|
.Skip((page - 1) * limit)
|
||||||
.Take(limit)
|
.Take(limit)
|
||||||
.Select(x => new
|
|
||||||
{
|
|
||||||
repoKey = x.RepoKey,
|
|
||||||
hash = x.Commit.Hash,
|
|
||||||
shortHash = x.Commit.ShortHash,
|
|
||||||
author = x.Commit.Author,
|
|
||||||
date = x.Commit.Date,
|
|
||||||
subject = x.Commit.Subject,
|
|
||||||
files = x.Commit.Files,
|
|
||||||
})
|
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
|
// Annotate each commit with the local branches whose tip is a descendant of that commit.
|
||||||
|
var branchMap = new Dictionary<string, List<string>>(StringComparer.Ordinal);
|
||||||
|
foreach (var grp in pageEntries.GroupBy(x => x.RepoKey))
|
||||||
|
{
|
||||||
|
if (!repos.TryGetValue(grp.Key, out var rPath) || !Directory.Exists(rPath)) continue;
|
||||||
|
using var annotRepo = new Repository(rPath);
|
||||||
|
var localBranches = annotRepo.Branches.Where(b => !b.IsRemote && b.Tip != null).ToList();
|
||||||
|
foreach (var (_, _, c) in grp)
|
||||||
|
{
|
||||||
|
var target = annotRepo.Lookup<Commit>(c.Hash);
|
||||||
|
if (target is null) { branchMap[c.Hash] = []; continue; }
|
||||||
|
branchMap[c.Hash] = localBranches
|
||||||
|
.Where(b => annotRepo.ObjectDatabase.FindMergeBase(b.Tip, target)?.Sha == target.Sha)
|
||||||
|
.Select(b => b.FriendlyName)
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var commits = pageEntries.Select(x => new
|
||||||
|
{
|
||||||
|
repoKey = x.RepoKey,
|
||||||
|
hash = x.Commit.Hash,
|
||||||
|
shortHash = x.Commit.ShortHash,
|
||||||
|
author = x.Commit.Author,
|
||||||
|
date = x.Commit.Date,
|
||||||
|
subject = x.Commit.Subject,
|
||||||
|
files = x.Commit.Files,
|
||||||
|
branches = branchMap.TryGetValue(x.Commit.Hash, out var br) ? (IReadOnlyList<string>)br : Array.Empty<string>(),
|
||||||
|
}).ToList();
|
||||||
|
|
||||||
return Results.Ok(commits);
|
return Results.Ok(commits);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,18 +167,55 @@ public static class GitEndpoints
|
|||||||
return Results.NotFound();
|
return Results.NotFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
// GET /api/git/branches
|
// GET /api/git/branches?repo=all
|
||||||
private static IResult GetBranches(IConfiguration config)
|
// repo defaults to "default" (single configured repo). Pass "all" to get branches from all
|
||||||
|
// registered repos. Each result includes repoKey so the caller can group branches by repo.
|
||||||
|
private static IResult GetBranches(IConfiguration config, string repo = "default")
|
||||||
{
|
{
|
||||||
var repoPath = ResolveRepo(config);
|
if (repo == "all")
|
||||||
|
{
|
||||||
|
var allRepos = ResolveAllRepos(config);
|
||||||
|
if (allRepos.Count == 0)
|
||||||
|
return Results.Problem("Could not locate any git repositories.");
|
||||||
|
|
||||||
|
var allBranches = new List<object>();
|
||||||
|
foreach (var (repoKey, rPath) in allRepos)
|
||||||
|
{
|
||||||
|
if (!Directory.Exists(rPath)) continue;
|
||||||
|
using var gitRepo = new Repository(rPath);
|
||||||
|
allBranches.AddRange(gitRepo.Branches
|
||||||
|
.Where(b => !b.IsRemote && b.Tip != null)
|
||||||
|
.OrderBy(b => b.FriendlyName)
|
||||||
|
.Select(b => (object)new
|
||||||
|
{
|
||||||
|
repoKey,
|
||||||
|
name = b.FriendlyName,
|
||||||
|
hash = b.Tip.Sha,
|
||||||
|
shortHash = b.Tip.Sha[..7],
|
||||||
|
subject = b.Tip.MessageShort,
|
||||||
|
author = b.Tip.Author.Name,
|
||||||
|
date = b.Tip.Author.When.ToString("yyyy-MM-dd HH:mm:ss zzz"),
|
||||||
|
isHead = b.IsCurrentRepositoryHead,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
return Results.Ok(allBranches);
|
||||||
|
}
|
||||||
|
|
||||||
|
var repoPath = repo == "default"
|
||||||
|
? ResolveRepo(config)
|
||||||
|
: ResolveNamedRepo(config, repo) ?? ResolveRepo(config);
|
||||||
|
|
||||||
if (repoPath is null)
|
if (repoPath is null)
|
||||||
return Results.Problem("Could not locate a git repository.");
|
return Results.Problem("Could not locate a git repository.");
|
||||||
|
|
||||||
using var repo = new Repository(repoPath);
|
var repoLabel = repo == "default" ? "default" : repo;
|
||||||
var branches = repo.Branches
|
using var singleRepo = new Repository(repoPath);
|
||||||
|
var branches = singleRepo.Branches
|
||||||
.Where(b => !b.IsRemote && b.Tip != null)
|
.Where(b => !b.IsRemote && b.Tip != null)
|
||||||
|
.OrderBy(b => b.FriendlyName)
|
||||||
.Select(b => new
|
.Select(b => new
|
||||||
{
|
{
|
||||||
|
repoKey = repoLabel,
|
||||||
name = b.FriendlyName,
|
name = b.FriendlyName,
|
||||||
hash = b.Tip.Sha,
|
hash = b.Tip.Sha,
|
||||||
shortHash = b.Tip.Sha[..7],
|
shortHash = b.Tip.Sha[..7],
|
||||||
@@ -147,7 +224,6 @@ public static class GitEndpoints
|
|||||||
date = b.Tip.Author.When.ToString("yyyy-MM-dd HH:mm:ss zzz"),
|
date = b.Tip.Author.When.ToString("yyyy-MM-dd HH:mm:ss zzz"),
|
||||||
isHead = b.IsCurrentRepositoryHead,
|
isHead = b.IsCurrentRepositoryHead,
|
||||||
})
|
})
|
||||||
.OrderBy(b => b.name)
|
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
return Results.Ok(branches);
|
return Results.Ok(branches);
|
||||||
|
|||||||
@@ -0,0 +1,159 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
using ControlPlane.Core.Messages;
|
||||||
|
using MassTransit;
|
||||||
|
|
||||||
|
namespace ControlPlane.Api.Endpoints;
|
||||||
|
|
||||||
|
public static class GiteaWebhookEndpoints
|
||||||
|
{
|
||||||
|
// Map of Gitea repo name → solution file (relative to cloned repo root)
|
||||||
|
private static readonly Dictionary<string, string> RepoSolutions = new(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{
|
||||||
|
["OPC"] = "ControlPlane.slnx",
|
||||||
|
["Clarity"] = "Clarity.slnx",
|
||||||
|
};
|
||||||
|
|
||||||
|
public static IEndpointRouteBuilder MapGiteaWebhookEndpoints(this IEndpointRouteBuilder app)
|
||||||
|
{
|
||||||
|
app.MapPost("/api/hooks/gitea/push", HandlePushAsync)
|
||||||
|
.WithName("Gitea:PushWebhook")
|
||||||
|
.AllowAnonymous(); // validated via HMAC below
|
||||||
|
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<IResult> HandlePushAsync(
|
||||||
|
HttpRequest request,
|
||||||
|
IPublishEndpoint bus,
|
||||||
|
IConfiguration config,
|
||||||
|
ILogger<GiteaWebhookEndpointsMarker> logger,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
// ── HMAC-SHA256 signature validation ─────────────────────────────────
|
||||||
|
var secret = config["Gitea:WebhookSecret"];
|
||||||
|
if (!string.IsNullOrWhiteSpace(secret))
|
||||||
|
{
|
||||||
|
if (!request.Headers.TryGetValue("X-Gitea-Signature", out var sigHeader))
|
||||||
|
return Results.Unauthorized();
|
||||||
|
|
||||||
|
var body = await ReadBodyAsync(request, ct);
|
||||||
|
var expectedSig = ComputeHmacSha256(body, secret);
|
||||||
|
|
||||||
|
if (!CryptographicOperations.FixedTimeEquals(
|
||||||
|
Encoding.ASCII.GetBytes(sigHeader.ToString()),
|
||||||
|
Encoding.ASCII.GetBytes(expectedSig)))
|
||||||
|
{
|
||||||
|
logger.LogWarning("Gitea push webhook: HMAC signature mismatch — ignoring.");
|
||||||
|
return Results.Unauthorized();
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload = JsonSerializer.Deserialize<GiteaPushPayload>(body, JsonOpts);
|
||||||
|
return await ProcessPayloadAsync(payload, bus, logger, ct);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// No secret configured — accept without validation (dev only)
|
||||||
|
logger.LogWarning("Gitea:WebhookSecret is not configured — webhook signature validation is disabled.");
|
||||||
|
var payload = await JsonSerializer.DeserializeAsync<GiteaPushPayload>(
|
||||||
|
request.Body, JsonOpts, ct);
|
||||||
|
return await ProcessPayloadAsync(payload, bus, logger, ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<IResult> ProcessPayloadAsync(
|
||||||
|
GiteaPushPayload? payload,
|
||||||
|
IPublishEndpoint bus,
|
||||||
|
ILogger<GiteaWebhookEndpointsMarker> logger,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (payload is null)
|
||||||
|
return Results.BadRequest("Could not parse push payload.");
|
||||||
|
|
||||||
|
// Only act on pushes to develop
|
||||||
|
if (payload.Ref != "refs/heads/develop")
|
||||||
|
{
|
||||||
|
logger.LogDebug("Gitea push webhook: ignoring push to {Ref}", payload.Ref);
|
||||||
|
return Results.Ok(new { skipped = true, reason = "not develop" });
|
||||||
|
}
|
||||||
|
|
||||||
|
var repoName = payload.Repository?.Name;
|
||||||
|
if (string.IsNullOrWhiteSpace(repoName) || !RepoSolutions.TryGetValue(repoName, out var solutionPath))
|
||||||
|
{
|
||||||
|
logger.LogWarning("Gitea push webhook: unknown or unsupported repo '{Repo}'", repoName);
|
||||||
|
return Results.Ok(new { skipped = true, reason = "unsupported repo" });
|
||||||
|
}
|
||||||
|
|
||||||
|
var headSha = payload.After;
|
||||||
|
if (string.IsNullOrWhiteSpace(headSha) || headSha == "0000000000000000000000000000000000000000")
|
||||||
|
{
|
||||||
|
logger.LogInformation("Gitea push webhook: branch deleted — nothing to build.");
|
||||||
|
return Results.Ok(new { skipped = true, reason = "branch deleted" });
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogInformation(
|
||||||
|
"Gitea push webhook: queuing build for {Repo}@{Sha} ({Branch})",
|
||||||
|
repoName, headSha[..8], payload.Ref);
|
||||||
|
|
||||||
|
await bus.Publish(new BuildRequestedCommand
|
||||||
|
{
|
||||||
|
RepoName = repoName,
|
||||||
|
HeadSha = headSha,
|
||||||
|
Branch = "develop",
|
||||||
|
SolutionPath = solutionPath,
|
||||||
|
}, ct);
|
||||||
|
|
||||||
|
return Results.Accepted(value: new { queued = true, repo = repoName, sha = headSha[..8] });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private static async Task<byte[]> ReadBodyAsync(HttpRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
request.EnableBuffering();
|
||||||
|
using var ms = new MemoryStream();
|
||||||
|
await request.Body.CopyToAsync(ms, ct);
|
||||||
|
request.Body.Position = 0;
|
||||||
|
return ms.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ComputeHmacSha256(byte[] body, string secret)
|
||||||
|
{
|
||||||
|
var key = Encoding.UTF8.GetBytes(secret);
|
||||||
|
var hash = HMACSHA256.HashData(key, body);
|
||||||
|
return Convert.ToHexString(hash).ToLowerInvariant();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly JsonSerializerOptions JsonOpts = new(JsonSerializerDefaults.Web);
|
||||||
|
|
||||||
|
// Marker type for logger category
|
||||||
|
private sealed class GiteaWebhookEndpointsMarker;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Payload DTOs ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
public sealed class GiteaPushPayload
|
||||||
|
{
|
||||||
|
[JsonPropertyName("ref")]
|
||||||
|
public string Ref { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonPropertyName("before")]
|
||||||
|
public string Before { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonPropertyName("after")]
|
||||||
|
public string After { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonPropertyName("repository")]
|
||||||
|
public GiteaPushRepo? Repository { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class GiteaPushRepo
|
||||||
|
{
|
||||||
|
[JsonPropertyName("name")]
|
||||||
|
public string Name { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonPropertyName("full_name")]
|
||||||
|
public string FullName { get; init; } = string.Empty;
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using ControlPlane.Api.Services;
|
using ControlPlane.Api.Services;
|
||||||
|
using ControlPlane.Core.Models;
|
||||||
using ControlPlane.Core.Services;
|
using ControlPlane.Core.Services;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
|
||||||
@@ -16,6 +17,7 @@ public static class ProjectBuildEndpoints
|
|||||||
var group = app.MapGroup("/api/builds").WithTags("Builds");
|
var group = app.MapGroup("/api/builds").WithTags("Builds");
|
||||||
group.MapGet("/projects", GetProjects);
|
group.MapGet("/projects", GetProjects);
|
||||||
group.MapGet("/history", GetHistory);
|
group.MapGet("/history", GetHistory);
|
||||||
|
group.MapGet("/by-sha", GetBySha);
|
||||||
group.MapPost("/{projectName}", TriggerProjectBuild);
|
group.MapPost("/{projectName}", TriggerProjectBuild);
|
||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
@@ -27,6 +29,31 @@ public static class ProjectBuildEndpoints
|
|||||||
private static async Task<IResult> GetHistory(BuildHistoryService history) =>
|
private static async Task<IResult> GetHistory(BuildHistoryService history) =>
|
||||||
Results.Ok(await history.GetBuildsAsync());
|
Results.Ok(await history.GetBuildsAsync());
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Returns the latest SolutionBuild record for the given commit SHA, or null if none exists.
|
||||||
|
/// Used by the OPC CommitsTab to render per-commit CI status dots.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task<IResult> GetBySha(string sha, BuildHistoryService history)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(sha))
|
||||||
|
return Results.BadRequest("sha is required");
|
||||||
|
|
||||||
|
var builds = await history.GetBuildsByShaAsync(sha);
|
||||||
|
var latest = builds
|
||||||
|
.Where(b => b.Kind == BuildKind.SolutionBuild)
|
||||||
|
.MaxBy(b => b.StartedAt);
|
||||||
|
|
||||||
|
return Results.Ok(latest is null ? null : new
|
||||||
|
{
|
||||||
|
latest.Id,
|
||||||
|
latest.Status,
|
||||||
|
latest.StartedAt,
|
||||||
|
latest.FinishedAt,
|
||||||
|
latest.DurationMs,
|
||||||
|
latest.CommitSha,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Triggers a build for a named project and streams SSE output.
|
/// Triggers a build for a named project and streams SSE output.
|
||||||
/// projectName must match one of the names returned by GET /api/builds/projects.
|
/// projectName must match one of the names returned by GET /api/builds/projects.
|
||||||
|
|||||||
@@ -79,6 +79,7 @@ app.MapPromotionEndpoints();
|
|||||||
app.MapOpcEndpoints();
|
app.MapOpcEndpoints();
|
||||||
app.MapGiteaEndpoints();
|
app.MapGiteaEndpoints();
|
||||||
app.MapInfraEndpoints();
|
app.MapInfraEndpoints();
|
||||||
|
app.MapGiteaWebhookEndpoints();
|
||||||
|
|
||||||
// Ensure OPC tables exist (idempotent — IF NOT EXISTS)
|
// Ensure OPC tables exist (idempotent — IF NOT EXISTS)
|
||||||
var ds = app.Services.GetRequiredService<NpgsqlDataSource>();
|
var ds = app.Services.GetRequiredService<NpgsqlDataSource>();
|
||||||
|
|||||||
@@ -251,6 +251,40 @@ public class GiteaService
|
|||||||
return await res.Content.ReadFromJsonAsync<GiteaWebhook>(JsonOpts, ct);
|
return await res.Content.ReadFromJsonAsync<GiteaWebhook>(JsonOpts, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Commit Status ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Posts a commit status to Gitea (the CI "check" shown on a commit / PR).
|
||||||
|
/// State values: "pending" | "success" | "failure" | "error".
|
||||||
|
/// Context identifies which check — use "controlplane/build" for the build gate.
|
||||||
|
/// </summary>
|
||||||
|
public async Task PostCommitStatusAsync(
|
||||||
|
string repoKey, string sha, string state, string description,
|
||||||
|
string context = "controlplane/build", CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var (owner, repo) = ResolveOwnerRepo(repoKey);
|
||||||
|
var body = JsonSerializer.Serialize(new
|
||||||
|
{
|
||||||
|
state,
|
||||||
|
description,
|
||||||
|
context,
|
||||||
|
}, JsonOpts);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var res = await _http.PostAsync(
|
||||||
|
$"repos/{owner}/{repo}/statuses/{sha}",
|
||||||
|
new StringContent(body, Encoding.UTF8, "application/json"), ct);
|
||||||
|
|
||||||
|
if (!res.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
var err = await res.Content.ReadAsStringAsync(ct);
|
||||||
|
_log.LogWarning("Gitea PostCommitStatus {State} failed for {Sha}: {Err}", state, sha[..8], err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex) { _log.LogWarning(ex, "Gitea PostCommitStatus threw"); }
|
||||||
|
}
|
||||||
|
|
||||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
private static string SlugifyTitle(string title) =>
|
private static string SlugifyTitle(string title) =>
|
||||||
|
|||||||
@@ -18,14 +18,18 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"Gitea": {
|
"Gitea": {
|
||||||
"BaseUrl": "https://opc.clarity.test",
|
"BaseUrl": "https://opc.clarity.test",
|
||||||
"Owner": "ClarityStack",
|
"Owner": "ClarityStack",
|
||||||
"Repo": "OPC",
|
"Repo": "OPC",
|
||||||
"Token": "fcf9f66415754fb639a8343e3904e06b1d78c646",
|
"Token": "fcf9f66415754fb639a8343e3904e06b1d78c646",
|
||||||
|
"WebhookSecret": "",
|
||||||
"Repos": {
|
"Repos": {
|
||||||
"Clarity": { "Owner": "ClarityStack", "Repo": "Clarity" },
|
"Clarity": { "Owner": "ClarityStack", "Repo": "Clarity" },
|
||||||
"OPC": { "Owner": "ClarityStack", "Repo": "OPC" },
|
"OPC": { "Owner": "ClarityStack", "Repo": "OPC" },
|
||||||
"Gateway": { "Owner": "ClarityStack", "Repo": "Gateway" }
|
"Gateway": { "Owner": "ClarityStack", "Repo": "Gateway" }
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"Build": {
|
||||||
|
"WorkDir": "C:\\Users\\amadzarak\\source\\clarity-builds"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -20,6 +20,9 @@ var clientAssetsPath = Path.GetFullPath(Path.Combine(builder.AppHostDirectory, "
|
|||||||
var nginxConfDPath = Path.GetFullPath(Path.Combine(builder.AppHostDirectory, "..", "infra", "nginx", "conf.d"));
|
var nginxConfDPath = Path.GetFullPath(Path.Combine(builder.AppHostDirectory, "..", "infra", "nginx", "conf.d"));
|
||||||
var vaultKeysFile = Path.GetFullPath(Path.Combine(builder.AppHostDirectory, "..", "infra", "vault", "data", "init.json"));
|
var vaultKeysFile = Path.GetFullPath(Path.Combine(builder.AppHostDirectory, "..", "infra", "vault", "data", "init.json"));
|
||||||
|
|
||||||
|
// Build working directory for BuildConsumer (clone/pull repos here when running builds)
|
||||||
|
var buildWorkDir = Path.GetFullPath(Path.Combine(builder.AppHostDirectory, "..", "..", "..", "clarity-builds"));
|
||||||
|
|
||||||
#region CONTROLPLANE POSTGRES
|
#region CONTROLPLANE POSTGRES
|
||||||
// ControlPlane owns this — isolated from platform infra postgres.
|
// ControlPlane owns this — isolated from platform infra postgres.
|
||||||
// Override via: dotnet user-secrets set "Parameters:cp-postgres-password" "yourpassword"
|
// Override via: dotnet user-secrets set "Parameters:cp-postgres-password" "yourpassword"
|
||||||
@@ -48,6 +51,7 @@ var api = builder.AddProject<Projects.ControlPlane_Api>("controlplane-api")
|
|||||||
.WaitFor(controlPlaneDb)
|
.WaitFor(controlPlaneDb)
|
||||||
.WithEnvironment("ClientAssets__Folder", clientAssetsPath)
|
.WithEnvironment("ClientAssets__Folder", clientAssetsPath)
|
||||||
.WithEnvironment("Docker__RepoRoot", Path.GetFullPath(Path.Combine(builder.AppHostDirectory, "..", ".."))) // ClarityStack/ root — needed for Directory.*.props
|
.WithEnvironment("Docker__RepoRoot", Path.GetFullPath(Path.Combine(builder.AppHostDirectory, "..", ".."))) // ClarityStack/ root — needed for Directory.*.props
|
||||||
|
.WithEnvironment("Build__WorkDir", buildWorkDir)
|
||||||
.WithExternalHttpEndpoints();
|
.WithExternalHttpEndpoints();
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
@@ -82,6 +86,10 @@ builder.AddProject<Projects.ControlPlane_Worker>("controlplane-worker")
|
|||||||
// Platform Postgres connection string for tenant database provisioning (infra/docker-compose.yml)
|
// Platform Postgres connection string for tenant database provisioning (infra/docker-compose.yml)
|
||||||
.WithEnvironment("ConnectionStrings__platformdb",
|
.WithEnvironment("ConnectionStrings__platformdb",
|
||||||
"Host=localhost;Port=5432;Username=postgres;Password=postgres")
|
"Host=localhost;Port=5432;Username=postgres;Password=postgres")
|
||||||
|
.WithEnvironment("Build__WorkDir", buildWorkDir)
|
||||||
|
.WithEnvironment("Gitea__BaseUrl", "https://opc.clarity.test")
|
||||||
|
.WithEnvironment("Gitea__Owner", "ClarityStack")
|
||||||
|
.WithEnvironment("Gitea__Token", "fcf9f66415754fb639a8343e3904e06b1d78c646")
|
||||||
.WithReference(controlPlaneDb)
|
.WithReference(controlPlaneDb)
|
||||||
.WaitFor(controlPlaneDb);
|
.WaitFor(controlPlaneDb);
|
||||||
#endregion
|
#endregion
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
namespace ControlPlane.Core.Messages;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// API -> Worker: run dotnet build for the given repo at the given commit SHA.
|
||||||
|
/// Published when Gitea fires a push webhook for refs/heads/develop.
|
||||||
|
/// </summary>
|
||||||
|
public record BuildRequestedCommand
|
||||||
|
{
|
||||||
|
/// <summary>Gitea repo name (e.g. "OPC" or "Clarity").</summary>
|
||||||
|
public string RepoName { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>HEAD commit SHA of the push that triggered this build.</summary>
|
||||||
|
public string HeadSha { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Branch that was pushed to (e.g. "develop").</summary>
|
||||||
|
public string Branch { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Relative path to the solution file to build, e.g. "ControlPlane.slnx".
|
||||||
|
/// Relative to the cloned repo root.
|
||||||
|
/// </summary>
|
||||||
|
public string SolutionPath { get; init; } = string.Empty;
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using ControlPlane.Core.Messages;
|
||||||
|
using ControlPlane.Core.Models;
|
||||||
|
using ControlPlane.Core.Services;
|
||||||
|
using LibGit2Sharp;
|
||||||
|
using MassTransit;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace ControlPlane.Worker;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// MassTransit consumer. Triggered by BuildRequestedCommand (published by the Gitea push webhook).
|
||||||
|
/// Clones or updates the repo, runs dotnet build, and reports status back to Gitea.
|
||||||
|
/// Runs inside the SDK-based Worker container — dotnet CLI is always available.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class BuildConsumer(
|
||||||
|
BuildHistoryService history,
|
||||||
|
IConfiguration config,
|
||||||
|
IHttpClientFactory httpFactory,
|
||||||
|
ILogger<BuildConsumer> logger) : IConsumer<BuildRequestedCommand>
|
||||||
|
{
|
||||||
|
private static readonly JsonSerializerOptions JsonOpts = new(JsonSerializerDefaults.Web);
|
||||||
|
|
||||||
|
public async Task Consume(ConsumeContext<BuildRequestedCommand> context)
|
||||||
|
{
|
||||||
|
var cmd = context.Message;
|
||||||
|
var ct = context.CancellationToken;
|
||||||
|
|
||||||
|
logger.LogInformation(
|
||||||
|
"BuildConsumer: starting build for {Repo}@{Sha}",
|
||||||
|
cmd.RepoName, cmd.HeadSha[..Math.Min(8, cmd.HeadSha.Length)]);
|
||||||
|
|
||||||
|
// 1. Create a build record — CommitSha written on Complete
|
||||||
|
var record = await history.CreateBuildAsync(BuildKind.SolutionBuild, cmd.SolutionPath);
|
||||||
|
record.CommitSha = cmd.HeadSha;
|
||||||
|
|
||||||
|
// 2. Signal pending to Gitea immediately so the commit shows ⏳
|
||||||
|
await PostCommitStatusAsync(cmd.RepoName, cmd.HeadSha, "pending", "Build running…", ct);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 3. Ensure repo is cloned / up-to-date
|
||||||
|
var workDir = await Task.Run(() => EnsureRepo(cmd.RepoName, cmd.HeadSha, record), ct);
|
||||||
|
if (workDir is null)
|
||||||
|
{
|
||||||
|
await FailAsync(record, cmd, "Failed to prepare repository clone.", ct);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Run dotnet build
|
||||||
|
var solutionPath = Path.Combine(workDir, cmd.SolutionPath
|
||||||
|
.Replace('/', Path.DirectorySeparatorChar));
|
||||||
|
|
||||||
|
var exitCode = await RunBuildAsync(solutionPath, record, ct);
|
||||||
|
var status = exitCode == 0 ? BuildStatus.Succeeded : BuildStatus.Failed;
|
||||||
|
var summary = exitCode == 0
|
||||||
|
? "✔ Build succeeded."
|
||||||
|
: $"✖ Build failed (exit {exitCode}).";
|
||||||
|
|
||||||
|
record.Log.Add(summary);
|
||||||
|
logger.LogInformation("BuildConsumer: {Repo} build {Status}", cmd.RepoName, status);
|
||||||
|
|
||||||
|
// 5. Persist final record + post status to Gitea
|
||||||
|
await history.CompleteBuildAsync(record, status);
|
||||||
|
await PostCommitStatusAsync(
|
||||||
|
cmd.RepoName, cmd.HeadSha,
|
||||||
|
exitCode == 0 ? "success" : "failure",
|
||||||
|
summary, ct);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "BuildConsumer: unhandled exception for {Repo}@{Sha}", cmd.RepoName, cmd.HeadSha);
|
||||||
|
await FailAsync(record, cmd, $"Unhandled exception: {ex.Message}", ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Repository management ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private string? EnsureRepo(string repoName, string headSha, BuildRecord record)
|
||||||
|
{
|
||||||
|
var baseDir = config["Build:WorkDir"] ?? "/opt/clarity-builds";
|
||||||
|
var repoDir = Path.Combine(baseDir, repoName);
|
||||||
|
var remoteUrl = BuildRemoteUrl(repoName);
|
||||||
|
|
||||||
|
void Log(string msg)
|
||||||
|
{
|
||||||
|
record.Log.Add(msg);
|
||||||
|
logger.LogInformation("[{Repo}] {Msg}", repoName, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!Repository.IsValid(repoDir))
|
||||||
|
{
|
||||||
|
Log($"Cloning {remoteUrl} → {repoDir}");
|
||||||
|
Directory.CreateDirectory(repoDir);
|
||||||
|
Repository.Clone(remoteUrl, repoDir, new CloneOptions
|
||||||
|
{
|
||||||
|
FetchOptions =
|
||||||
|
{
|
||||||
|
CredentialsProvider = MakeCredentials(),
|
||||||
|
CertificateCheck = (_, _, _) => true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Log($"Pulling latest for {repoName}");
|
||||||
|
using var repo = new Repository(repoDir);
|
||||||
|
var remote = EnsureRemote(repo, repoName);
|
||||||
|
Commands.Fetch(repo, remote.Name, remote.FetchRefSpecs.Select(r => r.Specification), new FetchOptions
|
||||||
|
{
|
||||||
|
CredentialsProvider = MakeCredentials(),
|
||||||
|
CertificateCheck = (_, _, _) => true,
|
||||||
|
}, null);
|
||||||
|
|
||||||
|
// Reset to the exact SHA we want to build
|
||||||
|
var commit = repo.Lookup<Commit>(headSha);
|
||||||
|
if (commit is null)
|
||||||
|
{
|
||||||
|
Log($"Warning: SHA {headSha[..8]} not found after fetch — building HEAD instead.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
repo.Reset(ResetMode.Hard, commit);
|
||||||
|
Log($"Reset to {headSha[..8]}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return repoDir;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log($"✖ Git error: {ex.Message}");
|
||||||
|
logger.LogError(ex, "Failed to prepare repo {Repo}", repoName);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Remote EnsureRemote(Repository repo, string repoName)
|
||||||
|
{
|
||||||
|
var url = BuildRemoteUrl(repoName);
|
||||||
|
var remote = repo.Network.Remotes["origin"];
|
||||||
|
if (remote is null)
|
||||||
|
return repo.Network.Remotes.Add("origin", url);
|
||||||
|
if (remote.Url != url)
|
||||||
|
repo.Network.Remotes.Update("origin", r => r.Url = url);
|
||||||
|
return repo.Network.Remotes["origin"]!;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string BuildRemoteUrl(string repoName)
|
||||||
|
{
|
||||||
|
var baseUrl = (config["Gitea:BaseUrl"] ?? "https://opc.clarity.test").TrimEnd('/');
|
||||||
|
var owner = config["Gitea:Owner"] ?? "ClarityStack";
|
||||||
|
return $"{baseUrl}/{owner}/{repoName}.git";
|
||||||
|
}
|
||||||
|
|
||||||
|
private LibGit2Sharp.Handlers.CredentialsHandler MakeCredentials()
|
||||||
|
{
|
||||||
|
var user = config["Gitea:Owner"] ?? "git";
|
||||||
|
var token = config["Gitea:Token"] ?? string.Empty;
|
||||||
|
return (_, _, _) => new UsernamePasswordCredentials { Username = user, Password = token };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Build execution ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private async Task<int> RunBuildAsync(string solutionPath, BuildRecord record, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var psi = new ProcessStartInfo("dotnet",
|
||||||
|
$"build \"{solutionPath}\" -c Release --no-incremental --nologo")
|
||||||
|
{
|
||||||
|
RedirectStandardOutput = true,
|
||||||
|
RedirectStandardError = true,
|
||||||
|
UseShellExecute = false,
|
||||||
|
CreateNoWindow = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
record.Log.Add($"▶ dotnet build {Path.GetFileName(solutionPath)} -c Release");
|
||||||
|
record.Log.Add("──────────────────────────────────────────────────");
|
||||||
|
|
||||||
|
using var proc = new Process { StartInfo = psi, EnableRaisingEvents = true };
|
||||||
|
|
||||||
|
void HandleLine(string? line)
|
||||||
|
{
|
||||||
|
if (line is null) return;
|
||||||
|
// Non-blocking fire-and-forget flush every 20 lines
|
||||||
|
_ = history.AppendBuildLogAsync(record, line);
|
||||||
|
}
|
||||||
|
|
||||||
|
proc.OutputDataReceived += (_, e) => HandleLine(e.Data);
|
||||||
|
proc.ErrorDataReceived += (_, e) => HandleLine(e.Data);
|
||||||
|
|
||||||
|
proc.Start();
|
||||||
|
proc.BeginOutputReadLine();
|
||||||
|
proc.BeginErrorReadLine();
|
||||||
|
|
||||||
|
await proc.WaitForExitAsync(ct);
|
||||||
|
return proc.ExitCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Gitea commit status ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private async Task PostCommitStatusAsync(
|
||||||
|
string repoName, string sha, string state, string description, CancellationToken ct)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var owner = config["Gitea:Owner"] ?? "ClarityStack";
|
||||||
|
|
||||||
|
using var http = httpFactory.CreateClient("gitea");
|
||||||
|
|
||||||
|
var url = $"api/v1/repos/{owner}/{repoName}/statuses/{sha}";
|
||||||
|
var body = JsonSerializer.Serialize(new
|
||||||
|
{
|
||||||
|
state,
|
||||||
|
description,
|
||||||
|
context = "controlplane/build",
|
||||||
|
}, JsonOpts);
|
||||||
|
|
||||||
|
var resp = await http.PostAsync(
|
||||||
|
url,
|
||||||
|
new StringContent(body, Encoding.UTF8, "application/json"),
|
||||||
|
ct);
|
||||||
|
|
||||||
|
if (!resp.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
var err = await resp.Content.ReadAsStringAsync(ct);
|
||||||
|
logger.LogWarning(
|
||||||
|
"PostCommitStatus failed for {Repo}@{Sha}: {Status} {Err}",
|
||||||
|
repoName, sha[..Math.Min(8, sha.Length)], resp.StatusCode, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// Never let a failed status post break the build flow
|
||||||
|
logger.LogWarning(ex, "PostCommitStatus threw for {Repo}", repoName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private async Task FailAsync(
|
||||||
|
BuildRecord record, BuildRequestedCommand cmd, string reason, CancellationToken ct)
|
||||||
|
{
|
||||||
|
record.Log.Add($"✖ {reason}");
|
||||||
|
await history.CompleteBuildAsync(record, BuildStatus.Failed);
|
||||||
|
await PostCommitStatusAsync(cmd.RepoName, cmd.HeadSha, "failure", reason, ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Docker.DotNet" />
|
<PackageReference Include="Docker.DotNet" />
|
||||||
|
<PackageReference Include="LibGit2Sharp" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Hosting" />
|
<PackageReference Include="Microsoft.Extensions.Hosting" />
|
||||||
<PackageReference Include="Npgsql" />
|
<PackageReference Include="Npgsql" />
|
||||||
<PackageReference Include="Keycloak.AuthServices.Sdk" />
|
<PackageReference Include="Keycloak.AuthServices.Sdk" />
|
||||||
|
|||||||
@@ -14,17 +14,10 @@ RUN dotnet publish "ControlPlane.Worker/ControlPlane.Worker.csproj" \
|
|||||||
-c Release -o /app/publish --no-restore
|
-c Release -o /app/publish --no-restore
|
||||||
|
|
||||||
# ── Runtime stage ─────────────────────────────────────────────────────────────
|
# ── Runtime stage ─────────────────────────────────────────────────────────────
|
||||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime
|
# SDK image — required so BuildConsumer can invoke `dotnet build` on cloned repos.
|
||||||
|
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS runtime
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Install Pulumi CLI so the Automation API can shell out to it
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates \
|
|
||||||
&& curl -fsSL https://get.pulumi.com | sh \
|
|
||||||
&& apt-get purge -y curl \
|
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
ENV PATH="/root/.pulumi/bin:${PATH}"
|
|
||||||
|
|
||||||
COPY --from=build /app/publish .
|
COPY --from=build /app/publish .
|
||||||
|
|
||||||
ENTRYPOINT ["dotnet", "ControlPlane.Worker.dll"]
|
ENTRYPOINT ["dotnet", "ControlPlane.Worker.dll"]
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ using ControlPlane.Worker.Services;
|
|||||||
using ControlPlane.Worker.Steps;
|
using ControlPlane.Worker.Steps;
|
||||||
using Keycloak.AuthServices.Sdk;
|
using Keycloak.AuthServices.Sdk;
|
||||||
using MassTransit;
|
using MassTransit;
|
||||||
|
using Npgsql;
|
||||||
|
|
||||||
var builder = Host.CreateApplicationBuilder(args);
|
var builder = Host.CreateApplicationBuilder(args);
|
||||||
|
|
||||||
@@ -26,6 +27,22 @@ builder.Services.AddKeycloakAdminHttpClient(o =>
|
|||||||
// Custom admin client - handles realm creation, roles, role assignment (not in SDK)
|
// Custom admin client - handles realm creation, roles, role assignment (not in SDK)
|
||||||
builder.Services.AddSingleton<KeycloakAdminClient>();
|
builder.Services.AddSingleton<KeycloakAdminClient>();
|
||||||
|
|
||||||
|
// Named HttpClient for Gitea commit status API (self-signed cert + token auth)
|
||||||
|
builder.Services.AddHttpClient("gitea", (sp, client) =>
|
||||||
|
{
|
||||||
|
var cfg = sp.GetRequiredService<IConfiguration>();
|
||||||
|
client.BaseAddress = new Uri(cfg["Gitea:BaseUrl"] ?? "https://opc.clarity.test");
|
||||||
|
client.DefaultRequestHeaders.Authorization =
|
||||||
|
new System.Net.Http.Headers.AuthenticationHeaderValue("token", cfg["Gitea:Token"]);
|
||||||
|
}).ConfigurePrimaryHttpMessageHandler(() =>
|
||||||
|
new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator });
|
||||||
|
|
||||||
|
// opcdb for build/release history tracking
|
||||||
|
var opcConnStr = builder.Configuration.GetConnectionString("opcdb");
|
||||||
|
builder.Services.AddSingleton(NpgsqlDataSource.Create(
|
||||||
|
!string.IsNullOrWhiteSpace(opcConnStr) ? opcConnStr : "Host=127.0.0.1;Port=5433;Database=opcdb;Username=postgres;Password=controlplane-dev"));
|
||||||
|
builder.Services.AddSingleton<BuildHistoryService>();
|
||||||
|
|
||||||
// Docker container manager for per-tenant Clarity.Server instances
|
// Docker container manager for per-tenant Clarity.Server instances
|
||||||
builder.Services.AddSingleton<ClarityContainerService>();
|
builder.Services.AddSingleton<ClarityContainerService>();
|
||||||
|
|
||||||
@@ -44,6 +61,7 @@ builder.Services.AddMassTransit(x =>
|
|||||||
x.SetKebabCaseEndpointNameFormatter();
|
x.SetKebabCaseEndpointNameFormatter();
|
||||||
|
|
||||||
x.AddConsumer<ProvisioningConsumer>();
|
x.AddConsumer<ProvisioningConsumer>();
|
||||||
|
x.AddConsumer<BuildConsumer>();
|
||||||
|
|
||||||
x.UsingRabbitMq((ctx, cfg) =>
|
x.UsingRabbitMq((ctx, cfg) =>
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
{
|
{
|
||||||
"Vault": {
|
"Vault": {
|
||||||
"KeysFile": "C:\\Users\\amadzarak\\source\\repos\\ClarityStack\\OPC\\infra\\vault\\data\\init.json"
|
"KeysFile": "C:\\Users\\amadzarak\\source\\repos\\ClarityStack\\OPC\\infra\\vault\\data\\init.json"
|
||||||
|
},
|
||||||
|
"Build": {
|
||||||
|
"WorkDir": "C:\\Users\\amadzarak\\source\\clarity-builds"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,14 @@
|
|||||||
"ContainerAddress": "http://vault:8200"
|
"ContainerAddress": "http://vault:8200"
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// ── Gitea ─────────────────────────────────────────────────────────────────────
|
||||||
|
// Used by BuildConsumer to post commit statuses and clone repos.
|
||||||
|
"Gitea": {
|
||||||
|
"BaseUrl": "https://opc.clarity.test",
|
||||||
|
"Owner": "ClarityStack",
|
||||||
|
"Token": "fcf9f66415754fb639a8343e3904e06b1d78c646"
|
||||||
|
},
|
||||||
|
|
||||||
// ── ClarityInfraOptions (Clarity section) ─────────────────────────────────────
|
// ── ClarityInfraOptions (Clarity section) ─────────────────────────────────────
|
||||||
// These values describe what gets injected INTO tenant containers at docker run time.
|
// These values describe what gets injected INTO tenant containers at docker run time.
|
||||||
// Containers live on clarity-net → use Docker DNS names (keycloak, vault, postgres).
|
// Containers live on clarity-net → use Docker DNS names (keycloak, vault, postgres).
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||||
|
</PropertyGroup>
|
||||||
|
<!-- Aspire Packages -->
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageVersion Include="Aspire.Hosting.PostgreSQL" Version="13.2.2" />
|
||||||
|
<PackageVersion Include="Aspire.Keycloak.Authentication" Version="13.2.2-preview.1.26207.2" />
|
||||||
|
<PackageVersion Include="Aspire.Npgsql.EntityFrameworkCore.PostgreSQL" Version="13.2.2" />
|
||||||
|
<PackageVersion Include="Aspire.StackExchange.Redis.OutputCaching" Version="13.2.2" />
|
||||||
|
<PackageVersion Include="Aspire.Hosting.JavaScript" Version="13.2.2" />
|
||||||
|
<PackageVersion Include="Aspire.Hosting.Keycloak" Version="13.2.2-preview.1.26207.2" />
|
||||||
|
<PackageVersion Include="Aspire.Hosting.Redis" Version="13.2.2" />
|
||||||
|
<PackageVersion Include="CommunityToolkit.Aspire.Hosting.Minio" Version="13.2.1-beta.532" />
|
||||||
|
<PackageVersion Include="CommunityToolkit.Aspire.Minio.Client" Version="13.2.1-beta.532" />
|
||||||
|
<PackageVersion Include="Docker.DotNet" Version="3.125.15" />
|
||||||
|
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="10.0.6" />
|
||||||
|
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.6" />
|
||||||
|
<PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.6" />
|
||||||
|
<PackageVersion Include="Microsoft.Extensions.Configuration.Abstractions" Version="10.0.7" />
|
||||||
|
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.7" />
|
||||||
|
<PackageVersion Include="Npgsql" Version="10.0.2" />
|
||||||
|
<PackageVersion Include="LibGit2Sharp" Version="0.31.0" />
|
||||||
|
<PackageVersion Include="Scalar.Aspire" Version="0.9.24" />
|
||||||
|
<PackageVersion Include="VaultSharp" Version="1.17.5.1" />
|
||||||
|
<PackageVersion Include="Yarp.ReverseProxy" Version="2.3.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
<!-- Clarity.MigrationService -->
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="10.0.6" />
|
||||||
|
</ItemGroup>
|
||||||
|
<!-- ControlPlane -->
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageVersion Include="Aspire.Hosting.Sdk" Version="13.2.2" />
|
||||||
|
<PackageVersion Include="Aspire.Hosting.RabbitMQ" Version="13.2.2" />
|
||||||
|
<PackageVersion Include="Aspire.RabbitMQ.Client" Version="13.2.2" />
|
||||||
|
<PackageVersion Include="Keycloak.AuthServices.Sdk" Version="2.9.0" />
|
||||||
|
<PackageVersion Include="MassTransit" Version="8.4.1" />
|
||||||
|
<PackageVersion Include="MassTransit.RabbitMQ" Version="8.4.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
<!-- Clarity.Server -->
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.6" />
|
||||||
|
<PackageVersion Include="Microsoft.Extensions.Http.Resilience" Version="10.5.0" />
|
||||||
|
<PackageVersion Include="Microsoft.Extensions.ServiceDiscovery" Version="10.5.0" />
|
||||||
|
<PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.15.2" />
|
||||||
|
<PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="1.15.2" />
|
||||||
|
<PackageVersion Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.15.1" />
|
||||||
|
<PackageVersion Include="OpenTelemetry.Instrumentation.Http" Version="1.15.0" />
|
||||||
|
<PackageVersion Include="OpenTelemetry.Instrumentation.Runtime" Version="1.15.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -30,6 +30,29 @@ export async function getBuildHistory(): Promise<BuildRecord[]> {
|
|||||||
return res.json();
|
return res.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ShaBuildResult {
|
||||||
|
id: string;
|
||||||
|
status: 'Running' | 'Succeeded' | 'Failed';
|
||||||
|
startedAt: string;
|
||||||
|
finishedAt?: string;
|
||||||
|
durationMs?: number;
|
||||||
|
commitSha?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns the latest SolutionBuild for a given SHA, or null if none exists. */
|
||||||
|
export async function getBuildBySha(sha: string): Promise<ShaBuildResult | null> {
|
||||||
|
const res = await fetch(`${BASE_URL}/api/builds/by-sha?sha=${encodeURIComponent(sha)}`);
|
||||||
|
if (!res.ok) throw new Error(`getBuildBySha failed: ${res.statusText}`);
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Batch-fetches SolutionBuild status for multiple SHAs. Returns a map of sha -> result|null. */
|
||||||
|
export async function getBuildsByShas(shas: string[]): Promise<Map<string, ShaBuildResult | null>> {
|
||||||
|
const unique = [...new Set(shas.filter(Boolean))];
|
||||||
|
const entries = await Promise.all(unique.map(async (sha) => [sha, await getBuildBySha(sha)] as const));
|
||||||
|
return new Map(entries);
|
||||||
|
}
|
||||||
|
|
||||||
export function triggerProjectBuild(
|
export function triggerProjectBuild(
|
||||||
projectName: string,
|
projectName: string,
|
||||||
onLine: (line: string) => void,
|
onLine: (line: string) => void,
|
||||||
|
|||||||
@@ -121,6 +121,7 @@ export interface LinkedCommit {
|
|||||||
date: string;
|
date: string;
|
||||||
subject: string;
|
subject: string;
|
||||||
files: string[];
|
files: string[];
|
||||||
|
branches: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getLinkedCommits(opcNumber: string): Promise<LinkedCommit[]> {
|
export async function getLinkedCommits(opcNumber: string): Promise<LinkedCommit[]> {
|
||||||
@@ -208,18 +209,35 @@ export async function getBranchCoverageForRepo(repoKey: string, hashes: string[]
|
|||||||
// Reuses LinkedCommit shape — repoKey identifies which repo each commit came from.
|
// Reuses LinkedCommit shape — repoKey identifies which repo each commit came from.
|
||||||
|
|
||||||
export async function getChangesets(
|
export async function getChangesets(
|
||||||
page = 1,
|
page = 1,
|
||||||
limit = 25,
|
limit = 25,
|
||||||
repo = 'all',
|
repo = 'all',
|
||||||
grep?: string,
|
grep?: string,
|
||||||
|
branch?: string,
|
||||||
): Promise<LinkedCommit[]> {
|
): Promise<LinkedCommit[]> {
|
||||||
const params = new URLSearchParams({ page: String(page), limit: String(limit), repo });
|
const params = new URLSearchParams({ page: String(page), limit: String(limit), repo });
|
||||||
if (grep) params.set('grep', grep);
|
if (grep) params.set('grep', grep);
|
||||||
|
if (branch) params.set('branch', branch);
|
||||||
const res = await fetch(`${BASE_URL}/api/git/log?${params}`);
|
const res = await fetch(`${BASE_URL}/api/git/log?${params}`);
|
||||||
if (!res.ok) throw new Error(`Failed to load changesets: ${res.statusText}`);
|
if (!res.ok) throw new Error(`Failed to load changesets: ${res.statusText}`);
|
||||||
return res.json();
|
return res.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Local git branches (from LibGit2 repos) ───────────────────────────────────
|
||||||
|
|
||||||
|
export interface RepoBranchInfo {
|
||||||
|
repoKey: string;
|
||||||
|
name: string;
|
||||||
|
hash: string;
|
||||||
|
isHead: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getBranches(repo = 'all'): Promise<RepoBranchInfo[]> {
|
||||||
|
const res = await fetch(`${BASE_URL}/api/git/branches?repo=${encodeURIComponent(repo)}`);
|
||||||
|
if (!res.ok) throw new Error(`Failed to load branches: ${res.statusText}`);
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
// ── Commit detail (full diff) ─────────────────────────────────────────────────
|
// ── Commit detail (full diff) ─────────────────────────────────────────────────
|
||||||
|
|
||||||
export interface CommitFile {
|
export interface CommitFile {
|
||||||
|
|||||||
@@ -1292,3 +1292,50 @@ body {
|
|||||||
min-width: 60px;
|
min-width: 60px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.cs-page-with-tree {
|
||||||
|
display: flex;
|
||||||
|
gap: 1.5rem;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cs-branch-tree {
|
||||||
|
width: 200px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
position: sticky;
|
||||||
|
top: 1rem;
|
||||||
|
border: 1px solid #dce0e6;
|
||||||
|
border-radius: 8px;
|
||||||
|
overflow: hidden;
|
||||||
|
padding: 0.25rem 0;
|
||||||
|
max-height: calc(100vh - 8rem);
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cs-branch-tree .bp6-tree-node-content {
|
||||||
|
font-size: 0.82rem;
|
||||||
|
height: 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cs-branch-tree .bp6-tree-node-content:hover {
|
||||||
|
background: #f6f7f9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cs-branch-tree .bp6-tree-node.bp6-tree-node-selected > .bp6-tree-node-content {
|
||||||
|
background: #e8f0fb;
|
||||||
|
color: #215db0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cs-content-area {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cs-branch-badge {
|
||||||
|
font-size: 0.67rem;
|
||||||
|
letter-spacing: 0.01em;
|
||||||
|
white-space: nowrap;
|
||||||
|
margin-left: 0.5rem;
|
||||||
|
opacity: 0.85;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,13 +1,18 @@
|
|||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
Button, Callout, Intent, Tag, Spinner, NonIdealState,
|
AnchorButton, Button, Callout, Collapse, HTMLTable, Intent, NonIdealState, Spinner, Tag,
|
||||||
Collapse, HTMLTable,
|
|
||||||
} from '@blueprintjs/core';
|
} from '@blueprintjs/core';
|
||||||
import { getProjects, getBuildHistory, type ProjectDefinition, type BuildRecord } from '../api/buildApi';
|
import { getProjects, getBuildHistory, type ProjectDefinition, type BuildRecord } from '../api/buildApi';
|
||||||
import { getGitLog, type GitCommit } from '../api/gitApi';
|
|
||||||
|
|
||||||
const BASE_URL = import.meta.env.VITE_API_URL ?? '';
|
const BASE_URL = import.meta.env.VITE_API_URL ?? '';
|
||||||
|
|
||||||
|
const KIND_LABEL: Record<string, string> = {
|
||||||
|
DotnetProject: '.NET',
|
||||||
|
NpmProject: 'npm',
|
||||||
|
DockerImage: 'Docker',
|
||||||
|
SolutionBuild: 'CI',
|
||||||
|
};
|
||||||
|
|
||||||
const KIND_INTENT: Record<string, Intent> = {
|
const KIND_INTENT: Record<string, Intent> = {
|
||||||
DotnetProject: Intent.PRIMARY,
|
DotnetProject: Intent.PRIMARY,
|
||||||
NpmProject: Intent.WARNING,
|
NpmProject: Intent.WARNING,
|
||||||
@@ -21,90 +26,31 @@ const STATUS_INTENT: Record<string, Intent> = {
|
|||||||
Running: Intent.PRIMARY,
|
Running: Intent.PRIMARY,
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── Git history panel ─────────────────────────────────────────────────────────
|
// ── Inline log viewer ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function GitHistoryPanel({ relativePath }: { relativePath: string }) {
|
|
||||||
const [commits, setCommits] = useState<GitCommit[]>([]);
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [open, setOpen] = useState(false);
|
|
||||||
const [fetched, setFetched] = useState(false);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
const toggle = async () => {
|
|
||||||
if (!open && !fetched) {
|
|
||||||
setLoading(true);
|
|
||||||
setError(null);
|
|
||||||
try {
|
|
||||||
const data = await getGitLog(relativePath, 10);
|
|
||||||
setCommits(data);
|
|
||||||
setFetched(true);
|
|
||||||
} catch (e) {
|
|
||||||
setError(e instanceof Error ? e.message : 'Failed to load git history');
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setOpen((o) => !o);
|
|
||||||
};
|
|
||||||
|
|
||||||
|
function LogRow({ lines }: { lines: string[] }) {
|
||||||
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
|
useEffect(() => { if (ref.current) ref.current.scrollTop = ref.current.scrollHeight; }, [lines]);
|
||||||
return (
|
return (
|
||||||
<div style={{ marginTop: '0.5rem' }}>
|
<tr>
|
||||||
<Button
|
<td colSpan={7} style={{ padding: 0 }}>
|
||||||
minimal small
|
<div ref={ref} style={{
|
||||||
icon="git-branch"
|
fontFamily: 'monospace', fontSize: '0.7rem',
|
||||||
text={open ? 'Hide history' : 'Git history'}
|
background: '#111', color: '#d4d4d4',
|
||||||
onClick={toggle}
|
padding: '0.5rem 0.75rem', maxHeight: 200, overflowY: 'auto',
|
||||||
loading={loading}
|
whiteSpace: 'pre-wrap', wordBreak: 'break-all',
|
||||||
/>
|
}}>
|
||||||
|
{lines.map((l, i) => <div key={i}>{l}</div>)}
|
||||||
<Collapse isOpen={open && !loading}>
|
</div>
|
||||||
{error && <Callout intent={Intent.DANGER} compact style={{ marginTop: '0.25rem' }}>{error}</Callout>}
|
</td>
|
||||||
{commits.length === 0 && !error && (
|
</tr>
|
||||||
<p style={{ fontSize: '0.75rem', color: '#8f99a8', marginTop: '0.5rem' }}>No commits found for this path.</p>
|
|
||||||
)}
|
|
||||||
{commits.length > 0 && (
|
|
||||||
<HTMLTable className="bp6-html-table-condensed bp6-html-table-striped" style={{ width: '100%', marginTop: '0.5rem', fontSize: '0.72rem' }}>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th style={{ width: 60 }}>Commit</th>
|
|
||||||
<th>Message</th>
|
|
||||||
<th>Author</th>
|
|
||||||
<th style={{ width: 140 }}>Date</th>
|
|
||||||
<th style={{ width: 40, textAlign: 'right' }}>Files</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{commits.map((c) => (
|
|
||||||
<tr key={c.hash}>
|
|
||||||
<td>
|
|
||||||
<code style={{ fontSize: '0.7rem', color: '#4a90d9' }}>{c.shortHash}</code>
|
|
||||||
</td>
|
|
||||||
<td style={{ maxWidth: 320, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
|
||||||
{c.subject}
|
|
||||||
</td>
|
|
||||||
<td style={{ color: '#738091' }}>{c.author}</td>
|
|
||||||
<td style={{ color: '#738091' }}>
|
|
||||||
{new Date(c.date).toLocaleString(undefined, { dateStyle: 'short', timeStyle: 'short' })}
|
|
||||||
</td>
|
|
||||||
<td style={{ textAlign: 'right', color: '#8f99a8' }}>
|
|
||||||
<span title={c.files.join('\n')}>{c.files.length}</span>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</HTMLTable>
|
|
||||||
)}
|
|
||||||
</Collapse>
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Per-project card ──────────────────────────────────────────────────────────
|
// ── Manual project row ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function ProjectCard({
|
function ProjectRow({
|
||||||
project,
|
project, lastBuild, onBuilt,
|
||||||
lastBuild,
|
|
||||||
onBuilt,
|
|
||||||
}: {
|
}: {
|
||||||
project: ProjectDefinition;
|
project: ProjectDefinition;
|
||||||
lastBuild: BuildRecord | undefined;
|
lastBuild: BuildRecord | undefined;
|
||||||
@@ -114,29 +60,18 @@ function ProjectCard({
|
|||||||
const [logs, setLogs] = useState<string[]>([]);
|
const [logs, setLogs] = useState<string[]>([]);
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const logRef = useRef<HTMLDivElement>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;
|
|
||||||
}, [logs]);
|
|
||||||
|
|
||||||
const handleBuild = async () => {
|
const handleBuild = async () => {
|
||||||
setBuilding(true);
|
setBuilding(true);
|
||||||
setOpen(true);
|
setOpen(true);
|
||||||
setLogs([]);
|
setLogs([]);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(
|
const res = await fetch(`${BASE_URL}/api/builds/${encodeURIComponent(project.name)}`, { method: 'POST' });
|
||||||
`${BASE_URL}/api/builds/${encodeURIComponent(project.name)}`,
|
|
||||||
{ method: 'POST' }
|
|
||||||
);
|
|
||||||
if (!res.ok || !res.body) throw new Error(res.statusText);
|
if (!res.ok || !res.body) throw new Error(res.statusText);
|
||||||
|
|
||||||
const reader = res.body.getReader();
|
const reader = res.body.getReader();
|
||||||
const decoder = new TextDecoder();
|
const decoder = new TextDecoder();
|
||||||
let buffer = '';
|
let buffer = '';
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
const { done, value } = await reader.read();
|
const { done, value } = await reader.read();
|
||||||
if (done) break;
|
if (done) break;
|
||||||
@@ -149,8 +84,7 @@ function ProjectCard({
|
|||||||
try {
|
try {
|
||||||
const msg = JSON.parse(dataLine);
|
const msg = JSON.parse(dataLine);
|
||||||
if (msg.done) onBuilt();
|
if (msg.done) onBuilt();
|
||||||
else if (typeof msg.line === 'string')
|
else if (typeof msg.line === 'string') setLogs((p) => [...p.slice(-1000), msg.line]);
|
||||||
setLogs((p) => [...p.slice(-1000), msg.line]);
|
|
||||||
} catch { /* ignore */ }
|
} catch { /* ignore */ }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -162,70 +96,86 @@ function ProjectCard({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const statusIntent = lastBuild ? STATUS_INTENT[lastBuild.status] : Intent.NONE;
|
const statusIntent = lastBuild ? STATUS_INTENT[lastBuild.status] : Intent.NONE;
|
||||||
const statusLabel = lastBuild?.status ?? 'Never built';
|
const duration = lastBuild?.durationMs != null ? `${(lastBuild.durationMs / 1000).toFixed(1)}s` : '—';
|
||||||
const lastRun = lastBuild ? new Date(lastBuild.startedAt).toLocaleString() : '—';
|
const lastRun = lastBuild ? new Date(lastBuild.startedAt).toLocaleString() : '—';
|
||||||
const duration = lastBuild?.durationMs != null
|
|
||||||
? `${(lastBuild.durationMs / 1000).toFixed(1)}s` : null;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="job-card">
|
<>
|
||||||
<div className="job-card-header">
|
<tr>
|
||||||
<div>
|
<td>
|
||||||
<strong>{project.name}</strong>
|
<span style={{ fontWeight: 600 }}>{project.name}</span>
|
||||||
<span className="job-card-subdomain" style={{ fontFamily: 'monospace', fontSize: '0.72rem' }}>
|
<br />
|
||||||
{project.relativePath}
|
<code style={{ fontSize: '0.68rem', color: '#8f99a8' }}>{project.relativePath}</code>
|
||||||
</span>
|
</td>
|
||||||
</div>
|
<td><Tag intent={KIND_INTENT[project.kind] ?? Intent.NONE} minimal round>{KIND_LABEL[project.kind] ?? project.kind}</Tag></td>
|
||||||
<div style={{ display: 'flex', gap: '0.4rem', alignItems: 'center' }}>
|
<td><Tag minimal round style={{ color: '#8f99a8' }}>manual</Tag></td>
|
||||||
<Tag intent={KIND_INTENT[project.kind] ?? Intent.NONE} minimal round>{project.kind}</Tag>
|
<td><Tag intent={statusIntent} minimal round>{lastBuild?.status ?? 'Never'}</Tag></td>
|
||||||
<Tag intent={statusIntent} round>{statusLabel}</Tag>
|
<td style={{ color: '#8f99a8', fontSize: '0.8rem' }}>{lastRun}</td>
|
||||||
{duration && <Tag minimal round>{duration}</Tag>}
|
<td style={{ color: '#8f99a8', fontSize: '0.8rem', textAlign: 'right' }}>{duration}</td>
|
||||||
</div>
|
<td style={{ textAlign: 'right' }}>
|
||||||
</div>
|
<Button icon="play" small intent={Intent.PRIMARY} loading={building} onClick={handleBuild} text="Build" />
|
||||||
|
{logs.length > 0 && (
|
||||||
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', padding: '0.5rem 0 0.25rem' }}>
|
<Button minimal small icon={open ? 'chevron-up' : 'chevron-down'} onClick={() => setOpen((o) => !o)} style={{ marginLeft: 4 }} />
|
||||||
<Button
|
)}
|
||||||
icon="play"
|
</td>
|
||||||
small
|
</tr>
|
||||||
intent={Intent.PRIMARY}
|
{error && (
|
||||||
loading={building}
|
<tr><td colSpan={7}><Callout intent={Intent.DANGER} compact>{error}</Callout></td></tr>
|
||||||
onClick={handleBuild}
|
|
||||||
text="Build"
|
|
||||||
/>
|
|
||||||
<span style={{ fontSize: '0.75rem', color: '#999' }}>Last run: {lastRun}</span>
|
|
||||||
{logs.length > 0 && (
|
|
||||||
<Button minimal small
|
|
||||||
icon={open ? 'chevron-up' : 'chevron-down'}
|
|
||||||
onClick={() => setOpen((o) => !o)}
|
|
||||||
text={open ? 'Hide log' : 'Show log'}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{error && <Callout intent={Intent.DANGER} compact style={{ marginTop: '0.25rem' }}>{error}</Callout>}
|
|
||||||
|
|
||||||
{open && logs.length > 0 && (
|
|
||||||
<div
|
|
||||||
ref={logRef}
|
|
||||||
style={{
|
|
||||||
fontFamily: 'monospace', fontSize: '0.7rem',
|
|
||||||
background: '#111', color: '#d4d4d4',
|
|
||||||
padding: '0.5rem 0.75rem', borderRadius: 4,
|
|
||||||
height: 200, overflowY: 'auto',
|
|
||||||
whiteSpace: 'pre-wrap', wordBreak: 'break-all',
|
|
||||||
marginTop: '0.5rem',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{logs.map((l, i) => <div key={i}>{l}</div>)}
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
|
<Collapse isOpen={open && logs.length > 0} keepChildrenMounted>
|
||||||
<GitHistoryPanel relativePath={project.relativePath} />
|
<LogRow lines={logs} />
|
||||||
</div>
|
</Collapse>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Page ──────────────────────────────────────────────────────────────────────
|
// ── CI (SolutionBuild) row ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function CiRow({ build, giteaBase }: { build: BuildRecord; giteaBase: string }) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
|
const repo = build.target.replace(/\.slnx?$/, ''); // "ControlPlane.slnx" → "ControlPlane"
|
||||||
|
const shortSha = build.commitSha?.slice(0, 7);
|
||||||
|
const shaUrl = build.commitSha
|
||||||
|
? `${giteaBase}/ClarityStack/${repo === 'ControlPlane' ? 'OPC' : repo}/commit/${build.commitSha}`
|
||||||
|
: null;
|
||||||
|
const duration = build.durationMs != null ? `${(build.durationMs / 1000).toFixed(1)}s` : '—';
|
||||||
|
const lastRun = new Date(build.startedAt).toLocaleString();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<span style={{ fontWeight: 600 }}>{repo}</span>
|
||||||
|
<br />
|
||||||
|
<code style={{ fontSize: '0.68rem', color: '#8f99a8' }}>{build.target}</code>
|
||||||
|
</td>
|
||||||
|
<td><Tag intent={Intent.SUCCESS} minimal round>CI</Tag></td>
|
||||||
|
<td>
|
||||||
|
{shortSha && shaUrl ? (
|
||||||
|
<AnchorButton href={shaUrl} target="_blank" rel="noopener noreferrer" minimal small
|
||||||
|
style={{ fontFamily: 'monospace', fontSize: '0.72rem', padding: '0 4px' }}>
|
||||||
|
{shortSha}
|
||||||
|
</AnchorButton>
|
||||||
|
) : <span style={{ color: '#8f99a8', fontSize: '0.8rem' }}>—</span>}
|
||||||
|
</td>
|
||||||
|
<td><Tag intent={STATUS_INTENT[build.status] ?? Intent.NONE} minimal round>{build.status}</Tag></td>
|
||||||
|
<td style={{ color: '#8f99a8', fontSize: '0.8rem' }}>{lastRun}</td>
|
||||||
|
<td style={{ color: '#8f99a8', fontSize: '0.8rem', textAlign: 'right' }}>{duration}</td>
|
||||||
|
<td style={{ textAlign: 'right' }}>
|
||||||
|
{build.log.length > 0 && (
|
||||||
|
<Button minimal small icon={open ? 'chevron-up' : 'chevron-down'} onClick={() => setOpen((o) => !o)} text={open ? 'Hide' : 'Log'} />
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<Collapse isOpen={open} keepChildrenMounted>
|
||||||
|
<LogRow lines={build.log} />
|
||||||
|
</Collapse>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Page ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export default function BuildMonitorPage() {
|
export default function BuildMonitorPage() {
|
||||||
const [projects, setProjects] = useState<ProjectDefinition[]>([]);
|
const [projects, setProjects] = useState<ProjectDefinition[]>([]);
|
||||||
@@ -233,6 +183,8 @@ export default function BuildMonitorPage() {
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const giteaBase = (import.meta.env.VITE_GITEA_URL as string | undefined) ?? 'https://opc.clarity.test';
|
||||||
|
|
||||||
const load = async () => {
|
const load = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
@@ -247,9 +199,20 @@ export default function BuildMonitorPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => { (async () => { await load(); })(); }, []);
|
useEffect(() => { load(); }, []);
|
||||||
|
|
||||||
// Find latest build per project — match exactly by relativePath (= build target)
|
// Latest SolutionBuild per solution target (one CI row per repo)
|
||||||
|
const ciBuilds = Object.values(
|
||||||
|
history
|
||||||
|
.filter((b) => b.kind === 'SolutionBuild')
|
||||||
|
.reduce<Record<string, BuildRecord>>((acc, b) => {
|
||||||
|
if (!acc[b.target] || new Date(b.startedAt) > new Date(acc[b.target].startedAt))
|
||||||
|
acc[b.target] = b;
|
||||||
|
return acc;
|
||||||
|
}, {})
|
||||||
|
);
|
||||||
|
|
||||||
|
// Latest manual build per project path
|
||||||
const lastBuildFor = (project: ProjectDefinition): BuildRecord | undefined =>
|
const lastBuildFor = (project: ProjectDefinition): BuildRecord | undefined =>
|
||||||
history.find((b) => b.target === project.relativePath);
|
history.find((b) => b.target === project.relativePath);
|
||||||
|
|
||||||
@@ -258,44 +221,42 @@ export default function BuildMonitorPage() {
|
|||||||
<div className="page-header">
|
<div className="page-header">
|
||||||
<div>
|
<div>
|
||||||
<h1>Build Monitor</h1>
|
<h1>Build Monitor</h1>
|
||||||
<p>Trigger and track builds for every project in the solution.</p>
|
<p>CI gate builds (webhook-triggered) and manual per-project builds.</p>
|
||||||
</div>
|
|
||||||
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
|
|
||||||
<Button icon="refresh" minimal onClick={load} loading={loading} title="Refresh" />
|
|
||||||
<Button
|
|
||||||
icon="play"
|
|
||||||
text="Build All"
|
|
||||||
intent={Intent.WARNING}
|
|
||||||
disabled={loading || projects.length === 0}
|
|
||||||
onClick={async () => {
|
|
||||||
for (const p of projects) {
|
|
||||||
await fetch(`${BASE_URL}/api/builds/${encodeURIComponent(p.name)}`, { method: 'POST' });
|
|
||||||
}
|
|
||||||
load();
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
|
<Button icon="refresh" minimal onClick={load} loading={loading} title="Refresh" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<Callout intent={Intent.DANGER} title="Failed to load projects" style={{ marginBottom: '1rem' }}>
|
<Callout intent={Intent.DANGER} title="Failed to load" style={{ marginBottom: '1rem' }}>{error}</Callout>
|
||||||
{error}
|
|
||||||
</Callout>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{loading && <NonIdealState icon={<Spinner />} title="Loading projects..." />}
|
{loading && <NonIdealState icon={<Spinner />} title="Loading..." />}
|
||||||
|
|
||||||
{!loading && !error && (
|
{!loading && !error && (
|
||||||
<div className="job-list">
|
<HTMLTable className="bp6-html-table-condensed bp6-html-table-striped" style={{ width: '100%' }}>
|
||||||
{projects.map((p) => (
|
<thead>
|
||||||
<ProjectCard
|
<tr>
|
||||||
key={p.name}
|
<th>Name</th>
|
||||||
project={p}
|
<th>Kind</th>
|
||||||
lastBuild={lastBuildFor(p)}
|
<th>Commit / Trigger</th>
|
||||||
onBuilt={load}
|
<th>Status</th>
|
||||||
/>
|
<th>Last Run</th>
|
||||||
))}
|
<th style={{ textAlign: 'right' }}>Duration</th>
|
||||||
</div>
|
<th style={{ textAlign: 'right' }}>Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{ciBuilds.map((b) => (
|
||||||
|
<CiRow key={`ci-${b.target}`} build={b} giteaBase={giteaBase} />
|
||||||
|
))}
|
||||||
|
{projects.map((p) => (
|
||||||
|
<ProjectRow key={p.name} project={p} lastBuild={lastBuildFor(p)} onBuilt={load} />
|
||||||
|
))}
|
||||||
|
{ciBuilds.length === 0 && projects.length === 0 && (
|
||||||
|
<tr><td colSpan={7} style={{ textAlign: 'center', color: '#8f99a8', padding: '2rem' }}>No builds yet.</td></tr>
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</HTMLTable>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { useState, useEffect, useCallback } from 'react';
|
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||||
import { Button, HTMLSelect, InputGroup, Intent, NonIdealState, Spinner, Tag, Tooltip } from '@blueprintjs/core';
|
import { Button, HTMLSelect, InputGroup, Intent, NonIdealState, Spinner, Tag, Tooltip, Tree } from '@blueprintjs/core';
|
||||||
|
import type { TreeNodeInfo } from '@blueprintjs/core';
|
||||||
import { GitCommitDrawer } from '../components/GitCommitDrawer';
|
import { GitCommitDrawer } from '../components/GitCommitDrawer';
|
||||||
import { getChangesets } from '../api/opcApi';
|
import { getChangesets, getBranches } from '../api/opcApi';
|
||||||
import type { LinkedCommit } from '../api/opcApi';
|
import type { LinkedCommit } from '../api/opcApi';
|
||||||
|
|
||||||
const PAGE_SIZE = 25;
|
const PAGE_SIZE = 25;
|
||||||
@@ -19,23 +20,62 @@ const REPO_INTENT: Record<string, Intent> = {
|
|||||||
Gateway: Intent.SUCCESS,
|
Gateway: Intent.SUCCESS,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function ChangesetsPage() {
|
const REPO_COLOR: Record<string, string> = {
|
||||||
const [commits, setCommits] = useState<LinkedCommit[]>([]);
|
Clarity: '#215db0',
|
||||||
const [loading, setLoading] = useState(true);
|
OPC: '#935610',
|
||||||
const [error, setError] = useState<string | null>(null);
|
Gateway: '#1c6e42',
|
||||||
const [page, setPage] = useState(1);
|
};
|
||||||
const [hasMore, setHasMore] = useState(false);
|
|
||||||
const [repoFilter, setRepoFilter] = useState('all');
|
|
||||||
const [grepFilter, setGrepFilter] = useState('');
|
|
||||||
const [grepInput, setGrepInput] = useState('');
|
|
||||||
const [viewingHash, setViewingHash] = useState<string | null>(null);
|
|
||||||
|
|
||||||
const load = useCallback(async (p: number, repo: string, grep: string) => {
|
const SDLC_ORDER = ['develop', 'staging', 'uat', 'main'] as const;
|
||||||
|
|
||||||
|
function getBranchLabel(branches: string[]): string | null {
|
||||||
|
if (branches.length === 0) return null;
|
||||||
|
const sdlc = branches.filter(b => (SDLC_ORDER as readonly string[]).includes(b));
|
||||||
|
if (sdlc.length === 0) return branches[0];
|
||||||
|
const highest = sdlc.reduce((a, b) =>
|
||||||
|
SDLC_ORDER.indexOf(b as typeof SDLC_ORDER[number]) > SDLC_ORDER.indexOf(a as typeof SDLC_ORDER[number]) ? b : a,
|
||||||
|
);
|
||||||
|
const idx = SDLC_ORDER.indexOf(highest as typeof SDLC_ORDER[number]);
|
||||||
|
if (idx > 0) {
|
||||||
|
const prev = SDLC_ORDER[idx - 1];
|
||||||
|
if (branches.includes(prev)) return `${prev} → ${highest}`;
|
||||||
|
}
|
||||||
|
return highest;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ChangesetsPage() {
|
||||||
|
const [commits, setCommits] = useState<LinkedCommit[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [hasMore, setHasMore] = useState(false);
|
||||||
|
const [repoFilter, setRepoFilter] = useState('all');
|
||||||
|
const [grepFilter, setGrepFilter] = useState('');
|
||||||
|
const [grepInput, setGrepInput] = useState('');
|
||||||
|
const [viewingHash, setViewingHash] = useState<string | null>(null);
|
||||||
|
const [branchMap, setBranchMap] = useState<Record<string, string[]>>({});
|
||||||
|
const [selectedBranch, setSelectedBranch] = useState<{ repoKey: string; branch: string } | null>(null);
|
||||||
|
const [expandedRepos, setExpandedRepos] = useState<Set<string>>(new Set());
|
||||||
|
|
||||||
|
// Load branches for the tree once on mount
|
||||||
|
useEffect(() => {
|
||||||
|
getBranches('all')
|
||||||
|
.then(data => {
|
||||||
|
const map: Record<string, string[]> = {};
|
||||||
|
for (const b of data) {
|
||||||
|
if (!map[b.repoKey]) map[b.repoKey] = [];
|
||||||
|
map[b.repoKey].push(b.name);
|
||||||
|
}
|
||||||
|
setBranchMap(map);
|
||||||
|
})
|
||||||
|
.catch(() => { /* branch tree is non-critical */ });
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const load = useCallback(async (p: number, repo: string, grep: string, branch?: string) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
// Fetch one extra to detect whether there's a next page
|
const rows = await getChangesets(p, PAGE_SIZE + 1, repo, grep || undefined, branch);
|
||||||
const rows = await getChangesets(p, PAGE_SIZE + 1, repo, grep || undefined);
|
|
||||||
setHasMore(rows.length > PAGE_SIZE);
|
setHasMore(rows.length > PAGE_SIZE);
|
||||||
setCommits(rows.slice(0, PAGE_SIZE));
|
setCommits(rows.slice(0, PAGE_SIZE));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -47,25 +87,77 @@ export default function ChangesetsPage() {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
load(page, repoFilter, grepFilter);
|
const effectiveRepo = selectedBranch ? selectedBranch.repoKey : repoFilter;
|
||||||
}, [load, page, repoFilter, grepFilter]);
|
const effectiveBranch = selectedBranch?.branch;
|
||||||
|
load(page, effectiveRepo, grepFilter, effectiveBranch);
|
||||||
|
}, [load, page, repoFilter, grepFilter, selectedBranch]);
|
||||||
|
|
||||||
const applySearch = () => {
|
const applySearch = () => { setPage(1); setGrepFilter(grepInput); };
|
||||||
setPage(1);
|
const clearSearch = () => { setGrepInput(''); setGrepFilter(''); setPage(1); };
|
||||||
setGrepFilter(grepInput);
|
|
||||||
};
|
|
||||||
|
|
||||||
const clearSearch = () => {
|
|
||||||
setGrepInput('');
|
|
||||||
setGrepFilter('');
|
|
||||||
setPage(1);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleRepoChange = (repo: string) => {
|
const handleRepoChange = (repo: string) => {
|
||||||
setPage(1);
|
setPage(1);
|
||||||
|
setSelectedBranch(null);
|
||||||
setRepoFilter(repo);
|
setRepoFilter(repo);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const treeNodes = useMemo((): TreeNodeInfo[] => [
|
||||||
|
{
|
||||||
|
id: 'all',
|
||||||
|
label: 'All Branches',
|
||||||
|
icon: 'git-branch',
|
||||||
|
isSelected: selectedBranch === null,
|
||||||
|
},
|
||||||
|
...Object.keys(branchMap).map(repoKey => ({
|
||||||
|
id: `repo|${repoKey}`,
|
||||||
|
label: <span style={{ color: REPO_COLOR[repoKey] ?? 'inherit', fontWeight: 500 }}>{repoKey}</span>,
|
||||||
|
icon: (expandedRepos.has(repoKey) ? 'folder-open' : 'folder-close') as TreeNodeInfo['icon'],
|
||||||
|
isExpanded: expandedRepos.has(repoKey),
|
||||||
|
isSelected: false,
|
||||||
|
childNodes: branchMap[repoKey].map(name => ({
|
||||||
|
id: `branch|${repoKey}|${name}`,
|
||||||
|
label: name,
|
||||||
|
icon: 'git-commit' as TreeNodeInfo['icon'],
|
||||||
|
isSelected: selectedBranch?.repoKey === repoKey && selectedBranch?.branch === name,
|
||||||
|
})),
|
||||||
|
})),
|
||||||
|
], [branchMap, expandedRepos, selectedBranch]);
|
||||||
|
|
||||||
|
const handleNodeClick = (node: TreeNodeInfo) => {
|
||||||
|
const id = String(node.id);
|
||||||
|
if (id === 'all') {
|
||||||
|
setPage(1);
|
||||||
|
setSelectedBranch(null);
|
||||||
|
} else if (id.startsWith('branch|')) {
|
||||||
|
const [, repoKey, ...rest] = id.split('|');
|
||||||
|
setPage(1);
|
||||||
|
setSelectedBranch({ repoKey, branch: rest.join('|') });
|
||||||
|
} else if (id.startsWith('repo|')) {
|
||||||
|
const repoKey = id.slice(5);
|
||||||
|
setExpandedRepos(s => {
|
||||||
|
const next = new Set(s);
|
||||||
|
next.has(repoKey) ? next.delete(repoKey) : next.add(repoKey);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleNodeExpand = (node: TreeNodeInfo) => {
|
||||||
|
const id = String(node.id);
|
||||||
|
if (id.startsWith('repo|')) setExpandedRepos(s => new Set([...s, id.slice(5)]));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleNodeCollapse = (node: TreeNodeInfo) => {
|
||||||
|
const id = String(node.id);
|
||||||
|
if (id.startsWith('repo|')) setExpandedRepos(s => { const n = new Set(s); n.delete(id.slice(5)); return n; });
|
||||||
|
};
|
||||||
|
|
||||||
|
const doRefresh = () => {
|
||||||
|
const effectiveRepo = selectedBranch ? selectedBranch.repoKey : repoFilter;
|
||||||
|
const effectiveBranch = selectedBranch?.branch;
|
||||||
|
load(page, effectiveRepo, grepFilter, effectiveBranch);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div className="page-header">
|
<div className="page-header">
|
||||||
@@ -73,100 +165,132 @@ export default function ChangesetsPage() {
|
|||||||
<h1>Changesets</h1>
|
<h1>Changesets</h1>
|
||||||
<p>Chronological commit timeline across all three repos.</p>
|
<p>Chronological commit timeline across all three repos.</p>
|
||||||
</div>
|
</div>
|
||||||
<Button icon="refresh" minimal onClick={() => load(page, repoFilter, grepFilter)} />
|
<Button icon="refresh" minimal onClick={doRefresh} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Filter bar */}
|
<div className="cs-page-with-tree">
|
||||||
<div className="opc-filter-bar">
|
{/* Branch tree */}
|
||||||
<HTMLSelect
|
<div className="cs-branch-tree">
|
||||||
value={repoFilter}
|
<Tree
|
||||||
onChange={e => handleRepoChange(e.target.value)}
|
contents={treeNodes}
|
||||||
options={REPO_OPTIONS}
|
onNodeClick={handleNodeClick}
|
||||||
/>
|
onNodeExpand={handleNodeExpand}
|
||||||
<InputGroup
|
onNodeCollapse={handleNodeCollapse}
|
||||||
leftIcon="search"
|
/>
|
||||||
placeholder="Filter commits by text or OPC number…"
|
</div>
|
||||||
value={grepInput}
|
|
||||||
onChange={e => setGrepInput(e.target.value)}
|
|
||||||
onKeyDown={e => { if (e.key === 'Enter') applySearch(); }}
|
|
||||||
style={{ width: 320 }}
|
|
||||||
rightElement={
|
|
||||||
<Button minimal icon="arrow-right" intent={Intent.PRIMARY}
|
|
||||||
disabled={!grepInput.trim()} onClick={applySearch} />
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
{grepFilter && (
|
|
||||||
<Button minimal small icon="cross" text="Clear" onClick={clearSearch} />
|
|
||||||
)}
|
|
||||||
<span className="opc-count-badge">{loading ? '…' : `${commits.length} shown`}</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Content */}
|
{/* Main content */}
|
||||||
{loading ? (
|
<div className="cs-content-area">
|
||||||
<NonIdealState icon={<Spinner />} title="Loading changesets…" />
|
{/* Filter bar */}
|
||||||
) : error ? (
|
<div className="opc-filter-bar">
|
||||||
<NonIdealState icon="warning-sign" title="Could not load commits"
|
<HTMLSelect
|
||||||
description={error} intent={Intent.DANGER} />
|
value={repoFilter}
|
||||||
) : commits.length === 0 ? (
|
onChange={e => handleRepoChange(e.target.value)}
|
||||||
<NonIdealState icon="git-commit" title="No commits found"
|
options={REPO_OPTIONS}
|
||||||
description="Try changing the repo filter or clearing the search." />
|
disabled={!!selectedBranch}
|
||||||
) : (
|
/>
|
||||||
<div className="cs-timeline">
|
<InputGroup
|
||||||
{commits.map(c => (
|
leftIcon="search"
|
||||||
<div
|
placeholder="Filter commits by text or OPC number…"
|
||||||
key={`${c.repoKey}-${c.hash}`}
|
value={grepInput}
|
||||||
className="cs-row"
|
onChange={e => setGrepInput(e.target.value)}
|
||||||
onClick={() => setViewingHash(c.hash)}
|
onKeyDown={e => { if (e.key === 'Enter') applySearch(); }}
|
||||||
>
|
style={{ width: 320 }}
|
||||||
<div className="cs-row-left">
|
rightElement={
|
||||||
<Tag
|
<Button minimal icon="arrow-right" intent={Intent.PRIMARY}
|
||||||
intent={REPO_INTENT[c.repoKey] ?? Intent.NONE}
|
disabled={!grepInput.trim()} onClick={applySearch} />
|
||||||
minimal round
|
}
|
||||||
className="cs-repo-badge"
|
/>
|
||||||
>
|
{grepFilter && (
|
||||||
{c.repoKey || '?'}
|
<Button minimal small icon="cross" text="Clear" onClick={clearSearch} />
|
||||||
</Tag>
|
)}
|
||||||
</div>
|
{selectedBranch && (
|
||||||
|
<Tag
|
||||||
|
minimal
|
||||||
|
intent={REPO_INTENT[selectedBranch.repoKey] ?? Intent.NONE}
|
||||||
|
icon="git-branch"
|
||||||
|
onRemove={() => { setPage(1); setSelectedBranch(null); }}
|
||||||
|
>
|
||||||
|
{selectedBranch.repoKey} / {selectedBranch.branch}
|
||||||
|
</Tag>
|
||||||
|
)}
|
||||||
|
<span className="opc-count-badge">{loading ? '…' : `${commits.length} shown`}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="cs-row-body">
|
{/* Content */}
|
||||||
<div className="cs-row-top">
|
{loading ? (
|
||||||
<Tooltip content="View diff" placement="top">
|
<NonIdealState icon={<Spinner />} title="Loading changesets…" />
|
||||||
<code className="opc-commit-hash">{c.shortHash}</code>
|
) : error ? (
|
||||||
</Tooltip>
|
<NonIdealState icon="warning-sign" title="Could not load commits"
|
||||||
<span className="cs-subject">{c.subject}</span>
|
description={error} />
|
||||||
</div>
|
) : commits.length === 0 ? (
|
||||||
<div className="cs-row-meta">
|
<NonIdealState icon="git-commit" title="No commits found"
|
||||||
{c.author} · {c.date}
|
description="Try changing the repo filter or clearing the search." />
|
||||||
{c.files.length > 0 && (
|
) : (
|
||||||
<span className="cs-file-count"> · {c.files.length} file{c.files.length !== 1 ? 's' : ''}</span>
|
<div className="cs-timeline">
|
||||||
)}
|
{commits.map(c => {
|
||||||
</div>
|
const branchLabel = getBranchLabel(c.branches ?? []);
|
||||||
</div>
|
return (
|
||||||
|
<div
|
||||||
|
key={`${c.repoKey}-${c.hash}`}
|
||||||
|
className="cs-row"
|
||||||
|
onClick={() => setViewingHash(c.hash)}
|
||||||
|
>
|
||||||
|
<div className="cs-row-left">
|
||||||
|
<Tag
|
||||||
|
intent={REPO_INTENT[c.repoKey] ?? Intent.NONE}
|
||||||
|
minimal round
|
||||||
|
className="cs-repo-badge"
|
||||||
|
>
|
||||||
|
{c.repoKey || '?'}
|
||||||
|
</Tag>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="cs-row-body">
|
||||||
|
<div className="cs-row-top">
|
||||||
|
<Tooltip content="View diff" placement="top">
|
||||||
|
<code className="opc-commit-hash">{c.shortHash}</code>
|
||||||
|
</Tooltip>
|
||||||
|
<span className="cs-subject">{c.subject}</span>
|
||||||
|
</div>
|
||||||
|
<div className="cs-row-meta">
|
||||||
|
{c.author} · {c.date}
|
||||||
|
{c.files.length > 0 && (
|
||||||
|
<span className="cs-file-count"> · {c.files.length} file{c.files.length !== 1 ? 's' : ''}</span>
|
||||||
|
)}
|
||||||
|
{branchLabel && (
|
||||||
|
<Tag minimal className="cs-branch-badge">{branchLabel}</Tag>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
))}
|
)}
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Pagination */}
|
{/* Pagination */}
|
||||||
{!loading && !error && (commits.length > 0 || page > 1) && (
|
{!loading && !error && (commits.length > 0 || page > 1) && (
|
||||||
<div className="cs-pagination">
|
<div className="cs-pagination">
|
||||||
<Button
|
<Button
|
||||||
icon="arrow-left"
|
icon="arrow-left"
|
||||||
minimal
|
minimal
|
||||||
text="Previous"
|
text="Previous"
|
||||||
disabled={page <= 1}
|
disabled={page <= 1}
|
||||||
onClick={() => setPage(p => p - 1)}
|
onClick={() => setPage(p => p - 1)}
|
||||||
/>
|
/>
|
||||||
<span className="cs-page-label">Page {page}</span>
|
<span className="cs-page-label">Page {page}</span>
|
||||||
<Button
|
<Button
|
||||||
rightIcon="arrow-right"
|
rightIcon="arrow-right"
|
||||||
minimal
|
minimal
|
||||||
text="Next"
|
text="Next"
|
||||||
disabled={!hasMore}
|
disabled={!hasMore}
|
||||||
onClick={() => setPage(p => p + 1)}
|
onClick={() => setPage(p => p + 1)}
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
</div>
|
||||||
|
|
||||||
<GitCommitDrawer hash={viewingHash} onClose={() => setViewingHash(null)} />
|
<GitCommitDrawer hash={viewingHash} onClose={() => setViewingHash(null)} />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -43,6 +43,15 @@ function TenantCard({ t }: { t: TenantRecord }) {
|
|||||||
<div style={{ display: 'flex', gap: '0.4rem', alignItems: 'center' }}>
|
<div style={{ display: 'flex', gap: '0.4rem', alignItems: 'center' }}>
|
||||||
<Tag intent={ENV_INTENT[t.environment] ?? Intent.NONE} round minimal>{t.environment}</Tag>
|
<Tag intent={ENV_INTENT[t.environment] ?? Intent.NONE} round minimal>{t.environment}</Tag>
|
||||||
<Tag intent={t.status === 'Provisioned' ? Intent.SUCCESS : Intent.WARNING} round>{t.status}</Tag>
|
<Tag intent={t.status === 'Provisioned' ? Intent.SUCCESS : Intent.WARNING} round>{t.status}</Tag>
|
||||||
|
{t.containerImage && (() => {
|
||||||
|
const sha = t.containerImage.includes(':') ? t.containerImage.split(':').pop()! : t.containerImage;
|
||||||
|
return (
|
||||||
|
<Tag minimal round style={{ fontFamily: 'monospace', fontSize: '0.7rem', color: '#8f99a8' }}
|
||||||
|
title={t.containerImage}>
|
||||||
|
{sha.slice(0, 7)}
|
||||||
|
</Tag>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -177,6 +177,7 @@ services:
|
|||||||
GITEA__server__SSH_DOMAIN: opc.clarity.test
|
GITEA__server__SSH_DOMAIN: opc.clarity.test
|
||||||
GITEA__server__SSH_PORT: "2222"
|
GITEA__server__SSH_PORT: "2222"
|
||||||
GITEA__service__DISABLE_REGISTRATION: "true"
|
GITEA__service__DISABLE_REGISTRATION: "true"
|
||||||
|
GITEA__webhook__ALLOWED_HOST_LIST: "host.docker.internal,loopback,private"
|
||||||
volumes:
|
volumes:
|
||||||
- clarity-gitea-data:/data
|
- clarity-gitea-data:/data
|
||||||
depends_on:
|
depends_on:
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# OPC # 0004: One-time migration — make postgres-data and minio-data external volumes
|
||||||
|
# Run this ONCE before doing `docker compose up -d` with the updated docker-compose.yml.
|
||||||
|
# Safe to run while containers are stopped. Do NOT run while containers are running.
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# cd OPC/scripts
|
||||||
|
# .\create-external-volumes.ps1
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
function Migrate-Volume($composeName, $externalName) {
|
||||||
|
Write-Host "`nMigrating: $composeName -> $externalName" -ForegroundColor Cyan
|
||||||
|
|
||||||
|
$existing = docker volume ls --format "{{.Name}}" | Where-Object { $_ -eq $externalName }
|
||||||
|
if ($existing) {
|
||||||
|
Write-Host " Volume '$externalName' already exists — skipping copy." -ForegroundColor Yellow
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check source exists
|
||||||
|
$source = docker volume ls --format "{{.Name}}" | Where-Object { $_ -eq $composeName }
|
||||||
|
if (-not $source) {
|
||||||
|
Write-Host " Source volume '$composeName' not found — creating empty external volume." -ForegroundColor Yellow
|
||||||
|
docker volume create $externalName | Out-Null
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
# Create external volume
|
||||||
|
docker volume create $externalName | Out-Null
|
||||||
|
Write-Host " Created '$externalName'"
|
||||||
|
|
||||||
|
# Copy data using a temporary alpine container
|
||||||
|
docker run --rm `
|
||||||
|
-v "${composeName}:/from" `
|
||||||
|
-v "${externalName}:/to" `
|
||||||
|
alpine sh -c "cd /from && cp -a . /to"
|
||||||
|
Write-Host " Data copied." -ForegroundColor Green
|
||||||
|
}
|
||||||
|
|
||||||
|
# The compose project name prefixes anonymous volumes as "clarity-platform_<name>"
|
||||||
|
Migrate-Volume "clarity-platform_postgres-data" "postgres-data"
|
||||||
|
Migrate-Volume "clarity-platform_minio-data" "minio-data"
|
||||||
|
|
||||||
|
Write-Host "`nDone. You can now run: docker compose up -d" -ForegroundColor Green
|
||||||
|
Write-Host "The old 'clarity-platform_postgres-data' and 'clarity-platform_minio-data' volumes can be removed with 'docker volume rm' once you've verified everything is working."
|
||||||
Reference in New Issue
Block a user