refactor: web hook

This commit is contained in:
h z
2025-03-13 11:00:11 +00:00
parent 2715909a41
commit 9f55972e60
13 changed files with 265 additions and 67 deletions

View File

@@ -12,15 +12,12 @@
<Content Include="..\.dockerignore"> <Content Include="..\.dockerignore">
<Link>.dockerignore</Link> <Link>.dockerignore</Link>
</Content> </Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="RabbitMQ.Client" Version="7.1.1" /> <PackageReference Include="RabbitMQ.Client" Version="7.1.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Alchegos.Core\Alchegos.Core.csproj" /> <ProjectReference Include="..\Alchegos.Core\Alchegos.Core.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="EventHandlerDispatchers\" />
</ItemGroup>
</Project> </Project>

View File

@@ -0,0 +1,6 @@
namespace Alchegos.Gitea.Webhook;
public class AlchegosEventDispatcher
{
}

25
GiteaEventDispatcher.cs Normal file
View File

@@ -0,0 +1,25 @@
using System.Text.Json.Nodes;
using Alchegos.Core.Services.RabbitMQ;
using Alchegos.Gitea.Webhook.Handlers;
namespace Alchegos.Gitea.Webhook;
public class GiteaEventDispatcher
{
private Dictionary<string, IGiteaEventHandler> Handlers { get; set; } = new (StringComparer.OrdinalIgnoreCase)
{
{"push", new PushEventHandler()},
{"issues", new IssuesEventHandler()},
{"issue_comment", new IssueCommentEventHandler()},
{"pull_request", new PullRequestEventHandler()}
};
public async Task DispatchAsync(string eventType, JsonNode payload, IRabbitPublisher publisher)
{
if (Handlers.TryGetValue(eventType, out var handler))
{
await handler.HandleAsync(payload, publisher);
}
}
}

View File

@@ -0,0 +1,6 @@
namespace Alchegos.Gitea.Webhook.Handlers;
public interface IAlchegosEventHandler : IWebhookEventHandler
{
}

View File

@@ -0,0 +1,6 @@
namespace Alchegos.Gitea.Webhook.Handlers;
public interface IGiteaEventHandler: IWebhookEventHandler
{
}

View File

@@ -0,0 +1,9 @@
using System.Text.Json.Nodes;
using Alchegos.Core.Services.RabbitMQ;
namespace Alchegos.Gitea.Webhook.Handlers;
public interface IWebhookEventHandler
{
Task HandleAsync(JsonNode payload, IRabbitPublisher publisher);
}

View File

@@ -0,0 +1,24 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Alchegos.Core.Services.RabbitMQ;
namespace Alchegos.Gitea.Webhook.Handlers;
public class IssueCommentEventHandler : IGiteaEventHandler
{
public async Task HandleAsync(JsonNode payload, IRabbitPublisher publisher)
{
if (payload["action"]?.ToString() != "created")
return;
var message = new Dictionary<string, string>
{
{"repo_url", payload["repository"]?["url"]?.ToString()},
{"repo_owner", payload["repository"]?["owner"]?["login"]?.ToString()},
{"repo_name", payload["repository"]?["name"]?.ToString()},
{"issue_id", payload["issue"]?["id"]?.ToString()},
{"comment_id", payload["comment"]?["id"]?.ToString()},
};
await publisher.PublishAsync("alchegos", "issue_commented", JsonSerializer.Serialize(message));
}
}

View File

