ModernUO/Projects/UOContent/Engines/Chat/Channel.cs
Kamron Batman cce035f1c3
fix: Removes unnecessary dictionary removal guards (#2565)
## What

`Dictionary<K,V>.Remove` and `HashSet<T>.Remove` do not bump the collection's version, so removing an entry during a `foreach` does not invalidate the enumerator. A number of loops were still paying for a `PooledRefQueue`/`PooledRefList` to collect keys and drain them in a second pass. This drops those guards.

## Why it's safe

Verified against .NET 10.0.10 rather than taken on trust, since the documented guarantee covers only `Dictionary<TKey,TValue>.Remove` while several of these call sites are `HashSet<T>` or enumerate `.Keys`/`.Values`:

| Case | Result |
|---|---|
| `Dictionary` foreach + `Remove` | safe, all entries visited |
| `Dictionary.Keys` / `.Values` foreach + `Remove` | safe, all entries visited |
| `HashSet` foreach + `Remove` | safe, all entries visited |
| `Dictionary` foreach + `Remove` **then `Add`** | throws `InvalidOperationException` |

Reflection on `_version` confirms the mechanism: neither `Dictionary.Remove` nor `HashSet.Remove` touches it. Because `Remove` never bumps the version, the `Keys` and `Values` enumerators are just as safe as the dictionary's own, even though only `Dictionary.Remove` documents the behaviour. No entries were skipped in any case.

The `HashSet` half is confirmed by [stephentoub on dotnet/dotnet-api-docs#8177](https://github.com/dotnet/dotnet-api-docs/issues/8177#issuecomment-1167251052): *"Both HashSet and Dictionary have been improved to support removal during enumeration. The docs may just benefit from updating."* The gap is in the documentation, not the runtime.

`Remove` followed by `Add` in the same enumeration still throws. That is the line this PR does not cross.

## Guards removed

`VisibilityList`, `ChampionTitleSystem`, `Channel`, `BombingRun`, `Ruleset`, `PuzzleChest`, `RaceChangeGump`, `StepCache`, `PlayerMurderSystem`, `VirtueSystem`, `ProjectedItem`, `StaminaSystem`, `AIGroupMovement`, `PromotedGuard`, `AutoDenylist`, `LoginAllowlist`, `AntiMacroSystem`, `DetectHidden`.

Both collection kinds are covered: `Dictionary` (including loops over `.Keys` and `.Values`) and `HashSet` (`ProjectedItem._active`, `PlayerMurderSystem._contextTerms`, `StaminaSystem._resetHash`). In `StaminaSystem.ResetTimer` the `Count == queue.Count → Clear()` branch goes away with the queue — it only existed to avoid paying for N individual removes.

Where the collection supports it, `Contains` + `Remove` and `TryGetValue` + `Remove` also collapse into a single lookup (`if (list.Remove(x))`, `if (m_Pending.Remove(ns, out var state))`).

`Utility.Tidy<K,V>` keeps its two branches: when `K` is serializable the value is not inspected, otherwise the value is. Only the serializable side may be cast, so `Dictionary<Mobile, int>` and `Dictionary<Mobile, string>` stay valid.

## Deliberately unchanged

**`BaseCreature.LoyaltyTimer.OnTick`** keeps its deferred-delete queue. Removing from `World.Mobiles` while enumerating it is safe, but `Mobile.Delete()` is not a `Remove` — it runs `OnDelete`/`OnAfterDelete`, the `OnParentDeleted` cascade over the creature's pack, `DropHolding()`, and region and guild callbacks. Anything in that surface that constructs a `Mobile` is an `Add` into the dictionary being enumerated, which does invalidate it. `BaseHire.PayTimer.OnTick` has the same shape and is likewise untouched.

**Spatial-query buffers** — `GuardedRegion.CallGuards`, `Thunderstorm`, `Exorcism`, `LeverPuzzleController`, `BaseCreature.TeleportPets` — are a different hazard. They buffer the result of a range query because the drain moves or harms mobiles, which mutates sectors mid-enumeration.

**Re-entrant drains.** The `_users` sets in `Firebomb` and the explosion, conflagration and confusion-blast potions look like this pattern but are not: the loop collects, `Clear()`s, and only then runs `Target.Cancel` on each, which can re-enter. `AnimalTrainer` enumerates `pm.Stabled` and drains through `RemoveStabled`, which nulls the `Stabled` field once it empties — safe for an in-flight enumerator, which holds the set reference rather than the field, but subtle enough not to be worth inlining on a cold path.

## Verification

`dotnet build` clean with 0 warnings; 810 Server and 684 UOContent tests pass.
2026-08-08 11:50:01 -07:00

481 lines
14 KiB
C#

using System.Collections.Generic;
namespace Server.Engines.Chat
{
public class Channel
{
private readonly List<ChatUser> m_Banned;
private readonly List<ChatUser> m_Moderators;
private readonly List<ChatUser> m_Users;
private readonly List<ChatUser> m_Voices;
private string m_Name;
private string m_Password;
private bool m_VoiceRestricted;
public Channel(string name)
{
m_Name = name;
m_Users = new List<ChatUser>();
m_Banned = new List<ChatUser>();
m_Moderators = new List<ChatUser>();
m_Voices = new List<ChatUser>();
}
public Channel(string name, string password) : this(name) => m_Password = password;
public string Name
{
get => m_Name;
set
{
SendCommand(ChatCommand.RemoveChannel, m_Name);
m_Name = value;
SendCommand(ChatCommand.AddChannel, m_Name);
SendCommand(ChatCommand.JoinedChannel, m_Name);
}
}
public string Password
{
get => m_Password;
set => m_Password = (value?.Trim()).DefaultIfNullOrEmpty(null);
}
public bool VoiceRestricted
{
get => m_VoiceRestricted;
set
{
m_VoiceRestricted = value;
if (value)
{
// From now on, only moderators will have speaking privileges in this conference by default.
SendMessage(56);
}
else
{
// From now on, everyone in the conference will have speaking privileges by default.
SendMessage(55);
}
}
}
public bool AlwaysAvailable { get; set; }
public static List<Channel> Channels { get; } = new();
public bool Contains(ChatUser user) => m_Users.Contains(user);
public bool IsBanned(ChatUser user) => m_Banned.Contains(user);
public bool CanTalk(ChatUser user) => !m_VoiceRestricted || m_Voices.Contains(user) || m_Moderators.Contains(user);
public bool IsModerator(ChatUser user) => m_Moderators.Contains(user);
public bool IsVoiced(ChatUser user) => m_Voices.Contains(user);
public bool ValidatePassword(string password) => m_Password?.InsensitiveEquals(password) != false;
public bool ValidateModerator(ChatUser user)
{
if (user != null && !IsModerator(user))
{
user.SendMessage(29); // You must have operator status to do this.
return false;
}
return true;
}
public bool ValidateAccess(ChatUser from, ChatUser target)
{
if (from == null || target == null || from.Mobile.AccessLevel >= target.Mobile.AccessLevel)
{
return true;
}
from.Mobile.SendMessage("Your access level is too low to do this.");
return false;
}
public bool AddUser(ChatUser user, string password = null)
{
if (Contains(user))
{
user.SendMessage(46, m_Name); // You are already in the conference '%1'.
return true;
}
if (IsBanned(user))
{
user.SendMessage(64); // You have been banned from this conference.
return false;
}
if (!ValidatePassword(password))
{
user.SendMessage(34); // That is not the correct password.
return false;
}
user.CurrentChannel?.RemoveUser(user); // Remove them from their current channel first
ChatSystem.SendCommandTo(user.Mobile, ChatCommand.JoinedChannel, m_Name);
SendCommand(ChatCommand.AddUserToChannel, user.GetColorCharacter() + user.Username);
m_Users.Add(user);
user.CurrentChannel = this;
if (user.Mobile.AccessLevel >= AccessLevel.GameMaster || !AlwaysAvailable && m_Users.Count == 1)
{
AddModerator(user);
}
SendUsersTo(user);
return true;
}
public void RemoveUser(ChatUser user)
{
if (Contains(user))
{
m_Users.Remove(user);
user.CurrentChannel = null;
m_Moderators.Remove(user);
m_Voices.Remove(user);
SendCommand(ChatCommand.RemoveUserFromChannel, user, user.Username);
ChatSystem.SendCommandTo(user.Mobile, ChatCommand.LeaveChannel);
if (m_Users.Count == 0 && !AlwaysAvailable)
{
RemoveChannel(this);
}
}
}
public void AddBan(ChatUser user, ChatUser moderator = null)
{
if (!ValidateModerator(moderator) || !ValidateAccess(moderator, user))
{
return;
}
if (!m_Banned.Contains(user))
{
m_Banned.Add(user);
}
Kick(user, moderator, true);
}
public void RemoveBan(ChatUser user)
{
m_Banned.Remove(user);
}
public void Kick(ChatUser user, ChatUser moderator = null)
{
Kick(user, moderator, false);
}
public void Kick(ChatUser user, ChatUser moderator, bool wasBanned)
{
if (!ValidateModerator(moderator) || !ValidateAccess(moderator, user))
{
return;
}
if (Contains(user))
{
if (moderator != null)
{
if (wasBanned)
{
// %1, a conference moderator, has banned you from the conference.
user.SendMessage(63, moderator.Username);
}
else
{
// %1, a conference moderator, has kicked you out of the conference.
user.SendMessage(45, moderator.Username);
}
}
RemoveUser(user);
ChatSystem.SendCommandTo(
user.Mobile,
ChatCommand.AddUserToChannel,
user.GetColorCharacter() + user.Username
);
SendMessage(44, user.Username); // %1 has been kicked out of the conference.
}
if (wasBanned)
{
moderator?.SendMessage(62, user.Username); // You are banning %1 from this conference.
}
}
public void AddVoiced(ChatUser user, ChatUser moderator = null)
{
if (!ValidateModerator(moderator))
{
return;
}
if (!IsBanned(user) && !IsModerator(user) && !IsVoiced(user))
{
m_Voices.Add(user);
if (moderator != null)
{
// %1, a conference moderator, has granted you speaking privileges in this conference.
user.SendMessage(54, moderator.Username);
}
SendMessage(52, user, user.Username); // %1 now has speaking privileges in this conference.
SendCommand(ChatCommand.AddUserToChannel, user, user.GetColorCharacter() + user.Username);
}
}
public void RemoveVoiced(ChatUser user, ChatUser moderator)
{
if (!ValidateModerator(moderator) || !ValidateAccess(moderator, user))
{
return;
}
if (!IsModerator(user) && IsVoiced(user))
{
m_Voices.Remove(user);
if (moderator != null)
{
// %1, a conference moderator, has removed your speaking privileges for this conference.
user.SendMessage(53, moderator.Username);
}
SendMessage(51, user, user.Username); // %1 no longer has speaking privileges in this conference.
SendCommand(ChatCommand.AddUserToChannel, user, user.GetColorCharacter() + user.Username);
}
}
public void AddModerator(ChatUser user, ChatUser moderator = null)
{
if (!ValidateModerator(moderator))
{
return;
}
if (IsBanned(user) || IsModerator(user))
{
return;
}
if (IsVoiced(user))
{
m_Voices.Remove(user);
}
m_Moderators.Add(user);
if (moderator != null)
{
user.SendMessage(50, moderator.Username); // %1 has made you a conference moderator.
}
SendMessage(48, user, user.Username); // %1 is now a conference moderator.
SendCommand(ChatCommand.AddUserToChannel, user.GetColorCharacter() + user.Username);
}
public void RemoveModerator(ChatUser user, ChatUser moderator = null)
{
if (!ValidateModerator(moderator) || !ValidateAccess(moderator, user))
{
return;
}
if (IsModerator(user))
{
m_Moderators.Remove(user);
if (moderator != null)
{
user.SendMessage(49, moderator.Username); // %1 has removed you from the list of conference moderators.
}
SendMessage(47, user, user.Username); // %1 is no longer a conference moderator.
SendCommand(ChatCommand.AddUserToChannel, user.GetColorCharacter() + user.Username);
}
}
public void SendMessage(int number, string param1 = null)
{
SendMessage(number, null, param1);
}
public void SendMessage(int number, ChatUser initiator, string param1 = null, string param2 = null)
{
for (var i = 0; i < m_Users.Count; ++i)
{
var user = m_Users[i];
if (user == initiator)
{
continue;
}
if (user.CheckOnline())
{
user.SendMessage(number, param1, param2);
}
else if (!Contains(user))
{
--i;
}
}
}
public void SendIgnorableMessage(int number, ChatUser from, string param1, string param2)
{
for (var i = 0; i < m_Users.Count; ++i)
{
var user = m_Users[i];
if (user.IsIgnored(from))
{
continue;
}
if (user.CheckOnline())
{
user.SendMessage(number, from.Mobile, param1, param2);
}
else if (!Contains(user))
{
--i;
}
}
}
public void SendCommand(ChatCommand command, string param1 = null, string param2 = null)
{
SendCommand(command, null, param1, param2);
}
public void SendCommand(ChatCommand command, ChatUser initiator, string param1 = null, string param2 = null)
{
for (var i = 0; i < m_Users.Count; ++i)
{
var user = m_Users[i];
if (user == initiator)
{
continue;
}
if (user.CheckOnline())
{
ChatSystem.SendCommandTo(user.Mobile, command, param1, param2);
}
else if (!Contains(user))
{
--i;
}
}
}
public void SendUsersTo(ChatUser to)
{
for (var i = 0; i < m_Users.Count; ++i)
{
var user = m_Users[i];
ChatSystem.SendCommandTo(to.Mobile, ChatCommand.AddUserToChannel, user.GetColorCharacter() + user.Username);
}
}
public static void SendChannelsTo(ChatUser user)
{
for (var i = 0; i < Channels.Count; ++i)
{
var channel = Channels[i];
if (!channel.IsBanned(user))
{
ChatSystem.SendCommandTo(user.Mobile, ChatCommand.AddChannel, channel.Name, "0");
}
}
}
public static Channel AddChannel(string name, string password = null)
{
var channel = FindChannelByName(name);
if (channel == null)
{
channel = new Channel(name, password);
Channels.Add(channel);
}
ChatUser.GlobalSendCommand(ChatCommand.AddChannel, name, "0");
return channel;
}
public static void RemoveChannel(string name)
{
RemoveChannel(FindChannelByName(name));
}
public static void RemoveChannel(Channel channel)
{
if (channel == null)
{
return;
}
if (Channels.Contains(channel) && channel.m_Users.Count == 0)
{
ChatUser.GlobalSendCommand(ChatCommand.RemoveChannel, channel.Name);
channel.m_Moderators.Clear();
channel.m_Voices.Clear();
Channels.Remove(channel);
}
}
public static Channel FindChannelByName(string name)
{
for (var i = 0; i < Channels.Count; ++i)
{
var channel = Channels[i];
if (channel.m_Name == name)
{
return channel;
}
}
return null;
}
public static void Initialize()
{
AddStaticChannel("Newbie Help");
}
public static void AddStaticChannel(string name)
{
AddChannel(name).AlwaysAvailable = true;
}
}
}