From d74709e583994d8a4f5505546eba688293acbd18 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 21 Oct 2022 09:34:47 -0500 Subject: add Waiter --- src/slskd/Common/WaitKey.cs | 106 ++++++++++ src/slskd/Common/Waiter.cs | 462 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 568 insertions(+) create mode 100644 src/slskd/Common/WaitKey.cs create mode 100644 src/slskd/Common/Waiter.cs (limited to 'src') diff --git a/src/slskd/Common/WaitKey.cs b/src/slskd/Common/WaitKey.cs new file mode 100644 index 00000000..302064db --- /dev/null +++ b/src/slskd/Common/WaitKey.cs @@ -0,0 +1,106 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// 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, either version 3 of the License, or +// (at your option) any later version. +// +// 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/. +// + +namespace slskd +{ + using System; + + /// + /// Uniquely identifies a Wait. + /// + public sealed class WaitKey : IEquatable + { + /// + /// Initializes a new instance of the class. + /// + /// The parts which make up the key. + public WaitKey(params object[] tokenParts) + { + TokenParts = tokenParts; + Token = string.Join(":", TokenParts); + } + + /// + /// Gets the wait token. + /// + public string Token { get; } + + /// + /// Gets the parts which make up the key. + /// + public object[] TokenParts { get; } + + public static bool operator !=(WaitKey lhs, WaitKey rhs) + { + return !lhs.Equals(rhs); + } + + public static bool operator ==(WaitKey lhs, WaitKey rhs) + { + return lhs.Equals(rhs); + } + + /// + /// Compares the specified to this instance. + /// + /// The object to which to compare. + /// A value indicating whether the specified object is equal to this instance. + public override bool Equals(object obj) + { + try + { + return Equals((WaitKey)obj); + } + catch (InvalidCastException) + { + return false; + } + } + + /// + /// Compares the specified WaitKey to this instance. + /// + /// The WaitKey to which to compare. + /// A value indicating whether the specified WaitKey is equal to this instance. + public bool Equals(WaitKey other) + { + return Token == other.Token; + } + + /// + /// Returns the hash code of this instance. + /// + /// The hash code of this instance. + public override int GetHashCode() + { +#if NETSTANDARD2_0 + return string.IsNullOrEmpty(Token) ? 0 : Token.GetHashCode(); +#else + return string.IsNullOrEmpty(Token) ? 0 : Token.GetHashCode(StringComparison.InvariantCulture); +#endif + } + + /// + /// Returns the string representation of the key. + /// + /// The string representation of the key. + public override string ToString() + { + return Token; + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/Waiter.cs b/src/slskd/Common/Waiter.cs new file mode 100644 index 00000000..0c9cca98 --- /dev/null +++ b/src/slskd/Common/Waiter.cs @@ -0,0 +1,462 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// 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, either version 3 of the License, or +// (at your option) any later version. +// +// 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/. +// + +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 ContainsKey(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 ContainsKey(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 enqueing 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 guarateed 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; + } + } + } + } +} \ No newline at end of file -- cgit v1.2.3