Skip to content

Commit

Permalink
Fix sonar warnings
Browse files Browse the repository at this point in the history
Signed-off-by: krivchenko_kv <[email protected]>
  • Loading branch information
krivchenko_kv authored and zarusz committed Sep 20, 2024
1 parent bd33379 commit 55547bd
Show file tree
Hide file tree
Showing 28 changed files with 71 additions and 79 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

private readonly ILogger<WeatherForecastController> _logger;

Expand Down
8 changes: 8 additions & 0 deletions src/Samples/Sample.Images.Worker/GlobalSuppressions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.

using System.Diagnostics.CodeAnalysis;

[assembly: SuppressMessage("Interoperability", "CA1416:Validate platform compatibility")]
2 changes: 1 addition & 1 deletion src/Samples/Sample.Nats.WebApi/PingConsumer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public class PingConsumer(ILogger<PingConsumer> logger) : IConsumer<PingMessage>
{
private readonly ILogger _logger = logger;

public IConsumerContext Context { get; set; }
public IConsumerContext Context { get; set; } = default!;

public Task OnHandle(PingMessage message)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,27 +62,27 @@ public static T CheckpointEvery<T>(this T builder, int numberOfMessages)
}

/// <summary>
/// Checkpoint after T elapsed time.
/// Checkpoint every N-th processed message.
/// </summary>
/// <param name="builder"></param>
/// <param name="duration"></param>
/// <param name="numberOfMessages"></param>
/// <returns></returns>
public static T CheckpointAfter<T>(this T builder, TimeSpan duration)
where T : AbstractConsumerBuilder
public static RequestResponseBuilder CheckpointEvery(this RequestResponseBuilder builder, int numberOfMessages)
{
builder.ConsumerSettings.Properties[CheckpointSettings.CheckpointDuration] = duration;
builder.Settings.Properties[CheckpointSettings.CheckpointCount] = numberOfMessages;
return builder;
}

