Browse Source

Use reference assembly annotator for Zebus

Lucas Trzesniewski 5 years ago
parent
commit
b6ea13d0c6

+ 9 - 0
src/Abc.Zebus/Abc.Zebus.csproj

@@ -57,4 +57,13 @@
     <Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" /> <!-- T4 -->
   </ItemGroup>
 
+  <!-- Reference Assembly Annotator -->
+  <PropertyGroup>
+    <GenerateNullableAttributes>false</GenerateNullableAttributes>
+  </PropertyGroup>
+  <ItemGroup>
+    <PackageReference Include="TunnelVisionLabs.ReferenceAssemblyAnnotator" Version="1.0.0-alpha.154" PrivateAssets="all" />
+    <PackageDownload Include="Microsoft.NETCore.App.Ref" Version="[3.1.0]" />
+  </ItemGroup>
+
 </Project>

+ 3 - 3
src/Abc.Zebus/Core/Bus.cs

@@ -628,7 +628,7 @@ namespace Abc.Zebus.Core
                 jsonMessage = $"Unable to serialize message :{System.Environment.NewLine}{ex}";
             }
 
-            var messageProcessingFailed = new MessageProcessingFailed(failingTransportMessage, jsonMessage, errorMessage, SystemDateTime.UtcNow, dispatchResult.ErrorHandlerTypes.Select(x => x.FullName).ToArray());
+            var messageProcessingFailed = new MessageProcessingFailed(failingTransportMessage, jsonMessage, errorMessage, SystemDateTime.UtcNow, dispatchResult.ErrorHandlerTypes.Select(x => x.FullName!).ToArray());
             Publish(messageProcessingFailed);
         }
 
@@ -641,7 +641,7 @@ namespace Abc.Zebus.Core
                 return;
 
             var errorMessage = $"Unable to handle local message\r\nMessage is not serializable\r\nMessageType: {messageTypeName}\r\nDispatch error: {dispatchErrorMessage}\r\nSerialization error: {serializationException}";
-            var processingFailed = new CustomProcessingFailed(GetType().FullName, errorMessage, SystemDateTime.UtcNow);
+            var processingFailed = new CustomProcessingFailed(GetType().FullName!, errorMessage, SystemDateTime.UtcNow);
             Publish(processingFailed);
         }
 
@@ -661,7 +661,7 @@ namespace Abc.Zebus.Core
             if (!_messageIdToTaskCompletionSources.TryRemove(message.SourceCommandId, out var taskCompletionSource))
                 return;
 
-            var response = message.PayloadTypeId != null ? ToMessage(message.PayloadTypeId.Value, new MemoryStream(message.Payload), transportMessage) : null;
+            var response = message.PayloadTypeId != null ? ToMessage(message.PayloadTypeId.Value, new MemoryStream(message.Payload ?? Array.Empty<byte>()), transportMessage) : null;
             var commandResult = new CommandResult(message.ErrorCode, message.ResponseMessage, response);
 
             taskCompletionSource.SetResult(commandResult);

+ 1 - 1
src/Abc.Zebus/Core/BusMessageLogger.cs

@@ -18,7 +18,7 @@ namespace Abc.Zebus.Core
         private bool _logInfoEnabled;
 
         public BusMessageLogger(Type loggerType)
-            : this(loggerType.FullName)
+            : this(loggerType.FullName!)
         {
         }
 

+ 2 - 2
src/Abc.Zebus/Dispatch/BatchedMessageHandlerInvoker.cs

