// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Threading;
namespace Microsoft.CodeAnalysis.Shared.Utilities;
/// <summary>
/// A class similar to a <see cref="AsyncBatchingWorkQueue{TItem}"/> but with a few key differences:
///
/// <list type="bullet">
/// <item>Each item has a priority, higher priorities (defined as a larger number away from zero) are processed first.</item>
/// <item>Each item has a single priority and only appears in the queue once; unlike <see cref="AsyncBatchingWorkQueue{TItem}"/> where deduplication is optional.</item>
/// <item>When a batch is started, it is given a <see cref="WorkToProcess"/> that invokes callbacks for eligible items, rather than a list. This allows items to be reprioritized or added until a consumer finds no eligible work.</item>
/// <item>We don't support cancelling currently queued work, since the users of this don't have a need. If that becomes a need, that can be added.</item>
/// </list>
///
/// The assumption here is this type is helpful for situations when batches are long-running, so being able to reprioritize items or "sneak things in" to a batch already running
/// is more helpful.
/// </summary>
internal sealed class AsyncPriorityWorkQueue<TItem> : IDisposable where TItem : notnull
{
private readonly Func<WorkToProcess, CancellationToken, ValueTask> _processBatchAsync;
private readonly IAsynchronousOperationListener _asyncListener;
/// <summary>
/// Delay we wait after finishing the processing of one batch and starting up another.
/// </summary>
private readonly TimeSpan _delay;
/// <summary>
/// The gate for all mutable fields of this type that are listed below this.
/// </summary>
private readonly object _gate = new();
/// <summary>
/// Cancellation token controlling the entire queue. Once this is triggered, we don't want to do any more work
/// at all. This is cancelled by a call to <see cref="Dispose()"/>; the IsCancellationRequested flag of this token
/// can be used as the "is disposed" flag for this object.
/// </summary>
private readonly CancellationTokenSource _entireQueueCancellationTokenSource;
/// <summary>
/// The items that have been added to the queue by priority; the array index is the priority and the end of the array is the highest priority.
/// Unfortunately .NET doesn't have a PriorityQueue type that allows priorities to be changed, so this is the simplest implementation.
/// The assumption is the number of priorities is fixed -- if that is not the case then a different implementation is needed here.
/// </summary>
private readonly HashSet<TItem>[] _itemsByPriority;
private readonly IEqualityComparer<TItem> _equalityComparer;
/// <summary>
/// Task kicked off to do the next batch of processing of <see cref="_itemsByPriority"/>. These
/// tasks form a chain so that the next task only processes when the previous one completes.
/// </summary>
private Task _updateTask = Task.CompletedTask;
/// <summary>
/// Whether or not there is an existing task in flight that will process the current batch
/// of items in <see cref="_itemsByPriority"/> If there is an existing in flight task, we don't need to
/// kick off a new one if we receive more work before it runs.
/// </summary>
private bool _taskInFlight = false;
public AsyncPriorityWorkQueue(
int maximumPriority,
TimeSpan delay,
Func<WorkToProcess, CancellationToken, ValueTask> processBatchAsync,
IEqualityComparer<TItem> equalityComparer,
IAsynchronousOperationListener asyncListener)
{
if (maximumPriority < 0)
throw new ArgumentOutOfRangeException(nameof(maximumPriority), maximumPriority, "Maximum priority must be non-negative.");
_itemsByPriority = new HashSet<TItem>[maximumPriority + 1];
_equalityComparer = equalityComparer;
_delay = delay;
_processBatchAsync = processBatchAsync;
_asyncListener = asyncListener;
for (var i = 0; i < _itemsByPriority.Length; i++)
_itemsByPriority[i] = new HashSet<TItem>(equalityComparer);
_entireQueueCancellationTokenSource = new CancellationTokenSource();
}
public void AddWork(TItem item, int priority)
{
if (priority < 0 || priority >= _itemsByPriority.Length)
throw new ArgumentOutOfRangeException(paramName: nameof(priority), message: $"Priority must be between 0 and {_itemsByPriority.Length - 1}");
lock (_gate)
{
if (_entireQueueCancellationTokenSource.IsCancellationRequested)
return;
if (!TryRaiseWorkPriority_NoLock(item, priority, addIfUnscheduled: true))
return;
// If we don't already have an active task, start one
if (!_taskInFlight)
StartWork();
}
}
public void RaiseWorkPriorityIfScheduled(TItem item, int newPriority)
{
if (newPriority < 0 || newPriority >= _itemsByPriority.Length)
throw new ArgumentOutOfRangeException(paramName: nameof(newPriority), message: $"Priority must be between 0 and {_itemsByPriority.Length - 1}");
if (newPriority == 0)
return;
lock (_gate)
{
if (_entireQueueCancellationTokenSource.IsCancellationRequested)
return;
TryRaiseWorkPriority_NoLock(item, newPriority, addIfUnscheduled: false);
}
}
/// <summary>
/// Lowers the priority of the specified work item if it is currently scheduled at a higher priority.
/// </summary>
public void LowerWorkPriorityIfScheduled(TItem item, int newPriority)
{
if (newPriority < 0 || newPriority >= _itemsByPriority.Length)
throw new ArgumentOutOfRangeException(paramName: nameof(newPriority), message: $"Priority must be between 0 and {_itemsByPriority.Length - 1}");
lock (_gate)
{
if (_entireQueueCancellationTokenSource.IsCancellationRequested)
return;
for (var priorityToCheck = _itemsByPriority.Length - 1; priorityToCheck > newPriority; priorityToCheck--)
{
if (_itemsByPriority[priorityToCheck].Remove(item))
{
Contract.ThrowIfFalse(_itemsByPriority[newPriority].Add(item));
return;
}
}
}
}
/// <summary>
/// Raises the priority of the specified work item. Optionally adds it if it is not already scheduled.
/// </summary>
/// <returns>True if the item was added or its priority was successfully raised.</returns>
private bool TryRaiseWorkPriority_NoLock(TItem item, int priority, bool addIfUnscheduled)
{
for (var priorityToCheck = _itemsByPriority.Length - 1; priorityToCheck >= 0; priorityToCheck--)
{
if (_itemsByPriority[priorityToCheck].Contains(item))
{
// Check if the item is already scheduled at a sufficient priority.
if (priorityToCheck >= priority)
return false;
// Found the item at a lower priority, remove it and add it to the new priority.
Contract.ThrowIfFalse(_itemsByPriority[priorityToCheck].Remove(item));
Contract.ThrowIfFalse(_itemsByPriority[priority].Add(item));
return true;
}
}
// Add the item to the correct priority since it was not found.
return addIfUnscheduled && _itemsByPriority[priority].Add(item);
}
private void StartWork()
{
lock (_gate)
{
// Kick one off to process the items
// We always attach the task to the previous one so that batches are processed
// in order.
_updateTask = ContinueAfterDelayAsync(_updateTask);
_taskInFlight = true;
async Task ContinueAfterDelayAsync(Task lastTask)
{
using var _ = _asyncListener.BeginAsyncOperation(nameof(AddWork));
// Await the previous item in the task chain in a non-throwing fashion. Regardless of whether that last
// task completed successfully or not, we want to move onto the next batch.
await lastTask.NoThrowAwaitableInternal(captureContext: false);
// If we were asked to shutdown, immediately transition to the canceled state without doing any more work.
if (_entireQueueCancellationTokenSource.IsCancellationRequested)
return;
// Ensure that we always yield the current thread this is necessary for correctness as we are called
// inside a lock that _taskInFlight to true. We must ensure that the work to process the next batch
// must be on another thread that runs afterwards, can only grab the thread once we release it and will
// then reset that bool back to false
await Task.Yield().ConfigureAwait(false);
await _asyncListener.Delay(_delay, _entireQueueCancellationTokenSource.Token).NoThrowAwaitableInternal(false);
// If we were asked to shutdown, immediately transition to the canceled state without doing any more work.
if (_entireQueueCancellationTokenSource.IsCancellationRequested)
return;
await ProcessNextBatchAsync().ConfigureAwait(false);
}
}
}
private async Task ProcessNextBatchAsync()
{
lock (_gate)
{
// If we don't have any items left, then the work was cancelled and we can immediately be done.
if (_itemsByPriority.All(static s => s.Count == 0))
{
_taskInFlight = false;
return;
}
}
try
{
await _processBatchAsync(new WorkToProcess(this), _entireQueueCancellationTokenSource.Token).ConfigureAwait(false);
}
finally
{
// We have completed that batch. It's possible the enumeration was stopped prematurely, or that new items were added while we were processing but we couldn't process
// them yet. If there is remaining work, let's queue a new task to start it again.
lock (_gate)
{
if (_itemsByPriority.Any(static s => s.Count > 0))
StartWork();
else
_taskInFlight = false;
}
}
}
/// <summary>
/// Tries to get the next item from the queue that is not already in flight. If there are no items left, returns false and sets <paramref name="item"/> to default.
/// </summary>
/// <param name="itemsInFlight">The list of items currently being processed; we want to skip these so we're not processing an item in parallel.</param>
private bool TryGetNextItem(ICollection<TItem> itemsInFlight, [NotNullWhen(true)] out TItem? item)
{
lock (_gate)
{
for (var priorityToCheck = _itemsByPriority.Length - 1; priorityToCheck >= 0; priorityToCheck--)
{
var items = _itemsByPriority[priorityToCheck];
foreach (var itemToCheck in items)
{
if (!itemsInFlight.Contains(itemToCheck))
{
items.Remove(itemToCheck);
item = itemToCheck;
return true;
}
}
}
// We have no items left; we'll end the enumeration here; if a new item is added, we need to start a task again
item = default;
return false;
}
}
public void Dispose()
{
lock (_gate)
{
// If we've previously disposed, we don't need to do anything further
if (_entireQueueCancellationTokenSource.IsCancellationRequested)
return;
// Cancel all work in the queue
for (var i = 0; i < _itemsByPriority.Length; i++)
_itemsByPriority[i].Clear();
_entireQueueCancellationTokenSource.Cancel();
}
}
/// <summary>
/// Represents the work available to a single batch. Multiple consumers may call <see cref="TryProcessNextItemAsync"/>
/// concurrently to process items in priority order; equivalent items are never processed concurrently.
/// All processing calls must complete before the batch callback returns.
/// </summary>
public sealed class WorkToProcess(AsyncPriorityWorkQueue<TItem> queue)
{
private readonly object _gate = new object();
private readonly HashSet<TItem> _itemsInFlight = new HashSet<TItem>(queue._equalityComparer);
private bool _enumeratorStopped;
/// <summary>
/// Invokes <paramref name="processItemAsync"/> on the next item in the queue, if there is one. Returns true if an item was processed, false if there are no more items to process.
/// </summary>
public async ValueTask<bool> TryProcessNextItemAsync(Func<TItem, ValueTask> processItemAsync)
{
TItem? item;
lock (_gate)
{
if (_enumeratorStopped)
return false;
if (!queue.TryGetNextItem(_itemsInFlight, out item))
{
// Callers may process a batch by launching several parallel tasks or threads to process all the items.
// If we were to hit the end of the batch, those parallel tasks/threads will start to shut down. If we let
// new work get picked up, then we'll be using only the remaining parallel tasks/threads to process it, which
// might end up with less parallelism than expected. It's easier just to let everything stop here and wait for
// the next batch to pick it up.
_enumeratorStopped = true;
return false;
}
Contract.ThrowIfFalse(_itemsInFlight.Add(item));
}
try
{
await processItemAsync(item).ConfigureAwait(false);
return true;
}
finally
{
lock (_gate)
{
Contract.ThrowIfFalse(_itemsInFlight.Remove(item));
}
}
}
}
}