/// <summary>
/// Checkpoint every N-th processed message.
/// Checkpoint after T elapsed time.
/// </summary>
/// <param name="builder"></param>
/// <param name="numberOfMessages"></param>
/// <param name="duration"></param>
/// <returns></returns>
public static RequestResponseBuilder CheckpointEvery(this RequestResponseBuilder builder, int numberOfMessages)
public static T CheckpointAfter<T>(this T builder, TimeSpan duration)
where T : AbstractConsumerBuilder
{
builder.Settings.Properties[CheckpointSettings.CheckpointCount] = numberOfMessages;
builder.ConsumerSettings.Properties[CheckpointSettings.CheckpointDuration] = duration;
return builder;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,12 @@ namespace SlimMessageBus.Host.AzureEventHub;
/// </summary>
public class EhPartitionConsumerForResponses : EhPartitionConsumer
{
private readonly RequestResponseSettings _requestResponseSettings;

public EhPartitionConsumerForResponses(EventHubMessageBus messageBus, RequestResponseSettings requestResponseSettings, GroupPathPartitionId pathGroupPartition)
: base(messageBus, pathGroupPartition)
{
_requestResponseSettings = requestResponseSettings ?? throw new ArgumentNullException(nameof(requestResponseSettings));
if (requestResponseSettings == null) throw new ArgumentNullException(nameof(requestResponseSettings));

MessageProcessor = new ResponseMessageProcessor<EventData>(MessageBus.LoggerFactory, _requestResponseSettings, MessageBus, messagePayloadProvider: eventData => eventData.EventBody.ToArray());
CheckpointTrigger = new CheckpointTrigger(_requestResponseSettings, MessageBus.LoggerFactory);
MessageProcessor = new ResponseMessageProcessor<EventData>(MessageBus.LoggerFactory, requestResponseSettings, MessageBus, messagePayloadProvider: eventData => eventData.EventBody.ToArray());
CheckpointTrigger = new CheckpointTrigger(requestResponseSettings, MessageBus.LoggerFactory);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ public MessageBusBuilder AddChildBus(string busName, Action<MessageBusBuilder> b
child.MergeFrom(Settings);
}

builderAction?.Invoke(child);
builderAction.Invoke(child);

return this;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,7 @@ public abstract class HasProviderExtensions
/// <summary>
/// Provider specific properties bag.
/// </summary>
public IDictionary<string, object> Properties { get; } = new Dictionary<string, object>();

public T GetOrDefault<T>(string key, T defaultValue = default)
{
if (Properties.TryGetValue(key, out var value))
{
return (T)value;
}
return defaultValue;
}
public IDictionary<string, object> Properties { get; } = new Dictionary<string, object>();

public T GetOrCreate<T>(string key, Func<T> factoryMethod)
{
Expand All @@ -27,6 +18,15 @@ public T GetOrCreate<T>(string key, Func<T> factoryMethod)
return typedValue;
}

public T GetOrDefault<T>(string key, T defaultValue = default)
{
if (Properties.TryGetValue(key, out var value))
{
return (T)value;
}
return defaultValue;
}

public T GetOrDefault<T>(string key, MessageBusSettings messageBusSettings, T defaultValue = default)
{
if (Properties.TryGetValue(key, out var value)
Expand Down
2 changes: 1 addition & 1 deletion src/SlimMessageBus.Host.Mqtt/MqttTopicConsumer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

public class MqttTopicConsumer : AbstractConsumer
{
public IMessageProcessor<MqttApplicationMessage> MessageProcessor;
public IMessageProcessor<MqttApplicationMessage> MessageProcessor { get; }
public string Topic { get; }

public MqttTopicConsumer(ILogger logger, string topic, IMessageProcessor<MqttApplicationMessage> messageProcessor) : base(logger)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public sealed class OutboxForwardingPublishInterceptor<T>(
OutboxSettings outboxSettings)
: OutboxForwardingPublishInterceptor, IInterceptorWithOrder, IPublishInterceptor<T>, IDisposable where T : class
{
static readonly internal string SkipOutboxHeader = "__SkipOutbox";
internal const string SkipOutboxHeader = "__SkipOutbox";

private readonly ILogger _logger = logger;
private readonly IOutboxRepository _outboxRepository = outboxRepository;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ async internal Task<int> SendMessages(IServiceProvider serviceProvider, IOutboxR
if (messageType == null)
{
abortedIds.Add(outboxMessage.Id);
_logger.LogError("Outbox message with Id {id} - the MessageType {messageType} is not recognized. The type might have been renamed or moved namespaces.", outboxMessage.Id, outboxMessage.MessageType);
_logger.LogError("Outbox message with Id {Id} - the MessageType {MessageType} is not recognized. The type might have been renamed or moved namespaces.", outboxMessage.Id, outboxMessage.MessageType);
return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public abstract class CommonSqlMigrationService<TRepository, TSettings>
protected TRepository Repository { get; }
public ISqlTransactionService TransactionService { get; }

public CommonSqlMigrationService(ILogger logger, TRepository repository, ISqlTransactionService transactionService, TSettings settings)
protected CommonSqlMigrationService(ILogger logger, TRepository repository, ISqlTransactionService transactionService, TSettings settings)
{
Logger = logger;
Settings = settings;
Expand Down
4 changes: 1 addition & 3 deletions src/SlimMessageBus.Host/Collections/KindMapping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ private void AddTypeMapping(ProducerSettings producerSettings, PathKind producer
}
}

private PathKind AddPathMapping(PathKind producerKind, string path)
private void AddPathMapping(PathKind producerKind, string path)
{
if (_kindByTopic.TryGetValue(path, out var existingKind))
{
Expand All @@ -56,8 +56,6 @@ private PathKind AddPathMapping(PathKind producerKind, string path)
{
_kindByTopic.Add(path, producerKind);
}

return existingKind;
}

public PathKind GetKind(Type messageType, string path)
Expand Down
9 changes: 3 additions & 6 deletions src/SlimMessageBus.Host/Collections/SafeDictionaryWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,8 @@ public IReadOnlyDictionary<TKey, TValue> Dictionary
{
lock (_lock)
{
if (_readonlyDict == null)
{
// Lazily create the read only snapshot
_readonlyDict = new ReadOnlyDictionary<TKey, TValue>(_mutableDict);
}
// Lazily create the read only snapshot
_readonlyDict ??= new ReadOnlyDictionary<TKey, TValue>(_mutableDict);
}
}
return _readonlyDict;
Expand Down Expand Up @@ -118,7 +115,7 @@ public IReadOnlyCollection<TValue> ClearAndSnapshot()
{
lock (_lock)
{
var snapshot = Dictionary.Values.ToList();
var snapshot = Snapshot();
_mutableDict.Clear();
OnChanged();
return snapshot;
Expand Down
2 changes: 1 addition & 1 deletion src/SlimMessageBus.Host/Consumer/AbstractConsumer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public abstract class AbstractConsumer : IAsyncDisposable, IConsumerControl

protected CancellationToken CancellationToken => _cancellationTokenSource.Token;

public AbstractConsumer(ILogger logger)
protected AbstractConsumer(ILogger logger)
{
Logger = logger;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,13 +185,10 @@ protected IEnumerable<IMessageTypeConsumerInvokerSettings> TryMatchConsumerInvok
else
{
var found = false;
foreach (var invoker in _invokers)
foreach (var invoker in _invokers.Where(x => RuntimeTypeCache.IsAssignableFrom(messageType, x.MessageType)))
{
if (RuntimeTypeCache.IsAssignableFrom(messageType, invoker.MessageType))
{
found = true;
yield return invoker;
}
found = true;
yield return invoker;
}

if (!found)
Expand Down
5 changes: 1 addition & 4 deletions src/SlimMessageBus.Host/Consumer/MessageScopeWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,18 @@
/// </summary>
public sealed class MessageScopeWrapper : IMessageScope
{
private readonly ILogger _logger;
private readonly IServiceProvider _messageScope;
private readonly IServiceProvider _prevMessageScope;
private IDisposable _messageScopeDisposable;

public IServiceProvider ServiceProvider => _messageScope;

public MessageScopeWrapper(ILogger logger, IServiceProvider serviceProvider, bool createMessageScope, object message)
public MessageScopeWrapper(IServiceProvider serviceProvider, bool createMessageScope)
{
_logger = logger;
_messageScope = serviceProvider;

if (createMessageScope)
{
_logger.LogDebug("Creating message scope for {Message} of type {MessageType}", message, message.GetType());
var ms = serviceProvider.CreateScope();
_messageScope = ms.ServiceProvider;
_messageScopeDisposable = ms;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public static class ServiceCollectionExtensions
/// <param name="services"></param>
/// <param name="configure">Action to configure the master (root) message bus</param>
/// <returns></returns>
public static IServiceCollection AddSlimMessageBus(this IServiceCollection services, Action<MessageBusBuilder> configure = null)
public static IServiceCollection AddSlimMessageBus(this IServiceCollection services, Action<MessageBusBuilder> configure)
{
services.AddSlimMessageBus();

Expand Down
1 change: 1 addition & 0 deletions src/SlimMessageBus.Host/GlobalSuppressions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@
[assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "This is intended.", Scope = "member", Target = "~M:SlimMessageBus.Host.MessageQueueWorker`1.WaitAll~System.Threading.Tasks.Task{SlimMessageBus.Host.MessageQueueResult{`0}}")]
[assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "This is intended.", Scope = "member", Target = "~M:SlimMessageBus.Host.Utils.DisposeSilently(System.IDisposable,System.Action{System.Exception})")]
[assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Intended", Scope = "member", Target = "~M:SlimMessageBus.Host.MessageBusBase.OnProducedHook(System.Object,System.String,SlimMessageBus.Host.Config.ProducerSettings)")]
[assembly: SuppressMessage("Minor Code Smell", "S2094:Classes should not be empty", Justification = "<Pending>")]
6 changes: 2 additions & 4 deletions src/SlimMessageBus.Host/Hybrid/HybridMessageBus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ public class HybridMessageBus : IMasterMessageBus, ICompositeMessageBus, IDispos
private readonly ILogger _logger;
private readonly Dictionary<string, MessageBusBase> _busByName;
private readonly ProducerByMessageTypeCache<MessageBusBase[]> _busesByMessageType;
private readonly RuntimeTypeCache _runtimeTypeCache;
private readonly ConcurrentDictionary<Type, bool> _undeclaredMessageType;

public ILoggerFactory LoggerFactory { get; }
Expand All @@ -32,8 +31,6 @@ public HybridMessageBus(MessageBusSettings settings, HybridMessageBusSettings pr

_logger = LoggerFactory.CreateLogger<HybridMessageBus>();

_runtimeTypeCache = new RuntimeTypeCache();

_busByName = [];
foreach (var childBus in mbb.Children)
{
Expand All @@ -56,7 +53,8 @@ public HybridMessageBus(MessageBusSettings settings, HybridMessageBusSettings pr
throw new ConfigurationMessageBusException($"Found request messages that are handled by more than one child bus: {string.Join(", ", requestTypesWithMoreThanOneBus)}. Double check your Produce configuration.");
}

_busesByMessageType = new ProducerByMessageTypeCache<MessageBusBase[]>(_logger, busesByMessageType, _runtimeTypeCache);
var runtimeTypeCache = new RuntimeTypeCache();
_busesByMessageType = new ProducerByMessageTypeCache<MessageBusBase[]>(_logger, busesByMessageType, runtimeTypeCache);

_undeclaredMessageType = new();

Expand Down
13 changes: 9 additions & 4 deletions src/SlimMessageBus.Host/MessageBusBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ protected virtual void BuildPendingRequestStore()
private Dictionary<Type, ProducerSettings> BuildProducerByBaseMessageType()
{
var producerByBaseMessageType = Settings.Producers.ToDictionary(producerSettings => producerSettings.MessageType);

foreach (var consumerSettings in Settings.Consumers.Where(x => x.ResponseType != null))
{
// A response type can be used across different requests hence TryAdd
Expand Down Expand Up @@ -314,7 +314,7 @@ public void Dispose()
GC.SuppressFinalize(this);
}

protected void Dispose(bool disposing)
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Expand Down Expand Up @@ -717,10 +717,15 @@ public virtual Task<Exception> OnResponseArrived(byte[] responsePayload, string
public virtual bool IsMessageScopeEnabled(ConsumerSettings consumerSettings, IDictionary<string, object> consumerContextProperties)
=> consumerSettings.IsMessageScopeEnabled ?? Settings.IsMessageScopeEnabled ?? true;

public virtual IMessageScope CreateMessageScope(ConsumerSettings consumerSettings, object message, IDictionary<string, object> consumerContextProperties, IServiceProvider currentServiceProvider = null)
public virtual IMessageScope CreateMessageScope(ConsumerSettings consumerSettings, object message, IDictionary<string, object> consumerContextProperties, IServiceProvider currentServiceProvider)
{
var createMessageScope = IsMessageScopeEnabled(consumerSettings, consumerContextProperties);
return new MessageScopeWrapper(_logger, currentServiceProvider ?? Settings.ServiceProvider, createMessageScope, message);

if (createMessageScope)
{
_logger.LogDebug("Creating message scope for {Message} of type {MessageType}", message, message.GetType());
}
return new MessageScopeWrapper(currentServiceProvider ?? Settings.ServiceProvider, createMessageScope);
}

public virtual Task ProvisionTopology() => Task.CompletedTask;
Expand Down
4 changes: 2 additions & 2 deletions src/SlimMessageBus.Host/MessageWithHeadersSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ private int WriteObject(byte[] payload, int index, object v)
payload[index] = TypeIdGuid;
return 1 + WriteGuid(payload, index + 1, g);
default:
throw new InvalidOperationException($"Not supported header value type {v?.GetType().FullName ?? "(null)"}");
throw new InvalidOperationException($"Not supported header value type {v.GetType().FullName ?? "(null)"}");
}
}

Expand All @@ -95,7 +95,7 @@ private int CalculateWriteObjectByteLength(object v)
int _ => sizeof(int),
long _ => sizeof(long),
Guid _ => 16,
_ => throw new InvalidOperationException($"Not supported header value type {v?.GetType().FullName ?? "(null)"}"),
_ => throw new InvalidOperationException($"Not supported header value type {v.GetType().FullName ?? "(null)"}"),
};
return 1 + byteLength;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,16 @@

internal class PublishInterceptorPipeline : ProducerInterceptorPipeline<PublishContext>
{
private readonly IEnumerable<object> _publishInterceptors;
private readonly Func<object, object, Func<Task>, IProducerContext, Task> _publishInterceptorFunc;
private IEnumerator<object> _publishInterceptorsEnumerator;
private bool _publishInterceptorsVisited = false;

public PublishInterceptorPipeline(MessageBusBase bus, object message, ProducerSettings producerSettings, IMessageBusTarget targetBus, PublishContext context, IEnumerable<object> producerInterceptors, IEnumerable<object> publishInterceptors)
: base(bus, message, producerSettings, targetBus, context, producerInterceptors)
{
_publishInterceptors = publishInterceptors;
_publishInterceptorFunc = bus.RuntimeTypeCache.PublishInterceptorType[message.GetType()];
_publishInterceptorsVisited = publishInterceptors is null;
_publishInterceptorsEnumerator = _publishInterceptors?.GetEnumerator();
_publishInterceptorsEnumerator = publishInterceptors?.GetEnumerator();
}

public async Task<object> Next()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,16 @@

internal class SendInterceptorPipeline<TResponse> : ProducerInterceptorPipeline<SendContext>
{
private readonly IEnumerable<object> _sendInterceptors;
private readonly Func<object, object, object, IProducerContext, Task> _sendInterceptorFunc;
private IEnumerator<object> _sendInterceptorsEnumerator;
private bool _sendInterceptorsVisited = false;

public SendInterceptorPipeline(MessageBusBase bus, object message, ProducerSettings producerSettings, IMessageBusTarget targetBus, SendContext context, IEnumerable<object> producerInterceptors, IEnumerable<object> sendInterceptors)
: base(bus, message, producerSettings, targetBus, context, producerInterceptors)
{
_sendInterceptors = sendInterceptors;
_sendInterceptorFunc = bus.RuntimeTypeCache.SendInterceptorType[(message.GetType(), typeof(TResponse))];
_sendInterceptorsVisited = sendInterceptors is null;
_sendInterceptorsEnumerator = _sendInterceptors?.GetEnumerator();
_sendInterceptorsEnumerator = sendInterceptors?.GetEnumerator();
}

private async Task<object> NextOfObject() => await Next();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public virtual void CleanPendingRequests()

if (canceled)
{
_logger.LogDebug("Pending request timed-out: {0}, now: {1}", requestState, now);
_logger.LogDebug("Pending request timed-out: {RequestState}, now: {TimeNow}", requestState, now);
_onRequestTimeout?.Invoke(requestState.Request);
}
}
Expand Down
Loading

0 comments on commit 55547bd

Please sign in to comment.