From 82416af83ac484b455d4c7b1cf2e35bc33d9cb55 Mon Sep 17 00:00:00 2001 From: Savorboard Date: Wed, 27 Nov 2019 09:31:24 +0800 Subject: [PATCH] Code cleanup --- .../Diagnostics/CapDiagnosticListenerNames.cs | 4 +- src/DotNetCore.CAP/Internal/CapCache.cs | 378 ------------------ .../Internal/ConsumerInvokerFactory.cs | 13 +- .../Internal/HashCodeCombiner.cs | 85 ---- .../Internal/IConsumerInvoker.Default.cs | 2 +- .../Internal/IConsumerRegister.Default.cs | 9 +- .../Internal/IMongoTransaction.cs | 21 - .../Internal/ISubscriberExecutor.Default.cs | 6 +- src/DotNetCore.CAP/Internal/WaitHandleEx.cs | 39 -- 9 files changed, 15 insertions(+), 542 deletions(-) delete mode 100644 src/DotNetCore.CAP/Internal/CapCache.cs delete mode 100644 src/DotNetCore.CAP/Internal/HashCodeCombiner.cs delete mode 100644 src/DotNetCore.CAP/Internal/IMongoTransaction.cs delete mode 100644 src/DotNetCore.CAP/Internal/WaitHandleEx.cs diff --git a/src/DotNetCore.CAP/Diagnostics/CapDiagnosticListenerNames.cs b/src/DotNetCore.CAP/Diagnostics/CapDiagnosticListenerNames.cs index a724a27..91bedb1 100644 --- a/src/DotNetCore.CAP/Diagnostics/CapDiagnosticListenerNames.cs +++ b/src/DotNetCore.CAP/Diagnostics/CapDiagnosticListenerNames.cs @@ -8,10 +8,10 @@ namespace DotNetCore.CAP.Diagnostics /// public static class CapDiagnosticListenerNames { - public const string DiagnosticListenerName = "CapDiagnosticListener"; - private const string CapPrefix = "DotNetCore.CAP."; + public const string DiagnosticListenerName = "CapDiagnosticListener"; + public const string BeforePublishMessageStore = CapPrefix + "WritePublishMessageStoreBefore"; public const string AfterPublishMessageStore = CapPrefix + "WritePublishMessageStoreAfter"; public const string ErrorPublishMessageStore = CapPrefix + "WritePublishMessageStoreError"; diff --git a/src/DotNetCore.CAP/Internal/CapCache.cs b/src/DotNetCore.CAP/Internal/CapCache.cs deleted file mode 100644 index 243f935..0000000 --- a/src/DotNetCore.CAP/Internal/CapCache.cs +++ /dev/null @@ -1,378 +0,0 @@ -// Copyright (c) .NET Core Community. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; - -namespace DotNetCore.CAP.Internal -{ - #region Cache class - - /// - /// This is a generic cache subsystem based on key/value pairs, where key is generic, too. Key must be unique. - /// Every cache entry has its own timeout. - /// Cache is thread safe and will delete expired entries on its own using System.Threading.Timers (which run on - /// threads). - /// - // ReSharper disable once InheritdocConsiderUsage - // ReSharper disable once InconsistentNaming - internal class Cache : IDisposable - { - #region Constructor and class members - - private readonly Dictionary _cache = new Dictionary(); - private readonly Dictionary _timers = new Dictionary(); - private readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim(); - - #endregion - - #region IDisposable implementation & Clear - - private bool disposed; - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - /// - protected virtual void Dispose(bool disposing) - { - if (!disposed) - { - disposed = true; - - if (disposing) - { - // Dispose managed resources. - Clear(); - _locker.Dispose(); - } - - // Dispose unmanaged resources - } - } - - /// - /// Clears the entire cache and disposes all active timers. - /// - public void Clear() - { - _locker.EnterWriteLock(); - try - { - try - { - foreach (var t in _timers.Values) - { - t.Dispose(); - } - } - catch - { - } - - _timers.Clear(); - _cache.Clear(); - } - finally - { - _locker.ExitWriteLock(); - } - } - - #endregion - - #region CheckTimer - - // Checks whether a specific timer already exists and adds a new one, if not - private void CheckTimer(K key, TimeSpan? cacheTimeout, bool restartTimerIfExists) - { - Timer timer; - - if (_timers.TryGetValue(key, out timer)) - { - if (restartTimerIfExists) - { - timer.Change( - cacheTimeout ?? Timeout.InfiniteTimeSpan, - Timeout.InfiniteTimeSpan); - } - } - else - { - _timers.Add( - key, - new Timer( - RemoveByTimer, - key, - cacheTimeout ?? Timeout.InfiniteTimeSpan, - Timeout.InfiniteTimeSpan)); - } - } - - private void RemoveByTimer(object state) - { - Remove((K) state); - } - - #endregion - - #region AddOrUpdate, Get, Remove, Exists, Clear - - /// - /// Adds or updates the specified cache-key with the specified cacheObject and applies a specified timeout (in seconds) - /// to this key. - /// - /// The cache-key to add or update. - /// The cache object to store. - /// - /// The cache timeout (lifespan) of this object. Must be 1 or greater. - /// Specify Timeout.Infinite to keep the entry forever. - /// - /// - /// (Optional). If set to true, the timer for this cacheObject will be reset if the object already - /// exists in the cache. (Default = false). - /// - public void AddOrUpdate(K key, T cacheObject, TimeSpan? cacheTimeout, bool restartTimerIfExists = false) - { - if (disposed) - { - return; - } - - _locker.EnterWriteLock(); - try - { - CheckTimer(key, cacheTimeout, restartTimerIfExists); - - if (!_cache.ContainsKey(key)) - { - _cache.Add(key, cacheObject); - } - else - { - _cache[key] = cacheObject; - } - } - finally - { - _locker.ExitWriteLock(); - } - } - - /// - /// Adds or updates the specified cache-key with the specified cacheObject and applies Timeout.Infinite to this - /// key. - /// - /// The cache-key to add or update. - /// The cache object to store. - public void AddOrUpdate(K key, T cacheObject) - { - AddOrUpdate(key, cacheObject, Timeout.InfiniteTimeSpan); - } - - /// - /// Gets the cache entry with the specified key or returns default(T) if the key is not found. - /// - /// The cache-key to retrieve. - /// The object from the cache or default(T), if not found. - public T this[K key] => Get(key); - - /// - /// Gets the cache entry with the specified key or return default(T) if the key is not found. - /// - /// The cache-key to retrieve. - /// The object from the cache or default(T), if not found. - public T Get(K key) - { - if (disposed) - { - return default(T); - } - - _locker.EnterReadLock(); - try - { - T rv; - return _cache.TryGetValue(key, out rv) ? rv : default(T); - } - finally - { - _locker.ExitReadLock(); - } - } - - /// - /// Tries to gets the cache entry with the specified key. - /// - /// The key. - /// (out) The value, if found, or default(T), if not. - /// True, if key exists, otherwise false. - public bool TryGet(K key, out T value) - { - if (disposed) - { - value = default(T); - return false; - } - - _locker.EnterReadLock(); - try - { - return _cache.TryGetValue(key, out value); - } - finally - { - _locker.ExitReadLock(); - } - } - - /// - /// Removes a series of cache entries in a single call for all key that match the specified key pattern. - /// - /// The key pattern to remove. The Predicate has to return true to get key removed. - public void Remove(Predicate keyPattern) - { - if (disposed) - { - return; - } - - _locker.EnterWriteLock(); - try - { - var removers = (from k in _cache.Keys.Cast() - where keyPattern(k) - select k).ToList(); - - foreach (var workKey in removers) - { - try - { - _timers[workKey].Dispose(); - } - catch - { - } - - _timers.Remove(workKey); - _cache.Remove(workKey); - } - } - finally - { - _locker.ExitWriteLock(); - } - } - - /// - /// Removes the specified cache entry with the specified key. - /// If the key is not found, no exception is thrown, the statement is just ignored. - /// - /// The cache-key to remove. - public void Remove(K key) - { - if (disposed) - { - return; - } - - _locker.EnterWriteLock(); - try - { - if (_cache.ContainsKey(key)) - { - try - { - _timers[key].Dispose(); - } - catch - { - } - - _timers.Remove(key); - _cache.Remove(key); - } - } - finally - { - _locker.ExitWriteLock(); - } - } - - /// - /// Checks if a specified key exists in the cache. - /// - /// The cache-key to check. - /// True if the key exists in the cache, otherwise False. - public bool Exists(K key) - { - if (disposed) - { - return false; - } - - _locker.EnterReadLock(); - try - { - return _cache.ContainsKey(key); - } - finally - { - _locker.ExitReadLock(); - } - } - - #endregion - } - - #endregion - - #region Other Cache classes (derived) - - /// - /// This is a generic cache subsystem based on key/value pairs, where key is a string. - /// You can add any item to this cache as long as the key is unique, so treat keys as something like namespaces and - /// build them with a - /// specific system/syntax in your application. - /// Every cache entry has its own timeout. - /// Cache is thread safe and will delete expired entries on its own using System.Threading.Timers (which run on - /// threads). - /// - /// - /// The non-generic Cache class instanciates a Cache{object} that can be used with any type of (mixed) contents. - /// It also publishes a static .Global member, so a cache can be used even without creating a dedicated - /// instance. - /// The .Global member is lazy instanciated. - /// - internal class CapCache : Cache - { - #region Static Global Cache instance - - private static readonly Lazy global = new Lazy(); - - /// - /// Gets the global shared cache instance valid for the entire process. - /// - /// - /// The global shared cache instance. - /// - public static CapCache Global => global.Value; - - #endregion - } - - #endregion -} \ No newline at end of file diff --git a/src/DotNetCore.CAP/Internal/ConsumerInvokerFactory.cs b/src/DotNetCore.CAP/Internal/ConsumerInvokerFactory.cs index 10381af..689e608 100644 --- a/src/DotNetCore.CAP/Internal/ConsumerInvokerFactory.cs +++ b/src/DotNetCore.CAP/Internal/ConsumerInvokerFactory.cs @@ -8,21 +8,14 @@ namespace DotNetCore.CAP.Internal { internal class ConsumerInvokerFactory : IConsumerInvokerFactory { - private readonly ILoggerFactory _loggerFactory; - //private readonly IMessagePacker _messagePacker; - // - //private readonly IModelBinderFactory _modelBinderFactory; + private readonly ILoggerFactory _loggerFactory; private readonly IServiceProvider _serviceProvider; public ConsumerInvokerFactory( - ILoggerFactory loggerFactory, - //IMessagePacker messagePacker, - //IModelBinderFactory modelBinderFactory, + ILoggerFactory loggerFactory, IServiceProvider serviceProvider) { - _loggerFactory = loggerFactory; - //_messagePacker = messagePacker; - //_modelBinderFactory = modelBinderFactory; + _loggerFactory = loggerFactory; _serviceProvider = serviceProvider; } diff --git a/src/DotNetCore.CAP/Internal/HashCodeCombiner.cs b/src/DotNetCore.CAP/Internal/HashCodeCombiner.cs deleted file mode 100644 index 43f000e..0000000 --- a/src/DotNetCore.CAP/Internal/HashCodeCombiner.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) .NET Core Community. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System.Collections; -using System.Collections.Generic; -using System.Runtime.CompilerServices; - -namespace DotNetCore.CAP.Internal -{ - internal struct HashCodeCombiner - { - private long _combinedHash64; - - public int CombinedHash - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get { return _combinedHash64.GetHashCode(); } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private HashCodeCombiner(long seed) - { - _combinedHash64 = seed; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Add(IEnumerable e) - { - if (e == null) - { - Add(0); - } - else - { - var count = 0; - foreach (var o in e) - { - Add(o); - count++; - } - - Add(count); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator int(HashCodeCombiner self) - { - return self.CombinedHash; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Add(int i) - { - _combinedHash64 = ((_combinedHash64 << 5) + _combinedHash64) ^ i; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Add(string s) - { - var hashCode = s != null ? s.GetHashCode() : 0; - Add(hashCode); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Add(object o) - { - var hashCode = o != null ? o.GetHashCode() : 0; - Add(hashCode); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Add(TValue value, IEqualityComparer comparer) - { - var hashCode = value != null ? comparer.GetHashCode(value) : 0; - Add(hashCode); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static HashCodeCombiner Start() - { - return new HashCodeCombiner(0x1505L); - } - } -} \ No newline at end of file diff --git a/src/DotNetCore.CAP/Internal/IConsumerInvoker.Default.cs b/src/DotNetCore.CAP/Internal/IConsumerInvoker.Default.cs index 4542032..d50bb50 100644 --- a/src/DotNetCore.CAP/Internal/IConsumerInvoker.Default.cs +++ b/src/DotNetCore.CAP/Internal/IConsumerInvoker.Default.cs @@ -17,7 +17,7 @@ namespace DotNetCore.CAP.Internal private readonly ILogger _logger; private readonly IServiceProvider _serviceProvider; - public DefaultConsumerInvoker(ILoggerFactory loggerFactory,IServiceProvider serviceProvider) + public DefaultConsumerInvoker(ILoggerFactory loggerFactory, IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; _logger = loggerFactory.CreateLogger(); diff --git a/src/DotNetCore.CAP/Internal/IConsumerRegister.Default.cs b/src/DotNetCore.CAP/Internal/IConsumerRegister.Default.cs index d1f67f4..cd7a648 100644 --- a/src/DotNetCore.CAP/Internal/IConsumerRegister.Default.cs +++ b/src/DotNetCore.CAP/Internal/IConsumerRegister.Default.cs @@ -157,9 +157,6 @@ namespace DotNetCore.CAP.Internal { tracingTimestamp = TracingBefore(transportMessage, _serverAddress); - var startTime = DateTimeOffset.UtcNow; - var stopwatch = Stopwatch.StartNew(); - var name = transportMessage.GetName(); var group = transportMessage.GetGroup(); @@ -171,7 +168,11 @@ namespace DotNetCore.CAP.Internal if (!canFindSubscriber) { var error = $"Message can not be found subscriber. Name:{name}, Group:{group}. {Environment.NewLine} see: https://github.com/dotnetcore/CAP/issues/63"; - throw new SubscriberNotFoundException(error); + var ex = new SubscriberNotFoundException(error); + + TracingError(tracingTimestamp, transportMessage, client.ServersAddress, ex); + + throw ex; } var type = executor.Parameters.FirstOrDefault(x => x.IsFromCap == false)?.ParameterType; diff --git a/src/DotNetCore.CAP/Internal/IMongoTransaction.cs b/src/DotNetCore.CAP/Internal/IMongoTransaction.cs deleted file mode 100644 index abb0388..0000000 --- a/src/DotNetCore.CAP/Internal/IMongoTransaction.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) .NET Core Community. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using System.Threading.Tasks; - -namespace DotNetCore.CAP.Internal -{ - public interface IMongoTransaction : IDisposable - { - /// - /// If set true, the session.CommitTransaction() will be called automatically. - /// - /// - bool AutoCommit { get; set; } - - Task BeginAsync(bool autoCommit = true); - - IMongoTransaction Begin(bool autoCommit = true); - } -} \ No newline at end of file diff --git a/src/DotNetCore.CAP/Internal/ISubscriberExecutor.Default.cs b/src/DotNetCore.CAP/Internal/ISubscriberExecutor.Default.cs index 14500b7..4e7d9e3 100644 --- a/src/DotNetCore.CAP/Internal/ISubscriberExecutor.Default.cs +++ b/src/DotNetCore.CAP/Internal/ISubscriberExecutor.Default.cs @@ -196,9 +196,11 @@ namespace DotNetCore.CAP.Internal } catch (Exception ex) { - TracingError(tracingTimestamp, message.Origin, descriptor.MethodInfo, ex); + var e = new SubscriberExecutionFailedException(ex.Message, ex); + + TracingError(tracingTimestamp, message.Origin, descriptor.MethodInfo, e); - throw new SubscriberExecutionFailedException(ex.Message, ex); + throw e; } } diff --git a/src/DotNetCore.CAP/Internal/WaitHandleEx.cs b/src/DotNetCore.CAP/Internal/WaitHandleEx.cs deleted file mode 100644 index e5f5ba2..0000000 --- a/src/DotNetCore.CAP/Internal/WaitHandleEx.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) .NET Core Community. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace DotNetCore.CAP.Internal -{ - public static class WaitHandleEx - { - public static Task WaitAnyAsync(WaitHandle handle1, WaitHandle handle2, TimeSpan timeout) - { - var t1 = handle1.WaitOneAsync(timeout); - var t2 = handle2.WaitOneAsync(timeout); - return Task.WhenAny(t1, t2); - } - - public static async Task WaitOneAsync(this WaitHandle handle, TimeSpan timeout) - { - RegisteredWaitHandle registeredHandle = null; - try - { - var tcs = new TaskCompletionSource(); - registeredHandle = ThreadPool.RegisterWaitForSingleObject( - handle, - (state, timedOut) => ((TaskCompletionSource) state).TrySetResult(!timedOut), - tcs, - timeout, - true); - return await tcs.Task; - } - finally - { - registeredHandle?.Unregister(null); - } - } - } -} \ No newline at end of file