// // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ // █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ // ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ // │ Copyright (c) JP Dillingham. // │ // │ This program is free software: you can redistribute it and/or modify // │ it under the terms of the GNU Affero General Public License as published // │ by the Free Software Foundation, version 3. // │ // │ This program is distributed in the hope that it will be useful, // │ but WITHOUT ANY WARRANTY; without even the implied warranty of // │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // │ GNU Affero General Public License for more details. // │ // │ You should have received a copy of the GNU Affero General Public License // │ along with this program. If not, see https://www.gnu.org/licenses/. // │ // │ This program is distributed with Additional Terms pursuant to Section 7 // │ of the AGPLv3. See the LICENSE file in the root directory of this // │ project for the complete terms and conditions. // │ // │ https://slskd.org // │ // ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ // │ SPDX-FileCopyrightText: JP Dillingham // │ SPDX-License-Identifier: AGPL-3.0-only // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // namespace slskd { using System; using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Threading.Tasks; /// /// Enables arbitrary await-able things. /// public interface IWaiter : IDisposable { /// /// Gets the default timeout duration. /// int DefaultTimeout { get; } /// /// Cancels the oldest wait matching the specified . /// /// The unique WaitKey for the wait. void Cancel(WaitKey key); /// /// Cancels all waits. /// void CancelAll(); /// /// Completes the oldest wait matching the specified with the specified . /// /// The wait result type. /// The unique WaitKey for the wait. /// The wait result. void Complete(WaitKey key, T result); /// /// Completes the oldest wait matching the specified . /// /// The unique WaitKey for the wait. void Complete(WaitKey key); /// /// Returns a value indicating whether the specified is being waited upon. /// /// The unique WaitKey to check. /// A value indicating whether the specified key is being waited upon. bool IsWaitingFor(WaitKey key); /// /// Throws the specified on the oldest wait matching the specified . /// /// The unique WaitKey for the wait. /// The Exception to throw. void Throw(WaitKey key, Exception exception); /// /// Causes the oldest wait matching the specified to time out. /// /// The unique WaitKey for the wait. void Timeout(WaitKey key); /// /// Adds a new wait for the specified and with the specified . /// /// The wait result type. /// A unique WaitKey for the wait. /// The wait timeout. /// The cancellation token for the wait. /// A Task representing the wait. Task Wait(WaitKey key, int? timeout = null, CancellationToken? cancellationToken = null); /// /// Adds a new wait for the specified and with the specified . /// /// A unique WaitKey for the wait. /// The wait timeout. /// The cancellation token for the wait. /// A Task representing the wait. Task Wait(WaitKey key, int? timeout = null, CancellationToken? cancellationToken = null); /// /// Adds a new wait for the specified which does not time out. /// /// The wait result type. /// A unique WaitKey for the wait. /// The cancellation token for the wait. /// A Task representing the wait. Task WaitIndefinitely(WaitKey key, CancellationToken? cancellationToken = null); /// /// Adds a new wait for the specified which does not time out. /// /// A unique WaitKey for the wait. /// The cancellation token for the wait. /// A Task representing the wait. Task WaitIndefinitely(WaitKey key, CancellationToken? cancellationToken = null); } /// /// Enables arbitrary await-able things. /// public sealed class Waiter : IWaiter { private const int DefaultTimeoutValue = 5000; /// /// Initializes a new instance of the class with the default timeout. /// public Waiter() : this(DefaultTimeoutValue) { } /// /// Initializes a new instance of the class with the specified . /// /// The default timeout duration for message waits. public Waiter(int defaultTimeout) { DefaultTimeout = defaultTimeout; } /// /// Gets the default timeout duration, in milliseconds. /// public int DefaultTimeout { get; private set; } private bool Disposed { get; set; } private ConcurrentDictionary Locks { get; } = new ConcurrentDictionary(); private ConcurrentDictionary> Waits { get; } = new ConcurrentDictionary>(); /// /// Cancels the oldest wait matching the specified . /// /// The unique WaitKey for the wait. public void Cancel(WaitKey key) { Disposition(key, wait => wait.TaskCompletionSource.TrySetCanceled()); } /// /// Cancels all waits. /// public void CancelAll() { var keys = Waits.Keys.ToList(); foreach (var key in keys) { Cancel(key); } } /// /// Completes the oldest wait matching the specified with the specified . /// /// The wait result type. /// The unique WaitKey for the wait. /// The wait result. public void Complete(WaitKey key, T result) { Disposition(key, wait => ((TaskCompletionSource)wait.TaskCompletionSource).TrySetResult(result)); } /// /// Completes the oldest wait matching the specified . /// /// The unique WaitKey for the wait. public void Complete(WaitKey key) { Complete(key, null); } /// /// Returns a value indicating whether the specified is being waited upon. /// /// The unique WaitKey to check. /// A value indicating whether the specified key is being waited upon. public bool IsWaitingFor(WaitKey key) => Waits.ContainsKey(key); /// /// Disposes this instance. /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// /// Disposes this instance. /// /// A value indicating whether disposal is in progress. public void Dispose(bool disposing) { if (!Disposed) { if (disposing) { CancelAll(); } Disposed = true; } } /// /// Throws the specified on the oldest wait matching the specified . /// /// The unique WaitKey for the wait. /// The Exception to throw. public void Throw(WaitKey key, Exception exception) { Disposition(key, wait => wait.TaskCompletionSource.TrySetException(exception)); } /// /// Causes the oldest wait matching the specified to time out. /// /// The unique WaitKey for the wait. public void Timeout(WaitKey key) { Disposition(key, wait => wait.TaskCompletionSource.TrySetException(new TimeoutException($"The wait timed out after {wait.Timeout} milliseconds"))); } /// /// Adds a new wait for the specified and with the specified . /// /// A unique WaitKey for the wait. /// The wait timeout, in milliseconds. /// The cancellation token for the wait. /// A Task representing the wait. public Task Wait(WaitKey key, int? timeout = null, CancellationToken? cancellationToken = null) { return Wait(key, timeout, cancellationToken); } /// /// Adds a new wait for the specified and with the specified . /// /// The wait result type. /// A unique WaitKey for the wait. /// The wait timeout, in milliseconds. /// The cancellation token for the wait. /// A Task representing the wait. public Task Wait(WaitKey key, int? timeout = null, CancellationToken? cancellationToken = null) { timeout ??= DefaultTimeout; cancellationToken ??= CancellationToken.None; var taskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var wait = new PendingWait( taskCompletionSource, timeout.Value, cancelAction: () => Cancel(key), timeoutAction: () => Timeout(key), cancellationToken.Value); // obtain a read lock for the key. this is necessary to prevent this code from adding a wait to the ConcurrentQueue // while the containing dictionary entry is being cleaned up in Disposition(), effectively discarding the new wait. var recordLock = Locks.GetOrAdd(key, new ReaderWriterLockSlim()); recordLock.EnterReadLock(); try { Waits.AddOrUpdate(key, new ConcurrentQueue(new[] { wait }), (_, queue) => { queue.Enqueue(wait); return queue; }); } finally { recordLock.ExitReadLock(); } // defer registration to prevent the wait from being dispositioned prior to being successfully queued this is a // concern if we are given a timeout of 0, or a cancellation token which is already cancelled wait.Register(); return ((TaskCompletionSource)wait.TaskCompletionSource).Task; } /// /// Adds a new wait for the specified which does not time out. /// /// A unique WaitKey for the wait. /// The cancellation token for the wait. /// A Task representing the wait. public Task WaitIndefinitely(WaitKey key, CancellationToken? cancellationToken = null) { return WaitIndefinitely(key, cancellationToken); } /// /// Adds a new wait for the specified which does not time out. /// /// The wait result type. /// A unique WaitKey for the wait. /// The cancellation token for the wait. /// A Task representing the wait. public Task WaitIndefinitely(WaitKey key, CancellationToken? cancellationToken = null) { return Wait(key, int.MaxValue, cancellationToken); } private void Disposition(WaitKey key, Action action) { if (Waits.TryGetValue(key, out var queue) && queue.TryDequeue(out var wait)) { action(wait); wait.Dispose(); if (Locks.TryGetValue(key, out var recordLock)) { // enter a read lock first; TryPeek and TryDequeue are atomic so there's no risky operation until later. recordLock.EnterUpgradeableReadLock(); try { // clean up entries in the Waits and Locks dictionaries if the corresponding ConcurrentQueue is empty. // this is tricky, because we don't want to remove a record if another thread is in the process of // enqueueing a new wait. if (queue.IsEmpty) { // enter the write lock to prevent Wait() (which obtains a read lock) from enqueuing any more waits // before we can delete the dictionary record. it's ok and expected that Wait() might add this record // back to the dictionary as soon as this unblocks; we're preventing new waits from being discarded if // they are added by another thread just prior to the TryRemove() operation below. recordLock.EnterWriteLock(); try { // check the queue again to ensure Wait() didn't enqueue anything between the last check and when // we entered the write lock. this is guaranteed to be safe since we now have exclusive access to // the record and it should be impossible to remove a record containing a non-empty queue if (queue.IsEmpty) { Waits.TryRemove(key, out _); Locks.TryRemove(key, out _); } } finally { recordLock.ExitWriteLock(); } } } finally { recordLock.ExitUpgradeableReadLock(); } } } } /// /// The composite value for the wait dictionary. /// internal class PendingWait : IDisposable { /// /// Initializes a new instance of the class. /// /// The task completion source for the wait task. /// The number of milliseconds after which the wait is to time out. /// The action to invoke when the task is cancelled. /// The action to invoke when the task times out. /// The cancellation token for the wait. public PendingWait(dynamic taskCompletionSource, int timeout, Action cancelAction, Action timeoutAction, CancellationToken cancellationToken) { TaskCompletionSource = taskCompletionSource; Timeout = timeout; CancelAction = cancelAction; TimeoutAction = timeoutAction; CancellationToken = cancellationToken; } /// /// Gets the task completion source for the wait task. /// public dynamic TaskCompletionSource { get; } /// /// Gets the number of milliseconds after which the wait is to time out. /// public int Timeout { get; } private Action CancelAction { get; set; } private CancellationToken CancellationToken { get; set; } private CancellationTokenRegistration CancellationTokenRegistration { get; set; } private bool Disposed { get; set; } private Action TimeoutAction { get; set; } private CancellationTokenRegistration TimeoutTokenRegistration { get; set; } private CancellationTokenSource TimeoutTokenSource { get; set; } /// /// Releases the managed and unmanaged resources used by the . /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// /// Register cancellation and timeout actions. /// public void Register() { CancellationTokenRegistration = CancellationToken.Register(() => CancelAction()); TimeoutTokenSource = new CancellationTokenSource(Timeout); TimeoutTokenRegistration = TimeoutTokenSource.Token.Register(() => TimeoutAction()); } /// /// Releases the managed and unmanaged resources used by the . /// /// A value indicating whether the object is being disposed. protected virtual void Dispose(bool disposing) { if (!Disposed) { if (disposing) { CancellationTokenRegistration.Dispose(); TimeoutTokenSource?.Dispose(); TimeoutTokenRegistration.Dispose(); } Disposed = true; } } } } }