English
Rules of chats
Step 1. Errors and limits
Why. The chat rules of Docs/ChatRules.md produce a dozen distinct failures. Each gets a stable code, so the Angular client can react precisely — owner_must_transfer opens the "choose a new owner" dialog, handle_taken marks the handle field. The numeric limits live next to them.
Do. Create the folder Chats:
cs
using Chatex.Core.Common;
namespace Chatex.Core.Chats;
public static class ChatErrors
{
/// <summary>Also returned for private chats the caller is not in, so their existence does not leak.</summary>
public static Error NotFound { get; } = Error.NotFound("chat_not_found", "The chat does not exist.");
public static Error NotAMember { get; } = Error.Forbidden("not_a_member", "Join the chat first.");
public static Error NotAllowed { get; } = Error.Forbidden("not_allowed", "You do not have permission to do this.");
public static Error MemberNotFound { get; } = Error.NotFound("member_not_found", "The user is not a member of this chat.");
public static Error DirectWithSelf { get; } =
Error.Validation("userId", "direct_with_self", "You cannot start a direct chat with yourself.");
public static Error NotForDirectChats { get; } =
Error.Validation("not_for_direct_chats", "This cannot be done in a direct chat.");
public static Error HandleTaken { get; } = Error.Conflict("handle_taken", "This public handle is already taken.");
public static Error OwnerMustTransfer { get; } =
Error.Conflict("owner_must_transfer", "Make someone else the owner before leaving.");
public static Error ChatFull { get; } =
Error.Conflict("chat_full", $"A group can have at most {ChatLimits.MaxGroupMembers} members.");
public static Error UnknownUsers { get; } =
Error.Validation("memberIds", "unknown_users", "Some of the users do not exist.");
public static Error InvalidRole { get; } =
Error.Validation("role", "invalid_role", "This role is not available in this chat.");
public static Error UseLeave { get; } =
Error.Validation("userId", "use_leave", "To remove yourself, leave the chat.");
}
internal static class ChatLimits
{
public const int MaxGroupMembers = 1000;
public const int MaxMembersPerRequest = 100;
public const int MaxTitle = 128;
public const int MaxDescription = 1000;
}Three different kinds of "no" appear here, and the difference matters:
NotFound(404) — the chat does not exist, or it is private and the caller is not a member. Answering "403 forbidden" for a private chat would confirm that it exists.Forbidden(403) — the caller can see the chat but may not do this:not_a_member(join first),not_allowed(a role is missing).Validation(400) andConflict(409) — the request itself is wrong, or collides with the current state (chat_full,handle_taken).
Step 2. Permissions as small functions
Why. Who may edit the title? Who may remove whom? Such rules tend to scatter as if statements through a service and drift apart. Chatex collects them in one static class of pure functions: they take the chat and the member and return bool, read nothing from the database and change nothing. They are trivial to read side by side with the table of permissions, and trivial to test.
Do.
cs
using Chatex.Data.Entities;
namespace Chatex.Core.Chats;
/// <summary>Who may do what in a chat. Posting rules live on <see cref="ChatMember.CanPost"/>.</summary>
public static class ChatPermissions
{
public static bool IsAdmin(ChatMember member) => member.Role is ChatMemberRole.Owner or ChatMemberRole.Admin;
public static bool CanEditInfo(Chat chat, ChatMember member) => chat.Type != ChatType.Direct && IsAdmin(member);
public static bool CanManageMembers(Chat chat, ChatMember member) => chat.Type != ChatType.Direct && IsAdmin(member);
public static bool CanDelete(Chat chat, ChatMember member) =>
chat.Type != ChatType.Direct && member.Role == ChatMemberRole.Owner;
/// <summary>Channel subscriber lists are visible to admins only.</summary>
public static bool CanListMembers(Chat chat, ChatMember member) => chat.Type != ChatType.Channel || IsAdmin(member);
/// <summary>The owner removes anyone else; an admin removes plain members and subscribers only.</summary>
public static bool CanRemove(ChatMember actor, ChatMember target) => actor.Role switch
{
ChatMemberRole.Owner => target.Role != ChatMemberRole.Owner,
ChatMemberRole.Admin => target.Role is ChatMemberRole.Member or ChatMemberRole.Subscriber,
_ => false,
};
public static bool CanDeleteMessage(ChatMember member, Message message) =>
message.SenderId == member.UserId || IsAdmin(member);
/// <summary>The role of a regular, non-admin member: groups have members, channels have subscribers.</summary>
public static ChatMemberRole RegularRole(ChatType type) =>
type == ChatType.Channel ? ChatMemberRole.Subscriber : ChatMemberRole.Member;
}Compare the code with the rules (Table 10.1):
Table 10.1. Permissions and the functions that implement them
| Rule | Function |
|---|---|
| Owner and admins edit title, description, handle, avatar — not in direct chats | CanEditInfo |
| Owner and admins add and remove members — not in direct chats | CanManageMembers |
| Only the owner deletes a group or channel | CanDelete |
| Everyone sees the members of a group; only admins see channel subscribers | CanListMembers |
| The owner removes anyone else; an admin removes members and subscribers | CanRemove |
| The sender deletes a message, and so do the owner and admins | CanDeleteMessage |
| Joining a group makes a member, joining a channel a subscriber | RegularRole |
CanRemove is a switch expression on the actor's role, with the pattern target.Role is … or … in one arm and a discard _ => false for every other role. Adding a role to the enumeration without deciding what it may remove would quietly fall into false — the safe default.
Step 3. Visibility
Why. Almost every chat operation starts the same way: load the chat, load the caller's membership, apply the visibility rule. A private chat of others must look exactly like a chat that does not exist. One small class does this for every service, so the rule cannot be implemented differently in two places.
Do.
cs
using Chatex.Core.Common;
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
namespace Chatex.Core.Chats;
/// <summary>Loads a chat together with the caller's membership, applying the visibility rules.</summary>
internal sealed class ChatAccess(IChatRepository chats, IChatMemberRepository members)
{
/// <summary>
/// The chat if the caller is a member or the chat is public. <c>Member</c> is null for a public chat the caller has not joined.
/// Private chats of others are reported as not found.
/// </summary>
public async Task<Result<(Chat Chat, ChatMember? Member)>> GetVisibleAsync(
Guid userId, Guid chatId, CancellationToken cancellationToken)
{
var chat = await chats.GetByIdAsync(chatId, cancellationToken);
if (chat is null)
{
return ChatErrors.NotFound;
}
var member = await members.GetAsync(chatId, userId, cancellationToken);
if (member is null && chat.PublicHandle is null)
{
return ChatErrors.NotFound;
}
return (chat, member);
}
/// <summary>The chat and the caller's membership; fails unless the caller is a member.</summary>
public async Task<Result<(Chat Chat, ChatMember Member)>> GetMembershipAsync(
Guid userId, Guid chatId, CancellationToken cancellationToken)
{
var visible = await GetVisibleAsync(userId, chatId, cancellationToken);
if (!visible.IsSuccess)
{
return visible.Error;
}
var (chat, member) = visible.Value;
return member is null ? ChatErrors.NotAMember : (chat, member);
}
}GetVisibleAsync— reading: a member may read, and so may anybody for a public chat (one with a handle); thenMemberisnull. A private chat of others giveschat_not_found.GetMembershipAsync— acting: builds on the first and additionally requires membership,not_a_memberotherwise.- Tuples as results.
Result<(Chat Chat, ChatMember? Member)>returns two values with names; the caller deconstructs them:var (chat, member) = access.Value;. - Returning a failure of another type:
return visible.Error;converts theErrorinto aResult<(Chat, ChatMember)>— the success types of the two results differ (ChatMember?andChatMember), but an error fits both.
Check
dotnet build succeeds.