Add global/lobby auto-join and match chat lifecycle

This commit is contained in:
dingo
2026-03-05 21:30:43 -05:00
parent cd43880a9a
commit 2cfcaf6853
11 changed files with 332 additions and 9 deletions
@@ -0,0 +1,155 @@
namespace SOR.Chat;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Chat;
using SOR.Database.Enums;
internal static class ChatChannelMembership
{
public static async Task EnsureDefaultMembershipsAsync(
ChatDbContext chatDb,
Guid accountId,
CancellationToken ct)
{
var now = DateTimeOffset.UtcNow;
var global = await GetOrCreateSingletonChannelAsync(chatDb, ChatChannelType.Global, "global", now, ct);
await EnsureMemberAsync(chatDb, global.Id, accountId, now, ct);
var lobby = await GetOrCreateSingletonChannelAsync(chatDb, ChatChannelType.Lobby, "lobby", now, ct);
await EnsureMemberAsync(chatDb, lobby.Id, accountId, now, ct);
}
public static async Task EnsureMatchMembershipsAsync(
ChatDbContext chatDb,
Guid matchId,
IReadOnlyCollection<Guid> accountIds,
CancellationToken ct)
{
if (accountIds.Count == 0)
return;
var now = DateTimeOffset.UtcNow;
var channel = await GetOrCreateMatchChannelAsync(chatDb, matchId, now, ct);
foreach (var accountId in accountIds.Distinct())
await EnsureMemberAsync(chatDb, channel.Id, accountId, now, ct);
}
public static async Task EndMatchMembershipsAsync(
ChatDbContext chatDb,
Guid matchId,
CancellationToken ct)
{
var matchKey = matchId.ToString("D");
var channel = await chatDb.Channels
.Where(c => c.ChannelType == ChatChannelType.Match && c.MatchId == matchKey)
.OrderBy(c => c.CreatedAt)
.FirstOrDefaultAsync(ct);
if (channel is null)
return;
var members = await chatDb.Members
.Where(m => m.ChannelId == channel.Id && m.LeftAt == null)
.ToListAsync(ct);
if (members.Count == 0)
return;
var now = DateTimeOffset.UtcNow;
foreach (var member in members)
member.LeftAt = now;
await chatDb.SaveChangesAsync(ct);
}
private static async Task<ChatChannel> GetOrCreateSingletonChannelAsync(
ChatDbContext chatDb,
ChatChannelType channelType,
string name,
DateTimeOffset now,
CancellationToken ct)
{
var existing = await chatDb.Channels
.Where(c => c.ChannelType == channelType && c.MatchId == null)
.OrderBy(c => c.CreatedAt)
.FirstOrDefaultAsync(ct);
if (existing is not null)
return existing;
var channel = new ChatChannel
{
Name = name,
ChannelType = channelType,
MatchId = null,
CreatedAt = now,
};
chatDb.Channels.Add(channel);
await chatDb.SaveChangesAsync(ct);
return channel;
}
private static async Task<ChatChannel> GetOrCreateMatchChannelAsync(
ChatDbContext chatDb,
Guid matchId,
DateTimeOffset now,
CancellationToken ct)
{
var matchKey = matchId.ToString("D");
var existing = await chatDb.Channels
.Where(c => c.ChannelType == ChatChannelType.Match && c.MatchId == matchKey)
.OrderBy(c => c.CreatedAt)
.FirstOrDefaultAsync(ct);
if (existing is not null)
return existing;
var channel = new ChatChannel
{
Name = $"game:{matchKey}",
ChannelType = ChatChannelType.Match,
MatchId = matchKey,
CreatedAt = now,
};
chatDb.Channels.Add(channel);
await chatDb.SaveChangesAsync(ct);
return channel;
}
private static async Task EnsureMemberAsync(
ChatDbContext chatDb,
Guid channelId,
Guid accountId,
DateTimeOffset now,
CancellationToken ct)
{
var member = await chatDb.Members
.FirstOrDefaultAsync(m => m.ChannelId == channelId && m.AccountId == accountId, ct);
if (member is null)
{
chatDb.Members.Add(new ChatMember
{
ChannelId = channelId,
AccountId = accountId,
JoinedAt = now,
LeftAt = null,
});
await chatDb.SaveChangesAsync(ct);
return;
}
if (member.LeftAt is null)
return;
member.LeftAt = null;
member.JoinedAt = now;
await chatDb.SaveChangesAsync(ct);
}
}
@@ -0,0 +1,82 @@
namespace SOR.Chat;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SOR.Database.Contexts;
using SOR.Networking.Abstractions.EventBus;
using SOR.Shared.Nats;
internal sealed class ChatLifecycleHostedService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly IEventBus _eventBus;
private readonly ILogger<ChatLifecycleHostedService> _logger;
public ChatLifecycleHostedService(
IServiceScopeFactory scopeFactory,
IEventBus eventBus,
ILogger<ChatLifecycleHostedService> logger)
{
_scopeFactory = scopeFactory;
_eventBus = eventBus;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var startedTask = RunGameStartedSubscriptionAsync(stoppingToken);
var endedTask = RunGameEndedSubscriptionAsync(stoppingToken);
await Task.WhenAll(startedTask, endedTask);
}
private async Task RunGameStartedSubscriptionAsync(CancellationToken ct)
{
try
{
await foreach (var evt in _eventBus
.SubscribeAsync<GameStartedEvent>(NatsSubjects.GameStarted, ct)
.WithCancellation(ct))
{
await using var scope = _scopeFactory.CreateAsyncScope();
var chatDb = scope.ServiceProvider.GetRequiredService<ChatDbContext>();
await ChatChannelMembership.EnsureMatchMembershipsAsync(
chatDb,
evt.GameId,
evt.PlayerIds,
ct);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
catch (Exception ex)
{
_logger.LogError(ex, "Game-started subscription loop crashed.");
}
}
private async Task RunGameEndedSubscriptionAsync(CancellationToken ct)
{
try
{
await foreach (var evt in _eventBus
.SubscribeAsync<GameEndedEvent>(NatsSubjects.GameEnded, ct)
.WithCancellation(ct))
{
await using var scope = _scopeFactory.CreateAsyncScope();
var chatDb = scope.ServiceProvider.GetRequiredService<ChatDbContext>();
await ChatChannelMembership.EndMatchMembershipsAsync(chatDb, evt.GameId, ct);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
catch (Exception ex)
{
_logger.LogError(ex, "Game-ended subscription loop crashed.");
}
}
}
@@ -24,6 +24,7 @@ internal sealed class ChatGetChannelsHandler : ChatHandlerBase, IMessageHandler
CancellationToken cancellationToken)
{
var accountId = Guid.Parse(connection.UserId);
await ChatChannelMembership.EnsureDefaultMembershipsAsync(_chatDb, accountId, cancellationToken);
var channels = await _chatDb.Members
.Where(m => m.AccountId == accountId && m.LeftAt == null)
@@ -35,6 +35,7 @@ public static class ServiceRegistration
services.AddTransient<IMessageHandler, ChatGetPresenceHandler>();
services.AddTransient<IMessageHandler, ChatGetNotificationsHandler>();
services.AddTransient<IMessageHandler, ChatMarkNotificationsReadHandler>();
services.AddHostedService<ChatLifecycleHostedService>();
return services;
}