Add global/lobby auto-join and match chat lifecycle
This commit is contained in:
@@ -370,6 +370,7 @@ else
|
||||
private static string TypeBadge(SOR.Database.Enums.ChatChannelType t) => t switch
|
||||
{
|
||||
SOR.Database.Enums.ChatChannelType.Global => "bg-primary",
|
||||
SOR.Database.Enums.ChatChannelType.Lobby => "bg-secondary",
|
||||
SOR.Database.Enums.ChatChannelType.Direct => "bg-info text-dark",
|
||||
SOR.Database.Enums.ChatChannelType.Match => "bg-success",
|
||||
SOR.Database.Enums.ChatChannelType.Guild => "bg-warning text-dark",
|
||||
|
||||
@@ -156,6 +156,7 @@ else
|
||||
private static string TypeBadge(ChatChannelType t) => t switch
|
||||
{
|
||||
ChatChannelType.Global => "bg-primary",
|
||||
ChatChannelType.Lobby => "bg-secondary",
|
||||
ChatChannelType.Direct => "bg-info text-dark",
|
||||
ChatChannelType.Match => "bg-success",
|
||||
ChatChannelType.Guild => "bg-warning text-dark",
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ public enum ChatChannelType
|
||||
{
|
||||
/// <summary>Server-wide public chat.</summary>
|
||||
Global,
|
||||
/// <summary>Server-wide pre-game lobby chat.</summary>
|
||||
Lobby,
|
||||
/// <summary>Private channel for an active match.</summary>
|
||||
Match,
|
||||
/// <summary>Direct message between two accounts.</summary>
|
||||
|
||||
@@ -2,12 +2,15 @@ namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Game;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.EventBus;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Nats;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
@@ -22,15 +25,21 @@ internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHand
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
private readonly IClientPush _clientPush;
|
||||
private readonly IEventBus _eventBus;
|
||||
private readonly ILogger<GameJoinCustomLobbyHandler> _logger;
|
||||
|
||||
public GameJoinCustomLobbyHandler(
|
||||
IMessageSerializer serializer,
|
||||
GameDbContext gameDb,
|
||||
IClientPush clientPush)
|
||||
IClientPush clientPush,
|
||||
IEventBus eventBus,
|
||||
ILogger<GameJoinCustomLobbyHandler> logger)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
_clientPush = clientPush;
|
||||
_eventBus = eventBus;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public string MessageType => "game.custom.join";
|
||||
@@ -88,6 +97,23 @@ internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHand
|
||||
|
||||
await _gameDb.SaveChangesAsync(ct);
|
||||
|
||||
try
|
||||
{
|
||||
await _eventBus.PublishAsync(
|
||||
NatsSubjects.GameStarted,
|
||||
new GameStartedEvent(
|
||||
session.Id,
|
||||
new[] { lobby.HostAccountId, accountId },
|
||||
DateTimeOffset.UtcNow),
|
||||
ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"Failed publishing game-started event for custom lobby session {SessionId}",
|
||||
session.Id);
|
||||
}
|
||||
|
||||
// Push game-started notification to both players.
|
||||
var push = new CustomLobbyGameStartedPush(session.Id, accountId);
|
||||
var pushToHost = new CustomLobbyGameStartedPush(session.Id, accountId);
|
||||
|
||||
@@ -9,7 +9,9 @@ using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Game;
|
||||
using SOR.Database.Entities.Identity;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.EventBus;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Shared.Nats;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
@@ -67,6 +69,7 @@ internal sealed class MatchmakerService : BackgroundService
|
||||
var gameDb = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
var identityDb = scope.ServiceProvider.GetRequiredService<SorIdentityDbContext>();
|
||||
var clientPush = scope.ServiceProvider.GetRequiredService<IClientPush>();
|
||||
var eventBus = scope.ServiceProvider.GetRequiredService<IEventBus>();
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
// Load all searching entries, ordered by wait time (longest waiting first).
|
||||
@@ -148,6 +151,23 @@ internal sealed class MatchmakerService : BackgroundService
|
||||
"Match found: {A} vs {B} (session {S})",
|
||||
entry.AccountId, opponent.AccountId, session.Id);
|
||||
|
||||
try
|
||||
{
|
||||
await eventBus.PublishAsync(
|
||||
NatsSubjects.GameStarted,
|
||||
new GameStartedEvent(
|
||||
session.Id,
|
||||
new[] { entry.AccountId, opponent.AccountId },
|
||||
now),
|
||||
ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"Failed publishing game-started event for session {SessionId}",
|
||||
session.Id);
|
||||
}
|
||||
|
||||
// Fetch display names for the push payloads.
|
||||
var names = await identityDb.Set<Account>()
|
||||
.AsNoTracking()
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace SOR.Shared.Nats;
|
||||
|
||||
public sealed record GameStartedEvent(
|
||||
Guid GameId,
|
||||
IReadOnlyList<Guid> PlayerIds,
|
||||
DateTimeOffset StartedAt);
|
||||
|
||||
public sealed record GameEndedEvent(
|
||||
Guid GameId,
|
||||
Guid WinnerId,
|
||||
Guid LoserId,
|
||||
int DurationSeconds,
|
||||
DateTimeOffset EndedAt);
|
||||
Reference in New Issue
Block a user