@@ -9,11 +9,11 @@ namespace Abc.Zebus.Dispatch
 {
     public class BatchedMessageHandlerInvoker : MessageHandlerInvoker
     {
-        private static readonly MethodInfo _castMethodInfo = typeof(Enumerable).GetMethod(nameof(Enumerable.Cast));
+        private static readonly MethodInfo _castMethodInfo = typeof(Enumerable).GetMethod(nameof(Enumerable.Cast))!;
 
         private readonly IContainer _container;
         private readonly Action<object, IList<IMessage>> _handleAction;
-        private static readonly MethodInfo _toListMethodInfo = typeof(Enumerable).GetMethod(nameof(Enumerable.ToList));
+        private static readonly MethodInfo _toListMethodInfo = typeof(Enumerable).GetMethod(nameof(Enumerable.ToList))!;
 
         public BatchedMessageHandlerInvoker(IContainer container, Type handlerType, Type messageType, bool shouldBeSubscribedOnStartup = true)
             : base(handlerType, messageType, shouldBeSubscribedOnStartup)

+ 1 - 1
src/Abc.Zebus/Dispatch/DispatchQueue.cs

@@ -381,7 +381,7 @@ namespace Abc.Zebus.Dispatch
                 _dispatchQueue = dispatchQueue;
             }
 
-            public override void Post(SendOrPostCallback d, object state)
+            public override void Post(SendOrPostCallback d, object? state)
             {
                 _dispatchQueue.Enqueue(() => d(state));
             }

+ 1 - 1
src/Abc.Zebus/Dispatch/MessageHandlerInvoker.cs

@@ -73,7 +73,7 @@ namespace Abc.Zebus.Dispatch
 
         internal static SubscriptionMode? GetExplicitSubscriptionMode(Type handlerType)
         {
-            var subscriptionModeAttribute = (SubscriptionModeAttribute)Attribute.GetCustomAttribute(handlerType, typeof(SubscriptionModeAttribute));
+            var subscriptionModeAttribute = (SubscriptionModeAttribute?)Attribute.GetCustomAttribute(handlerType, typeof(SubscriptionModeAttribute));
             if (subscriptionModeAttribute != null)
                 return subscriptionModeAttribute.SubscriptionMode;
 

+ 1 - 1
src/Abc.Zebus/Hosting/PeriodicActionHostInitializer.cs

@@ -141,7 +141,7 @@ namespace Abc.Zebus.Hosting
         {
             try
             {
-                _bus.Publish(new CustomProcessingFailed(GetType().FullName, error.ToString()));
+                _bus.Publish(new CustomProcessingFailed(GetType().FullName!, error.ToString()));
             }
             catch (Exception ex)
             {

+ 2 - 2
src/Abc.Zebus/PeerId.cs

@@ -10,9 +10,9 @@ namespace Abc.Zebus
     public readonly struct PeerId : IEquatable<PeerId>
     {
         [ProtoMember(1, IsRequired = true)]
-        private readonly string _value;
+        private readonly string? _value;
 
-        public PeerId(string value)
+        public PeerId(string? value)
         {
             _value = value;
         }

+ 2 - 0
src/Abc.Zebus/Routing/BindingKey.cs

@@ -129,6 +129,7 @@ namespace Abc.Zebus.Routing
             public BindingKey BuildKey(IMessage message)
             {
                 var parts = new string[_tokens.Length];
+
                 for (var tokenIndex = 0; tokenIndex < parts.Length; ++tokenIndex)
                 {
                     parts[tokenIndex] = _tokens[tokenIndex].GetValue(message);
@@ -140,6 +141,7 @@ namespace Abc.Zebus.Routing
             public BindingKey BuildKey(IDictionary<string, string> fieldValues)
             {
                 var parts = new string[_tokens.Length];
+
                 for (var tokenIndex = 0; tokenIndex < _tokens.Length; ++tokenIndex)
                 {
                     parts[tokenIndex] = fieldValues.GetValueOrDefault(_tokens[tokenIndex].Name, _star);

+ 4 - 4
src/Abc.Zebus/Routing/BindingKeyPredicateBuilder.cs

@@ -10,8 +10,8 @@ namespace Abc.Zebus.Routing
 {
     public class BindingKeyPredicateBuilder : IBindingKeyPredicateBuilder
     {
-        private static readonly MethodInfo _toStringMethod = typeof(object).GetMethod(nameof(ToString));
-        private static readonly MethodInfo _toStringWithFormatMethod = typeof(IConvertible).GetMethod(nameof(IConvertible.ToString));
+        private static readonly MethodInfo _toStringMethod = typeof(object).GetMethod(nameof(ToString))!;
+        private static readonly MethodInfo _toStringWithFormatMethod = typeof(IConvertible).GetMethod(nameof(IConvertible.ToString))!;
         private readonly ConcurrentDictionary<Type, CacheItem> _cacheItems = new ConcurrentDictionary<Type, CacheItem>();
 
         public Func<IMessage, bool> GetPredicate(Type messageType, BindingKey bindingKey)
@@ -50,7 +50,7 @@ namespace Abc.Zebus.Routing
                 var routingMembers = type.GetMembers(BindingFlags.Public | BindingFlags.Instance)
                                          .Select(x => new MemberExtendedInfo(x))
                                          .Where(x => x.Attribute != null)
-                                         .OrderBy(x => x.Attribute.Position)
+                                         .OrderBy(x => x.Attribute!.Position)
                                          .ToList();
 
                 var parameterExpression = Expression.Parameter(typeof(IMessage), "m");
@@ -101,7 +101,7 @@ namespace Abc.Zebus.Routing
         private class MemberExtendedInfo
         {
             public MemberInfo Member { get; }
-            public RoutingPositionAttribute Attribute { get; }
+            public RoutingPositionAttribute? Attribute { get; }
 
             public MemberExtendedInfo(MemberInfo member)
             {

+ 7 - 7
src/Abc.Zebus/Routing/BindingKeyToken.cs

@@ -7,9 +7,9 @@ namespace Abc.Zebus.Routing
 {
     internal class BindingKeyToken
     {
-        private static readonly MethodInfo _toStringMethod = typeof(object).GetMethod(nameof(ToString));
-        private static readonly MethodInfo _toStringWithFormatMethod = typeof(IConvertible).GetMethod(nameof(IConvertible.ToString));
-        private readonly Func<IMessage, string> _valueAccessorFunc;
+        private static readonly MethodInfo _toStringMethod = typeof(object).GetMethod(nameof(ToString))!;
+        private static readonly MethodInfo _toStringWithFormatMethod = typeof(IConvertible).GetMethod(nameof(IConvertible.ToString))!;
+        private readonly Func<IMessage, string?> _valueAccessorFunc;
 
         public BindingKeyToken(int position, Type messageType, FieldInfo fieldInfo)
         {
@@ -36,7 +36,7 @@ namespace Abc.Zebus.Routing
         {
             try
             {
-                return _valueAccessorFunc(message);
+                return _valueAccessorFunc(message) ?? string.Empty;
             }
             catch (NullReferenceException)
             {
@@ -44,7 +44,7 @@ namespace Abc.Zebus.Routing
             }
         }
 
-        private Func<IMessage, string> GenerateValueAccessor(Func<Expression, Expression> valueAccessor, Type messageType, Type memberType)
+        private static Func<IMessage, string?> GenerateValueAccessor(Func<Expression, Expression> valueAccessor, Type messageType, Type memberType)
         {
             var message = Expression.Parameter(typeof(IMessage), "m");
             var castedMessage = Expression.Convert(message, messageType);
@@ -53,8 +53,8 @@ namespace Abc.Zebus.Routing
                 ? Expression.Call(valueAccessor(castedMessage), _toStringWithFormatMethod, Expression.Constant(CultureInfo.InvariantCulture))
                 : Expression.Call(valueAccessor(castedMessage), _toStringMethod);
 
-            var lambda = Expression.Lambda(typeof(Func<IMessage, string>), body, message);
-            return (Func<IMessage, string>)lambda.Compile();
+            var lambda = Expression.Lambda(typeof(Func<IMessage, string?>), body, message);
+            return (Func<IMessage, string?>)lambda.Compile();
         }
     }
 }

+ 3 - 3
src/Abc.Zebus/Scan/DispatchQueueNameScanner.cs

@@ -22,7 +22,7 @@ namespace Abc.Zebus.Scan
 
         private static string LoadQueueName(Type type)
         {
-            var queueNameAttribute = (DispatchQueueNameAttribute)Attribute.GetCustomAttribute(type, typeof(DispatchQueueNameAttribute), true);
+            var queueNameAttribute = (DispatchQueueNameAttribute?)Attribute.GetCustomAttribute(type, typeof(DispatchQueueNameAttribute), true);
             if (queueNameAttribute != null)
                 return queueNameAttribute.QueueName;
 
@@ -32,7 +32,7 @@ namespace Abc.Zebus.Scan
         private static string LoadQueueNameFromNamespace(Type type)
         {
             var assemblyCache = _assemblyCaches.GetOrAdd(type.Assembly, x => new AssemblyCache(x));
-            return assemblyCache.GetQueueNameFromNamespace(type.Namespace);
+            return assemblyCache.GetQueueNameFromNamespace(type.Namespace ?? string.Empty);
         }
 
         private class AssemblyCache
@@ -47,7 +47,7 @@ namespace Abc.Zebus.Scan
                     if (queueNameProviderType.Namespace == null)
                         continue;
 
-                    var queueNameProvider = (IProvideDispatchQueueNameForCurrentNamespace)Activator.CreateInstance(queueNameProviderType);
+                    var queueNameProvider = (IProvideDispatchQueueNameForCurrentNamespace)Activator.CreateInstance(queueNameProviderType)!;
                     _knownQueueNames[queueNameProviderType.Namespace] = queueNameProvider.QueueName;
                 }
             }

+ 1 - 1
src/Abc.Zebus/Serialization/PeerIdConverter.cs

@@ -13,7 +13,7 @@ namespace Abc.Zebus.Serialization
             writer.WriteValue(peerId.ToString());
         }
 
-        public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
+        public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
         {
             if (reader.TokenType != JsonToken.String)
                 return Activator.CreateInstance(objectType); // objectType can be Nullable<PeerId>

+ 4 - 4
src/Abc.Zebus/Subscription.cs

@@ -15,7 +15,7 @@ namespace Abc.Zebus
     [ProtoContract]
     public class Subscription : IEquatable<Subscription>
     {
-        private static readonly MethodInfo _wildCardTokenMethod = typeof(Builder).GetMethod(nameof(Builder.Any));
+        private static readonly MethodInfo _wildCardTokenMethod = typeof(Builder).GetMethod(nameof(Builder.Any))!;
         private int _computedHashCode;
 
         [ProtoMember(1, IsRequired = true)]
@@ -110,11 +110,11 @@ namespace Abc.Zebus
                 for (var argumentIndex = 0; argumentIndex < newExpression.Arguments.Count; ++argumentIndex)
                 {
                     var argumentExpression = newExpression.Arguments[argumentIndex];
-                    var parameterName = parameters[argumentIndex].Name;
+                    var parameterName = parameters[argumentIndex].Name!;
                     var parameterValue = GetExpressionValue(argumentExpression);
 
                     if (parameterValue != null)
-                        parameterValues[parameterName] = parameterValue.ToString();
+                        parameterValues[parameterName] = parameterValue.ToString() ?? string.Empty;
                 }
             }
 
@@ -239,7 +239,7 @@ namespace Abc.Zebus
                 return;
 
             var valueAsText = memberExpression.Type.IsEnum ? Enum.GetName(memberExpression.Type, memberValue) : memberValue.ToString();
-            fieldValues.Add(memberName, valueAsText);
+            fieldValues.Add(memberName, valueAsText ?? string.Empty);
         }
 
         private static bool TryGetMessageMemberExpression<TMessage>(Expression? expression, [NotNullWhen(true)] out MemberExpression? memberExpression)

+ 1 - 1
src/Abc.Zebus/Util/BackgroundThread.cs

@@ -48,7 +48,7 @@ namespace Abc.Zebus.Util
             {
                 try
                 {
-                    action((T)s);
+                    action((T)s!);
                 }
                 catch (ThreadAbortException ex)
                 {

+ 8 - 8
src/Abc.Zebus/Util/PathUtil.cs

@@ -8,13 +8,13 @@ namespace Abc.Zebus.Util
     {
         public static string InBaseDirectory(string path)
         {
-            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
+            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory!, path);
         }
 
         public static string InBaseDirectory(params string[] paths)
         {
             var allPaths = new string[paths.Length + 1];
-            allPaths[0] = AppDomain.CurrentDomain.BaseDirectory;
+            allPaths[0] = AppDomain.CurrentDomain.BaseDirectory!;
             paths.CopyTo(allPaths, 1);
             return Path.Combine(allPaths);
         }
@@ -22,18 +22,18 @@ namespace Abc.Zebus.Util
         public static string InCurrentNamespaceDirectory(params string[] paths)
         {
             var stack = new StackTrace();
-            var callingFrame = stack.GetFrame(1);
-            var callingType = callingFrame.GetMethod().DeclaringType;
+            var callingFrame = stack.GetFrame(1)!;
+            var callingType = callingFrame.GetMethod()!.DeclaringType!;
 
-            var rootNamespace = callingType.Assembly.GetName().Name;
-            var classNamespace = callingType.Namespace;
+            var rootNamespace = callingType.Assembly.GetName().Name!;
+            var classNamespace = callingType.Namespace ?? string.Empty;
             var extraNamespaces = classNamespace.Replace(rootNamespace, "").Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries);
             var allPaths = new string[extraNamespaces.Length + 1 + paths.Length];
-            allPaths[0] = AppDomain.CurrentDomain.BaseDirectory;
+            allPaths[0] = AppDomain.CurrentDomain.BaseDirectory!;
             extraNamespaces.CopyTo(allPaths, 1);
             paths.CopyTo(allPaths, extraNamespaces.Length + 1);
 
             return Path.Combine(allPaths);
         }
     }
-}
+}

+ 2 - 2
src/Abc.Zebus/Util/TypeUtil.cs

@@ -64,12 +64,12 @@ namespace Abc.Zebus.Util
         public static string GetFullnameWithNoAssemblyOrVersion(Type messageType)
         {
             if (!messageType.IsGenericType)
-                return messageType.FullName;
+                return messageType.FullName!;
 
             var genericTypeDefinition = messageType.GetGenericTypeDefinition();
             var builder = new StringBuilder();
             if (messageType.IsNested)
-                builder.AppendFormat("{0}+", messageType.DeclaringType.FullName);
+                builder.AppendFormat("{0}+", messageType.DeclaringType!.FullName);
             else
                 builder.AppendFormat("{0}.", genericTypeDefinition.Namespace);