Українська
Сервіс повідомлень
Крок 1. Перевірка вхідних даних
Навіщо. Повідомлення потребує тексту або принаймні одного вкладення: фото без підпису припустиме, порожнє повідомлення – ні. Текст має щонайбільше 4000 символів, кількість вкладень – щонайбільше 10.
Що зробити.
cs
using FluentValidation;
namespace Chatex.Core.Messages;
internal sealed class SendMessageCommandValidator : AbstractValidator<SendMessageCommand>
{
public SendMessageCommandValidator()
{
RuleFor(c => c.Body)
.NotEmpty()
.When(c => c.AttachmentIds is not { Count: > 0 })
.WithMessage("Write a message or attach a file.");
RuleFor(c => c.Body).MaximumLength(MessageLimits.MaxBody);
RuleFor(c => c.AttachmentIds)
.Must(ids => ids is null || ids.Count <= MessageLimits.MaxAttachments)
.WithMessage($"A message can have at most {MessageLimits.MaxAttachments} attachments.");
}
}
internal sealed class EditMessageCommandValidator : AbstractValidator<EditMessageCommand>
{
public EditMessageCommandValidator()
{
RuleFor(c => c.Body).NotEmpty().MaximumLength(MessageLimits.MaxBody);
}
}.When(...) робить правило NotEmpty умовним: воно застосовується лише тоді, коли вкладень немає. Шаблон c.AttachmentIds is not { Count: > 0 } істинний і для null, і для порожнього списку.
Крок 2. Надсилання повідомлення
Навіщо. Надсилання зачіпає три таблиці: новий рядок у messages, message_id вкладень і last_activity_at чату, що піднімає чат нагору списку кожного учасника. Мають відбутися всі три зміни або жодна. І лише після коміту інші учасники можуть про це дізнатися (рис. 11.2).
Рис. 11.2. Надсилання повідомлення
Що зробити.
cs
using Chatex.Core.Abstractions;
using Chatex.Core.Chats;
using Chatex.Core.Common;
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
using FluentValidation;
namespace Chatex.Core.Messages;
public interface IMessageService
{
Task<Result<MessageDto>> SendAsync(Guid userId, Guid chatId, SendMessageCommand command, CancellationToken cancellationToken = default);
/// <summary>Only the sender can edit, and only messages that are not deleted.</summary>
Task<Result<MessageDto>> EditAsync(Guid userId, Guid messageId, EditMessageCommand command, CancellationToken cancellationToken = default);
/// <summary>The sender or a chat admin can delete. The text and attachments are removed; a placeholder stays.</summary>
Task<Result> DeleteAsync(Guid userId, Guid messageId, CancellationToken cancellationToken = default);
/// <summary>
/// A page of history. No cursor: newest messages, newest first. <paramref name="before"/>: older messages, newest first.
/// <paramref name="after"/>: newer messages, oldest first (catching up after a reconnect).
/// </summary>
Task<Result<PageDto<MessageDto>>> GetHistoryAsync(
Guid userId, Guid chatId, string? before, string? after, int? limit, CancellationToken cancellationToken = default);
}
internal sealed class MessageService(
IMessageRepository messages,
IChatRepository chats,
IAttachmentRepository attachments,
IUnitOfWork unitOfWork,
IFileStorage storage,
ChatAccess chatAccess,
IChatNotifier notifier,
TimeProvider timeProvider,
IValidator<SendMessageCommand> sendValidator,
IValidator<EditMessageCommand> editValidator) : IMessageService
{
public async Task<Result<MessageDto>> SendAsync(
Guid userId, Guid chatId, SendMessageCommand command, CancellationToken cancellationToken = default)
{
if (await sendValidator.ValidateToErrorAsync(command, cancellationToken) is { } invalid)
{
return invalid;
}
var access = await chatAccess.GetMembershipAsync(userId, chatId, cancellationToken);
if (!access.IsSuccess)
{
return access.Error;
}
var (chat, member) = access.Value;
if (!member.CanPost(chat.Type))
{
return MessageErrors.CannotPost;
}
if (command.ReplyToMessageId is { } replyTo && !await messages.ExistsInChatAsync(chatId, replyTo, cancellationToken))
{
return MessageErrors.ReplyNotFound;
}
var attachmentIds = (command.AttachmentIds ?? []).Distinct().ToList();
var pending = attachmentIds.Count == 0
? []
: await attachments.GetPendingAsync(userId, attachmentIds, cancellationToken);
if (pending.Count != attachmentIds.Count)
{
return MessageErrors.InvalidAttachments;
}
var message = new Message
{
ChatId = chatId,
SenderId = userId,
Body = command.Body?.Trim() ?? "",
ReplyToMessageId = command.ReplyToMessageId,
};
await unitOfWork.ExecuteInTransactionAsync(async ct =>
{
// Track everything inside the transaction: a retried transaction starts from a cleared change tracker
// and replays only this lambda. On the first run the query returns the already tracked attachments.
messages.Add(message);
var toLink = attachmentIds.Count == 0 ? pending : await attachments.GetPendingAsync(userId, attachmentIds, ct);
foreach (var attachment in toLink)
{
attachment.MessageId = message.Id;
}
await unitOfWork.SaveChangesAsync(ct);
await chats.TouchAsync(chatId, message.CreatedAt, ct);
}, cancellationToken);
var dto = await LoadDtoAsync(message.Id, cancellationToken);
await notifier.MessageCreatedAsync(dto, cancellationToken);
return dto;
}
public async Task<Result<MessageDto>> EditAsync(
Guid userId, Guid messageId, EditMessageCommand command, CancellationToken cancellationToken = default)
{
if (await editValidator.ValidateToErrorAsync(command, cancellationToken) is { } invalid)
{
return invalid;
}
var message = await messages.GetByIdAsync(messageId, cancellationToken);
if (message is null || message.DeletedAt is not null)
{
return MessageErrors.NotFound;
}
var access = await chatAccess.GetMembershipAsync(userId, message.ChatId, cancellationToken);
if (!access.IsSuccess)
{
return access.Error;
}
if (message.SenderId != userId)
{
return MessageErrors.NotSender;
}
message.Body = command.Body.Trim();
message.EditedAt = timeProvider.GetUtcNow();
await unitOfWork.SaveChangesAsync(cancellationToken);
var dto = await LoadDtoAsync(messageId, cancellationToken);
await notifier.MessageUpdatedAsync(dto, cancellationToken);
return dto;
}
public async Task<Result> DeleteAsync(Guid userId, Guid messageId, CancellationToken cancellationToken = default)
{
var message = await messages.GetByIdAsync(messageId, cancellationToken);
if (message is null)
{
return MessageErrors.NotFound;
}
var access = await chatAccess.GetMembershipAsync(userId, message.ChatId, cancellationToken);
if (!access.IsSuccess)
{
return access.Error;
}
if (message.DeletedAt is not null)
{
return Result.Success;
}
if (!ChatPermissions.CanDeleteMessage(access.Value.Member, message))
{
return ChatErrors.NotAllowed;
}
var files = message.Attachments.Select(a => a.StoragePath).ToList();
foreach (var attachment in message.Attachments.ToList())
{
attachments.Remove(attachment);
}
message.DeletedAt = timeProvider.GetUtcNow();
message.Body = "";
await unitOfWork.SaveChangesAsync(cancellationToken);
foreach (var file in files)
{
await storage.DeleteAsync(file, cancellationToken);
}
await notifier.MessageDeletedAsync(message.ChatId, messageId, cancellationToken);
return Result.Success;
}
public async Task<Result<PageDto<MessageDto>>> GetHistoryAsync(
Guid userId, Guid chatId, string? before, string? after, int? limit, CancellationToken cancellationToken = default)
{
if (!CursorCodec.TryDecode(before, out Guid? beforeId) || !CursorCodec.TryDecode(after, out Guid? afterId))
{
return Paging.InvalidCursor;
}
if (beforeId is not null && afterId is not null)
{
return Error.Validation("cursor", "both_cursors", "Pass either 'before' or 'after', not both.");
}
var access = await chatAccess.GetVisibleAsync(userId, chatId, cancellationToken);
if (!access.IsSuccess)
{
return access.Error;
}
var page = await messages.GetPageAsync(chatId, beforeId, afterId, Paging.Clamp(limit), cancellationToken);
return new PageDto<MessageDto>(page.Items.Select(m => m.ToDto()).ToList(), CursorCodec.Encode(page.NextCursor));
}
private async Task<MessageDto> LoadDtoAsync(Guid messageId, CancellationToken cancellationToken)
{
var message = await messages.GetDetailsAsync(messageId, cancellationToken)
?? throw new InvalidOperationException($"Message {messageId} was just saved but could not be loaded.");
return message.ToDto();
}
}SendAsync крок за кроком:
- Перевірте команду.
- Членство: писати можуть лише учасники (
GetMembershipAsync), аmember.CanPost(chat.Type)із теми 3 мовчазно утримує підписників каналу:cannot_post. - Відповідь має вказувати на повідомлення того самого чату, інакше
reply_not_found. Клієнт не може процитувати повідомлення з чату, якого користувач не бачить. - Вкладення:
GetPendingAsyncповертає лише власні завантаження викликача, які ще не прикріплені (тема 5). Якщо повернулося менше, ніж запитано, деякі ідентифікатори чужі, уже надіслані або вигадані:invalid_attachments. - Транзакція додає повідомлення, прив’язує вкладення й зберігає, потім пересуває час активності чату через
TouchAsync– негайнийUPDATEусередині тієї самої транзакції. Коментар у коді пояснює тонкий момент: під час повтору відстежувач змін очищено (тема 5), тож лямбда має знову завантажити й відстежити вкладення; під час першого запуску запит просто повертає вже відстежені об’єкти. - Після коміту повідомлення завантажують із профілем відправника та вкладеннями (
GetDetailsAsync), відображають на DTO, надсилають сповіщувачу й повертають.
Час створення, який використовує TouchAsync, – це message.CreatedAt, який перехоплювач із теми 4 щойно задав під час SaveChangesAsync.
Редагування
Редагувати може лише відправник (навіть не адміністратор: змінювати чиїсь слова – не те саме, що вилучати їх), лише повідомлення, що не видалені, і лише в чаті, учасником якого редактор іще є. EditedAt береться з TimeProvider.
Видалення
Видаляти може відправник або адміністратор чату (CanDeleteMessage із теми 10). Видалення м’яке (тема 3): рядок лишається з DeletedAt і порожнім текстом, тож відповіді й позиції читання й далі вказують на нього. Вкладення видаляють – їхні рядки в тому самому збереженні, а файли пізніше. Повторне видалення видаленого повідомлення завершується успіхом: операція ідемпотентна, і клієнт, що повторює запит після мережевої помилки, не отримує заплутаної помилки.
Історія
GetHistoryAsync розкодовує два непрозорі курсори з теми 7, відхиляє обидва одразу, застосовує видимість (а не членство: публічний канал можна читати до приєднання) і повертає сторінку із запиту за ключем із теми 5. Видалені повідомлення лишаються в історії як заглушки.
Крок 3. Зареєструйте останні сервіси
Що зробити. Розширте AddCore (нові рядки зеленим). Тепер метод остаточний, як і його коментар:
cs
using Chatex.Core.Abstractions;
using Chatex.Core.Attachments;
using Chatex.Core.Auth;
using Chatex.Core.Chats;
using Chatex.Core.Common;
using Chatex.Core.Messages;
using Chatex.Core.Users;
using Chatex.Data;
using FluentValidation;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Chatex.Core;
public static class DependencyInjection
{
/// <summary>
/// Registers the business services and, beneath them, the data access layer. Reads the <c>Chatex</c>
/// connection string, <c>Storage:RootPath</c>, and the <c>Jwt</c> and <c>Attachments</c> sections.
/// Register your own <see cref="IChatNotifier"/> (SignalR) before calling this to replace the no-op one.
/// </summary>
public static IServiceCollection AddCore(this IServiceCollection services, IConfiguration configuration)
{
var connectionString = configuration.GetConnectionString("Chatex")
?? throw new InvalidOperationException("Connection string 'Chatex' is not configured.");
services.AddData(connectionString, o => o.RootPath = configuration["Storage:RootPath"] ?? "");
services.AddOptions<JwtOptions>()
.Bind(configuration.GetSection(JwtOptions.Section))
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddOptions<AttachmentOptions>()
.Bind(configuration.GetSection(AttachmentOptions.Section))
.ValidateDataAnnotations()
.ValidateOnStart();
services.Configure<IdentityOptions>(o =>
{
o.User.RequireUniqueEmail = true;
o.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyz0123456789_";
o.Password.RequiredLength = 8;
o.Password.RequireDigit = true;
o.Password.RequireLowercase = false;
o.Password.RequireUppercase = false;
o.Password.RequireNonAlphanumeric = false;
o.Lockout.MaxFailedAccessAttempts = 5;
o.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
});
services.AddValidatorsFromAssemblyContaining<AuthService>(includeInternalTypes: true);
services.TryAddSingleton<IChatNotifier, NullChatNotifier>();
services.AddSingleton<ITokenService, TokenService>();
services.AddScoped<AvatarStore>();
services.AddScoped<ChatAccess>();
services.AddScoped<IAuthService, AuthService>();
services.AddScoped<IProfileService, ProfileService>();
services.AddScoped<IChatService, ChatService>();
services.AddScoped<IMessageService, MessageService>();
services.AddScoped<IAttachmentService, AttachmentService>();
return services;
}
}Параметри вкладень зв’язують і перевіряють так само, як параметри JWT. Якщо розділу Attachments немає, застосовуються типові значення AttachmentOptions (20 МБ, вбудований список типів).
Перевірка
dotnet build завершується успішно, і 26 бізнес-тестів із теми 10, як і раніше, проходять.