English
Chats and members
Step 1. Chat types and roles
Why. A direct chat, a group and a channel differ in who can be a member and who can post (Table 3.1), but they share everything else: a title, members, messages, a history. One Chat entity with a type covers all three, instead of three classes with a lot of duplicated code.
Table 3.1. Chat types and the roles they use
| Type | Members | Who posts | Roles |
|---|---|---|---|
Direct | exactly two users | both | Member |
Group | up to 1000 | everyone | Owner, Admin, Member |
Channel | unlimited | the owner and admins | Owner, Admin, Subscriber |
Do. Two enumerations describe the types and the roles:
cs
namespace Chatex.Data.Entities;
public enum ChatType
{
/// <summary>One-to-one conversation between exactly two users.</summary>
Direct,
/// <summary>Many members, everyone can post.</summary>
Group,
/// <summary>Broadcast: only owner and admins post, everyone else subscribes.</summary>
Channel,
}cs
namespace Chatex.Data.Entities;
public enum ChatMemberRole
{
Owner,
Admin,
/// <summary>Can post. Used in direct chats and groups.</summary>
Member,
/// <summary>Read-only member of a channel.</summary>
Subscriber,
}In topic 4 the database stores these values as strings ('Direct', 'Owner') rather than as numbers. A row then reads well in psql, and inserting a new value in the middle of an enumeration cannot silently change the meaning of the rows that already exist.
Step 2. The chat
Why. Besides the common data, a chat has three properties with a special meaning:
PublicHandle— a unique@handlesuch as@dotnet_news. A group or channel with a handle is public: anyone can find it in the search and join. Without a handle (null) it is private, invisible to non-members.DirectKey— Chatex must never create two direct chats between the same two people. A rule "check first, then insert" is not enough: two requests that arrive at the same moment can both pass the check. The reliable way is a unique index in the database, which rejects the second insert. But a unique index needs one column whose value is the same for the pair (Alice, Bob) and the pair (Bob, Alice).DirectKeyis that column: both ids in sorted order, so the order of the users does not matter. Groups and channels leave itnull.LastActivityAt— the time of the newest message, or the creation time. The chat list is ordered by it, newest first; storing it in the chat (and updating it together with each new message) makes that ordering one simple index scan instead of a search for the newest message in every chat.
A chat is never really deleted: DeletedAt marks it as deleted (soft delete), and every query skips such chats. The history stays consistent for other references, and an accidental deletion can be investigated.
Do.
cs
namespace Chatex.Data.Entities;
/// <summary>A conversation: a direct chat, a group or a channel (see <see cref="ChatType"/>).</summary>
public class Chat : IHasCreatedAt, IHasUpdatedAt
{
public Guid Id { get; set; } = Guid.CreateVersion7();
public ChatType Type { get; set; }
/// <summary>Null for direct chats; clients show the other member's name instead.</summary>
public string? Title { get; set; }
public string? Description { get; set; }
public string? AvatarPath { get; set; }
/// <summary>Unique lower-case public @handle that makes a group or channel findable. Null means private.</summary>
public string? PublicHandle { get; set; }
/// <summary>Set only for direct chats, see <see cref="MakeDirectKey"/>. Unique, so a pair of users has one direct chat.</summary>
public string? DirectKey { get; set; }
public Guid CreatedById { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
/// <summary>Time of the newest message, or creation time. Orders the user's chat list.</summary>
public DateTimeOffset LastActivityAt { get; set; }
public DateTimeOffset? DeletedAt { get; set; }
public User CreatedBy { get; set; } = null!;
public ICollection<ChatMember> Members { get; set; } = [];
public ICollection<Message> Messages { get; set; } = [];
public static string MakeDirectKey(Guid userA, Guid userB) =>
userA.CompareTo(userB) <= 0 ? $"{userA:N}:{userB:N}" : $"{userB:N}:{userA:N}";
}MakeDirectKey is static: it needs no chat object, only two ids, and the services call it before a chat exists ("is there already a direct chat with this key?"). The format specifier N writes a Guid as 32 hexadecimal digits without hyphens, and the ternary operator puts the smaller id first.
Step 3. The member
Why. ChatMember is the many-to-many link between users and chats, enriched with data:
- The key is the pair
(ChatId, UserId)— a composite key. A user can be in a chat only once, and the database enforces it without an extra unique index. (The key itself is configured in topic 4.) Role— what the member may do (Table 3.1).LastReadMessageId— the newest message the member has read. Because message ids are UUIDv7 and sort by time, every message with a greater id is unread. One column replaces a table of "message X was read by user Y" rows, which would grow with every message times every member. The position only moves forward: opening an older part of the history must not mark newer messages as unread again.IsMuted— the member does not want notifications from this chat.
Do.
cs
namespace Chatex.Data.Entities;
/// <summary>Membership of a user in a chat, with role and read position.</summary>
public class ChatMember : IHasCreatedAt
{
public Guid ChatId { get; set; }
public Guid UserId { get; set; }
public ChatMemberRole Role { get; set; }
public DateTimeOffset JoinedAt { get; set; }
/// <summary>Newest message the user has read. Only moves forward; unread = messages with a greater id.</summary>
public Guid? LastReadMessageId { get; set; }
public bool IsMuted { get; set; }
public Chat Chat { get; set; } = null!;
public User User { get; set; } = null!;
DateTimeOffset IHasCreatedAt.CreatedAt
{
get => JoinedAt;
set => JoinedAt = value;
}
public bool CanPost(ChatType chatType) =>
chatType != ChatType.Channel || Role is ChatMemberRole.Owner or ChatMemberRole.Admin;
}Two pieces of C# here deserve attention.
An explicit interface implementation. The interceptor of topic 4 fills CreatedAt of every IHasCreatedAt entity. For a member, the creation time is better called JoinedAt. Instead of a second property, ChatMember implements IHasCreatedAt.CreatedAt explicitly: the property is visible only through the interface, and its getter and setter forward to JoinedAt. Code that works with a ChatMember sees only JoinedAt; the interceptor, which works with IHasCreatedAt, sets the same value.
Pattern matching in CanPost. The rule reads: in any chat that is not a channel every member may post; in a channel only the owner and admins may. Role is ChatMemberRole.Owner or ChatMemberRole.Admin is a pattern with the or combinator (C# 9): shorter and clearer than Role == ChatMemberRole.Owner || Role == ChatMemberRole.Admin.
Check
Build the data project:
powershell
dotnet build Source/Chatex.DataIt still fails, but now only because Message (used in Chat.Messages) is missing. That is the next chapter.