diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-09-22 08:33:20 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-09-22 08:33:20 -0500 |
| commit | bc17beab782c8c9b9c04035a31c435d4d9c42596 (patch) | |
| tree | e20377685a358a977639531fc037405a74cb87d9 /src/slskd/Common | |
| parent | 597b44ff36d68a7263b7df60bc9a666994e5f82b (diff) | |
| parent | 1d50171490d6d4dbc025ef25bfbb373bc8a5331b (diff) | |
| download | slskd-bc17beab782c8c9b9c04035a31c435d4d9c42596.tar.gz | |
Merge pull request #202 from slskd/cleanup
General refactoring and removal of technical debt
Diffstat (limited to 'src/slskd/Common')
| -rw-r--r-- | src/slskd/Common/Exceptions/ApplicationShutdownException.cs | 72 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/IntentionalDisconnectException.cs | 72 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/RetryException.cs | 72 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/ShareAliasException.cs | 72 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/ShareScanInProgressException.cs | 72 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/SlskdException.cs | 72 | ||||
| -rw-r--r-- | src/slskd/Common/Extensions.cs | 30 | ||||
| -rw-r--r-- | src/slskd/Common/IStateMonitor.cs | 47 | ||||
| -rw-r--r-- | src/slskd/Common/ManagedState.cs | 231 | ||||
| -rw-r--r-- | src/slskd/Common/StateMonitor.cs | 102 | ||||
| -rw-r--r-- | src/slskd/Common/UserEndPointCache.cs | 61 |
11 files changed, 724 insertions, 179 deletions
diff --git a/src/slskd/Common/Exceptions/ApplicationShutdownException.cs b/src/slskd/Common/Exceptions/ApplicationShutdownException.cs new file mode 100644 index 00000000..e30b5c79 --- /dev/null +++ b/src/slskd/Common/Exceptions/ApplicationShutdownException.cs @@ -0,0 +1,72 @@ +// <copyright file="ApplicationShutdownException.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// <summary> + /// Represents a normal application shutdown. + /// </summary> + [ExcludeFromCodeCoverage] + [Serializable] + public class ApplicationShutdownException : SlskdException + { + /// <summary> + /// Initializes a new instance of the <see cref="ApplicationShutdownException"/> class. + /// </summary> + public ApplicationShutdownException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ApplicationShutdownException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public ApplicationShutdownException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ApplicationShutdownException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public ApplicationShutdownException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ApplicationShutdownException"/> class with serialized data. + /// </summary> + /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> + protected ApplicationShutdownException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Exceptions/IntentionalDisconnectException.cs b/src/slskd/Common/Exceptions/IntentionalDisconnectException.cs new file mode 100644 index 00000000..d5293e63 --- /dev/null +++ b/src/slskd/Common/Exceptions/IntentionalDisconnectException.cs @@ -0,0 +1,72 @@ +// <copyright file="IntentionalDisconnectException.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// <summary> + /// Represents an intentional client disconnect. + /// </summary> + [ExcludeFromCodeCoverage] + [Serializable] + public class IntentionalDisconnectException : SlskdException + { + /// <summary> + /// Initializes a new instance of the <see cref="IntentionalDisconnectException"/> class. + /// </summary> + public IntentionalDisconnectException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="IntentionalDisconnectException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public IntentionalDisconnectException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="IntentionalDisconnectException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public IntentionalDisconnectException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="IntentionalDisconnectException"/> class with serialized data. + /// </summary> + /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> + protected IntentionalDisconnectException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Exceptions/RetryException.cs b/src/slskd/Common/Exceptions/RetryException.cs new file mode 100644 index 00000000..c688f377 --- /dev/null +++ b/src/slskd/Common/Exceptions/RetryException.cs @@ -0,0 +1,72 @@ +// <copyright file="RetryException.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// <summary> + /// Represents erorrs that originate while attempting to execute retry logic. + /// </summary> + [ExcludeFromCodeCoverage] + [Serializable] + public class RetryException : Exception + { + /// <summary> + /// Initializes a new instance of the <see cref="RetryException"/> class. + /// </summary> + public RetryException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="RetryException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public RetryException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="RetryException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public RetryException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="RetryException"/> class with serialized data. + /// </summary> + /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> + protected RetryException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Exceptions/ShareAliasException.cs b/src/slskd/Common/Exceptions/ShareAliasException.cs new file mode 100644 index 00000000..3047d0a9 --- /dev/null +++ b/src/slskd/Common/Exceptions/ShareAliasException.cs @@ -0,0 +1,72 @@ +// <copyright file="ShareAliasException.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// <summary> + /// Represents an error that occurs when multiple share scans are attempted concurrently. + /// </summary> + [ExcludeFromCodeCoverage] + [Serializable] + public class ShareAliasException : SlskdException + { + /// <summary> + /// Initializes a new instance of the <see cref="ShareAliasException"/> class. + /// </summary> + public ShareAliasException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ShareAliasException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public ShareAliasException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ShareAliasException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public ShareAliasException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ShareAliasException"/> class with serialized data. + /// </summary> + /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> + protected ShareAliasException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Exceptions/ShareScanInProgressException.cs b/src/slskd/Common/Exceptions/ShareScanInProgressException.cs new file mode 100644 index 00000000..2e548930 --- /dev/null +++ b/src/slskd/Common/Exceptions/ShareScanInProgressException.cs @@ -0,0 +1,72 @@ +// <copyright file="ShareScanInProgressException.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// <summary> + /// Represents an error that occurs when multiple share scans are attempted concurrently. + /// </summary> + [ExcludeFromCodeCoverage] + [Serializable] + public class ShareScanInProgressException : SlskdException + { + /// <summary> + /// Initializes a new instance of the <see cref="ShareScanInProgressException"/> class. + /// </summary> + public ShareScanInProgressException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ShareScanInProgressException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public ShareScanInProgressException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ShareScanInProgressException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public ShareScanInProgressException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ShareScanInProgressException"/> class with serialized data. + /// </summary> + /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> + protected ShareScanInProgressException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Exceptions/SlskdException.cs b/src/slskd/Common/Exceptions/SlskdException.cs new file mode 100644 index 00000000..6b4cfc2a --- /dev/null +++ b/src/slskd/Common/Exceptions/SlskdException.cs @@ -0,0 +1,72 @@ +// <copyright file="SlskdException.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// <summary> + /// Represents erorrs that originate from slskd logic. + /// </summary> + [ExcludeFromCodeCoverage] + [Serializable] + public class SlskdException : Exception + { + /// <summary> + /// Initializes a new instance of the <see cref="SlskdException"/> class. + /// </summary> + public SlskdException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="SlskdException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public SlskdException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="SlskdException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public SlskdException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="SlskdException"/> class with serialized data. + /// </summary> + /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> + protected SlskdException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index 077f5b17..4f2cf29f 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -89,36 +89,6 @@ namespace slskd } /// <summary> - /// Computes a stable/consistent hash code for strings. - /// </summary> - /// <remarks> - /// https://stackoverflow.com/questions/5154970/how-do-i-create-a-hashcode-in-net-c-for-a-string-that-is-safe-to-store-in-a - /// </remarks> - /// <param name="str">The string for which the hash code is to be computed.</param> - /// <returns>The hash code.</returns> - public static int GetStableHashCode(this string str) - { - unchecked - { - int hash1 = 5381; - int hash2 = hash1; - - for (int i = 0; i < str.Length && str[i] != '\0'; i += 2) - { - hash1 = ((hash1 << 5) + hash1) ^ str[i]; - if (i == str.Length - 1 || str[i + 1] == '\0') - { - break; - } - - hash2 = ((hash2 << 5) + hash2) ^ str[i + 1]; - } - - return hash1 + (hash2 * 1566083941); - } - } - - /// <summary> /// Determines whether the string is a valid regular expression. /// </summary> /// <param name="pattern">The string to validate.</param> diff --git a/src/slskd/Common/IStateMonitor.cs b/src/slskd/Common/IStateMonitor.cs deleted file mode 100644 index 813dbfd5..00000000 --- a/src/slskd/Common/IStateMonitor.cs +++ /dev/null @@ -1,47 +0,0 @@ -// <copyright file="IStateMonitor.cs" company="slskd Team"> -// 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/. -// </copyright> - -namespace slskd -{ - using System; - - /// <summary> - /// Provideds observable management of state objects. - /// </summary> - /// <typeparam name="T">The type of the tracked state object.</typeparam> - public interface IStateMonitor<T> - { - /// <summary> - /// Gets the current application state. - /// </summary> - T CurrentValue { get; } - - /// <summary> - /// Registers a listener to be called whenever the tracked state changes. - /// </summary> - /// <param name="listener">Registers a listener to be called whenver state changes.</param> - /// <returns>An <see cref="IDisposable"/> which should be disposed to stop listening for changes.</returns> - IDisposable OnChange(Action<(T Previous, T Current)> listener); - - /// <summary> - /// Replaces the current state with the value resolved by the <paramref name="setter"/>. - /// </summary> - /// <param name="setter">Given the current state, resolves a new state value.</param> - /// <returns>The updated state.</returns> - T SetValue(Func<T, T> setter); - } -} diff --git a/src/slskd/Common/ManagedState.cs b/src/slskd/Common/ManagedState.cs new file mode 100644 index 00000000..bfde3c80 --- /dev/null +++ b/src/slskd/Common/ManagedState.cs @@ -0,0 +1,231 @@ +// <copyright file="ManagedState.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.Text.Json; + using Microsoft.Extensions.DependencyInjection; + + /// <summary> + /// Provides observable read access for state objects. + /// </summary> + /// <typeparam name="T">The type of the tracked state object.</typeparam> + public interface IStateMonitor<T> + { + /// <summary> + /// Gets the current state. + /// </summary> + T CurrentValue { get; } + + /// <summary> + /// Registers a listener to be called whenever the tracked state changes. + /// </summary> + /// <param name="listener">Registers a listener to be called whenver state changes.</param> + /// <returns>An <see cref="IDisposable"/> which should be disposed to stop listening for changes.</returns> + IDisposable OnChange(Action<(T Previous, T Current)> listener); + } + + /// <summary> + /// Provides write access for state objects. + /// </summary> + /// <typeparam name="T">The type of the tracked state object.</typeparam> + public interface IStateMutator<T> + { + /// <summary> + /// Replaces the current state with the value resolved by the <paramref name="setter"/>. + /// </summary> + /// <param name="setter">Given the current state, resolves a new state value.</param> + /// <returns>The updated state.</returns> + T SetValue(Func<T, T> setter); + } + + /// <summary> + /// Provides point-in-time read access for state objects. + /// </summary> + /// <typeparam name="T">The type of the tracked state object.</typeparam> + public interface IStateSnapshot<out T> + { + /// <summary> + /// Gets the snapshotted state. + /// </summary> + T Value { get; } + } + + /// <summary> + /// Provides observable management of state objects. + /// </summary> + /// <typeparam name="T">The type of the tracked state object.</typeparam> + public interface IManagedState<T> : IStateMonitor<T>, IStateMutator<T> + { + /// <summary> + /// Gets a point-in-time snapshot of the current state. + /// </summary> + IStateSnapshot<T> Snapshot { get; } + } + + /// <summary> + /// ManagedState extension methods. + /// </summary> + public static class ManagedStateExtensions + { + /// <summary> + /// <para> + /// Adds managed state of an object of the specified <typeparamref name="T"/> to the specified <see cref="IServiceCollection"/>. + /// </para> + /// <para> + /// <list type="bullet"> + /// <item>A singleton instance of <see cref="IManagedState{T}"/> to be used by instances requiring full control over the state</item> + /// <item>A singleton instance of <see cref="IStateMutator{T}"/> to be used by instances requiring the ability to mutate the state</item> + /// <item>A singleton instance of <see cref="IStateMonitor{T}"/> to be used by instances requiring observable read access to the state</item> + /// <item>A transient instance of <see cref="IStateSnapshot{T}"/> to be used by scoped or transient instances requiring the current state</item> + /// </list> + /// </para> + /// </summary> + /// <typeparam name="T">The type of the managed state object.</typeparam> + /// <param name="services">The IServiceCollection to which the managed state is to be added.</param> + /// <param name="setter">An optional anonymous function used to apply an initial state mutation.</param> + /// <returns>The IServiceCollection with managed state added.</returns> + public static IServiceCollection AddManagedState<T>(this IServiceCollection services, Func<T, T> setter = null) + where T : class + { + services.AddSingleton<IManagedState<T>, ManagedState<T>>(); + services.AddSingleton(services => + { + var monitor = (IStateMutator<T>)services.GetRequiredService<IManagedState<T>>(); + + if (setter != null) + { + monitor.SetValue(setter); + } + + return monitor; + }); + services.AddSingleton(services => (IStateMonitor<T>)services.GetRequiredService<IManagedState<T>>()); + services.AddTransient(services => services.GetRequiredService<IManagedState<T>>().Snapshot); + + return services; + } + } + + /// <summary> + /// Provides a point-in-time snapshot of state objects. + /// </summary> + /// <typeparam name="T">The type of the tracked state object.</typeparam> + public class StateSnapshot<T> : IStateSnapshot<T> + { + /// <summary> + /// Initializes a new instance of the <see cref="StateSnapshot{T}"/> class. + /// </summary> + /// <param name="value">The current value of the state.</param> + public StateSnapshot(T value) + { + Value = JsonSerializer.Deserialize<T>(JsonSerializer.Serialize(value)); + } + + /// <summary> + /// Gets a snapshot of the current application state. + /// </summary> + public T Value { get; } + } + + /// <summary> + /// Provides observable management of state objects. + /// </summary> + /// <typeparam name="T">The type of the tracked state object.</typeparam> + public class ManagedState<T> : IManagedState<T> + { + private event Action<(T, T)> Changed; + + /// <summary> + /// Gets the current application state. + /// </summary> + public T CurrentValue { get; private set; } = (T)Activator.CreateInstance(typeof(T)); + + /// <summary> + /// Gets a point-in-time snapshot of the current state. + /// </summary> + public IStateSnapshot<T> Snapshot => new StateSnapshot<T>(CurrentValue); + + private object Lock { get; } = new object(); + + /// <summary> + /// Registers a listener to be called whenever the stracked state changes. + /// </summary> + /// <param name="listener">Registers a listener to be called whenver state changes.</param> + /// <returns>An <see cref="IDisposable"/> which should be disposed to stop listening for changes.</returns> + public IDisposable OnChange(Action<(T Previous, T Current)> listener) + { + var disposable = new ManagedStateDisposable<T>(this, listener); + Changed += disposable.OnChange; + return disposable; + } + + /// <summary> + /// Replaces the current state with the value resolved by the <paramref name="setter"/>. + /// </summary> + /// <param name="setter">Given the current state, resolves a new state value.</param> + /// <returns>The updated state.</returns> + public T SetValue(Func<T, T> setter) + { + lock (Lock) + { + var previous = CurrentValue.ToJson().ToObject<T>(); + CurrentValue = setter(CurrentValue); + + Changed?.Invoke((previous, CurrentValue)); + return CurrentValue; + } + } + +#pragma warning disable CS0693 // Type parameter has the same name as the type parameter from outer type + private class ManagedStateDisposable<T> : IDisposable +#pragma warning restore CS0693 // Type parameter has the same name as the type parameter from outer type + { + public ManagedStateDisposable(ManagedState<T> stateMonitor, Action<(T Previous, T Current)> listener) + { + StateMonitor = stateMonitor; + Listener = listener; + } + + private bool Disposed { get; set; } + private Action<(T Previous, T Current)> Listener { get; } + private ManagedState<T> StateMonitor { get; } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + public void OnChange((T Previous, T Current) args) => Listener.Invoke(args); + + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + StateMonitor.Changed -= OnChange; + } + + Disposed = true; + } + } + } + } +} diff --git a/src/slskd/Common/StateMonitor.cs b/src/slskd/Common/StateMonitor.cs deleted file mode 100644 index 9397d9b2..00000000 --- a/src/slskd/Common/StateMonitor.cs +++ /dev/null @@ -1,102 +0,0 @@ -// <copyright file="StateMonitor.cs" company="slskd Team"> -// 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/. -// </copyright> - -namespace slskd -{ - using System; - - /// <summary> - /// Provideds observable management of state objects. - /// </summary> - /// <typeparam name="T">The type of the tracked state object.</typeparam> - public class StateMonitor<T> : IStateMonitor<T> - { - private event Action<(T, T)> Changed; - - /// <summary> - /// Gets the current application state. - /// </summary> - public T CurrentValue { get; private set; } = (T)Activator.CreateInstance(typeof(T)); - - private object Lock { get; } = new object(); - - /// <summary> - /// Registers a listener to be called whenever the stracked state changes. - /// </summary> - /// <param name="listener">Registers a listener to be called whenver state changes.</param> - /// <returns>An <see cref="IDisposable"/> which should be disposed to stop listening for changes.</returns> - public IDisposable OnChange(Action<(T Previous, T Current)> listener) - { - var disposable = new StateTrackerDisposable<T>(this, listener); - Changed += disposable.OnChange; - return disposable; - } - - /// <summary> - /// Replaces the current state with the value resolved by the <paramref name="setter"/>. - /// </summary> - /// <param name="setter">Given the current state, resolves a new state value.</param> - /// <returns>The updated state.</returns> - public T SetValue(Func<T, T> setter) - { - lock (Lock) - { - var previous = CurrentValue.ToJson().ToObject<T>(); - CurrentValue = setter(CurrentValue); - - Changed?.Invoke((previous, CurrentValue)); - return CurrentValue; - } - } - -#pragma warning disable CS0693 // Type parameter has the same name as the type parameter from outer type - private class StateTrackerDisposable<T> : IDisposable -#pragma warning restore CS0693 // Type parameter has the same name as the type parameter from outer type - { - public StateTrackerDisposable(StateMonitor<T> stateMonitor, Action<(T Previous, T Current)> listener) - { - StateMonitor = stateMonitor; - Listener = listener; - } - - private bool Disposed { get; set; } - private Action<(T Previous, T Current)> Listener { get; } - private StateMonitor<T> StateMonitor { get; } - - public void Dispose() - { - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - - public void OnChange((T Previous, T Current) args) => Listener.Invoke(args); - - protected virtual void Dispose(bool disposing) - { - if (!Disposed) - { - if (disposing) - { - StateMonitor.Changed -= OnChange; - } - - Disposed = true; - } - } - } - } -} diff --git a/src/slskd/Common/UserEndPointCache.cs b/src/slskd/Common/UserEndPointCache.cs new file mode 100644 index 00000000..29164cc4 --- /dev/null +++ b/src/slskd/Common/UserEndPointCache.cs @@ -0,0 +1,61 @@ +// <copyright file="UserEndPointCache.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.Net; + using Microsoft.Extensions.Caching.Memory; + using Soulseek; + + /// <summary> + /// Caches user EndPoints. + /// </summary> + public class UserEndPointCache : IUserEndPointCache + { + /// <summary> + /// Initializes a new instance of the <see cref="UserEndPointCache"/> class. + /// </summary> + public UserEndPointCache() + { + Cache = new MemoryCache(new MemoryCacheOptions()); + } + + private IMemoryCache Cache { get; } + + /// <summary> + /// Caches or updates an entry. + /// </summary> + /// <param name="username">The username for which to cache the endpoint.</param> + /// <param name="endPoint">The endpoint to cache.</param> + public void AddOrUpdate(string username, IPEndPoint endPoint) + { + Cache.Set(username, endPoint, TimeSpan.FromSeconds(60)); + } + + /// <summary> + /// Gets the cached endpoint for the specified <paramref name="username"/>, if it exists. + /// </summary> + /// <param name="username">The username for which to retrieve the endpoint.</param> + /// <param name="endPoint">The cached endpoint, if it exists.</param> + /// <returns>A value indicating whether the endpoint was found in the cache.</returns> + public bool TryGet(string username, out IPEndPoint endPoint) + { + return Cache.TryGetValue(username, out endPoint); + } + } +}
\ No newline at end of file |
