English
The message service
Step 1. Validators
Why. A message needs text or at least one attachment — a photo without a caption is fine, an empty message is not. The text has at most 4000 characters, the number of attachments at most 10.
Do.
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(...) makes the NotEmpty rule conditional: it applies only when there are no attachments. The pattern c.AttachmentIds is not { Count: > 0 } is true for null and for an empty list.
Step 2. Sending a message
Why. Sending touches three tables: a new row in messages, the message_id of the attachments, and the last_activity_at of the chat, which moves the chat to the top of every member's list. All three must happen or none. And only after the commit may the other members hear about it (Fig. 11.2).
Fig. 11.2. Sending a message
Do.
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 step by step:
- Validate the command.
- Membership: only members may post (
GetMembershipAsync), andmember.CanPost(chat.Type)from topic 3 keeps channel subscribers silent:cannot_post. - A reply must point to a message of the same chat:
reply_not_foundotherwise. A client cannot quote a message from a chat the user cannot see. - Attachments:
GetPendingAsyncreturns only the caller's own uploads that are not yet attached (topic 5). If fewer come back than were requested, some ids are foreign, already sent or invented:invalid_attachments. - The transaction adds the message, links the attachments and saves, then moves the chat's activity time with
TouchAsync— an immediateUPDATE, inside the same transaction. The comment in the code explains the subtle part: on a retry the change tracker has been cleared (topic 5), so the lambda must load and track the attachments again; on the first run the query simply returns the already tracked objects. - After the commit, the message is loaded with the sender's profile and the attachments (
GetDetailsAsync), mapped to a DTO, sent to the notifier and returned.
The creation time used by TouchAsync is message.CreatedAt, which the interceptor of topic 4 has just set during SaveChangesAsync.
Editing
Only the sender may edit (not even an admin: editing somebody's words is a different thing from removing them), only messages that are not deleted, and only in a chat the editor is still a member of. EditedAt comes from the TimeProvider.
Deleting
The sender or an admin of the chat may delete (CanDeleteMessage from topic 10). The deletion is soft (topic 3): the row stays with DeletedAt and an empty body, so replies and read positions keep pointing at it. The attachments are deleted — their rows in the same save, their files afterwards. Deleting a deleted message again succeeds: the operation is idempotent, and a client that retries after a network error gets no confusing error.
History
GetHistoryAsync decodes the two opaque cursors of topic 7, refuses both at once, applies visibility (not membership: a public channel can be read before joining) and returns a page from the keyset query of topic 5. Deleted messages stay in the history as placeholders.
Step 3. Register the last services
Do. Extend AddCore (new lines in green). The method is now final, and so is its comment:
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;
}
}The attachment options are bound and validated like the JWT options. If the Attachments section is missing, the defaults of AttachmentOptions apply (20 MB, the built-in list of types).
Check
dotnet build succeeds, and the 26 business tests of topic 10 still pass.