@@ -0,0 +1,50 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Alchegos.Core.Services.RabbitMQ;
namespace Alchegos.Gitea.Webhook.Handlers;
public class IssuesEventHandler : IGiteaEventHandler
{
public async Task HandleAsync(JsonNode payload, IRabbitPublisher publisher)
{
string action = payload["action"]?.ToString() ?? "";
string repo_url = payload["repository"]?["url"]?.ToString();
string repo_owner = payload["repository"]?["owner"]?["login"]?.ToString();
string repo_name = payload["repository"]?["name"]?.ToString();
string issue_url = payload["issue"]?["url"]?.ToString();
string issue_id = payload["issue"]?["id"]?.ToString();
var labels = payload["issue"]?["labels"]?.AsArray() ?? new JsonArray();
var routingKeys = new Dictionary<string, string>
{
{"status/ready", "ready_to_develop"},
{"status/completed", "task_completed"}
};
if (action is "opened" or "label_updated")
{
foreach (var label in labels)
{
string labelName = label["name"]?.ToString().Trim() ?? label.ToString().Trim();
if (routingKeys.TryGetValue(labelName, out string routingKey))
{
var message = new Dictionary<string, string>
{
{ "repo_url", repo_url },
{ "repo_owner", repo_owner },
{ "repo_name", repo_name },
{ "issue_url", issue_url },
{ "issue_id", issue_id },
};
await publisher.PublishAsync(
exchange: "alchegos",
routingKey: routingKey,
message: JsonSerializer.Serialize(message));
break;
}
}
}
}
}

View File

@@ -0,0 +1,32 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Alchegos.Core.Services.RabbitMQ;
namespace Alchegos.Gitea.Webhook.Handlers;
public class ProjectPlanEventHandler : IGiteaEventHandler
{
public async Task HandleAsync(JsonNode payload, IRabbitPublisher publisher)
{
string projectName = payload["title"]?.ToString();
string action = payload["action"]?.ToString();
string plan = payload["content"]?.ToString();
Dictionary<string, string> routingKeys = new Dictionary<string, string>
{
{"create", "new_project_plan_created"},
{"update", "project_plan_updated"},
};
Dictionary<string, string> message = new()
{
{ "project_name", projectName },
{ "project_plan", plan }
};
await publisher.PublishAsync(
exchange: "alchegos",
routingKey: routingKeys.GetValueOrDefault(action, ""),
message: JsonSerializer.Serialize(message)
);
}
}

View File

@@ -0,0 +1,49 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Alchegos.Core.Services.RabbitMQ;
namespace Alchegos.Gitea.Webhook.Handlers;
public class PullRequestEventHandler : IGiteaEventHandler
{
public async Task HandleAsync(JsonNode payload, IRabbitPublisher publisher)
{
string action = payload["action"]?.ToString() ?? "";
string repo_url = payload["repository"]?["url"]?.ToString();
string repo_owner = payload["repository"]?["owner"]?["login"]?.ToString();
string repo_name = payload["repository"]?["name"]?.ToString();
string branch = payload["pull_request"]?["head"]?["ref"]?.ToString();
JsonArray labels = payload["pull_request"]?["labels"]?.AsArray() ?? new JsonArray();
Dictionary<string, string> routingKeys = new Dictionary<string, string>
{
{"status/pending_review", "pull_request_pending_review"},
{"status/pending_test", "pull_request_pending_test"}
};
if (action is "opened" or "label_updated")
{
foreach (JsonNode label in labels)
{
string labelName = label["name"]?.ToString().Trim() ?? label.ToString().Trim();
if (routingKeys.TryGetValue(labelName, out string routingKey))
{
Dictionary<string, string> message = new Dictionary<string, string>
{
{"repo_url", repo_url},
{"repo_owner", repo_owner},
{"repo_name", repo_name},
{"branch", branch}
};
await publisher.PublishAsync(
exchange: "alchegos",
routingKey: routingKey,
message: JsonSerializer.Serialize(message)
);
break;
}
}
}
}
}

View File

@@ -0,0 +1,34 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Alchegos.Core.Services.RabbitMQ;
namespace Alchegos.Gitea.Webhook.Handlers;
public class PushEventHandler : IGiteaEventHandler
{
public async Task HandleAsync(JsonNode payload, IRabbitPublisher publisher)
{
string branch = payload["ref"]?.ToString()?.Replace("refs/heads/", "") ?? "";
if (branch == "main")
return;
JsonArray commits = payload["commits"]?.AsArray() ?? new JsonArray();
foreach (var commit in commits)
{
if (commit["message"]?.ToString()?.Trim() == "init")
{
Dictionary<string, string> message = new Dictionary<string, string>
{
{"repo_url", payload["repository"]?["url"]?.ToString()},
{"repo_owner", payload["repository"]?["owner"]?["login"]?.ToString()},
{"repo_name", payload["repository"]?["name"]?.ToString()}
};
await publisher.PublishAsync(
exchange: "alchegos",
routingKey:"project_initialized",
message: JsonSerializer.Serialize(message));
break;
}
}
}
}

