| | | 1 | | using System.Collections; |
| | | 2 | | |
| | | 3 | | namespace AsyncResponse; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Aggregates the registered <see cref="IAsyncResponseContextPropagator"/>s into a single |
| | | 7 | | /// capture/restore step used by the worker and lost-subscriber paths. With no propagators |
| | | 8 | | /// registered it is a zero-overhead no-op, so the feature has no effect on apps that don't use it. |
| | | 9 | | /// </summary> |
| | | 10 | | internal sealed class AsyncResponseContextPropagation |
| | | 11 | | { |
| | | 12 | | private readonly IReadOnlyList<IAsyncResponseContextPropagator> _propagators; |
| | | 13 | | |
| | | 14 | | /// <summary>Runs the AsyncResponseContextPropagation operation.</summary> |
| | | 15 | | public AsyncResponseContextPropagation(IEnumerable<IAsyncResponseContextPropagator> propagators) |
| | | 16 | | => _propagators = propagators as IReadOnlyList<IAsyncResponseContextPropagator> ?? propagators.ToArray(); |
| | | 17 | | |
| | | 18 | | /// <summary> |
| | | 19 | | /// Captures the current ambient context from every propagator into a serializable carrier. |
| | | 20 | | /// Returns <c>null</c> when there are no propagators or none wrote anything, so the carrier is |
| | | 21 | | /// left off the wire payload entirely. |
| | | 22 | | /// </summary> |
| | | 23 | | public Dictionary<string, string>? Capture() |
| | | 24 | | { |
| | | 25 | | var propagators = _propagators; |
| | | 26 | | var count = propagators.Count; |
| | | 27 | | if (count == 0) |
| | | 28 | | return null; |
| | | 29 | | |
| | | 30 | | // Hand each propagator a lazy carrier instead of a fully-formed Dictionary. The backing |
| | | 31 | | // dictionary is allocated only when a propagator actually writes a value, so the very |
| | | 32 | | // common "nothing to capture" path (no ambient trace/tenant/etc. set) allocates nothing. |
| | | 33 | | // The carrier wrapper itself is pooled per thread and never escapes this synchronous call, |
| | | 34 | | // so even when a propagator does write, the only surviving allocation is the dictionary |
| | | 35 | | // that gets returned — no wrapper and no enumerator. Indexing the list avoids the |
| | | 36 | | // IEnumerator<T> boxing that a foreach over an interface-typed list would incur. |
| | | 37 | | var carrier = LazyCapturingCarrier.Rent(count); |
| | | 38 | | for (var i = 0; i < count; i++) |
| | | 39 | | propagators[i].Capture(carrier); |
| | | 40 | | |
| | | 41 | | return carrier.Detach(); |
| | | 42 | | } |
| | | 43 | | |
| | | 44 | | /// <summary> |
| | | 45 | | /// Restores ambient context from <paramref name="carrier"/> for the lifetime of the returned |
| | | 46 | | /// scope. A no-op when there are no propagators or the carrier is null/empty. |
| | | 47 | | /// </summary> |
| | | 48 | | public IDisposable Restore(IReadOnlyDictionary<string, string>? carrier) |
| | | 49 | | { |
| | | 50 | | var propagators = _propagators; |
| | | 51 | | var count = propagators.Count; |
| | | 52 | | if (count == 0 || carrier is null || carrier.Count == 0) |
| | | 53 | | return NullScope.Instance; |
| | | 54 | | |
| | | 55 | | // Collect the real scopes without allocating until we genuinely need a composite. The 0/1/2 |
| | | 56 | | // active-scope cases — by far the most common — return either the shared no-op, the single |
| | | 57 | | // scope directly, or a fixed two-field CompositeScope2. Only 3+ active propagators fall back |
| | | 58 | | // to the List-backed CompositeScope. Indexing the list avoids the foreach enumerator alloc. |
| | | 59 | | IDisposable? first = null; |
| | | 60 | | IDisposable? second = null; |
| | | 61 | | List<IDisposable>? more = null; |
| | | 62 | | |
| | | 63 | | for (var i = 0; i < count; i++) |
| | | 64 | | { |
| | | 65 | | var scope = propagators[i].Restore(carrier); |
| | | 66 | | if (scope is null || ReferenceEquals(scope, NullScope.Instance)) |
| | | 67 | | continue; |
| | | 68 | | |
| | | 69 | | if (more is not null) |
| | | 70 | | more.Add(scope); |
| | | 71 | | else if (first is null) |
| | | 72 | | first = scope; |
| | | 73 | | else if (second is null) |
| | | 74 | | second = scope; |
| | | 75 | | else |
| | | 76 | | more = [first, second, scope]; |
| | | 77 | | } |
| | | 78 | | |
| | | 79 | | if (more is not null) |
| | | 80 | | return new CompositeScope(more); |
| | | 81 | | |
| | | 82 | | if (second is not null) |
| | | 83 | | return new CompositeScope2(first!, second); |
| | | 84 | | |
| | | 85 | | return first ?? NullScope.Instance; |
| | | 86 | | } |
| | | 87 | | |
| | | 88 | | private sealed class NullScope : IDisposable |
| | | 89 | | { |
| | | 90 | | public static readonly NullScope Instance = new(); |
| | | 91 | | /// <summary>Releases resources held by this instance.</summary> |
| | | 92 | | public void Dispose() { } |
| | | 93 | | } |
| | | 94 | | |
| | | 95 | | /// <summary> |
| | | 96 | | /// Disposes exactly two scopes in reverse order, mirroring nested <c>using</c> semantics without |
| | | 97 | | /// the <see cref="List{T}"/> + general <see cref="CompositeScope"/> allocation that the 1–2 |
| | | 98 | | /// propagator case (the overwhelmingly common one) would otherwise pay. |
| | | 99 | | /// </summary> |
| | 3 | 100 | | private sealed class CompositeScope2(IDisposable _first, IDisposable _second) : IDisposable |
| | | 101 | | { |
| | | 102 | | private int _disposed; |
| | | 103 | | |
| | | 104 | | /// <summary>Releases resources held by this instance.</summary> |
| | | 105 | | public void Dispose() |
| | | 106 | | { |
| | 3 | 107 | | if (Interlocked.Exchange(ref _disposed, 1) != 0) |
| | 2 | 108 | | return; |
| | | 109 | | |
| | 3 | 110 | | try { _second.Dispose(); } |
| | 2 | 111 | | catch { /* a misbehaving propagator scope must not mask the other */ } |
| | | 112 | | |
| | 3 | 113 | | try { _first.Dispose(); } |
| | 2 | 114 | | catch { /* swallow: best-effort restore of the remaining scope */ } |
| | 3 | 115 | | } |
| | | 116 | | } |
| | | 117 | | |
| | | 118 | | private sealed class CompositeScope(List<IDisposable> _scopes) : IDisposable |
| | | 119 | | { |
| | | 120 | | private int _disposed; |
| | | 121 | | |
| | | 122 | | /// <summary>Releases resources held by this instance.</summary> |
| | | 123 | | public void Dispose() |
| | | 124 | | { |
| | | 125 | | if (Interlocked.Exchange(ref _disposed, 1) != 0) |
| | | 126 | | return; |
| | | 127 | | |
| | | 128 | | // Dispose in reverse order, mirroring nested using semantics. |
| | | 129 | | for (int i = _scopes.Count - 1; i >= 0; i--) |
| | | 130 | | { |
| | | 131 | | try { _scopes[i].Dispose(); } |
| | | 132 | | catch { /* a misbehaving propagator scope must not mask the others */ } |
| | | 133 | | } |
| | | 134 | | } |
| | | 135 | | } |
| | | 136 | | |
| | | 137 | | /// <summary> |
| | | 138 | | /// An <see cref="IDictionary{TKey,TValue}"/> facade that defers creating its backing |
| | | 139 | | /// <see cref="Dictionary{TKey,TValue}"/> until the first mutation. Reads before any write see an |
| | | 140 | | /// empty map; the first write allocates a right-sized dictionary. A single instance is reused per |
| | | 141 | | /// thread (the carrier never escapes the synchronous <see cref="Capture"/> call), so capturing |
| | | 142 | | /// context adds no wrapper allocation on the hot path — only the backing dictionary, and only |
| | | 143 | | /// when a propagator writes. |
| | | 144 | | /// </summary> |
| | | 145 | | private sealed class LazyCapturingCarrier : IDictionary<string, string> |
| | | 146 | | { |
| | | 147 | | [ThreadStatic] private static LazyCapturingCarrier? _cached; |
| | | 148 | | |
| | | 149 | | // Shared, never-mutated empty map backing every read taken before the first write. |
| | | 150 | | private static readonly Dictionary<string, string> EmptyView = new(0, StringComparer.Ordinal); |
| | | 151 | | |
| | | 152 | | private Dictionary<string, string>? _inner; |
| | | 153 | | private int _capacity; |
| | | 154 | | |
| | | 155 | | private LazyCapturingCarrier(int capacity) => _capacity = capacity; |
| | | 156 | | |
| | | 157 | | /// <summary> |
| | | 158 | | /// Borrows the thread's pooled carrier (or allocates one on first use / under re-entrancy). |
| | | 159 | | /// The slot is cleared while borrowed so a re-entrant capture gets its own instance rather |
| | | 160 | | /// than corrupting the borrowed one. |
| | | 161 | | /// </summary> |
| | | 162 | | public static LazyCapturingCarrier Rent(int capacity) |
| | | 163 | | { |
| | | 164 | | var carrier = _cached; |
| | | 165 | | if (carrier is null) |
| | | 166 | | return new LazyCapturingCarrier(capacity); |
| | | 167 | | |
| | | 168 | | _cached = null; |
| | | 169 | | carrier._capacity = capacity; |
| | | 170 | | return carrier; |
| | | 171 | | } |
| | | 172 | | |
| | | 173 | | /// <summary> |
| | | 174 | | /// Returns the captured dictionary (or <c>null</c> when nothing was written), resets the |
| | | 175 | | /// carrier, and returns it to the thread pool for the next capture. |
| | | 176 | | /// </summary> |
| | | 177 | | public Dictionary<string, string>? Detach() |
| | | 178 | | { |
| | | 179 | | var inner = _inner; |
| | | 180 | | _inner = null; |
| | | 181 | | _cached = this; |
| | | 182 | | return inner is { Count: > 0 } ? inner : null; |
| | | 183 | | } |
| | | 184 | | |
| | | 185 | | private Dictionary<string, string> EnsureWritable() |
| | | 186 | | => _inner ??= new Dictionary<string, string>(_capacity, StringComparer.Ordinal); |
| | | 187 | | |
| | | 188 | | private Dictionary<string, string> ReadView => _inner ?? EmptyView; |
| | | 189 | | |
| | | 190 | | public string this[string key] |
| | | 191 | | { |
| | | 192 | | get => ReadView[key]; |
| | | 193 | | set => EnsureWritable()[key] = value; |
| | | 194 | | } |
| | | 195 | | |
| | | 196 | | public ICollection<string> Keys => ReadView.Keys; |
| | | 197 | | public ICollection<string> Values => ReadView.Values; |
| | | 198 | | public int Count => _inner?.Count ?? 0; |
| | | 199 | | public bool IsReadOnly => false; |
| | | 200 | | |
| | | 201 | | /// <summary>Runs the Add operation.</summary> |
| | | 202 | | public void Add(string key, string value) => EnsureWritable().Add(key, value); |
| | | 203 | | |
| | | 204 | | /// <summary>Runs the Add operation.</summary> |
| | | 205 | | public void Add(KeyValuePair<string, string> item) |
| | | 206 | | => ((ICollection<KeyValuePair<string, string>>)EnsureWritable()).Add(item); |
| | | 207 | | |
| | | 208 | | /// <summary>Runs the ContainsKey operation.</summary> |
| | | 209 | | public bool ContainsKey(string key) => _inner?.ContainsKey(key) ?? false; |
| | | 210 | | |
| | | 211 | | /// <summary>Runs the Contains operation.</summary> |
| | | 212 | | public bool Contains(KeyValuePair<string, string> item) |
| | | 213 | | => _inner is { } inner && ((ICollection<KeyValuePair<string, string>>)inner).Contains(item); |
| | | 214 | | |
| | | 215 | | /// <summary>Runs the TryGetValue operation.</summary> |
| | | 216 | | public bool TryGetValue(string key, out string value) |
| | | 217 | | { |
| | | 218 | | if (_inner is { } inner) |
| | | 219 | | return inner.TryGetValue(key, out value!); |
| | | 220 | | |
| | | 221 | | value = null!; |
| | | 222 | | return false; |
| | | 223 | | } |
| | | 224 | | |
| | | 225 | | /// <summary>Runs the Remove operation.</summary> |
| | | 226 | | public bool Remove(string key) => _inner?.Remove(key) ?? false; |
| | | 227 | | |
| | | 228 | | /// <summary>Runs the Remove operation.</summary> |
| | | 229 | | public bool Remove(KeyValuePair<string, string> item) |
| | | 230 | | => _inner is { } inner && ((ICollection<KeyValuePair<string, string>>)inner).Remove(item); |
| | | 231 | | |
| | | 232 | | /// <summary>Runs the Clear operation.</summary> |
| | | 233 | | public void Clear() => _inner?.Clear(); |
| | | 234 | | |
| | | 235 | | /// <summary>Runs the CopyTo operation.</summary> |
| | | 236 | | public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex) |
| | | 237 | | => ((ICollection<KeyValuePair<string, string>>)ReadView).CopyTo(array, arrayIndex); |
| | | 238 | | |
| | | 239 | | /// <summary>Runs the GetEnumerator operation.</summary> |
| | | 240 | | public IEnumerator<KeyValuePair<string, string>> GetEnumerator() => ReadView.GetEnumerator(); |
| | | 241 | | |
| | | 242 | | IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); |
| | | 243 | | } |
| | | 244 | | } |