Compare commits

..

8 Commits

Author SHA1 Message Date
Toutsu 492d47a863 fix(discord): add wget to Dockerfile for healthcheck
PR Checks / test-and-build (pull_request) Successful in 7m30s
Issue #32
2026-05-21 14:40:45 +03:00
Toutsu fe8d5fe026 test(discord): update version assertions to 2.7.1
PR Checks / test-and-build (pull_request) Successful in 7m7s
Issue #32
2026-05-21 14:26:02 +03:00
Toutsu a2fa9aaa6c chore(release): bump version to 2.7.1
Issue #32
2026-05-21 14:24:17 +03:00
Toutsu 5b65ac4a2f chore(discord): add healthcheck to compose.yaml discord service
Issue #32
2026-05-21 14:21:35 +03:00
Toutsu feb3e08b63 feat(discord): register health check hosted service in Program.cs
Issue #32
2026-05-21 14:20:40 +03:00
Toutsu f1d8f56fec feat(discord): add health check hosted service
Issue #32
2026-05-21 14:19:50 +03:00
Toutsu 08ffc6694e chore(discord): add DISCORD_BOT_TOKEN to .env.example
Issue #32
2026-05-21 14:19:02 +03:00
Toutsu 3199c48fcd Merge pull request #88: feat(platform): route scheduler notifications through platform messenger
Deploy Telegram Bot / build-and-push (push) Successful in 6m18s
Deploy Telegram Bot / scan-images (push) Successful in 1m44s
Deploy Telegram Bot / deploy (push) Successful in 16s
2026-05-21 12:40:22 +03:00
11 changed files with 217 additions and 13 deletions
+4
View File
@@ -10,6 +10,10 @@ TELEGRAM_BOT_USERNAME=YOUR_BOT_USERNAME_HERE
# Используется ботом для кнопки меню Telegram и кнопки /start.
TELEGRAM_MINI_APP_URL=
# Токен Discord application bot
# Можно получить в Discord Developer Portal (https://discord.com/developers/applications)
DISCORD_BOT_TOKEN=YOUR_DISCORD_BOT_TOKEN_HERE
# Пароль для базы данных PostgreSQL
POSTGRES_PASSWORD=StrongPasswordForDatabase
+1 -1
View File
@@ -6,7 +6,7 @@ on:
- main
env:
VERSION: 2.7.0
VERSION: 2.7.1
jobs:
# ЧАСТЬ 1: Собираем образы и кладем в Gitea (чтобы делиться с ребятами)
+1 -1
View File
@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<Version>2.7.0</Version>
<Version>2.7.1</Version>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>preview</LangVersion>
<Nullable>enable</Nullable>
+8 -3
View File
@@ -49,7 +49,7 @@ services:
crond -f
bot:
image: git.codeanddice.ru/toutsu/gmrelay-bot:2.7.0
image: git.codeanddice.ru/toutsu/gmrelay-bot:2.7.1
restart: always
depends_on:
db:
@@ -67,7 +67,7 @@ services:
retries: 3
discord:
image: git.codeanddice.ru/toutsu/gmrelay-discord-bot:2.7.0
image: git.codeanddice.ru/toutsu/gmrelay-discord-bot:2.7.1
restart: always
depends_on:
db:
@@ -77,9 +77,14 @@ services:
- "Discord__Token=${DISCORD_BOT_TOKEN:?Set DISCORD_BOT_TOKEN in .env}"
networks:
- gmrelay
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://localhost:8082/health || exit 1"]
interval: 10s
timeout: 5s
retries: 3
web:
image: git.codeanddice.ru/toutsu/gmrelay-web:2.7.0
image: git.codeanddice.ru/toutsu/gmrelay-web:2.7.1
restart: always
depends_on:
db:
+5
View File
@@ -15,6 +15,11 @@ RUN dotnet publish "GmRelay.DiscordBot.csproj" -c Release -o /app/publish /p:Use
# Stage 2: Runtime
FROM mcr.microsoft.com/dotnet/runtime:10.0-noble AS final
WORKDIR /app
# Install wget for healthcheck
RUN apt-get update && apt-get install -y --no-install-recommends wget \
&& rm -rf /var/lib/apt/lists/*
COPY --from=build /app/publish .
USER $APP_UID
ENTRYPOINT ["dotnet", "GmRelay.DiscordBot.dll"]
@@ -0,0 +1,101 @@
using System.Net;
namespace GmRelay.DiscordBot.Infrastructure.Health;
public sealed class DiscordHealthCheckHostedService : IHostedService
{
private readonly ILogger<DiscordHealthCheckHostedService> _logger;
private readonly string _prefix;
private HttpListener? _listener;
private CancellationTokenSource? _cts;
private Task? _listenerTask;
public DiscordHealthCheckHostedService(
ILogger<DiscordHealthCheckHostedService> logger,
IConfiguration configuration)
{
_logger = logger;
_prefix = configuration.GetValue("HealthCheck:Prefix", "http://+:8082/")!;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_cts = new CancellationTokenSource();
_listener = new HttpListener();
_listener.Prefixes.Add(_prefix);
_listener.Start();
_logger.LogInformation("Discord health check server started on {Prefix}", _prefix);
_listenerTask = Task.Run(async () => await ListenAsync(_cts.Token), cancellationToken);
return Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
_cts?.Cancel();
_listener?.Stop();
if (_listenerTask != null)
{
await Task.WhenAny(_listenerTask, Task.Delay(TimeSpan.FromSeconds(5), cancellationToken));
}
_listener?.Close();
_logger.LogInformation("Discord health check server stopped");
}
private async Task ListenAsync(CancellationToken cancellationToken)
{
while (_listener?.IsListening == true && !cancellationToken.IsCancellationRequested)
{
try
{
var context = await _listener.GetContextAsync();
_ = Task.Run(() => HandleRequestAsync(context), cancellationToken);
}
catch (HttpListenerException) when (cancellationToken.IsCancellationRequested)
{
break;
}
catch (ObjectDisposedException)
{
break;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in Discord health check listener");
}
}
}
private async Task HandleRequestAsync(HttpListenerContext context)
{
var response = context.Response;
try
{
var request = context.Request;
if (request.Url?.AbsolutePath == "/health")
{
response.StatusCode = (int)HttpStatusCode.OK;
response.ContentType = "application/json";
var body = "{\"status\":\"healthy\"}"u8.ToArray();
await response.OutputStream.WriteAsync(body);
}
else
{
response.StatusCode = (int)HttpStatusCode.NotFound;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error handling Discord health check request");
}
finally
{
response.Close();
}
}
}
+2
View File
@@ -2,6 +2,7 @@ using GmRelay.DiscordBot;
using GmRelay.DiscordBot.Features.Sessions;
using GmRelay.DiscordBot.Infrastructure;
using GmRelay.DiscordBot.Infrastructure.Discord;
using GmRelay.DiscordBot.Infrastructure.Health;
using GmRelay.DiscordBot.Infrastructure.Logging;
using GmRelay.Shared.Features.Confirmation.HandleRsvp;
using GmRelay.Shared.Features.Confirmation.SendConfirmation;
@@ -73,6 +74,7 @@ builder.Services.AddSingleton<HandleRsvpHandler>();
builder.Services.AddSingleton<RescheduleVotingFinalizer>();
builder.Services.AddHostedService<SessionSchedulerService>();
builder.Services.AddHostedService<DiscordRescheduleVotingDeadlineService>();
builder.Services.AddHostedService<DiscordHealthCheckHostedService>();
builder.Services
.AddDiscordGateway(options =>
@@ -56,7 +56,7 @@
</button>
</form>
<div class="nav-version">v2.7.0</div>
<div class="nav-version">v2.7.1</div>
</div>
</Authorized>
<NotAuthorized>
@@ -61,7 +61,7 @@ public sealed class DiscordProjectStructureTests
var prChecks = File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "pr-checks.yml"));
var deploy = File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "deploy.yml"));
Assert.Contains("gmrelay-discord-bot:2.7.0", compose);
Assert.Contains("gmrelay-discord-bot:2.7.1", compose);
Assert.Contains("Discord__Token=${DISCORD_BOT_TOKEN:?Set DISCORD_BOT_TOKEN in .env}", compose);
Assert.Contains("src/GmRelay.DiscordBot/Dockerfile", deploy);
Assert.Contains("DISCORD_BOT_TOKEN", deploy);
@@ -75,13 +75,39 @@ public sealed class DiscordProjectStructureTests
{
var repoRoot = GetRepoRoot();
Assert.Contains("<Version>2.7.0</Version>", File.ReadAllText(Path.Combine(repoRoot, "Directory.Build.props")));
Assert.Contains("VERSION: 2.7.0", File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "deploy.yml")));
Assert.Contains("gmrelay-bot:2.7.0", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
Assert.Contains("gmrelay-web:2.7.0", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
Assert.Contains("gmrelay-discord-bot:2.7.0", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
Assert.Contains("<Version>2.7.1</Version>", File.ReadAllText(Path.Combine(repoRoot, "Directory.Build.props")));
Assert.Contains("VERSION: 2.7.1", File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "deploy.yml")));
Assert.Contains("gmrelay-bot:2.7.1", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
Assert.Contains("gmrelay-web:2.7.1", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
Assert.Contains("gmrelay-discord-bot:2.7.1", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
Assert.Contains(
"v2.7.0",
"v2.7.1",
File.ReadAllText(Path.Combine(repoRoot, "src", "GmRelay.Web", "Components", "Layout", "NavMenu.razor")));
}
[Fact]
public void EnvExample_ShouldContainDiscordBotToken()
{
var repoRoot = GetRepoRoot();
var envExample = File.ReadAllText(Path.Combine(repoRoot, ".env.example"));
Assert.Contains("DISCORD_BOT_TOKEN", envExample);
}
[Fact]
public void Compose_ShouldIncludeDiscordHealthcheck()
{
var repoRoot = GetRepoRoot();
var compose = File.ReadAllText(Path.Combine(repoRoot, "compose.yaml"));
var discordIndex = compose.IndexOf("discord:", StringComparison.Ordinal);
Assert.True(discordIndex >= 0, "compose.yaml should contain discord service");
var nextServiceIndex = compose.IndexOf(" web:", StringComparison.Ordinal);
var discordBlock = compose[discordIndex..nextServiceIndex];
Assert.Contains("healthcheck:", discordBlock);
Assert.Contains("test:", discordBlock);
Assert.Contains("localhost:8082/health", discordBlock);
}
}
@@ -87,6 +87,14 @@ public sealed class DiscordStartupTests
Assert.Contains("HandleRsvpHandler", program);
}
[Fact]
public void Program_ShouldRegisterDiscordHealthCheckHostedService()
{
var program = ReadProgram();
Assert.Contains("DiscordHealthCheckHostedService", program);
Assert.Contains("AddHostedService<DiscordHealthCheckHostedService>", program);
}
private static string ReadProgram()
{
var repoRoot = GetRepoRoot();
@@ -0,0 +1,53 @@
using System.Net;
using System.Net.Sockets;
using GmRelay.DiscordBot.Infrastructure.Health;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging.Abstractions;
namespace GmRelay.Bot.Tests.Infrastructure.Health;
public sealed class DiscordHealthCheckHostedServiceTests : IDisposable
{
private readonly DiscordHealthCheckHostedService _service;
private readonly int _port;
public DiscordHealthCheckHostedServiceTests()
{
_port = GetAvailablePort();
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["HealthCheck:Prefix"] = $"http://localhost:{_port}/"
})
.Build();
_service = new DiscordHealthCheckHostedService(
NullLogger<DiscordHealthCheckHostedService>.Instance,
config);
}
public void Dispose()
{
_service.StopAsync(CancellationToken.None).Wait(TimeSpan.FromSeconds(5));
}
[Fact]
public async Task HealthEndpoint_ShouldReturn200_WhenServiceIsRunning()
{
await _service.StartAsync(CancellationToken.None);
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
var response = await client.GetAsync($"http://localhost:{_port}/health");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
private static int GetAvailablePort()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
}