View File

@@ -1,39 +0,0 @@
namespace Alchegos.Gitea.Webhook.Models;
using System.Text.Json.Serialization;
public class GiteaWebhookPayload
{
[JsonPropertyName("repository")]
public Repository? Repository { get; set; }
[JsonPropertyName("pusher")]
public User? Pusher { get; set; }
[JsonPropertyName("commits")]
public List<CommitInfo>? Commits { get; set; }
[JsonPropertyName("head_commit")]
public CommitInfo? HeadCommit { get; set; }
}
public class Repository
{
[JsonPropertyName("name")]
public string? Name { get; set; }
}
public class User
{
[JsonPropertyName("username")]
public string? UserName { get; set; }
}
public class CommitInfo
{
[JsonPropertyName("id")]
public string? Id { get; set; }
[JsonPropertyName("message")]
public string? Message { get; set; }
}

View File

@@ -1,9 +1,11 @@
using System.Text.Json.Nodes;
using Alchegos.Core; using Alchegos.Core;
using Alchegos.Core.Services.RabbitMQ; using Alchegos.Core.Services.RabbitMQ;
using Alchegos.Gitea.Webhook;
GlobalRegistry.Instance.Start(); GlobalRegistry.Instance.Start();
var builder = WebApplication.CreateBuilder(args); WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders(); builder.Logging.ClearProviders();
builder.Logging.AddConsole(); builder.Logging.AddConsole();
builder.Services.Configure<RabbitConnectionOptions>( builder.Services.Configure<RabbitConnectionOptions>(
@@ -14,26 +16,23 @@ builder.Services.AddSingleton<IRabbitService, RabbitService>();
builder.Services.AddSingleton<IRabbitPublisher, RabbitPublisher>(); builder.Services.AddSingleton<IRabbitPublisher, RabbitPublisher>();
builder.Services.AddSingleton<IRabbitPublisher, RabbitPublisher>(); builder.Services.AddSingleton<IRabbitPublisher, RabbitPublisher>();
var app = builder.Build(); builder.Services.AddSingleton<GiteaEventDispatcher>();
var logger = app.Services.GetRequiredService<ILogger<Program>>(); WebApplication app = builder.Build();
ILogger<Program> logger = app.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Starting web hook /webhook/gitea"); logger.LogInformation("Starting web hook /webhook/gitea");
app.MapPost("/webhook/gitea", async (HttpRequest request, HttpResponse response, IRabbitPublisher publisher) => app.MapPost("/webhook/gitea",
async (
HttpRequest request,
HttpResponse response,
IRabbitPublisher publisher,
GiteaEventDispatcher dispatcher
) =>
{ {
logger.LogInformation("Received gitea webhook request"); string jsonBody = await new StreamReader(request.Body).ReadToEndAsync();
using var reader = new StreamReader(request.Body); string giteaEvent = request.Headers["X-Gitea-Event"].ToString() ?? "unknown";
var jsonBody = await reader.ReadToEndAsync(); JsonNode payload = JsonNode.Parse(jsonBody);
if(payload is not null)
var giteaEvent = request.Headers["X-Gitea-Event"].ToString() ?? "unknown"; await dispatcher.DispatchAsync(giteaEvent, payload, publisher);
return Results.Ok();
logger.LogInformation($"Received gitea webhook post: {giteaEvent}");
logger.LogInformation($" {jsonBody}");
await publisher.PublishAsync(
exchange: "gitea.webhook.exchange",
routingKey: giteaEvent,
message: jsonBody
);
response.StatusCode = 200;
await response.WriteAsync(jsonBody);
}); });
app.Run(); app.Run();