English
Events
Step 1. A lower layer that must call a higher one
Why. When Alice adds Bob to a group, Bob's browser should show the group at once, and every member's member list should update. Pushing such events to browsers is the job of SignalR, which lives in Chatex.Api (topic 14). But the decision that something happened is made in Chatex.Core, in the middle of AddMembersAsync — and Chatex.Core cannot reference Chatex.Api.
The solution is the dependency inversion principle, the D of SOLID: the business layer declares the interface it needs, IChatNotifier, and the API implements it (Fig. 10.2). The arrow of the source dependency now points up, against the flow of control, from SignalRChatNotifier in the API to the interface in Chatex.Core.
Fig. 10.2. One interface, three implementations
Three implementations exist: the real one (SignalR), a Null Object that does nothing (for any host without real time — and for Chatex.Core until topic 14), and a recording fake for the tests of this topic.
Step 2. The shapes of messages and attachments
Why. The notifier also announces new and edited messages, and it sends the whole message, so the clients do not have to load it again. Its interface therefore needs the message DTO, and the message DTO needs the attachment DTO. Both belong to topic 11, but the notifier needs them now; we create them here and topic 11 completes them.
Do. Create the folder Attachments with the DTO of an attachment and its mapping:
cs
using Chatex.Data.Entities;
namespace Chatex.Core.Attachments;
public sealed record AttachmentDto(Guid Id, string FileName, string ContentType, long SizeBytes);
internal static class AttachmentMappings
{
public static AttachmentDto ToDto(this Attachment attachment) =>
new(attachment.Id, attachment.FileName, attachment.ContentType, attachment.SizeBytes);
}Then the folder Messages with the message DTOs — this file is complete:
cs
using Chatex.Core.Attachments;
using Chatex.Core.Users;
using Chatex.Data.Entities;
namespace Chatex.Core.Messages;
/// <param name="Body">Null for deleted messages.</param>
public sealed record MessageDto(
Guid Id,
Guid ChatId,
UserSummaryDto Sender,
string? Body,
Guid? ReplyToMessageId,
DateTimeOffset CreatedAt,
DateTimeOffset? EditedAt,
bool IsDeleted,
IReadOnlyList<AttachmentDto> Attachments);
/// <param name="Body">May be empty when the message carries attachments.</param>
/// <param name="AttachmentIds">Ids returned by uploads that are not yet attached to a message.</param>
public sealed record SendMessageCommand(string? Body, Guid? ReplyToMessageId = null, IReadOnlyList<Guid>? AttachmentIds = null);
public sealed record EditMessageCommand(string Body);
internal static class MessageMappings
{
/// <summary>Needs <see cref="Message.Sender"/> with profile and <see cref="Message.Attachments"/> loaded.</summary>
public static MessageDto ToDto(this Message message)
{
var deleted = message.DeletedAt is not null;
return new MessageDto(
message.Id,
message.ChatId,
message.Sender.ToSummaryDto(),
deleted ? null : message.Body,
message.ReplyToMessageId,
message.CreatedAt,
message.EditedAt,
deleted,
deleted ? [] : message.Attachments.OrderBy(a => a.Id).Select(a => a.ToDto()).ToList());
}
}- A deleted message keeps its id, chat, sender and time, but
Bodyisnull,IsDeletedistrueand the attachments are empty — the client shows a placeholder. - The attachments are ordered by id, which (UUIDv7) is the order of upload.
SendMessageCommandhas optional parameters: a reply and attachments are rare, sonew SendMessageCommand("hi")is enough.
The chat service also needs one error of messages — message_not_found, for marking as read a message that does not exist. Create the message errors complete:
cs
using Chatex.Core.Common;
namespace Chatex.Core.Messages;
public static class MessageErrors
{
public static Error NotFound { get; } = Error.NotFound("message_not_found", "The message does not exist.");
public static Error CannotPost { get; } =
Error.Forbidden("cannot_post", "Only the owner and admins can post in this channel.");
public static Error NotSender { get; } = Error.Forbidden("not_sender", "Only the sender can edit a message.");
public static Error ReplyNotFound { get; } =
Error.Validation("replyToMessageId", "reply_not_found", "The message you reply to is not in this chat.");
public static Error InvalidAttachments { get; } =
Error.Validation("attachmentIds", "invalid_attachments", "Some attachments do not exist, are not yours or are already sent.");
}
internal static class MessageLimits
{
public const int MaxBody = 4000;
public const int MaxAttachments = 10;
}Step 3. The notifier
Do. Create the folder Abstractions:
cs
using Chatex.Core.Messages;
namespace Chatex.Core.Abstractions;
/// <summary>
/// Pushes chat events to connected clients. Services call it only after the change is committed.
/// The Api implements it with SignalR; until then <see cref="NullChatNotifier"/> drops the events.
/// </summary>
public interface IChatNotifier
{
Task MessageCreatedAsync(MessageDto message, CancellationToken cancellationToken = default);
Task MessageUpdatedAsync(MessageDto message, CancellationToken cancellationToken = default);
Task MessageDeletedAsync(Guid chatId, Guid messageId, CancellationToken cancellationToken = default);
Task MessagesReadAsync(Guid chatId, Guid userId, Guid lastReadMessageId, CancellationToken cancellationToken = default);
/// <summary>Users joined or were added, including everyone in a newly created chat.</summary>
Task MembersAddedAsync(Guid chatId, IReadOnlyCollection<Guid> userIds, CancellationToken cancellationToken = default);
/// <summary>A user left or was removed.</summary>
Task MemberRemovedAsync(Guid chatId, Guid userId, CancellationToken cancellationToken = default);
/// <summary>Title, description, handle, avatar or member roles changed.</summary>
Task ChatUpdatedAsync(Guid chatId, CancellationToken cancellationToken = default);
Task ChatDeletedAsync(Guid chatId, CancellationToken cancellationToken = default);
}
public sealed class NullChatNotifier : IChatNotifier
{
public Task MessageCreatedAsync(MessageDto message, CancellationToken cancellationToken = default) => Task.CompletedTask;
public Task MessageUpdatedAsync(MessageDto message, CancellationToken cancellationToken = default) => Task.CompletedTask;
public Task MessageDeletedAsync(Guid chatId, Guid messageId, CancellationToken cancellationToken = default) => Task.CompletedTask;
public Task MessagesReadAsync(Guid chatId, Guid userId, Guid lastReadMessageId, CancellationToken cancellationToken = default) =>
Task.CompletedTask;
public Task MembersAddedAsync(Guid chatId, IReadOnlyCollection<Guid> userIds, CancellationToken cancellationToken = default) =>
Task.CompletedTask;
public Task MemberRemovedAsync(Guid chatId, Guid userId, CancellationToken cancellationToken = default) => Task.CompletedTask;
public Task ChatUpdatedAsync(Guid chatId, CancellationToken cancellationToken = default) => Task.CompletedTask;
public Task ChatDeletedAsync(Guid chatId, CancellationToken cancellationToken = default) => Task.CompletedTask;
}- Eight events, one per kind of change: three for messages, one for read positions, two for membership, two for the chat itself.
- "Only after the change is committed" (the comment on the interface) is the most important rule. An event about a message that is then rolled back would show other users a message that does not exist. Every service calls the notifier after
SaveChangesAsyncor after the transaction returns. - The events carry ids, not states, except for messages.
ChatUpdatedAsync(chatId)tells clients "reload this chat"; they then ask the API, which applies the permissions of each user. Pushing the whole chat would mean deciding here what every member may see. NullChatNotifieris the Null Object pattern: an implementation that does nothing, so the services never checkif (notifier is not null).
Check
dotnet build succeeds.