| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using System.Collections.Concurrent; |
| | 6 | | using System.Collections.Generic; |
| | 7 | | using System.Linq; |
| | 8 | | using System.Threading; |
| | 9 | | using System.Threading.Tasks; |
| | 10 | | using Azure.Core; |
| | 11 | |
|
| | 12 | | namespace Azure.Messaging.EventHubs.Core |
| | 13 | | { |
| | 14 | | /// <summary> |
| | 15 | | /// A pool of <see cref="TransportProducer" /> instances that automatically expire after a period of inactivity. |
| | 16 | | /// </summary> |
| | 17 | | /// |
| | 18 | | internal class TransportProducerPool |
| | 19 | | { |
| | 20 | | /// <summary>The period after which <see cref="CreateExpirationTimerCallback" /> is run.</summary> |
| 2 | 21 | | private static readonly TimeSpan DefaultPerformExpirationPeriod = TimeSpan.FromMinutes(10); |
| | 22 | |
|
| | 23 | | /// <summary> |
| | 24 | | /// The set of active Event Hub transport-specific producers specific to a given partition; |
| | 25 | | /// intended to perform delegated operations. |
| | 26 | | /// </summary> |
| | 27 | | /// |
| 80 | 28 | | private ConcurrentDictionary<string, PoolItem> Pool { get; } |
| | 29 | |
|
| | 30 | | /// <summary> |
| | 31 | | /// An abstracted Event Hub transport-specific producer that is associated with the |
| | 32 | | /// Event Hub gateway rather than a specific partition; intended to perform delegated operations. |
| | 33 | | /// </summary> |
| | 34 | | /// |
| 50 | 35 | | public TransportProducer EventHubProducer { get; } |
| | 36 | |
|
| | 37 | | /// <summary> |
| | 38 | | /// The active connection to the Azure Event Hubs service, enabling client communications for metadata |
| | 39 | | /// about the associated Event Hub and access to a transport-aware producer. |
| | 40 | | /// </summary> |
| | 41 | | /// |
| 10 | 42 | | private EventHubConnection Connection { get; } |
| | 43 | |
|
| | 44 | | /// <summary> |
| | 45 | | /// The policy to use for determining retry behavior for when an operation fails. |
| | 46 | | /// </summary> |
| | 47 | | /// |
| 10 | 48 | | private EventHubsRetryPolicy RetryPolicy { get; } |
| | 49 | |
|
| | 50 | | /// <summary> |
| | 51 | | /// A reference to a <see cref="Timer" /> periodically checking every <see cref="DefaultPerformExpirationPerio |
| | 52 | | /// the <see cref="TransportProducer" /> that are in use and those that can be closed. |
| | 53 | | /// </summary> |
| | 54 | | /// |
| 10 | 55 | | private Timer ExpirationTimer { get; } |
| | 56 | |
|
| | 57 | | /// <summary> |
| | 58 | | /// Initializes a new instance of the <see cref="TransportProducerPool" /> class. |
| | 59 | | /// </summary> |
| | 60 | | /// |
| 2 | 61 | | internal TransportProducerPool() |
| | 62 | | { |
| 2 | 63 | | } |
| | 64 | |
|
| | 65 | | /// <summary> |
| | 66 | | /// Initializes a new instance of the <see cref="TransportProducerPool" /> class. |
| | 67 | | /// </summary> |
| | 68 | | /// |
| | 69 | | /// <param name="connection">The <see cref="EventHubConnection" /> connection to use for communication with the |
| | 70 | | /// <param name="retryPolicy">The policy to use for determining retry behavior for when an operation fails.</par |
| | 71 | | /// <param name="pool">The pool of <see cref="PoolItem" /> that is going to be used to store the partition speci |
| | 72 | | /// <param name="performExpirationPeriod">The period after which <see cref="CreateExpirationTimerCallback" /> is |
| | 73 | | /// <param name="eventHubProducer">An abstracted Event Hub transport-specific producer that is associated with t |
| | 74 | | /// |
| 130 | 75 | | public TransportProducerPool(EventHubConnection connection, |
| 130 | 76 | | EventHubsRetryPolicy retryPolicy, |
| 130 | 77 | | ConcurrentDictionary<string, PoolItem> pool = default, |
| 130 | 78 | | TimeSpan? performExpirationPeriod = default, |
| 130 | 79 | | TransportProducer eventHubProducer = default) |
| | 80 | | { |
| 130 | 81 | | Connection = connection; |
| 130 | 82 | | RetryPolicy = retryPolicy; |
| 130 | 83 | | Pool = pool ?? new ConcurrentDictionary<string, PoolItem>(); |
| 130 | 84 | | performExpirationPeriod ??= DefaultPerformExpirationPeriod; |
| 130 | 85 | | EventHubProducer = eventHubProducer ?? connection.CreateTransportProducer(null, retryPolicy); |
| | 86 | |
|
| 130 | 87 | | ExpirationTimer = new Timer(CreateExpirationTimerCallback(), |
| 130 | 88 | | null, |
| 130 | 89 | | performExpirationPeriod.Value, |
| 130 | 90 | | performExpirationPeriod.Value); |
| 130 | 91 | | } |
| | 92 | |
|
| | 93 | | /// <summary> |
| | 94 | | /// Retrieves a <see cref="PooledProducer" /> for the requested partition, |
| | 95 | | /// creating one if needed or extending the expiration for an existing instance. |
| | 96 | | /// </summary> |
| | 97 | | /// |
| | 98 | | /// <param name="partitionId">The unique identifier of a partition associated with the Event Hub.</param> |
| | 99 | | /// <param name="removeAfterDuration">The period of inactivity after which a <see cref="PoolItem" /> will become |
| | 100 | | /// |
| | 101 | | /// <returns>A <see cref="PooledProducer" /> mapping to the partition id passed in as parameter.</returns> |
| | 102 | | /// |
| | 103 | | /// <remarks> |
| | 104 | | /// There is a slight probability that the returned producer may be closed at any time |
| | 105 | | /// after it is returned and the caller may want to handle that scenario. |
| | 106 | | /// </remarks> |
| | 107 | | /// |
| | 108 | | public virtual PooledProducer GetPooledProducer(string partitionId, |
| | 109 | | TimeSpan? removeAfterDuration = default) |
| | 110 | | { |
| 44 | 111 | | if (string.IsNullOrEmpty(partitionId)) |
| | 112 | | { |
| 28 | 113 | | return new PooledProducer(EventHubProducer); |
| | 114 | | } |
| | 115 | |
|
| 16 | 116 | | var identifier = Guid.NewGuid().ToString(); |
| | 117 | |
|
| 26 | 118 | | var item = Pool.GetOrAdd(partitionId, id => new PoolItem(partitionId, Connection.CreateTransportProducer(id, |
| | 119 | |
|
| | 120 | | // A race condition at this point may end with CloseAsync called on |
| | 121 | | // the returned PoolItem if it had expired. The probability is very low and |
| | 122 | | // possible exceptions should be handled by the invoking methods. |
| | 123 | |
|
| 16 | 124 | | if (item.PartitionProducer.IsClosed || !item.ActiveInstances.TryAdd(identifier, 0)) |
| | 125 | | { |
| 0 | 126 | | identifier = Guid.NewGuid().ToString(); |
| 0 | 127 | | item = Pool.GetOrAdd(partitionId, id => new PoolItem(partitionId, Connection.CreateTransportProducer(id, |
| 0 | 128 | | item.ActiveInstances.TryAdd(identifier, 0); |
| | 129 | | } |
| | 130 | |
|
| 16 | 131 | | item.ExtendRemoveAfter(removeAfterDuration); |
| | 132 | |
|
| 16 | 133 | | return new PooledProducer(item.PartitionProducer, cleanUp: producer => |
| 16 | 134 | | { |
| 28 | 135 | | Argument.AssertNotNull(producer, nameof(producer)); |
| 16 | 136 | |
|
| 28 | 137 | | if (Pool.TryGetValue(partitionId, out PoolItem pooledItem)) |
| 16 | 138 | | { |
| 28 | 139 | | pooledItem.ExtendRemoveAfter(removeAfterDuration); |
| 16 | 140 | | } |
| 16 | 141 | |
|
| 16 | 142 | | // If TryRemove returned false the PoolItem would not be closed deterministically |
| 16 | 143 | | // and the ExpirationTimer callback would eventually remove it from the |
| 16 | 144 | | // Pool leaving to the Garbage Collector the responsability of closing |
| 16 | 145 | | // the TransportProducer and the AMQP link. |
| 16 | 146 | |
|
| 28 | 147 | | item.ActiveInstances.TryRemove(identifier, out _); |
| 16 | 148 | |
|
| 16 | 149 | | // The second TryGetValue runs after the extension would have been seen, so it |
| 16 | 150 | | // is intended to be sure that the item wasn't removed in the meantime. |
| 16 | 151 | |
|
| 28 | 152 | | if (!Pool.TryGetValue(partitionId, out _) && !item.ActiveInstances.Any()) |
| 16 | 153 | | { |
| 0 | 154 | | return producer.CloseAsync(CancellationToken.None); |
| 16 | 155 | | } |
| 16 | 156 | |
|
| 28 | 157 | | return Task.CompletedTask; |
| 16 | 158 | | }); |
| | 159 | | } |
| | 160 | |
|
| | 161 | | /// <summary> |
| | 162 | | /// Closes the producers in the pool and performs any cleanup necessary |
| | 163 | | /// for resources used by the <see cref="TransportProducerPool" />. |
| | 164 | | /// </summary> |
| | 165 | | /// |
| | 166 | | /// <returns>A task to be resolved on when the operation has completed.</returns> |
| | 167 | | /// |
| | 168 | | public virtual async Task CloseAsync(CancellationToken cancellationToken = default) |
| | 169 | | { |
| | 170 | | try |
| | 171 | | { |
| 10 | 172 | | ExpirationTimer.Dispose(); |
| 10 | 173 | | } |
| 0 | 174 | | catch (Exception) |
| | 175 | | { |
| 0 | 176 | | } |
| | 177 | |
|
| 10 | 178 | | var pendingCloses = new List<Task>(); |
| | 179 | |
|
| 10 | 180 | | pendingCloses.Add(EventHubProducer.CloseAsync(cancellationToken)); |
| | 181 | |
|
| 32 | 182 | | foreach (var poolItem in Pool.Values) |
| | 183 | | { |
| 6 | 184 | | pendingCloses.Add(poolItem.PartitionProducer.CloseAsync(cancellationToken)); |
| | 185 | | } |
| | 186 | |
|
| 10 | 187 | | Pool.Clear(); |
| | 188 | |
|
| 10 | 189 | | await Task.WhenAll(pendingCloses).ConfigureAwait(false); |
| 6 | 190 | | } |
| | 191 | |
|
| | 192 | | /// <summary> |
| | 193 | | /// Returns a <see cref="TimerCallback" /> that will search for all the expired <see cref="PoolItem" /> |
| | 194 | | /// in the <see cref="Pool" /> and will try to close those that have expired. |
| | 195 | | /// </summary> |
| | 196 | | /// |
| | 197 | | /// <returns>A <see cref="TimerCallback" /> that is periodically run every <see cref="DefaultPerformExpirationPe |
| | 198 | | /// |
| | 199 | | private TimerCallback CreateExpirationTimerCallback() |
| | 200 | | { |
| 136 | 201 | | return _ => |
| 136 | 202 | | { |
| 136 | 203 | | // Capture the timestamp to use a consistent value. |
| 142 | 204 | | var now = DateTimeOffset.UtcNow; |
| 136 | 205 | |
|
| 168 | 206 | | foreach (var key in Pool.Keys.ToList()) |
| 136 | 207 | | { |
| 146 | 208 | | if (Pool.TryGetValue(key, out var poolItem)) |
| 136 | 209 | | { |
| 146 | 210 | | if (poolItem.RemoveAfter <= now) |
| 136 | 211 | | { |
| 140 | 212 | | if (Pool.TryRemove(key, out var _) && !poolItem.ActiveInstances.Any()) |
| 136 | 213 | | { |
| 136 | 214 | | // At this point the pool item may have been closed already |
| 136 | 215 | | // if there was a context switch between the if conditions |
| 136 | 216 | | // and the pool item clean up kicked in. |
| 136 | 217 | |
|
| 136 | 218 | | #pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extensi |
| 140 | 219 | | poolItem.PartitionProducer.CloseAsync(CancellationToken.None).GetAwaiter().GetResult(); |
| 136 | 220 | | #pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extensi |
| 136 | 221 | | } |
| 136 | 222 | | } |
| 136 | 223 | | } |
| 136 | 224 | | } |
| 142 | 225 | | }; |
| | 226 | | } |
| | 227 | |
|
| | 228 | | /// <summary> |
| | 229 | | /// An item of the pool, adding tracking information to a <see cref="TransportProducer" />. |
| | 230 | | /// </summary> |
| | 231 | | /// |
| | 232 | | internal class PoolItem |
| | 233 | | { |
| | 234 | | /// <summary>The period of inactivity after which an item would be removed from the pool.</summary> |
| 2 | 235 | | internal static readonly TimeSpan DefaultRemoveAfterDuration = TimeSpan.FromMinutes(10); |
| | 236 | |
|
| | 237 | | /// <summary> |
| | 238 | | /// An abstracted Event Hub transport-specific <see cref="TransportProducer" /> that is associated with a |
| | 239 | | /// </summary> |
| | 240 | | /// |
| 74 | 241 | | public TransportProducer PartitionProducer { get; private set; } |
| | 242 | |
|
| | 243 | | /// <summary> |
| | 244 | | /// The unique identifier of a partition associated with the Event Hub. |
| | 245 | | /// </summary> |
| | 246 | | /// |
| 0 | 247 | | public string PartitionId { get; private set; } |
| | 248 | |
|
| | 249 | | /// <summary> |
| | 250 | | /// A set of unique identifiers used to track which instances of a <see cref="PoolItem" /> are active. |
| | 251 | | /// </summary> |
| | 252 | | /// |
| 68 | 253 | | public ConcurrentDictionary<string, byte> ActiveInstances { get; } = new ConcurrentDictionary<string, byte>( |
| | 254 | |
|
| | 255 | | /// <summary> |
| | 256 | | /// The UTC date and time when a <see cref="PoolItem" /> will become eligible for eviction. |
| | 257 | | /// </summary> |
| | 258 | | /// |
| 72 | 259 | | public DateTimeOffset RemoveAfter { get; set; } |
| | 260 | |
|
| | 261 | | /// <summary> |
| | 262 | | /// Extends the UTC date and time when <see cref="PoolItem" /> will become eligible for eviction. |
| | 263 | | /// </summary> |
| | 264 | | /// |
| | 265 | | /// <param name="removeAfterDuration">The period of inactivity after which a <see cref="PoolItem" /> will be |
| | 266 | | /// |
| | 267 | | public void ExtendRemoveAfter(TimeSpan? removeAfterDuration) |
| | 268 | | { |
| 54 | 269 | | RemoveAfter = DateTimeOffset.UtcNow.Add(removeAfterDuration ?? DefaultRemoveAfterDuration); |
| 54 | 270 | | } |
| | 271 | |
|
| | 272 | | /// <summary> |
| | 273 | | /// Initializes a new instance of the <see cref="PoolItem" /> class with a default timespan of <see cref=" |
| | 274 | | /// </summary> |
| | 275 | | /// |
| | 276 | | /// <param name="partitionId">The unique identifier of a partition associated with the Event Hub.</param> |
| | 277 | | /// <param name="partitionProducer">An Event Hub transport-specific producer specific to a given partition.< |
| | 278 | | /// <param name="removeAfterDuration">The interval after which a <see cref="PoolItem" /> will become eligibl |
| | 279 | | /// <param name="removeAfter">The UTC date and time when a <see cref="PoolItem" /> will become eligible for |
| | 280 | | /// |
| 32 | 281 | | public PoolItem(string partitionId, |
| 32 | 282 | | TransportProducer partitionProducer, |
| 32 | 283 | | TimeSpan? removeAfterDuration = default, |
| 32 | 284 | | DateTimeOffset? removeAfter = default) |
| | 285 | | { |
| 32 | 286 | | Argument.AssertNotNullOrEmpty(partitionId, nameof(partitionId)); |
| 32 | 287 | | Argument.AssertNotNull(partitionProducer, nameof(partitionProducer)); |
| | 288 | |
|
| 32 | 289 | | PartitionProducer = partitionProducer; |
| 32 | 290 | | PartitionId = partitionId; |
| | 291 | |
|
| 32 | 292 | | if (removeAfter == default) |
| | 293 | | { |
| 26 | 294 | | ExtendRemoveAfter(removeAfterDuration); |
| | 295 | | } |
| | 296 | | else |
| | 297 | | { |
| 6 | 298 | | RemoveAfter = removeAfter.Value; |
| | 299 | | } |
| 6 | 300 | | } |
| | 301 | | } |
| | 302 | |
|
| | 303 | | /// <summary> |
| | 304 | | /// A class wrapping a <see cref="Core.TransportProducer" />, triggering a clean-up when the object is dispose |
| | 305 | | /// </summary> |
| | 306 | | /// |
| | 307 | | internal class PooledProducer: IAsyncDisposable |
| | 308 | | { |
| | 309 | | /// <summary> |
| | 310 | | /// A function responsible of cleaning up the resources in use. |
| | 311 | | /// </summary> |
| | 312 | | /// |
| 48 | 313 | | private Func<TransportProducer, Task> CleanUp { get; } |
| | 314 | |
|
| | 315 | | /// <summary> |
| | 316 | | /// An abstracted Event Hub transport-specific producer that is associated with the |
| | 317 | | /// Event Hub gateway or a specific partition. |
| | 318 | | /// </summary> |
| | 319 | | /// |
| 110 | 320 | | public TransportProducer TransportProducer { get; } |
| | 321 | |
|
| | 322 | | /// <summary> |
| | 323 | | /// Initializes a new instance of the <see cref="PooledProducer" /> class. |
| | 324 | | /// </summary> |
| | 325 | | /// |
| | 326 | | /// <param name="transportProducer">An abstracted Event Hub transport-specific producer that is associated w |
| | 327 | | /// <param name="cleanUp">The function responsible of cleaning up the resources in use.</param> |
| | 328 | | /// |
| 80 | 329 | | public PooledProducer(TransportProducer transportProducer, |
| 80 | 330 | | Func<TransportProducer, Task> cleanUp = default) |
| | 331 | | { |
| 80 | 332 | | Argument.AssertNotNull(transportProducer, nameof(transportProducer)); |
| | 333 | |
|
| 80 | 334 | | TransportProducer = transportProducer; |
| 80 | 335 | | CleanUp = cleanUp; |
| 80 | 336 | | } |
| | 337 | |
|
| | 338 | | /// <summary> |
| | 339 | | /// Performs the task needed to clean up resources used by the <see cref="PooledProducer" />. |
| | 340 | | /// </summary> |
| | 341 | | /// |
| | 342 | | /// <returns>A task to be resolved on when the operation has completed.</returns> |
| | 343 | | /// |
| | 344 | | public virtual ValueTask DisposeAsync() |
| | 345 | | { |
| 36 | 346 | | if (CleanUp != default) |
| | 347 | | { |
| 12 | 348 | | return new ValueTask(CleanUp(TransportProducer)); |
| | 349 | | } |
| | 350 | |
|
| 24 | 351 | | return new ValueTask(Task.CompletedTask); |
| | 352 | | } |
| | 353 | | } |
| | 354 | | } |
| | 355 | | } |