diff --git a/Core/src/Managed/Stellar.Core/Data/Catalog/Catalog.cs b/Core/src/Managed/Stellar.Core/Data/Catalog/Catalog.cs
new file mode 100644
index 0000000..f203007
--- /dev/null
+++ b/Core/src/Managed/Stellar.Core/Data/Catalog/Catalog.cs
@@ -0,0 +1,41 @@
+using Stellar.Core.Data.Collections;
+using Stellar.Kernel.Data.Catalog;
+
+namespace Stellar.Core.Data.Catalog;
+
+///
+/// The catalog of the engine: values by a key of their own, safe from any thread.
+///
+///
+/// A as an engine catalog: lookups take no lock, enumerations see a
+/// snapshot, tells what changed. A derived catalog brings keys to one
+/// form, refuses what it cannot hold and says what is missing, through the hooks of the map. A catalog refuses
+/// null values.
+///
+/// The key.
+/// The value.
+public class Catalog
+ : ConcurrentMap, ICatalog
+ where TKey : notnull
+{
+ ///
+ /// Makes an empty catalog.
+ ///
+ /// How keys compare; the default comparer of if null.
+ public Catalog(IEqualityComparer? comparer = null)
+ : base(comparer)
+ {
+ }
+
+ ///
+ public bool Contains(TKey key)
+ {
+ return ContainsKey(key);
+ }
+
+ ///
+ protected override void Validate(TKey key, TValue value)
+ {
+ if (value is null) throw new ArgumentNullException(nameof(value), $"No value for '{key}'");
+ }
+}
diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/CollectionChange.cs b/Core/src/Managed/Stellar.Core/Data/Collections/CollectionChange.cs
new file mode 100644
index 0000000..fae8a7f
--- /dev/null
+++ b/Core/src/Managed/Stellar.Core/Data/Collections/CollectionChange.cs
@@ -0,0 +1,123 @@
+namespace Stellar.Core.Data.Collections;
+
+///
+/// What happened to a collection.
+///
+public enum ChangeKind : byte
+{
+ /// An item came in.
+ Added,
+
+ /// An item went out.
+ Removed,
+
+ /// An item took the place of another.
+ Replaced,
+
+ /// Everything went out.
+ Cleared
+}
+
+///
+/// A change of a list or a set.
+///
+/// What happened.
+/// The item that came in or went out; for , the new one.
+/// Where, in a list; -1 in a set, or for .
+/// The item that was replaced; default otherwise.
+/// The type of the items.
+public readonly record struct CollectionChange(ChangeKind Kind, T Item, int Index = -1, T OldItem = default!);
+
+///
+/// A change of a map.
+///
+/// What happened.
+/// The key; default for .
+/// The value that came in or went out; for , the new one.
+/// The value that was replaced; default otherwise.
+/// The type of the keys.
+/// The type of the values.
+public readonly record struct MapChange(ChangeKind Kind, TKey Key, TValue Value, TValue OldValue = default!);
+
+///
+/// An array that stays valid until the collection changes: built once per change, then shared by every reader.
+///
+/// Builds the array from the collection as it is; made once, so a read allocates nothing.
+/// The type of the items.
+internal sealed class SnapshotCache(Func build)
+{
+ private int _version;
+ private volatile Holder? _holder;
+
+ ///
+ /// Marks the snapshot out of date: called after every change.
+ ///
+ public void Invalidate()
+ {
+ Interlocked.Increment(ref _version);
+ }
+
+ ///
+ /// Gets the snapshot, building it if the collection changed since.
+ ///
+ public T[] Get()
+ {
+ var version = Volatile.Read(ref _version);
+ var holder = _holder;
+ if (holder is not null && holder.Version == version) return holder.Items;
+
+ // Built after reading the version: a change in between only makes the next reader build again
+ var items = build();
+ _holder = new Holder(version, items);
+ return items;
+ }
+
+ private sealed class Holder(int version, T[] items)
+ {
+ public readonly int Version = version;
+ public readonly T[] Items = items;
+ }
+}
+
+///
+/// Enumerates a snapshot of a collection without allocating: what foreach over the collections of the engine uses.
+///
+/// The type of the items.
+public struct SnapshotEnumerator
+ : IEnumerator
+{
+ private readonly T[] _items;
+ private int _index;
+
+ internal SnapshotEnumerator(T[] items)
+ {
+ _items = items;
+ _index = -1;
+ }
+
+ ///
+ public readonly T Current => _items[_index];
+
+ readonly object? System.Collections.IEnumerator.Current => Current;
+
+ ///
+ public bool MoveNext()
+ {
+ var next = _index + 1;
+ if (next >= _items.Length) return false;
+
+ _index = next;
+ return true;
+ }
+
+ ///
+ public void Reset()
+ {
+ _index = -1;
+ }
+
+ ///
+ public readonly void Dispose()
+ {
+ }
+}
diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentIdentifierMap.cs b/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentIdentifierMap.cs
deleted file mode 100644
index 73a4ef1..0000000
--- a/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentIdentifierMap.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-using System.Collections.Concurrent;
-using Stellar.Kernel;
-
-namespace Stellar.Core.Data.Collections;
-
-///
-/// Thread-safe map keyed by identifier value.
-///
-/// The type of stored values.
-public sealed class ConcurrentIdentifierMap
- : ConcurrentDictionary
-{
- ///
- /// Creates an empty map.
- ///
- public ConcurrentIdentifierMap()
- : base(IdentifierComparer.Instance)
- {
- }
-
- ///
- /// Creates a map with initial data.
- ///
- /// The initial data.
- public ConcurrentIdentifierMap(IEnumerable> data)
- : base(data, IdentifierComparer.Instance)
- {
- }
-}
diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentList.cs b/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentList.cs
new file mode 100644
index 0000000..b32370c
--- /dev/null
+++ b/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentList.cs
@@ -0,0 +1,292 @@
+using System.Collections;
+
+namespace Stellar.Core.Data.Collections;
+
+///
+/// An ordered list, safe from any thread, for what is read far more often than it changes: the systems of a loop,
+/// the handlers of an event, the layers of a scene.
+///
+///
+/// Reads take no lock: the items live in an array that is never changed, a change makes a new one. Reading,
+/// indexing and enumerating see one consistent state, even while another thread changes the list; a writer pays a
+/// copy. For lists that change on every frame, a owned by one thread is the better tool.
+/// is raised after each change, out of the lock, on the thread that changed the list.
+///
+/// The type of the items.
+public sealed class ConcurrentList
+ : IReadOnlyList
+{
+ private readonly Lock _writing = new();
+ private readonly IEqualityComparer _comparer;
+ private volatile T[] _items;
+
+ ///
+ /// Makes a list.
+ ///
+ /// The first items, in order; none if null.
+ /// How items compare, for , , .
+ public ConcurrentList(IEnumerable? items = null, IEqualityComparer? comparer = null)
+ {
+ _items = items is null ? [] : items.ToArray();
+ _comparer = comparer ?? EqualityComparer.Default;
+ }
+
+ ///
+ /// Raised after each change, out of the lock.
+ ///
+ public event Action>? Changed;
+
+ ///
+ public int Count => _items.Length;
+
+ ///
+ /// Gets or replaces the item at an index.
+ ///
+ /// The index, from 0.
+ public T this[int index]
+ {
+ get => _items[index];
+ set
+ {
+ T old;
+ lock (_writing)
+ {
+ var items = (T[])_items.Clone();
+ old = items[index];
+ items[index] = value;
+ _items = items;
+ }
+
+ Changed?.Invoke(new CollectionChange(ChangeKind.Replaced, value, index, old));
+ }
+ }
+
+ ///
+ /// Gets the items as they are now, without a copy. The span never changes: a change of the list makes a new one.
+ ///
+ /// The items.
+ public ReadOnlySpan AsSpan()
+ {
+ return _items;
+ }
+
+ ///
+ /// Copies the items as they are now.
+ ///
+ /// A new array.
+ public T[] ToArray()
+ {
+ return (T[])_items.Clone();
+ }
+
+ ///
+ /// Copies a part of the list. A negative index counts from the end, as in Python: Slice(-2) is the last two.
+ ///
+ /// The first index.
+ /// The index after the last one; the end of the list if null.
+ /// A new array; empty if the range is.
+ public T[] Slice(int start, int? end = null)
+ {
+ var items = _items;
+ var from = Math.Clamp(start < 0 ? items.Length + start : start, 0, items.Length);
+ var to = Math.Clamp(end is null ? items.Length : end.Value < 0 ? items.Length + end.Value : end.Value, 0, items.Length);
+ return to <= from ? [] : items[from..to];
+ }
+
+ ///
+ /// Adds an item at the end.
+ ///
+ /// The item.
+ public void Add(T item)
+ {
+ int index;
+ lock (_writing)
+ {
+ index = _items.Length;
+ _items = [.. _items, item];
+ }
+
+ Changed?.Invoke(new CollectionChange(ChangeKind.Added, item, index));
+ }
+
+ ///
+ /// Adds items at the end, with one copy.
+ ///
+ /// The items, in order.
+ public void AddRange(IEnumerable items)
+ {
+ ArgumentNullException.ThrowIfNull(items);
+ var added = items.ToArray();
+ if (added.Length == 0) return;
+
+ int start;
+ lock (_writing)
+ {
+ start = _items.Length;
+ _items = [.. _items, .. added];
+ }
+
+ if (Changed is { } changed)
+ for (var i = 0; i < added.Length; i++) changed(new CollectionChange(ChangeKind.Added, added[i], start + i));
+ }
+
+ ///
+ /// Inserts an item at an index.
+ ///
+ /// Where; adds at the end.
+ /// The item.
+ public void Insert(int index, T item)
+ {
+ lock (_writing)
+ {
+ var items = _items;
+ ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)index, (uint)items.Length, nameof(index));
+ _items = [.. items.AsSpan(0, index), item, .. items.AsSpan(index)];
+ }
+
+ Changed?.Invoke(new CollectionChange(ChangeKind.Added, item, index));
+ }
+
+ ///
+ /// Removes the first occurrence of an item.
+ ///
+ /// The item.
+ /// true if it was there.
+ public bool Remove(T item)
+ {
+ int index;
+ T removed;
+ lock (_writing)
+ {
+ index = IndexOf(item);
+ if (index < 0) return false;
+ removed = RemoveAtLocked(index);
+ }
+
+ Changed?.Invoke(new CollectionChange(ChangeKind.Removed, removed, index));
+ return true;
+ }
+
+ ///
+ /// Removes the item at an index.
+ ///
+ /// The index.
+ /// The removed item.
+ public T RemoveAt(int index)
+ {
+ T removed;
+ lock (_writing)
+ {
+ ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual((uint)index, (uint)_items.Length, nameof(index));
+ removed = RemoveAtLocked(index);
+ }
+
+ Changed?.Invoke(new CollectionChange(ChangeKind.Removed, removed, index));
+ return removed;
+ }
+
+ ///
+ /// Removes and gives back the last item, as in Python.
+ ///
+ /// The item, or default.
+ /// true if the list had one.
+ public bool TryPop(out T item)
+ {
+ int index;
+ lock (_writing)
+ {
+ index = _items.Length - 1;
+ if (index < 0)
+ {
+ item = default!;
+ return false;
+ }
+
+ item = RemoveAtLocked(index);
+ }
+
+ Changed?.Invoke(new CollectionChange(ChangeKind.Removed, item, index));
+ return true;
+ }
+
+ ///
+ /// Removes every item.
+ ///
+ public void Clear()
+ {
+ lock (_writing)
+ {
+ if (_items.Length == 0) return;
+ _items = [];
+ }
+
+ Changed?.Invoke(new CollectionChange(ChangeKind.Cleared, default!));
+ }
+
+ ///
+ /// Sorts the list, as one change.
+ ///
+ /// The order; the default one of if null.
+ public void Sort(IComparer? comparer = null)
+ {
+ lock (_writing)
+ {
+ var items = (T[])_items.Clone();
+ Array.Sort(items, comparer);
+ _items = items;
+ }
+
+ Changed?.Invoke(new CollectionChange(ChangeKind.Replaced, default!));
+ }
+
+ ///
+ /// Gets the index of the first occurrence of an item.
+ ///
+ /// The item.
+ /// The index, or -1.
+ public int IndexOf(T item)
+ {
+ var items = _items;
+ for (var i = 0; i < items.Length; i++)
+ if (_comparer.Equals(items[i], item))
+ return i;
+
+ return -1;
+ }
+
+ ///
+ /// Gets whether an item is in the list.
+ ///
+ /// The item.
+ /// true if it is.
+ public bool Contains(T item)
+ {
+ return IndexOf(item) >= 0;
+ }
+
+ ///
+ /// Enumerates the items as they were when the enumeration started.
+ ///
+ public SnapshotEnumerator GetEnumerator()
+ {
+ return new SnapshotEnumerator(_items);
+ }
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
+
+ private T RemoveAtLocked(int index)
+ {
+ var items = _items;
+ var removed = items[index];
+ _items = [.. items.AsSpan(0, index), .. items.AsSpan(index + 1)];
+ return removed;
+ }
+}
diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentMap.cs b/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentMap.cs
new file mode 100644
index 0000000..9b1dace
--- /dev/null
+++ b/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentMap.cs
@@ -0,0 +1,325 @@
+using System.Collections;
+using System.Collections.Concurrent;
+using System.Diagnostics.CodeAnalysis;
+using System.Reflection;
+
+namespace Stellar.Core.Data.Collections;
+
+///
+/// Values by key, safe from any thread: lookups take no lock, enumerations see a snapshot.
+///
+///
+/// The snapshot is built once after a change and then shared by every reader. is raised
+/// after each change, on the thread that made it, with the old value of a replaced key.
+/// A derived map brings keys to one form (), refuses what it cannot hold
+/// () and says what is missing (): the catalogs of the engine are made
+/// this way. A key that cannot be brought to the form has no value: lookups answer no instead of throwing.
+///
+/// The type of the keys.
+/// The type of the values.
+public class ConcurrentMap
+ : IReadOnlyCollection>
+ where TKey : notnull
+{
+ // Whether a type of map brings keys to a form: a lookup in one that does not takes no virtual call and no try
+ private static readonly ConcurrentDictionary NormalizingTypes = new();
+
+ private readonly ConcurrentDictionary _items;
+ private readonly bool _normalizes;
+ private int _version;
+ private volatile View? _view;
+
+ ///
+ /// Makes an empty map.
+ ///
+ /// How keys compare; the default comparer of if null.
+ public ConcurrentMap(IEqualityComparer? comparer = null)
+ {
+ _items = new ConcurrentDictionary(comparer ?? EqualityComparer.Default);
+ _normalizes = GetType() != typeof(ConcurrentMap) && NormalizingTypes.GetOrAdd(GetType(),
+ static type => type.GetMethod(nameof(NormalizeKey), BindingFlags.Instance | BindingFlags.NonPublic, [typeof(TKey)])!
+ .DeclaringType != typeof(ConcurrentMap));
+ }
+
+ ///
+ /// Raised after each change, out of any lock.
+ ///
+ public event Action>? Changed;
+
+ ///
+ public int Count => _items.Count;
+
+ ///
+ /// Gets whether the map is empty.
+ ///
+ public bool IsEmpty => _items.IsEmpty;
+
+ ///
+ /// Gets the pairs as they are now: one array, shared until the map changes. Do not change it.
+ ///
+ public IReadOnlyList> Snapshot => CurrentView().Pairs;
+
+ ///
+ /// Gets the keys as they are now: one array, shared until the map changes.
+ ///
+ public IReadOnlyCollection Keys => CurrentView().Keys;
+
+ ///
+ /// Gets the values as they are now: one array, shared until the map changes.
+ ///
+ public IReadOnlyCollection Values => CurrentView().Values;
+
+ ///
+ /// Gets whether the map has a value for a key.
+ ///
+ /// The key.
+ /// true if it has one.
+ public bool ContainsKey(TKey key)
+ {
+ return TryNormalize(key, out var normalized) && _items.ContainsKey(normalized);
+ }
+
+ ///
+ /// Finds the value of a key.
+ ///
+ /// The key.
+ /// The value, or default.
+ /// true if the map has a value for the key.
+ public bool TryGet(TKey key, [MaybeNullWhen(false)] out TValue value)
+ {
+ if (TryNormalize(key, out var normalized)) return _items.TryGetValue(normalized, out value);
+
+ value = default;
+ return false;
+ }
+
+ ///
+ /// Gets the value of a key.
+ ///
+ /// The key.
+ /// The value.
+ /// Thrown if there is none, or the exception of .
+ public TValue Get(TKey key)
+ {
+ return TryGet(key, out var value) ? value : throw NotFound(key);
+ }
+
+ ///
+ /// Sets the value of a key, replacing the one it had.
+ ///
+ /// The key.
+ /// The value.
+ public void Set(TKey key, TValue value)
+ {
+ var normalized = NormalizeKey(key);
+ Validate(normalized, value);
+
+ while (true)
+ {
+ if (_items.TryGetValue(normalized, out var old))
+ {
+ if (!_items.TryUpdate(normalized, value, old)) continue;
+ OnChanged(new MapChange(ChangeKind.Replaced, normalized, value, old));
+ return;
+ }
+
+ if (!_items.TryAdd(normalized, value)) continue;
+ OnChanged(new MapChange(ChangeKind.Added, normalized, value));
+ return;
+ }
+ }
+
+ ///
+ /// Adds a value for a key that has none.
+ ///
+ /// The key.
+ /// The value.
+ /// true if it was added; false if the key already has a value, which stays.
+ public bool TryAdd(TKey key, TValue value)
+ {
+ var normalized = NormalizeKey(key);
+ Validate(normalized, value);
+ if (!_items.TryAdd(normalized, value)) return false;
+
+ OnChanged(new MapChange(ChangeKind.Added, normalized, value));
+ return true;
+ }
+
+ ///
+ /// Gets the value of a key, adding one made by a factory if it has none.
+ ///
+ /// The key.
+ /// Makes the value; may run even if another thread adds first, then its value is dropped.
+ /// The value of the key.
+ public TValue GetOrAdd(TKey key, Func factory)
+ {
+ ArgumentNullException.ThrowIfNull(factory);
+ var normalized = NormalizeKey(key);
+ if (_items.TryGetValue(normalized, out var existing)) return existing;
+
+ var value = factory(normalized);
+ Validate(normalized, value);
+ return TryAdd(normalized, value) ? value : _items[normalized];
+ }
+
+ ///
+ /// Removes the value of a key.
+ ///
+ /// The key.
+ /// true if there was one.
+ public bool Remove(TKey key)
+ {
+ return TryRemove(key, out _);
+ }
+
+ ///
+ /// Removes the value of a key and gives it back.
+ ///
+ /// The key.
+ /// The removed value, or default.
+ /// true if there was one.
+ public bool TryRemove(TKey key, [MaybeNullWhen(false)] out TValue value)
+ {
+ if (!TryNormalize(key, out var normalized) || !_items.TryRemove(normalized, out value))
+ {
+ value = default;
+ return false;
+ }
+
+ OnChanged(new MapChange(ChangeKind.Removed, normalized, value));
+ return true;
+ }
+
+ ///
+ /// Removes every value.
+ ///
+ public void Clear()
+ {
+ if (_items.IsEmpty) return;
+
+ _items.Clear();
+ OnChanged(new MapChange(ChangeKind.Cleared, default!, default!));
+ }
+
+ ///
+ /// Enumerates the pairs as they were when the enumeration started.
+ ///
+ public SnapshotEnumerator> GetEnumerator()
+ {
+ return new SnapshotEnumerator>(CurrentView().Pairs);
+ }
+
+ ///
+ /// Enumerates the values as they were when the enumeration started.
+ ///
+ public SnapshotEnumerator EnumerateValues()
+ {
+ return new SnapshotEnumerator(CurrentView().Values);
+ }
+
+ IEnumerator> IEnumerable>.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
+
+ ///
+ /// Brings a key to the form the map stores. The key as it is by default.
+ ///
+ /// The key.
+ /// The key in its form.
+ /// Thrown for a key the map cannot hold.
+ protected virtual TKey NormalizeKey(TKey key)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+ return key;
+ }
+
+ ///
+ /// Refuses a value the map cannot hold under a key. Accepts anything by default.
+ ///
+ /// The key, in its form.
+ /// The value.
+ /// Thrown for a value the map cannot hold.
+ protected virtual void Validate(TKey key, TValue value)
+ {
+ }
+
+ ///
+ /// Makes the exception of for a key without a value.
+ ///
+ /// The key, as it was asked for.
+ /// The exception.
+ protected virtual Exception NotFound(TKey key)
+ {
+ return new KeyNotFoundException($"Nothing for '{key}'");
+ }
+
+ private void OnChanged(MapChange change)
+ {
+ Interlocked.Increment(ref _version);
+ Changed?.Invoke(change);
+ }
+
+ // Built after reading the version: a change in between only makes the next reader build again
+ private View CurrentView()
+ {
+ var version = Volatile.Read(ref _version);
+ var view = _view;
+ if (view is not null && view.Version == version) return view;
+
+ view = new View(version, _items.ToArray());
+ _view = view;
+ return view;
+ }
+
+ // A key that cannot be held has no value: lookups answer no instead of throwing
+ private bool TryNormalize(TKey key, [MaybeNullWhen(false)] out TKey normalized)
+ {
+ if (!_normalizes)
+ {
+ normalized = key;
+ return key is not null;
+ }
+
+ try
+ {
+ normalized = NormalizeKey(key);
+ return true;
+ }
+ catch (ArgumentException)
+ {
+ normalized = default;
+ return false;
+ }
+ }
+
+ // The map at one version: the pairs, and the keys and the values made from them when first asked for
+ private sealed class View(int version, KeyValuePair[] pairs)
+ {
+ private TKey[]? _keys;
+ private TValue[]? _values;
+
+ public int Version { get; } = version;
+
+ public KeyValuePair[] Pairs { get; } = pairs;
+
+ // Two readers may both make them: either array is right
+ public TKey[] Keys => _keys ??= Project(Pairs, static pair => pair.Key);
+
+ public TValue[] Values => _values ??= Project(Pairs, static pair => pair.Value);
+
+ private static T[] Project(KeyValuePair[] pairs, Func, T> part)
+ {
+ if (pairs.Length == 0) return [];
+
+ var items = new T[pairs.Length];
+ for (var i = 0; i < pairs.Length; i++) items[i] = part(pairs[i]);
+ return items;
+ }
+ }
+}
diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentSet.cs b/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentSet.cs
new file mode 100644
index 0000000..873ea8e
--- /dev/null
+++ b/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentSet.cs
@@ -0,0 +1,182 @@
+using System.Collections;
+using System.Collections.Concurrent;
+
+namespace Stellar.Core.Data.Collections;
+
+///
+/// A set, safe from any thread: lookups take no lock, enumerations see a snapshot.
+///
+///
+/// The snapshot is built once after a change and then shared by every reader, so enumerating a set that
+/// does not change costs nothing. is raised after each change, on the thread that made it.
+/// The operations of sets (, , ) make new sets.
+///
+/// The type of the items.
+public sealed class ConcurrentSet
+ : IReadOnlyCollection
+ where T : notnull
+{
+ private readonly ConcurrentDictionary _items;
+ private readonly SnapshotCache _snapshot;
+
+ ///
+ /// Makes a set.
+ ///
+ /// The first items; none if null.
+ /// How items compare; the default comparer of if null.
+ public ConcurrentSet(IEnumerable? items = null, IEqualityComparer? comparer = null)
+ {
+ Comparer = comparer ?? EqualityComparer.Default;
+ _items = new ConcurrentDictionary(Comparer);
+ _snapshot = new SnapshotCache(() => _items.Keys.ToArray());
+ if (items is not null)
+ foreach (var item in items) _items.TryAdd(item, 0);
+ }
+
+ ///
+ /// Raised after each change, out of any lock.
+ ///
+ public event Action>? Changed;
+
+ ///
+ /// Gets how items compare.
+ ///
+ public IEqualityComparer Comparer { get; }
+
+ ///
+ public int Count => _items.Count;
+
+ ///
+ /// Gets the items as they are now: one array, shared until the set changes. Do not change it.
+ ///
+ public IReadOnlyList Snapshot => _snapshot.Get();
+
+ ///
+ /// Adds an item.
+ ///
+ /// The item.
+ /// true if it was not there.
+ public bool Add(T item)
+ {
+ if (!_items.TryAdd(item, 0)) return false;
+
+ _snapshot.Invalidate();
+ Changed?.Invoke(new CollectionChange(ChangeKind.Added, item));
+ return true;
+ }
+
+ ///
+ /// Adds items.
+ ///
+ /// The items.
+ /// How many were not there.
+ public int AddRange(IEnumerable items)
+ {
+ ArgumentNullException.ThrowIfNull(items);
+ var added = 0;
+ foreach (var item in items)
+ if (Add(item))
+ added++;
+ return added;
+ }
+
+ ///
+ /// Removes an item.
+ ///
+ /// The item.
+ /// true if it was there.
+ public bool Remove(T item)
+ {
+ if (!_items.TryRemove(item, out _)) return false;
+
+ _snapshot.Invalidate();
+ Changed?.Invoke(new CollectionChange(ChangeKind.Removed, item));
+ return true;
+ }
+
+ ///
+ /// Removes every item.
+ ///
+ public void Clear()
+ {
+ if (_items.IsEmpty) return;
+
+ _items.Clear();
+ _snapshot.Invalidate();
+ Changed?.Invoke(new CollectionChange(ChangeKind.Cleared, default!));
+ }
+
+ ///
+ /// Gets whether an item is in the set.
+ ///
+ /// The item.
+ /// true if it is.
+ public bool Contains(T item)
+ {
+ return _items.ContainsKey(item);
+ }
+
+ ///
+ /// Makes the set of the items of this set and of others.
+ ///
+ /// The other items.
+ /// A new set, with the comparer of this one.
+ public ConcurrentSet Union(IEnumerable other)
+ {
+ ArgumentNullException.ThrowIfNull(other);
+ return new ConcurrentSet(Snapshot.Concat(other), Comparer);
+ }
+
+ ///
+ /// Makes the set of the items of this set that are also in others.
+ ///
+ /// The other items.
+ /// A new set, with the comparer of this one.
+ public ConcurrentSet Intersect(IEnumerable other)
+ {
+ ArgumentNullException.ThrowIfNull(other);
+ var others = other.ToHashSet(Comparer);
+ return new ConcurrentSet(Snapshot.Where(others.Contains), Comparer);
+ }
+
+ ///
+ /// Makes the set of the items of this set that are not in others.
+ ///
+ /// The other items.
+ /// A new set, with the comparer of this one.
+ public ConcurrentSet Except(IEnumerable other)
+ {
+ ArgumentNullException.ThrowIfNull(other);
+ var others = other.ToHashSet(Comparer);
+ return new ConcurrentSet(Snapshot.Where(item => !others.Contains(item)), Comparer);
+ }
+
+ ///
+ /// Gets whether this set and others share an item.
+ ///
+ /// The other items.
+ /// true if they do.
+ public bool Overlaps(IEnumerable other)
+ {
+ ArgumentNullException.ThrowIfNull(other);
+ return other.Any(Contains);
+ }
+
+ ///
+ /// Enumerates the items as they were when the enumeration started.
+ ///
+ public SnapshotEnumerator GetEnumerator()
+ {
+ return new SnapshotEnumerator(_snapshot.Get());
+ }
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
+}
diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/ConstantTable.cs b/Core/src/Managed/Stellar.Core/Data/Collections/ConstantTable.cs
deleted file mode 100644
index ca98142..0000000
--- a/Core/src/Managed/Stellar.Core/Data/Collections/ConstantTable.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-using Stellar.Kernel;
-using Stellar.Kernel.Quantization;
-using Stellar.Core.Quantization;
-
-namespace Stellar.Core.Data.Collections;
-
-///
-/// Represents a quantum object that can only contain other identifiable quantum objects.
-///
-///
-public class ConstantTable
- : DataContainer
- where T : IIdentifiableQuantumObject
-{
- #region Constructors
-
- ///
- public ConstantTable(MetaQuant meta, FastConcurrentIdentifierMap data)
- : base(meta, data)
- {
- }
-
- ///
- public ConstantTable(MetaQuant meta, Dictionary data)
- : base(meta, data)
- {
- }
-
- ///
- public ConstantTable(MetaQuant meta)
- : base(meta)
- {
- }
-
- ///
- public ConstantTable()
- : base(new MetaQuant())
- {
- }
-
- #endregion
-
- #region item support
-
- ///
- public override IIdentifiableQuantumObject? Get(IIdentifier identifier)
- {
- return Data.GetValueOrDefault(identifier);
- }
-
- #endregion
-}
diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/DataContainer.cs b/Core/src/Managed/Stellar.Core/Data/Collections/DataContainer.cs
index fa1f314..3747c07 100644
--- a/Core/src/Managed/Stellar.Core/Data/Collections/DataContainer.cs
+++ b/Core/src/Managed/Stellar.Core/Data/Collections/DataContainer.cs
@@ -1,244 +1,149 @@
using System.Collections;
+using System.Diagnostics.CodeAnalysis;
using Stellar.Core.Data.Registry;
using Stellar.Core.Quantization;
-using Stellar.Kernel;
using Stellar.Kernel.Data.Collections;
-using Stellar.Kernel.Quantization;
+using Stellar.Kernel.Data.Registry;
namespace Stellar.Core.Data.Collections;
-///
-/// Type of stored data.
+///
+/// The base of the containers: items by key, a quant with an identity, always registered, sealable.
+///
///
-/// The membership lives on the native side, in , under the identifier of this
-/// container: native systems walk a container without calling managed code. This class keeps only the managed objects,
-/// so that it can hand them out.
-/// The native side is the source of truth: an item is stored here only after the native container accepted it.
+/// A new container goes into the registry of containers of the current engine (implicit registration, see
+/// ), so it can be found by its identifier from
+/// anywhere. Disposing it removes it from every registry it is in.
+/// Reads take no lock and enumerations see a snapshot ();
+/// tells what changed. fixes the contents for good.
///
-public abstract class DataContainer
- : Quant, IDataContainer, IEnumerable
- where T : IIdentifiableQuantumObject
+/// The key of an item.
+/// The item.
+public abstract class DataContainer
+ : Quant, IDataContainer
+ where TKey : notnull
{
- ///
- /// Gets the managed objects of the container.
- ///
- protected FastConcurrentIdentifierMap Data { get; }
-
- ///
- /// Gets the native containers.
- ///
- protected ContainerRegistry Native { get; } = Global.CoreEngine.Current.Native.Containers;
-
- // The registry of data containers of the engine the container was made in
- private readonly IQuantumObject _home = Global.CoreEngine.Current.Registry.DataContainers;
-
- #region Constructors
+ private volatile bool _sealed;
///
- /// Creates a container by using meta and typed data.
+ /// Makes a container.
///
- /// A meta quant of this container.
- /// Initial data for this container.
- protected DataContainer(MetaQuant meta, FastConcurrentIdentifierMap data)
- : base(meta)
+ /// Its primary meta; a new one if null.
+ /// How keys compare; the default comparer of if null.
+ protected DataContainer(MetaQuant? meta = null, IEqualityComparer? comparer = null)
+ : base(meta ?? new MetaQuant())
{
- ArgumentNullException.ThrowIfNull(data);
-
- Data = data;
- Native.Create(UID.UID);
+ Items = new ConcurrentMap(comparer);
+ Registrations = new Registrations(this);
- foreach (var item in data.GetSnapshot())
- Native.Add(UID.UID, item.UID.UID);
-
- if (IsReadOnly)
- Native.Seal(UID.UID);
-
- Register(_home);
+ // Called before the constructors of derived classes: an override returns a constant
+ if (RegistersImplicitly) Global.CoreEngine.Current.Registry.RegisterImplicitly(this, typeof(IDataContainer));
}
- ///
- /// Creates a container by using meta and data stored in a dictionary.
- ///
- /// A meta quant of this container.
- /// Initial data stored in a dictionary.
- protected DataContainer(MetaQuant meta, Dictionary data)
- : this(meta, new FastConcurrentIdentifierMap(data))
- {
- }
+ ///
+ public IRegistrations Registrations { get; }
///
- /// Creates a container by using meta only.
+ /// Raised after each change of the items, out of any lock.
///
- /// A meta quant of this container.
- protected DataContainer(MetaQuant meta)
- : this(meta, new FastConcurrentIdentifierMap())
+ public event Action>? Changed
{
+ add => Items.Changed += value;
+ remove => Items.Changed -= value;
}
- #endregion
-
- ///
- /// Gets a value indicating whether the content is fixed at creation.
- ///
- /// Read by the constructor of this class: an override must not depend on the state of the derived class.
- protected virtual bool IsReadOnly => true;
-
- ///
- /// Gets a container by its identifier.
- ///
- /// The identifier of the container.
- /// The container, or null if it is not registered.
- public static IDataContainer? GetContainer(IIdentifier identifier)
- {
- return Global.CoreEngine.Current.Registry.DataContainers.Get(identifier);
- }
+ ///
+ public int Count => Items.Count;
- #region Item support
+ ///
+ public bool IsEmpty => Items.IsEmpty;
///
- public abstract IIdentifiableQuantumObject? Get(IIdentifier identifier);
+ public bool IsSealed => _sealed;
- ///
- /// Stores a quantum object by its identifier.
- ///
- /// The object to store.
- /// true if the object was stored; otherwise, false.
- public virtual bool Set(IIdentifiableQuantumObject obj)
- {
- return false;
- }
+ ///
+ public IReadOnlyCollection Keys => Items.Keys;
- ///
- /// Attempts to remove and return the object stored in the container.
- ///
- /// The unique identifier of the object.
- /// The object if found; otherwise, default.
- public virtual T? Pop(IIdentifier id)
- {
- return default;
- }
+ ///
+ public IReadOnlyCollection Values => Items.Values;
///
- /// Base item operations with the container.
+ /// Gets the items, by key.
///
- /// The unique identifier of the object.
- /// Thrown if is not found in the container.
- public T this[IIdentifier key]
- {
- get => Get(key) is T value ? value : throw new KeyNotFoundException($"{key} is not in the container");
- set => Set(value);
- }
-
- #endregion
-
- #region Encapsulation
+ protected ConcurrentMap Items { get; }
///
- /// Updates the main snapshot with current values and clears the hot items list.
+ /// Gets whether a new container goes into the registries of the current engine by itself. true by default.
///
- ///
- /// Call this method once per frame before iteration. The method is thread-safe but acquires a write lock,
- /// so do not call it too frequently.
- ///
- public void RefreshSnapshot()
- {
- Data.RefreshSnapshot();
- }
+ protected virtual bool RegistersImplicitly => true;
///
- public bool ContainsKey(IIdentifier key)
+ public bool ContainsKey(TKey key)
{
- return key is not null && Native.Contains(UID.UID, key.UID);
+ return Items.ContainsKey(key);
}
///
- public bool Contains(IIdentifiableQuantumObject obj)
+ public bool TryGet(TKey key, [MaybeNullWhen(false)] out TValue value)
{
- return ContainsKey(obj.UID);
+ return Items.TryGet(key, out value);
}
///
- public int Count => Native.Count(UID.UID);
-
- ///
- public bool IsEmpty => Count == 0;
-
- ///
- /// Gets the values of the last snapshot.
- ///
- public T[] Values => Data.GetSnapshot();
-
- ///
- /// Gets the identifiers of the items, as the native side knows them. This is what is passed to native systems.
- ///
- public Guid[] Identifiers => Native.Items(UID.UID);
-
- ///
- /// Clears the container.
- ///
- /// false if the container is read-only.
- public bool Clear()
+ public TValue Get(TKey key)
{
- if (!Native.Clear(UID.UID))
- return false;
-
- Data.Clear();
- return true;
+ return Items.TryGet(key, out var value)
+ ? value
+ : throw new KeyNotFoundException($"{key} is not in {GetType().Name} {UID}");
}
///
- /// Executes an action for every element in the container, including hot items.
+ /// Fixes the contents for good: every change from now on throws.
///
- /// The action to perform on each element.
- ///
- /// Iterates first over the snapshot, then over hot items. The iteration is lock-free and thread-safe.
- ///
- public void ForEachReadOnly(Action action)
+ public void Seal()
{
- Data.ForEachReadOnly(action);
+ _sealed = true;
}
///
- /// Iterates over elements until a predicate returns false.
+ /// Enumerates the items as they were when the enumeration started.
///
- /// A function that receives an element and returns true to continue iteration.
- public void ForEachUntil(Func predicate)
+ public SnapshotEnumerator GetEnumerator()
{
- Data.ForEachUntil(predicate);
+ return Items.EnumerateValues();
}
- ///
- public IEnumerator GetEnumerator()
+ IEnumerator IEnumerable.GetEnumerator()
{
- return Data.GetEnumerator();
+ return GetEnumerator();
}
- ///
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
- #endregion
-
- ///
- public void Register(IQuantumObject? registry = null)
+ ///
+ /// Removes the container from every registry it is in.
+ ///
+ public virtual void Dispose()
{
- RegistryBinding.Register(registry ?? _home, this);
+ Registrations.UnregisterAll();
+ GC.SuppressFinalize(this);
}
///
- public void Unregister(IQuantumObject? registry = null)
+ public override string ToString()
{
- RegistryBinding.Unregister(registry ?? _home, UID);
+ return $"{GetType().Name} {UID} ({Count}{(IsSealed ? ", sealed" : "")})";
}
///
- /// Unregisters the container and destroys its native side.
+ /// Throws if the container is sealed: called before every change.
///
- public void Dispose()
+ /// Thrown if it is.
+ protected void ThrowIfSealed()
{
- Unregister();
- Native.Destroy(UID.UID);
+ if (_sealed) throw new InvalidOperationException($"{this} is sealed: its contents never change again");
}
}
diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/DataTable.cs b/Core/src/Managed/Stellar.Core/Data/Collections/DataTable.cs
new file mode 100644
index 0000000..0b521b1
--- /dev/null
+++ b/Core/src/Managed/Stellar.Core/Data/Collections/DataTable.cs
@@ -0,0 +1,77 @@
+using Stellar.Core.Quantization;
+
+namespace Stellar.Core.Data.Collections;
+
+///
+/// Rows of one type by name: tuning, loot, dialogue lines, the stats of the units.
+///
+///
+/// A container like the others: registered, found by its identifier, sealable. The rows are values of any
+/// type, a record or a struct, with no identity of their own: a row is its name. Names compare by ordinal and are
+/// not blank.
+/// Filled in code for now; loading tables from files comes with the assets.
+///
+/// The type of a row.
+public class DataTable
+ : DataContainer
+{
+ ///
+ /// Makes a data table.
+ ///
+ /// The first rows, by name; none if null.
+ /// Its primary meta; a new one if null.
+ public DataTable(IEnumerable>? rows = null, MetaQuant? meta = null)
+ : base(meta, StringComparer.Ordinal)
+ {
+ if (rows is null) return;
+ foreach (var (name, row) in rows) Add(name, row);
+ }
+
+ ///
+ /// Gets the type of a row.
+ ///
+ public Type RowType => typeof(TRow);
+
+ ///
+ /// Adds a row.
+ ///
+ /// Its name, not blank.
+ /// The row.
+ /// true if it was added; false if a row has the name.
+ /// Thrown if the table is sealed.
+ public bool Add(string name, TRow row)
+ {
+ ThrowIfSealed();
+ return Items.TryAdd(NameOf(name), row);
+ }
+
+ ///
+ /// Puts a row in, replacing the one with the name.
+ ///
+ /// Its name, not blank.
+ /// The row.
+ /// Thrown if the table is sealed.
+ public void Set(string name, TRow row)
+ {
+ ThrowIfSealed();
+ Items.Set(NameOf(name), row);
+ }
+
+ ///
+ /// Removes a row.
+ ///
+ /// Its name.
+ /// true if there was one.
+ /// Thrown if the table is sealed.
+ public bool Remove(string name)
+ {
+ ThrowIfSealed();
+ return Items.Remove(name);
+ }
+
+ private static string NameOf(string name)
+ {
+ if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("A row has a name", nameof(name));
+ return name;
+ }
+}
diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/FastConcurrentIdentifierMap.cs b/Core/src/Managed/Stellar.Core/Data/Collections/FastConcurrentIdentifierMap.cs
deleted file mode 100644
index 0909c7b..0000000
--- a/Core/src/Managed/Stellar.Core/Data/Collections/FastConcurrentIdentifierMap.cs
+++ /dev/null
@@ -1,317 +0,0 @@
-using System.Collections;
-using Stellar.Kernel;
-
-namespace Stellar.Core.Data.Collections;
-
-///
-/// High-performance thread-safe dictionary for keys.
-/// Uses snapshot-based iteration to avoid per-frame allocations and supports immediate visibility for "hot" items.
-///
-/// The type of stored values.
-///
-/// Optimized for read-heavy / iteration-heavy scenarios with rare writes.
-/// Iteration over the snapshot requires no locks and produces no garbage at runtime.
-/// Adding with immediate = true makes the item visible in the current frame without rebuilding the main
-/// snapshot.
-/// Typical usage in a game loop:
-///
-/// var map = new FastConcurrentIdentifierMap<GameObject>();
-/// // at the beginning of the frame
-/// map.RefreshSnapshot();
-/// // iteration
-/// map.ForEachReadOnly(obj => obj.Update(deltaTime));
-/// // add with immediate visibility
-/// map.TryAdd(newId, newObj, immediate: true);
-///
-///
-///
-public sealed class FastConcurrentIdentifierMap
- : IEnumerable
-{
- private readonly Dictionary _dict;
- private readonly ReaderWriterLockSlim _lock = new();
-
- // Both arrays are replaced, never mutated: a reader that grabbed one iterates it with no lock.
- private volatile T[] _snapshot;
- private volatile T[] _hotItems = [];
-
- ///
- /// Creates the map. Initial data is visible in the snapshot right away.
- ///
- /// The initial data.
- public FastConcurrentIdentifierMap(IEnumerable>? data = null)
- {
- _dict = new Dictionary(data ?? [], IdentifierComparer.Instance);
- _snapshot = _dict.Values.ToArray();
- }
-
- ///
- /// Updates the main snapshot with current dictionary values and clears the hot items list.
- ///
- ///
- /// Call this method once per frame before iteration. The method is thread-safe but acquires a write lock,
- /// so do not call it too frequently.
- ///
- public void RefreshSnapshot()
- {
- _lock.EnterWriteLock();
- try
- {
- RebuildSnapshot();
- }
- finally
- {
- _lock.ExitWriteLock();
- }
- }
-
- // Must be called with the write lock held.
- private void RebuildSnapshot()
- {
- var newSnapshot = new T[_dict.Count];
- _dict.Values.CopyTo(newSnapshot, 0);
-
- _snapshot = newSnapshot;
- _hotItems = [];
- }
-
- ///
- /// Returns the value associated with the specified key, or default if the key does not exist.
- ///
- /// The key.
- /// The value, or default.
- public T? GetValueOrDefault(IIdentifier key)
- {
- return TryGetValue(key, out var value) ? value : default;
- }
-
- ///
- /// Attempts to retrieve the value for the specified key.
- ///
- /// The key.
- /// The found value, or default if not found.
- /// true if the key was found; otherwise, false.
- public bool TryGetValue(IIdentifier key, out T? value)
- {
- if (key is null)
- {
- value = default;
- return false;
- }
-
- _lock.EnterReadLock();
- try
- {
- return _dict.TryGetValue(key, out value);
- }
- finally
- {
- _lock.ExitReadLock();
- }
- }
-
- ///
- /// Adds an element to the dictionary.
- ///
- /// The key.
- /// The value.
- ///
- /// If true, the element becomes visible in the current frame (added to the hot list).
- /// If false, it becomes visible only after the next call.
- ///
- /// true if the addition succeeded; false if the key already exists.
- public bool TryAdd(IIdentifier key, T value, bool immediate = false)
- {
- if (key is null) return false;
-
- _lock.EnterWriteLock();
- try
- {
- if (!_dict.TryAdd(key, value)) return false;
-
- if (immediate)
- _hotItems = [.. _hotItems, value];
-
- return true;
- }
- finally
- {
- _lock.ExitWriteLock();
- }
- }
-
- ///
- /// Removes an element from the dictionary and immediately updates the snapshot.
- ///
- /// The key.
- /// The removed value, or default.
- /// true if the element was removed; otherwise, false.
- ///
- /// This method rebuilds the snapshot inside the write lock, which may be expensive for bulk removals.
- /// For mass deletions, consider using .
- ///
- public bool TryRemove(IIdentifier key, out T? value)
- {
- if (key is null)
- {
- value = default;
- return false;
- }
-
- _lock.EnterWriteLock();
- try
- {
- if (!_dict.Remove(key, out value)) return false;
-
- RebuildSnapshot();
- return true;
- }
- finally
- {
- _lock.ExitWriteLock();
- }
- }
-
- ///
- /// Removes an element from the dictionary without updating the snapshot.
- ///
- /// The key.
- /// The removed value, or default.
- /// true if the element was removed; otherwise, false.
- ///
- /// The element will disappear from iterations only after the next call.
- /// Useful for bulk removals to avoid repeated snapshot copies.
- ///
- public bool TryRemoveDeferred(IIdentifier key, out T? value)
- {
- if (key is null)
- {
- value = default;
- return false;
- }
-
- _lock.EnterWriteLock();
- try
- {
- return _dict.Remove(key, out value);
- }
- finally
- {
- _lock.ExitWriteLock();
- }
- }
-
- ///
- /// Checks whether the dictionary contains the specified key.
- ///
- public bool ContainsKey(IIdentifier key)
- {
- if (key is null) return false;
-
- _lock.EnterReadLock();
- try
- {
- return _dict.ContainsKey(key);
- }
- finally
- {
- _lock.ExitReadLock();
- }
- }
-
- ///
- /// Gets the number of elements contained in the dictionary.
- ///
- public int Count
- {
- get
- {
- _lock.EnterReadLock();
- try
- {
- return _dict.Count;
- }
- finally
- {
- _lock.ExitReadLock();
- }
- }
- }
-
- ///
- /// Indicates whether the dictionary is empty.
- ///
- public bool IsEmpty => Count == 0;
-
- ///
- /// Removes all keys and values from the dictionary and clears the snapshot.
- ///
- public void Clear()
- {
- _lock.EnterWriteLock();
- try
- {
- _dict.Clear();
- RebuildSnapshot();
- }
- finally
- {
- _lock.ExitWriteLock();
- }
- }
-
- ///
- /// Returns the current snapshot of all values (without hot items).
- ///
- /// An array of values as of the last snapshot rebuild.
- public T[] GetSnapshot()
- {
- return _snapshot;
- }
-
- ///
- /// Executes an action for every element in the dictionary, including hot items.
- ///
- /// The action to perform on each element.
- ///
- /// Iterates first over the snapshot, then over hot items. The iteration is lock-free and thread-safe.
- ///
- public void ForEachReadOnly(Action action)
- {
- foreach (var item in _snapshot)
- action(item);
-
- foreach (var item in _hotItems)
- action(item);
- }
-
- ///
- /// Iterates over elements until a predicate returns false.
- ///
- /// A function that receives an element and returns true to continue iteration.
- public void ForEachUntil(Func predicate)
- {
- foreach (var item in _snapshot)
- if (!predicate(item))
- return;
-
- foreach (var item in _hotItems)
- if (!predicate(item))
- return;
- }
-
- ///
- /// Returns an enumerator that iterates only over the main snapshot (excluding hot items).
- ///
- /// Use if you need to include hot items.
- public IEnumerator GetEnumerator()
- {
- return ((IEnumerable)_snapshot).GetEnumerator();
- }
-
- ///
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
-}
diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/IdentifierComparer.cs b/Core/src/Managed/Stellar.Core/Data/Collections/IdentifierComparer.cs
deleted file mode 100644
index c9c05f1..0000000
--- a/Core/src/Managed/Stellar.Core/Data/Collections/IdentifierComparer.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-using Stellar.Kernel;
-
-namespace Stellar.Core.Data.Collections;
-
-///
-/// Compares identifiers by value: two instances with the same UID are equal,
-/// whatever their implementation is.
-///
-public sealed class IdentifierComparer
- : IEqualityComparer
-{
- ///
- /// Gets the shared instance.
- ///
- public static IdentifierComparer Instance { get; } = new();
-
- private IdentifierComparer()
- {
- }
-
- ///
- public bool Equals(IIdentifier? x, IIdentifier? y)
- {
- return ReferenceEquals(x, y) || (x is not null && y is not null && x.UID == y.UID);
- }
-
- ///
- public int GetHashCode(IIdentifier obj)
- {
- return obj.UID.GetHashCode();
- }
-}
diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/Roster.cs b/Core/src/Managed/Stellar.Core/Data/Collections/Roster.cs
index 5acbdf9..78f563a 100644
--- a/Core/src/Managed/Stellar.Core/Data/Collections/Roster.cs
+++ b/Core/src/Managed/Stellar.Core/Data/Collections/Roster.cs
@@ -5,134 +5,119 @@
namespace Stellar.Core.Data.Collections;
///
-/// Represents a quantum object that can contain and manage other identifiable quantum objects.
-/// Roster can store other Rosters in the Graph structure.
+/// A table with branches: rosters inside a roster, such as the teams of the players, the squads of a team.
///
-/// The tree of branches is native as well: native systems walk it by identifiers.
-///
+///
+/// A branch is a roster of its own: registered, found by its identifier, with its own objects. A roster never
+/// holds itself, at any depth. looks through the roster and every branch below it.
+///
+/// The type of the objects: a base class or a contract.
public class Roster
- : WritableTable
- where T : IIdentifiableQuantumObject
+ : Table
+ where T : class, IIdentifiableQuantumObject
{
- #region Constructors
+ private readonly ConcurrentMap> _branches = new();
///
- /// Creates a roster with typed data and branches.
+ /// Makes a roster.
///
- public Roster(MetaQuant meta, FastConcurrentIdentifierMap data,
- IEnumerable>> branches)
- : base(meta, data)
+ /// The first objects; none if null.
+ /// Its primary meta; a new one if null.
+ public Roster(IEnumerable? items = null, MetaQuant? meta = null)
+ : base(items, meta)
{
- Branches = new ConcurrentIdentifierMap>();
-
- foreach (var branch in branches)
- SaveBranch(branch.Value);
}
///
- /// Creates a roster with data and branches.
+ /// Gets a snapshot of the branches right below.
///
- public Roster(MetaQuant metaData, Dictionary data,
- IEnumerable>> branches)
- : this(metaData, new FastConcurrentIdentifierMap(data), branches)
- {
- }
+ public IReadOnlyCollection> Branches => _branches.Values;
///
- /// Creates a roster with data.
+ /// Adds a branch.
///
- public Roster(MetaQuant metaData, Dictionary data)
- : this(metaData, data, new Dictionary>())
+ /// The roster to add below this one.
+ /// true if it was added; false if it was there.
+ /// Thrown if the branch is this roster or holds it.
+ /// Thrown if the roster is sealed.
+ public bool AddBranch(Roster branch)
{
+ ArgumentNullException.ThrowIfNull(branch);
+ ThrowIfSealed();
+ if (ReferenceEquals(branch, this) || branch.Holds(this))
+ throw new ArgumentException($"{branch} holds {this}: a roster never holds itself", nameof(branch));
+
+ return _branches.TryAdd(branch.UID, branch);
}
///
- /// Creates an empty roster.
+ /// Makes a new branch below this roster.
///
- public Roster(MetaQuant metaData)
- : this(metaData, new Dictionary())
+ /// Its first objects; none if null.
+ /// The branch.
+ public Roster NewBranch(IEnumerable? items = null)
{
+ var branch = new Roster(items);
+ AddBranch(branch);
+ return branch;
}
///
- /// Creates an empty roster with a new meta quant.
+ /// Removes a branch right below.
///
- public Roster()
- : this(new MetaQuant())
+ /// The identifier of the branch.
+ /// The removed branch, or null if there was none.
+ /// Thrown if the roster is sealed.
+ public Roster? RemoveBranch(Identifier id)
{
+ ThrowIfSealed();
+ return _branches.TryRemove(id, out var branch) ? branch : null;
}
- #endregion
-
///
- /// Gets the managed objects of the nested rosters.
+ /// Finds a branch right below.
///
- public ConcurrentIdentifierMap> Branches { get; }
-
- #region Branch operations
-
- ///
- /// Gets a branch.
- ///
- /// Thrown if there is no such branch.
- public Roster GetBranch(IIdentifier identifier)
+ /// The identifier of the branch.
+ /// The branch, or null.
+ /// true if there is one.
+ public bool TryGetBranch(Identifier id, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out Roster? branch)
{
- return Branches.GetValueOrDefault(identifier) ??
- throw new KeyNotFoundException($"{identifier} is not a branch");
+ return _branches.TryGet(id, out branch);
}
///
- /// Adds a branch.
+ /// Gets a branch right below.
///
- /// false if it is already there.
- public bool SaveBranch(Roster branch)
+ /// The identifier of the branch.
+ /// The branch.
+ /// Thrown if there is none.
+ public Roster GetBranch(Identifier id)
{
- ArgumentNullException.ThrowIfNull(branch);
-
- if (!Native.AddBranch(UID.UID, branch.UID.UID))
- return false;
-
- return Branches.TryAdd(branch.UID, branch);
+ return TryGetBranch(id, out var branch) ? branch : throw new KeyNotFoundException($"{id} is not a branch of {this}");
}
///
- /// Removes a branch.
+ /// Finds an object in this roster or in any branch below it.
///
- /// The branch, or null if there is no such branch.
- public Roster? PopBranch(IIdentifier identifier)
+ /// The identifier of the object.
+ /// The object, or null.
+ public T? Find(Identifier id)
{
- if (identifier is null || !Native.RemoveBranch(UID.UID, identifier.UID))
- return null;
+ if (TryGet(id, out var item)) return item;
- Branches.TryRemove(identifier, out var branch);
- return branch;
- }
+ foreach (var (_, branch) in _branches.Snapshot)
+ if (branch.Find(id) is { } found)
+ return found;
- ///
- /// Creates and adds a branch with data.
- ///
- public Roster NewBranch(MetaQuant meta, Dictionary data)
- {
- var branch = new Roster(meta, data);
- SaveBranch(branch);
- return branch;
+ return null;
}
- ///
- /// Creates and adds an empty branch.
- ///
- public Roster NewBranch(MetaQuant metaData)
+ private bool Holds(Roster roster)
{
- return NewBranch(metaData, new Dictionary());
- }
+ foreach (var (_, branch) in _branches.Snapshot)
+ if (ReferenceEquals(branch, roster) || branch.Holds(roster))
+ return true;
- ///
- /// Checks for a branch.
- ///
- public bool ContainsBranch(IIdentifier identifier)
- {
- return identifier is not null && Native.ContainsBranch(UID.UID, identifier.UID);
+ return false;
}
-
- #endregion
}
diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/Table.cs b/Core/src/Managed/Stellar.Core/Data/Collections/Table.cs
new file mode 100644
index 0000000..c093a36
--- /dev/null
+++ b/Core/src/Managed/Stellar.Core/Data/Collections/Table.cs
@@ -0,0 +1,89 @@
+using Stellar.Core.Quantization;
+using Stellar.Kernel;
+using Stellar.Kernel.Quantization;
+
+namespace Stellar.Core.Data.Collections;
+
+///
+/// Objects of the engine by their identifiers: a container of the world.
+///
+///
+/// A table is found in the registry of containers of its engine, and finds its objects as what they are:
+/// table.Get<Player>(id) is a checked cast, null when the object is not a player.
+///
+/// The type of the objects: a base class or a contract.
+public class Table
+ : DataContainer
+ where T : class, IIdentifiableQuantumObject
+{
+ ///
+ /// Makes a table.
+ ///
+ /// The first objects; none if null.
+ /// Its primary meta; a new one if null.
+ public Table(IEnumerable? items = null, MetaQuant? meta = null)
+ : base(meta)
+ {
+ if (items is null) return;
+ foreach (var item in items) Add(item);
+ }
+
+ ///
+ /// Finds an object of a derived type.
+ ///
+ /// The type the object is expected to be.
+ /// Its identifier.
+ /// The object, or null if there is none or it is not a .
+ public TItem? Get(Identifier id)
+ where TItem : class, T
+ {
+ return Items.TryGet(id, out var item) ? item as TItem : null;
+ }
+
+ ///
+ /// Adds an object.
+ ///
+ /// The object.
+ /// true if it was added; false if an object with its identifier is there.
+ /// Thrown if the table is sealed.
+ public bool Add(T item)
+ {
+ ArgumentNullException.ThrowIfNull(item);
+ ThrowIfSealed();
+ return Items.TryAdd(item.UID, item);
+ }
+
+ ///
+ /// Puts an object in, replacing the one with its identifier.
+ ///
+ /// The object.
+ /// Thrown if the table is sealed.
+ public void Set(T item)
+ {
+ ArgumentNullException.ThrowIfNull(item);
+ ThrowIfSealed();
+ Items.Set(item.UID, item);
+ }
+
+ ///
+ /// Removes an object.
+ ///
+ /// Its identifier.
+ /// The removed object, or null if there was none.
+ /// Thrown if the table is sealed.
+ public T? Remove(Identifier id)
+ {
+ ThrowIfSealed();
+ return Items.TryRemove(id, out var item) ? item : null;
+ }
+
+ ///
+ /// Removes every object.
+ ///
+ /// Thrown if the table is sealed.
+ public void Clear()
+ {
+ ThrowIfSealed();
+ Items.Clear();
+ }
+}
diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/WritableTable.cs b/Core/src/Managed/Stellar.Core/Data/Collections/WritableTable.cs
deleted file mode 100644
index ba3095a..0000000
--- a/Core/src/Managed/Stellar.Core/Data/Collections/WritableTable.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-using Stellar.Core.Quantization;
-using Stellar.Kernel;
-using Stellar.Kernel.Quantization;
-
-namespace Stellar.Core.Data.Collections;
-
-///
-/// Represents a quantum object that can contain and manage other identifiable quantum objects.
-///
-///
-public class WritableTable
- : ConstantTable
- where T : IIdentifiableQuantumObject
-{
- #region Constructors
-
- ///
- public WritableTable(MetaQuant meta, FastConcurrentIdentifierMap data)
- : base(meta, data)
- {
- }
-
- ///
- public WritableTable(MetaQuant meta, Dictionary data)
- : base(meta, data)
- {
- }
-
- ///
- public WritableTable(MetaQuant meta)
- : base(meta)
- {
- }
-
- ///
- public WritableTable()
- {
- }
-
- #endregion
-
- ///
- protected override bool IsReadOnly => false;
-
- #region Item support
-
- ///
- public override bool Set(IIdentifiableQuantumObject obj)
- {
- if (obj is not T typed || !Native.Add(UID.UID, obj.UID.UID))
- return false;
-
- return Data.TryAdd(obj.UID, typed, true);
- }
-
- ///
- public override T? Pop(IIdentifier id)
- {
- if (id is null || !Native.Remove(UID.UID, id.UID))
- return default;
-
- Data.TryRemove(id, out var quant);
- return quant;
- }
-
- #endregion
-}
diff --git a/Core/src/Managed/Stellar.Core/Data/Registry/ConcurrentRegistry.cs b/Core/src/Managed/Stellar.Core/Data/Registry/ConcurrentRegistry.cs
deleted file mode 100644
index bdfa95c..0000000
--- a/Core/src/Managed/Stellar.Core/Data/Registry/ConcurrentRegistry.cs
+++ /dev/null
@@ -1,72 +0,0 @@
-using System.Collections.Concurrent;
-using Stellar.Kernel;
-using Stellar.Kernel.Data.Registry;
-using Stellar.Kernel.Quantization;
-
-namespace Stellar.Core.Data.Registry;
-
-///
-/// Thread-safe base of the engine registries.
-///
-/// The type of stored objects.
-public abstract class ConcurrentRegistry
- : IRegistry
- where T : class, IRegistrableQuantumObject
-{
- private readonly ConcurrentDictionary _items = new();
-
- ///
- /// Gets the identifier an object is stored under.
- ///
- protected abstract IIdentifier IdentifierOf(T obj);
-
- ///
- public bool Exists(IIdentifier id)
- {
- return id is not null && _items.ContainsKey(id.UID);
- }
-
- ///
- public virtual bool Register(T obj)
- {
- ArgumentNullException.ThrowIfNull(obj);
- return _items.TryAdd(IdentifierOf(obj).UID, obj);
- }
-
- ///
- public T? Get(IIdentifier id)
- {
- return id is null ? null : Get(id.UID);
- }
-
- ///
- /// Retrieves a registered object by the value of its identifier.
- ///
- public T? Get(Guid uid)
- {
- return _items.GetValueOrDefault(uid);
- }
-
- ///
- public T? Pop(IIdentifier id)
- {
- return id is null ? null : Pop(id.UID);
- }
-
- ///
- /// Removes and returns a registered object by the value of its identifier.
- ///
- public virtual T? Pop(Guid uid)
- {
- return _items.TryRemove(uid, out var obj) ? obj : null;
- }
-
- ///
- public int Size => _items.Count;
-
- ///
- public ICollection Keys => _items.Values.Select(IdentifierOf).ToArray();
-
- ///
- public ICollection Values => _items.Values.ToArray();
-}
diff --git a/Core/src/Managed/Stellar.Core/Data/Registry/DataContainerRegistry.cs b/Core/src/Managed/Stellar.Core/Data/Registry/DataContainerRegistry.cs
deleted file mode 100644
index 2b077e8..0000000
--- a/Core/src/Managed/Stellar.Core/Data/Registry/DataContainerRegistry.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using Stellar.Kernel;
-using Stellar.Kernel.Data.Collections;
-
-namespace Stellar.Core.Data.Registry;
-
-///
-/// Global registry of data containers.
-///
-public sealed class DataContainerRegistry
- : ConcurrentRegistry
-{
- ///
- /// Creates an empty registry. Each engine has one ().
- ///
- public DataContainerRegistry()
- {
- }
-
- ///
- protected override IIdentifier IdentifierOf(IDataContainer obj)
- {
- return obj.UID;
- }
-}
diff --git a/Core/src/Managed/Stellar.Core/Data/Registry/MetaQuantsRegistry.cs b/Core/src/Managed/Stellar.Core/Data/Registry/MetaQuantsRegistry.cs
deleted file mode 100644
index d79703f..0000000
--- a/Core/src/Managed/Stellar.Core/Data/Registry/MetaQuantsRegistry.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using Stellar.Kernel;
-using Stellar.Kernel.Quantization;
-
-namespace Stellar.Core.Data.Registry;
-
-///
-/// Global registry of the meta quants of one type.
-///
-/// The type of stored meta quants.
-public sealed class MetaQuantsRegistry
- : ConcurrentRegistry
- where TMeta : class, IRegistrableMetaQuant
-{
- ///
- /// Creates an empty registry. Each engine has one ().
- ///
- public MetaQuantsRegistry()
- {
- }
-
- ///
- protected override IIdentifier IdentifierOf(TMeta obj)
- {
- return obj.UID;
- }
-}
diff --git a/Core/src/Managed/Stellar.Core/Data/Registry/QuantsRegistry.cs b/Core/src/Managed/Stellar.Core/Data/Registry/QuantsRegistry.cs
deleted file mode 100644
index fd01884..0000000
--- a/Core/src/Managed/Stellar.Core/Data/Registry/QuantsRegistry.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using Stellar.Kernel;
-using Stellar.Kernel.Quantization;
-
-namespace Stellar.Core.Data.Registry;
-
-///
-/// Global registry of the quants of one type.
-///
-/// The type of stored quants.
-public sealed class QuantsRegistry
- : ConcurrentRegistry
- where T : class, IRegistrableQuant
-{
- ///
- /// Creates an empty registry. Each engine has one ().
- ///
- public QuantsRegistry()
- {
- }
-
- ///
- protected override IIdentifier IdentifierOf(T obj)
- {
- return obj.UID;
- }
-}
diff --git a/Core/src/Managed/Stellar.Core/Data/Registry/Registrations.cs b/Core/src/Managed/Stellar.Core/Data/Registry/Registrations.cs
new file mode 100644
index 0000000..73a6a72
--- /dev/null
+++ b/Core/src/Managed/Stellar.Core/Data/Registry/Registrations.cs
@@ -0,0 +1,76 @@
+using System.Collections;
+using Stellar.Core.Data.Collections;
+using Stellar.Kernel.Data.Registry;
+using Stellar.Kernel.Quantization;
+
+namespace Stellar.Core.Data.Registry;
+
+///
+/// The registries an object is in, kept by the registries themselves.
+///
+/// The object.
+public sealed class Registrations(IRegistrableQuantumObject owner)
+ : IRegistrations
+{
+ // Replaced on change, never mutated: readers need no lock, a writer swaps it whole
+ private IRegistry[] _registries = [];
+
+ ///
+ public int Count => Volatile.Read(ref _registries).Length;
+
+ ///
+ public bool Contains(IRegistry registry)
+ {
+ return Array.IndexOf(Volatile.Read(ref _registries), registry) >= 0;
+ }
+
+ ///
+ public void OnRegistered(IRegistry registry)
+ {
+ ArgumentNullException.ThrowIfNull(registry);
+ while (true)
+ {
+ var current = Volatile.Read(ref _registries);
+ if (Array.IndexOf(current, registry) >= 0) return;
+ if (Interlocked.CompareExchange(ref _registries, [.. current, registry], current) == current) return;
+ }
+ }
+
+ ///
+ public void OnUnregistered(IRegistry registry)
+ {
+ ArgumentNullException.ThrowIfNull(registry);
+ while (true)
+ {
+ var current = Volatile.Read(ref _registries);
+ var index = Array.IndexOf(current, registry);
+ if (index < 0) return;
+
+ IRegistry[] next = current.Length == 1 ? [] : [.. current.AsSpan(0, index), .. current.AsSpan(index + 1)];
+ if (Interlocked.CompareExchange(ref _registries, next, current) == current) return;
+ }
+ }
+
+ ///
+ public void UnregisterAll()
+ {
+ // Each registry tells back, which takes it off this list
+ foreach (var registry in Volatile.Read(ref _registries)) registry.Unregister(owner.UID);
+ }
+
+ ///
+ public SnapshotEnumerator GetEnumerator()
+ {
+ return new SnapshotEnumerator(Volatile.Read(ref _registries));
+ }
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
+}
diff --git a/Core/src/Managed/Stellar.Core/Data/Registry/Registry.cs b/Core/src/Managed/Stellar.Core/Data/Registry/Registry.cs
new file mode 100644
index 0000000..0a56e57
--- /dev/null
+++ b/Core/src/Managed/Stellar.Core/Data/Registry/Registry.cs
@@ -0,0 +1,119 @@
+using System.Collections.Concurrent;
+using Stellar.Core.Data.Collections;
+using Stellar.Kernel;
+using Stellar.Kernel.Data.Registry;
+using Stellar.Kernel.Quantization;
+
+namespace Stellar.Core.Data.Registry;
+
+///
+/// The registry of the engine: objects of one type by their identifiers, safe from any thread.
+///
+///
+/// Each engine has one registry per type (), and a registry can
+/// also be made on its own. It tells every object it takes and lets go ().
+///
+/// The type of the objects: a base class or a contract.
+public sealed class Registry
+ : IRegistry, IUntypedRegistry
+ where T : class, IRegistrableQuantumObject
+{
+ private readonly ConcurrentDictionary _items = new();
+ private readonly SnapshotCache _keys;
+ private readonly SnapshotCache _values;
+
+ ///
+ /// Makes an empty registry.
+ ///
+ public Registry()
+ {
+ _keys = new SnapshotCache(() => [.. _items.Keys]);
+ _values = new SnapshotCache(() => [.. _items.Values]);
+ }
+
+ ///
+ public Type ItemType => typeof(T);
+
+ ///
+ public int Size => _items.Count;
+
+ ///
+ public ICollection Keys => _keys.Get();
+
+ ///
+ public ICollection Values => _values.Get();
+
+ ///
+ public bool Register(T item)
+ {
+ ArgumentNullException.ThrowIfNull(item);
+ if (item.UID.IsEmpty) throw new ArgumentException("An object without an identifier cannot be registered", nameof(item));
+ if (!_items.TryAdd(item.UID, item)) return false;
+
+ Changed();
+ item.Registrations.OnRegistered(this);
+ return true;
+ }
+
+ ///
+ public bool Exists(Identifier id)
+ {
+ return _items.ContainsKey(id);
+ }
+
+ ///
+ public T? Get(Identifier id)
+ {
+ return _items.GetValueOrDefault(id);
+ }
+
+ ///
+ public TItem? Get(Identifier id)
+ where TItem : class, T
+ {
+ return _items.GetValueOrDefault(id) as TItem;
+ }
+
+ ///
+ public T? Pop(Identifier id)
+ {
+ if (!_items.TryRemove(id, out var item)) return null;
+
+ Changed();
+ item.Registrations.OnUnregistered(this);
+ return item;
+ }
+
+ ///
+ public bool Unregister(Identifier id)
+ {
+ return Pop(id) is not null;
+ }
+
+ bool IUntypedRegistry.Register(IRegistrableQuantumObject item)
+ {
+ return Register(item as T ?? throw new ArgumentException(
+ $"{item.GetType().Name} is not a {typeof(T).Name}: it cannot be in this registry", nameof(item)));
+ }
+
+ ///
+ public override string ToString()
+ {
+ return $"Registry of {typeof(T).Name} ({Size})";
+ }
+
+ private void Changed()
+ {
+ _keys.Invalidate();
+ _values.Invalidate();
+ }
+}
+
+///
+/// A registry reached by the type of its objects at run time: the implicit registration of Stellar.Core.
+///
+internal interface IUntypedRegistry
+ : IRegistry
+{
+ bool Register(IRegistrableQuantumObject item);
+}
diff --git a/Core/src/Managed/Stellar.Core/Data/Registry/RegistryBinding.cs b/Core/src/Managed/Stellar.Core/Data/Registry/RegistryBinding.cs
deleted file mode 100644
index 088d560..0000000
--- a/Core/src/Managed/Stellar.Core/Data/Registry/RegistryBinding.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-using Stellar.Kernel;
-using Stellar.Kernel.Data.Registry;
-using Stellar.Kernel.Quantization;
-
-namespace Stellar.Core.Data.Registry;
-
-///
-/// Implements the contract on top of a concrete registry type.
-///
-///
-/// takes a plain quantum object, so a wrong registry can only be
-/// detected at runtime. It is reported instead of being ignored: a silent no-op here means an object that
-/// quietly never gets registered.
-///
-internal static class RegistryBinding
-{
- public static void Register(IQuantumObject registry, T item)
- where T : IRegistrableQuantumObject
- {
- Cast(registry).Register(item);
- }
-
- public static void Unregister(IQuantumObject registry, IIdentifier id)
- where T : IRegistrableQuantumObject
- {
- Cast(registry).Pop(id);
- }
-
- private static IRegistry Cast(IQuantumObject registry)
- where T : IRegistrableQuantumObject
- {
- ArgumentNullException.ThrowIfNull(registry);
-
- return registry as IRegistry ?? throw new ArgumentException(
- $"{registry.GetType().Name} cannot store objects of type {typeof(T).Name}", nameof(registry));
- }
-}
diff --git a/Core/src/Managed/Stellar.Core/Data/Registry/RegistryTypes.cs b/Core/src/Managed/Stellar.Core/Data/Registry/RegistryTypes.cs
new file mode 100644
index 0000000..351b0e1
--- /dev/null
+++ b/Core/src/Managed/Stellar.Core/Data/Registry/RegistryTypes.cs
@@ -0,0 +1,56 @@
+using System.Collections.Concurrent;
+using System.Reflection;
+using Stellar.Kernel.Data.Registry;
+using Stellar.Kernel.Quantization;
+
+namespace Stellar.Core.Data.Registry;
+
+///
+/// The types whose registries an object goes into implicitly: the types of its hierarchy marked with
+/// .
+///
+///
+/// Read once per type and kept: this is metadata of types, the same for every engine.
+///
+public static class RegistryTypes
+{
+ private static readonly ConcurrentDictionary Marked = new();
+
+ ///
+ /// Gets the marked types of a hierarchy: its classes from the type up, then its contracts.
+ ///
+ /// The type of an object.
+ /// The marked types, each once.
+ public static IReadOnlyList MarkedIn(Type type)
+ {
+ ArgumentNullException.ThrowIfNull(type);
+ return Marked.GetOrAdd(type, static type =>
+ {
+ var classes = new List();
+ for (var current = type; current is not null; current = current.BaseType)
+ if (IsMarked(current)) classes.Add(current);
+
+ var contracts = type.GetInterfaces().Where(IsMarked).OrderBy(contract => contract.FullName, StringComparer.Ordinal);
+ return [.. classes, .. contracts];
+ });
+ }
+
+ ///
+ /// Checks that a type can have a registry: a class or a contract of registrable objects.
+ ///
+ /// The type.
+ /// Thrown if it cannot.
+ public static void Validate(Type type)
+ {
+ ArgumentNullException.ThrowIfNull(type);
+ if (!typeof(IRegistrableQuantumObject).IsAssignableFrom(type) || type.IsValueType || type.ContainsGenericParameters)
+ throw new ArgumentException($"{type.Name} cannot have a registry: it must be a class or a contract of IRegistrableQuantumObject",
+ nameof(type));
+ }
+
+ private static bool IsMarked(Type type)
+ {
+ var definition = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
+ return definition.GetCustomAttribute(inherit: false) is not null;
+ }
+}
diff --git a/Core/src/Managed/Stellar.Core/EntryPoint.cs b/Core/src/Managed/Stellar.Core/EntryPoint.cs
index baf7325..8196dae 100644
--- a/Core/src/Managed/Stellar.Core/EntryPoint.cs
+++ b/Core/src/Managed/Stellar.Core/EntryPoint.cs
@@ -1,16 +1,16 @@
using Stellar.Core.Failures;
-using Stellar.Core.Failures.Handlers;
using Stellar.Core.Global;
using Stellar.Kernel.Configuration;
using Stellar.Kernel.EntryPoint;
using Stellar.Kernel.Failures;
using Stellar.Kernel.Lifecycle;
+using Stellar.Kernel.LoggingSystem;
using Stellar.Kernel.Services;
namespace Stellar.Core;
///
-/// Entry point of the Core module: brings up the failure pipeline every other module relies on.
+/// Entry point of the Core module: brings up the failure system every other module relies on.
///
///
/// It owns the services of the engine (): the runtime publishes its own services there
@@ -20,7 +20,7 @@ namespace Stellar.Core;
public sealed class EntryPoint(RuntimeConfiguration runtimeConfiguration)
: StellarEntryPoint("S.C/MainEntry", runtimeConfiguration), IServiceHost
{
- private FailureDispatcher? _dispatcher;
+ private FailureSystem? _failures;
private CoreEngine? _engine;
///
@@ -30,7 +30,7 @@ public sealed class EntryPoint(RuntimeConfiguration runtimeConfiguration)
public CoreEngine Core => _engine ??= CoreEngine.Current;
///
- public IServiceRegistry Services => Core.Services;
+ public IServiceCatalog Services => Core.Services;
///
public override int Run(ref readonly TContext context)
@@ -39,16 +39,10 @@ public override int Run(ref readonly TContext context)
if (context.Engine is { } instance) _engine ??= CoreEngine.For(instance);
var core = Core;
- var meta = new FailureDispatcherMeta();
- core.FailureLevels.Initialize(meta);
- var provider = (FailureHandlerProvider)meta.FailureHandlerProvider;
- provider.RegisterDefaultHandler(new FailureHandler(context.Logger, core.Services.Find()));
-
- _dispatcher = new FailureDispatcher(meta);
- core.Services.Set(_dispatcher);
- core.Services.Set(
- new FailureReporter(_dispatcher, core.FailureLevels.Error!, core.FailureLevels.CriticalError!));
+ // The logger and the control of the engine may come after: they are looked up when a failure needs them
+ _failures = new FailureSystem(() => core.Services.Find(), () => core.Services.Find());
+ core.Services.Set(_failures);
return 0;
}
@@ -61,13 +55,11 @@ public override void RequestStop(ref readonly TContext context)
///
public override void Dispose()
{
- if (_dispatcher is null) return;
+ if (_failures is null) return;
var core = Core;
- core.Services.Remove();
- core.Services.Remove();
- core.FailureLevels.Reset();
- _dispatcher = null;
+ core.Services.Remove();
+ _failures = null;
// The engine is gone with its Core module: its registries, managed and native, go with it
if (core.Instance is { } instance) CoreEngine.Release(instance);
diff --git a/Core/src/Managed/Stellar.Core/EntryPoints/RunContext.cs b/Core/src/Managed/Stellar.Core/EntryPoints/RunContext.cs
index 5bb62e9..5666aef 100644
--- a/Core/src/Managed/Stellar.Core/EntryPoints/RunContext.cs
+++ b/Core/src/Managed/Stellar.Core/EntryPoints/RunContext.cs
@@ -10,14 +10,14 @@ namespace Stellar.Core.EntryPoints;
///
/// The quant that starts the module.
/// An already initialized logger.
-/// A failure dispatcher for failures during the run.
+/// The failure system of the engine.
/// The services of the engine.
/// The engine the module runs in.
public readonly ref struct RunContext(
IQuantumObject? sender,
ILogger? logger = null,
- IFailureDispatcher? failureDispatcher = null,
- IServiceRegistry? services = null,
+ IFailureSystem? failures = null,
+ IServiceCatalog? services = null,
IEngineInstance? engine = null
) : IRunContext
{
@@ -28,10 +28,10 @@ public readonly ref struct RunContext(
public ILogger? Logger { get; } = logger;
///
- public IFailureDispatcher? FailureDispatcher { get; } = failureDispatcher;
+ public IFailureSystem? Failures { get; } = failures;
///
- public IServiceRegistry? Services { get; } = services;
+ public IServiceCatalog? Services { get; } = services;
///
public IEngineInstance? Engine { get; } = engine;
diff --git a/Core/src/Managed/Stellar.Core/Failures/BaseLevels/CriticalError.cs b/Core/src/Managed/Stellar.Core/Failures/BaseLevels/CriticalError.cs
deleted file mode 100644
index 3fb86dc..0000000
--- a/Core/src/Managed/Stellar.Core/Failures/BaseLevels/CriticalError.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-namespace Stellar.Core.Failures.BaseLevels;
-
-///
-/// A failure that terminates the engine.
-///
-/// The meta of the dispatcher the level belongs to.
-public class CriticalError(IFailureDispatcherMeta dispatcherMeta)
- : FailureLevel("S.C/CriticalError", dispatcherMeta)
-{
- ///
- public override bool IsEnabled { get; set; } = true;
-
- ///
- public override bool IsLoggable { get; } = true;
-
- ///
- public override bool IsStopExecute { get; } = true;
-
- ///
- public override bool IsCritical { get; } = true;
-
- ///
- public override bool ShouldTerminate { get; } = true;
-}
diff --git a/Core/src/Managed/Stellar.Core/Failures/BaseLevels/Error.cs b/Core/src/Managed/Stellar.Core/Failures/BaseLevels/Error.cs
deleted file mode 100644
index 3ea734d..0000000
--- a/Core/src/Managed/Stellar.Core/Failures/BaseLevels/Error.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-namespace Stellar.Core.Failures.BaseLevels;
-
-///
-/// A failure that stops the current execution.
-///
-/// The meta of the dispatcher the level belongs to.
-public class Error(IFailureDispatcherMeta dispatcherMeta)
- : FailureLevel("S.C/Error", dispatcherMeta)
-{
- ///
- public override bool IsEnabled { get; set; } = true;
-
- ///
- public override bool IsLoggable { get; } = true;
-
- ///
- public override bool IsStopExecute { get; } = true;
-
- ///
- public override bool IsCritical { get; } = true;
-
- ///
- public override bool ShouldTerminate { get; } = false;
-}
diff --git a/Core/src/Managed/Stellar.Core/Failures/BaseLevels/FailureLevel.cs b/Core/src/Managed/Stellar.Core/Failures/BaseLevels/FailureLevel.cs
deleted file mode 100644
index ea35784..0000000
--- a/Core/src/Managed/Stellar.Core/Failures/BaseLevels/FailureLevel.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-using Stellar.Core.Data.Collections;
-using Stellar.Kernel;
-using Stellar.Kernel.Failures;
-using Stellar.Kernel.Quantization;
-
-namespace Stellar.Core.Failures.BaseLevels;
-
-///
-public abstract class FailureLevel
- : IFailureLevel
-{
- private readonly IFailureDispatcherMeta _dispatcherMeta;
-
- ///
- /// Creates a level and adds it to the levels of a dispatcher.
- ///
- /// The name of the level.
- /// The meta of the dispatcher the level belongs to.
- protected FailureLevel(string name, IFailureDispatcherMeta dispatcherMeta)
- {
- ArgumentNullException.ThrowIfNull(dispatcherMeta);
-
- // Levels belong to their dispatcher and two dispatchers may both have an "Error": the label is not global.
- Label = Core.Label.Create(name, UID, false)
- ?? throw new ArgumentException("A failure level needs a name", nameof(name));
-
- _dispatcherMeta = dispatcherMeta;
- Register(_dispatcherMeta.FailureLevels);
- }
-
- ///
- public IIdentifier UID { get; } = Identifier.CreateAndRegister();
-
- ///
- public ILabel Label { get; }
-
- ///
- public abstract bool IsEnabled { get; set; }
-
- ///
- public abstract bool IsLoggable { get; }
-
- ///
- public abstract bool IsStopExecute { get; }
-
- ///
- public abstract bool IsCritical { get; }
-
- ///
- public abstract bool ShouldTerminate { get; }
-
- ///
- public void Register(IQuantumObject registry)
- {
- if (registry is not DataContainer container)
- throw new ArgumentException("Failure levels are stored in a container of failure levels", nameof(registry));
-
- container.Set(this);
- }
-
- ///
- public void Unregister(IQuantumObject registry)
- {
- if (registry is not DataContainer container)
- throw new ArgumentException("Failure levels are stored in a container of failure levels", nameof(registry));
-
- container.Pop(UID);
- }
-
- ///
- public void Dispose()
- {
- Unregister(_dispatcherMeta.FailureLevels);
- }
-}
diff --git a/Core/src/Managed/Stellar.Core/Failures/BaseLevels/NonCritical.cs b/Core/src/Managed/Stellar.Core/Failures/BaseLevels/NonCritical.cs
deleted file mode 100644
index bf2fff3..0000000
--- a/Core/src/Managed/Stellar.Core/Failures/BaseLevels/NonCritical.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-namespace Stellar.Core.Failures.BaseLevels;
-
-///
-/// A failure that is neither logged nor stops execution.
-///
-/// The meta of the dispatcher the level belongs to.
-public class NonCritical(IFailureDispatcherMeta dispatcherMeta)
- : FailureLevel("S.C/NonCritical", dispatcherMeta)
-{
- ///
- public override bool IsEnabled { get; set; } = true;
-
- ///
- public override bool IsLoggable { get; } = false;
-
- ///
- public override bool IsStopExecute { get; } = false;
-
- ///
- public override bool IsCritical { get; } = false;
-
- ///
- public override bool ShouldTerminate { get; } = false;
-}
diff --git a/Core/src/Managed/Stellar.Core/Failures/BaseLevels/Warning.cs b/Core/src/Managed/Stellar.Core/Failures/BaseLevels/Warning.cs
deleted file mode 100644
index 0a8787b..0000000
--- a/Core/src/Managed/Stellar.Core/Failures/BaseLevels/Warning.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-namespace Stellar.Core.Failures.BaseLevels;
-
-///
-/// A failure that is logged and does not stop execution.
-///
-/// The meta of the dispatcher the level belongs to.
-public class Warning(IFailureDispatcherMeta dispatcherMeta)
- : FailureLevel("S.C/Warning", dispatcherMeta)
-{
- ///
- public override bool IsEnabled { get; set; } = true;
-
- ///
- public override bool IsLoggable { get; } = true;
-
- ///
- public override bool IsStopExecute { get; } = false;
-
- ///
- public override bool IsCritical { get; } = false;
-
- ///
- public override bool ShouldTerminate { get; } = false;
-}
diff --git a/Core/src/Managed/Stellar.Core/Failures/Failure.cs b/Core/src/Managed/Stellar.Core/Failures/Failure.cs
deleted file mode 100644
index c13b571..0000000
--- a/Core/src/Managed/Stellar.Core/Failures/Failure.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using Stellar.Kernel.Failures;
-
-namespace Stellar.Core.Failures;
-
-///
-public readonly struct Failure
- : IFailure
-{
- ///
- public required string Message { get; init; }
-
- ///
- public required Exception? InnerException { get; init; }
-
- ///
- public required FailureType Type { get; init; }
-
- ///
- public required IFailureLevel Level { get; init; }
-
- ///
- public required string Source { get; init; }
-}
diff --git a/Core/src/Managed/Stellar.Core/Failures/FailureCatch.cs b/Core/src/Managed/Stellar.Core/Failures/FailureCatch.cs
deleted file mode 100644
index e50b9e0..0000000
--- a/Core/src/Managed/Stellar.Core/Failures/FailureCatch.cs
+++ /dev/null
@@ -1,107 +0,0 @@
-using System.Runtime.ExceptionServices;
-using Stellar.Kernel;
-using Stellar.Kernel.Failures;
-using Stellar.Kernel.Quantization;
-
-namespace Stellar.Core.Failures;
-
-///
-///
-/// Receives the exceptions no block claimed. Without it they are rethrown.
-///
-/// The level of the failures reported to the dispatcher.
-/// The type of the failures reported to the dispatcher.
-/// The quant reported as the sender of the failures.
-public sealed class FailureCatch(
- IFailureDispatcher? dispatcher = null,
- IFailureLevel? level = null,
- FailureType type = FailureType.Unknown,
- IQuantumObject? sender = null
-) : IFailureCatch
-{
- private readonly List<(Type Exception, Action Handler)> _handlers = [];
- private Action? _try;
- private Action? _finally;
-
- ///
- public IIdentifier UID { get; } = Identifier.Create();
-
- ///
- public Exception? Caught { get; private set; }
-
- ///
- public IFailureCatch Try(Action action)
- {
- ArgumentNullException.ThrowIfNull(action);
-
- _try = action;
- return this;
- }
-
- ///
- public IFailureCatch Except(Action action)
- where T : Exception
- {
- ArgumentNullException.ThrowIfNull(action);
-
- _handlers.Add((typeof(T), (context, exception) => action(context, (T)exception)));
- return this;
- }
-
- ///
- public IFailureCatch Finally(Action action)
- {
- ArgumentNullException.ThrowIfNull(action);
-
- _finally = action;
- return this;
- }
-
- ///
- public IFailureCatch Handle()
- {
- Caught = null;
-
- try
- {
- _try?.Invoke(this);
- }
- catch (Exception exception)
- {
- Caught = exception;
- HandleException(exception);
- }
- finally
- {
- _finally?.Invoke(this);
- }
-
- return this;
- }
-
- private void HandleException(Exception exception)
- {
- foreach (var (exceptionType, handler) in _handlers)
- {
- if (!exceptionType.IsInstanceOfType(exception)) continue;
-
- handler(this, exception);
- return;
- }
-
- if (dispatcher is null || level is null)
- ExceptionDispatchInfo.Capture(exception).Throw();
-
- var failure = new Failure
- {
- Message = exception.Message,
- InnerException = exception,
- Type = type,
- Level = level,
- Source = exception.Source ?? string.Empty
- };
-
- var context = new FailureContext(sender, failure);
- dispatcher.Dispatch(in context);
- }
-}
diff --git a/Core/src/Managed/Stellar.Core/Failures/FailureContext.cs b/Core/src/Managed/Stellar.Core/Failures/FailureContext.cs
deleted file mode 100644
index a53a238..0000000
--- a/Core/src/Managed/Stellar.Core/Failures/FailureContext.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using Stellar.Kernel.Failures;
-using Stellar.Kernel.Quantization;
-
-namespace Stellar.Core.Failures;
-
-///
-/// The quant that reports the failure.
-/// The failure.
-public readonly ref struct FailureContext(IQuantumObject? sender, IFailure failure)
- : IFailureContext
-{
- ///
- public IQuantumObject? Sender { get; } = sender;
-
- ///
- public IFailure Failure { get; } = failure;
-}
diff --git a/Core/src/Managed/Stellar.Core/Failures/FailureDispatcher.cs b/Core/src/Managed/Stellar.Core/Failures/FailureDispatcher.cs
deleted file mode 100644
index cdc3b59..0000000
--- a/Core/src/Managed/Stellar.Core/Failures/FailureDispatcher.cs
+++ /dev/null
@@ -1,60 +0,0 @@
-using Stellar.Core.Data.Collections;
-using Stellar.Core.Failures.Handlers;
-using Stellar.Core.Quantization;
-using Stellar.Kernel.Failures;
-using Stellar.Kernel.Failures.Handlers;
-using Stellar.Kernel.Quantization;
-
-namespace Stellar.Core.Failures;
-
-///
-/// Meta of a failure dispatcher: its failure levels and handlers.
-///
-public interface IFailureDispatcherMeta
- : IMetaQuant
-{
- ///
- /// Gets the failure levels known to the dispatcher.
- ///
- DataContainer FailureLevels { get; }
-
- ///
- /// Gets the source of failure handlers.
- ///
- IFailureHandlerProvider FailureHandlerProvider { get; }
-}
-
-///
-/// The container of failure levels. A new one is created when omitted.
-/// The source of handlers. A new one is created when omitted.
-public class FailureDispatcherMeta(
- DataContainer? failureLevels = null,
- IFailureHandlerProvider? failureHandlerProvider = null
-) : MetaQuant(Identifier.CreateAndRegister()), IFailureDispatcherMeta
-{
- ///
- public DataContainer FailureLevels { get; } =
- failureLevels ?? new WritableTable();
-
- ///
- public IFailureHandlerProvider FailureHandlerProvider { get; } =
- failureHandlerProvider ?? new FailureHandlerProvider(new HandlerProviderMeta());
-}
-
-///
-/// The meta with failure levels and handlers.
-public class FailureDispatcher(IFailureDispatcherMeta meta)
- : Quant(meta), IFailureDispatcher
-{
- ///
- public bool Dispatch(ref readonly TContext failureContext)
- where TContext : IFailureContext, allows ref struct
- {
- var shouldStop = false;
-
- foreach (var handler in MetaQuant.FailureHandlerProvider.GetHandlers(failureContext.Failure))
- shouldStop |= handler.Handle(in failureContext);
-
- return shouldStop;
- }
-}
diff --git a/Core/src/Managed/Stellar.Core/Failures/FailureReporter.cs b/Core/src/Managed/Stellar.Core/Failures/FailureReporter.cs
deleted file mode 100644
index 3514db6..0000000
--- a/Core/src/Managed/Stellar.Core/Failures/FailureReporter.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-using Stellar.Kernel.Failures;
-using Stellar.Kernel.Quantization;
-
-namespace Stellar.Core.Failures;
-
-///
-/// Reports exceptions caught outside the failure system (by the runtime, which starts before Stellar.Core) as
-/// failures: , or
-/// for the critical ones, through the dispatcher.
-///
-/// The dispatcher.
-/// The level of failures.
-/// The level of critical failures.
-public sealed class FailureReporter(IFailureDispatcher dispatcher, IFailureLevel error, IFailureLevel criticalError)
- : IFailureReporter
-{
- ///
- public bool Report(Exception exception, FailureType type, bool critical, IQuantumObject? sender = null)
- {
- ArgumentNullException.ThrowIfNull(exception);
-
- var failure = new Failure
- {
- Message = exception.Message,
- InnerException = exception,
- Type = type,
- Level = critical ? criticalError : error,
- Source = exception.Source ?? string.Empty
- };
-
- var context = new FailureContext(sender, failure);
- return dispatcher.Dispatch(in context);
- }
-}
diff --git a/Core/src/Managed/Stellar.Core/Failures/FailureSystem.cs b/Core/src/Managed/Stellar.Core/Failures/FailureSystem.cs
new file mode 100644
index 0000000..786dd0a
--- /dev/null
+++ b/Core/src/Managed/Stellar.Core/Failures/FailureSystem.cs
@@ -0,0 +1,131 @@
+using Stellar.Core.Data.Catalog;
+using Stellar.Core.Data.Collections;
+using Stellar.Core.Quantization;
+using Stellar.Kernel.Data.Catalog;
+using Stellar.Kernel.EntryPoint;
+using Stellar.Kernel.Failures;
+using Stellar.Kernel.Lifecycle;
+using Stellar.Kernel.LoggingSystem;
+
+namespace Stellar.Core.Failures;
+
+///
+/// The failure system of one engine: reactions in catalogs, handlers that hear of failures, a log, a stop.
+///
+///
+/// Stellar.Core makes one per engine and publishes it in the services of the engine. The logger and the control of
+/// the engine are looked up when a failure needs them, so they can come after the system.
+///
+public sealed class FailureSystem
+ : Quant, IFailureSystem
+{
+ private sealed class Subscription(FailureSystem system, IFailureHandler handler, FailureFilter filter)
+ : IDisposable
+ {
+ public IFailureHandler Handler { get; } = handler;
+
+ public FailureFilter Filter { get; } = filter;
+
+ public void Dispose()
+ {
+ system._handlers.Remove(this);
+ }
+ }
+
+ private readonly Func _logger;
+ private readonly Func _control;
+ private readonly ConcurrentList _handlers = new();
+ private readonly Catalog _reactions = new();
+ private readonly Catalog<(FailureKind Kind, FailureLevel Level), FailureReaction> _kindReactions = new();
+
+ ///
+ public ICatalog Reactions => _reactions;
+
+ ///
+ public ICatalog<(FailureKind Kind, FailureLevel Level), FailureReaction> KindReactions => _kindReactions;
+
+ ///
+ /// Makes a failure system.
+ ///
+ /// Gives the logger, when there is one.
+ /// Gives the control of the engine, when there is one.
+ public FailureSystem(Func? logger = null, Func? control = null)
+ : base(new MetaQuant())
+ {
+ _logger = logger ?? (() => null);
+ _control = control ?? (() => null);
+
+ foreach (var level in Enum.GetValues())
+ _reactions.Set(level, FailureReactions.Default(level));
+ }
+
+ private static LogLevel LogLevelOf(FailureLevel level)
+ {
+ return level switch
+ {
+ FailureLevel.NonCritical => LogLevel.Info,
+ FailureLevel.Warning => LogLevel.Warning,
+ FailureLevel.Error => LogLevel.Error,
+ _ => LogLevel.Exception
+ };
+ }
+
+ private static string Describe(Failure failure)
+ {
+ return failure.Exception is { } exception and not FailureException { InnerException: null }
+ ? $"{failure}{Environment.NewLine}{exception}"
+ : failure.ToString();
+ }
+
+ ///
+ public FailureReaction ReactionTo(Failure failure)
+ {
+ ArgumentNullException.ThrowIfNull(failure);
+
+ if (_kindReactions.TryGet((failure.Kind, failure.Level), out var byKind)) return byKind;
+ return _reactions.TryGet(failure.Level, out var byLevel)
+ ? byLevel
+ : FailureReactions.Default(failure.Level);
+ }
+
+ ///
+ public FailureReaction Report(Failure failure)
+ {
+ ArgumentNullException.ThrowIfNull(failure);
+
+ var reaction = ReactionTo(failure);
+ if (!failure.MarkReported(reaction)) return failure.Reaction!.Value;
+
+ if ((reaction & FailureReaction.Log) != 0) _logger()?.Log(LogLevelOf(failure.Level), Describe(failure));
+
+ foreach (var subscription in _handlers.AsSpan())
+ {
+ if (!subscription.Filter.Matches(failure)) continue;
+
+ try
+ {
+ subscription.Handler.Handle(failure);
+ }
+ catch (Exception exception)
+ {
+ // A handler that fails is not a failure of the engine: it is told, and the others still hear
+ _logger()?.Log(LogLevel.Error,
+ $"The failure handler {subscription.Handler.GetType().Name} failed: {exception}");
+ }
+ }
+
+ if ((reaction & FailureReaction.StopEngine) != 0) _control()?.RequestStop(StopReason.CriticalError, failure);
+
+ return reaction;
+ }
+
+ ///
+ public IDisposable AddHandler(IFailureHandler handler, FailureFilter filter = default)
+ {
+ ArgumentNullException.ThrowIfNull(handler);
+
+ var subscription = new Subscription(this, handler, filter);
+ _handlers.Add(subscription);
+ return subscription;
+ }
+}
diff --git a/Core/src/Managed/Stellar.Core/Failures/Handlers/CompositeFailureHandlerProvider.cs b/Core/src/Managed/Stellar.Core/Failures/Handlers/CompositeFailureHandlerProvider.cs
deleted file mode 100644
index 952d584..0000000
--- a/Core/src/Managed/Stellar.Core/Failures/Handlers/CompositeFailureHandlerProvider.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-using Stellar.Core.Quantization;
-using Stellar.Kernel.Failures;
-using Stellar.Kernel.Failures.Handlers;
-
-namespace Stellar.Core.Failures.Handlers;
-
-///
-/// Joins several providers into one.
-///
-public class CompositeFailureHandlerProvider()
- : RegistrableQuant(new HandlerProviderMeta()),
- IFailureHandlerProvider
-{
- private volatile IFailureHandlerProvider[] _providers = [];
- private readonly Lock _lock = new();
-
- ///
- /// Adds a provider.
- ///
- public void AddProvider(IFailureHandlerProvider provider)
- {
- ArgumentNullException.ThrowIfNull(provider);
-
- lock (_lock)
- {
- _providers = [.. _providers, provider];
- }
- }
-
- ///
- /// Removes a provider.
- ///
- public void RemoveProvider(IFailureHandlerProvider provider)
- {
- lock (_lock)
- {
- _providers = _providers.Where(p => !ReferenceEquals(p, provider)).ToArray();
- }
- }
-
- ///
- public IEnumerable GetHandlers(IFailure failure)
- {
- return _providers.SelectMany(provider => provider.GetHandlers(failure));
- }
-}
diff --git a/Core/src/Managed/Stellar.Core/Failures/Handlers/FailureHandler.cs b/Core/src/Managed/Stellar.Core/Failures/Handlers/FailureHandler.cs
deleted file mode 100644
index 37ec766..0000000
--- a/Core/src/Managed/Stellar.Core/Failures/Handlers/FailureHandler.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using Stellar.Core.Quantization;
-using Stellar.Kernel.EntryPoint;
-using Stellar.Kernel.Failures;
-using Stellar.Kernel.Failures.Handlers;
-using Stellar.Kernel.Lifecycle;
-using Stellar.Kernel.LoggingSystem;
-
-namespace Stellar.Core.Failures.Handlers;
-
-///